text stringlengths 54 60.6k |
|---|
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Tests for the Command Buffer Helper.
#include "base/at_exit.h"
#include "base/callback.h"
#include "base/message_loop.h"
#include "base/scoped_nsautorelease_pool.h"
#include "gpu/command_buffer/client/cmd_buffer_helper.h"
#include "gpu/command_buffer/service/mocks.h"
#include "gpu/command_buffer/service/command_buffer_service.h"
#include "gpu/command_buffer/service/gpu_processor.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace gpu {
using testing::Return;
using testing::Mock;
using testing::Truly;
using testing::Sequence;
using testing::DoAll;
using testing::Invoke;
using testing::_;
const int32 kNumCommandEntries = 10;
const int32 kCommandBufferSizeBytes =
kNumCommandEntries * sizeof(CommandBufferEntry);
// Test fixture for CommandBufferHelper test - Creates a CommandBufferHelper,
// using a CommandBufferEngine with a mock AsyncAPIInterface for its interface
// (calling it directly, not through the RPC mechanism).
class CommandBufferHelperTest : public testing::Test {
protected:
virtual void SetUp() {
api_mock_.reset(new AsyncAPIMock);
// ignore noops in the mock - we don't want to inspect the internals of the
// helper.
EXPECT_CALL(*api_mock_, DoCommand(0, _, _))
.WillRepeatedly(Return(error::kNoError));
command_buffer_.reset(new CommandBufferService);
command_buffer_->Initialize(kNumCommandEntries);
Buffer ring_buffer = command_buffer_->GetRingBuffer();
parser_ = new CommandParser(ring_buffer.ptr,
ring_buffer.size,
0,
ring_buffer.size,
0,
api_mock_.get());
scoped_refptr<GPUProcessor> gpu_processor(new GPUProcessor(
command_buffer_.get(), NULL, parser_, 1));
command_buffer_->SetPutOffsetChangeCallback(NewCallback(
gpu_processor.get(), &GPUProcessor::ProcessCommands));
api_mock_->set_engine(gpu_processor.get());
helper_.reset(new CommandBufferHelper(command_buffer_.get()));
helper_->Initialize();
}
virtual void TearDown() {
// If the GPUProcessor posts any tasks, this forces them to run.
MessageLoop::current()->RunAllPending();
helper_.release();
}
// Adds a command to the buffer through the helper, while adding it as an
// expected call on the API mock.
void AddCommandWithExpect(error::Error _return,
unsigned int command,
int arg_count,
CommandBufferEntry *args) {
CommandHeader header;
header.size = arg_count + 1;
header.command = command;
CommandBufferEntry* cmds = helper_->GetSpace(arg_count + 1);
CommandBufferOffset put = 0;
cmds[put++].value_header = header;
for (int ii = 0; ii < arg_count; ++ii) {
cmds[put++] = args[ii];
}
EXPECT_CALL(*api_mock_, DoCommand(command, arg_count,
Truly(AsyncAPIMock::IsArgs(arg_count, args))))
.InSequence(sequence_)
.WillOnce(Return(_return));
}
// Checks that the buffer from put to put+size is free in the parser.
void CheckFreeSpace(CommandBufferOffset put, unsigned int size) {
CommandBufferOffset parser_put = parser_->put();
CommandBufferOffset parser_get = parser_->get();
CommandBufferOffset limit = put + size;
if (parser_get > parser_put) {
// "busy" buffer wraps, so "free" buffer is between put (inclusive) and
// get (exclusive).
EXPECT_LE(parser_put, put);
EXPECT_GT(parser_get, limit);
} else {
// "busy" buffer does not wrap, so the "free" buffer is the top side (from
// put to the limit) and the bottom side (from 0 to get).
if (put >= parser_put) {
// we're on the top side, check we are below the limit.
EXPECT_GE(kNumCommandEntries, limit);
} else {
// we're on the bottom side, check we are below get.
EXPECT_GT(parser_get, limit);
}
}
}
int32 GetGetOffset() {
return command_buffer_->GetState().get_offset;
}
int32 GetPutOffset() {
return command_buffer_->GetState().put_offset;
}
error::Error GetError() {
return command_buffer_->GetState().error;
}
CommandBufferOffset get_helper_put() { return helper_->put_; }
base::ScopedNSAutoreleasePool autorelease_pool_;
base::AtExitManager at_exit_manager_;
MessageLoop message_loop_;
scoped_ptr<AsyncAPIMock> api_mock_;
scoped_ptr<CommandBufferService> command_buffer_;
CommandParser* parser_;
scoped_ptr<CommandBufferHelper> helper_;
Sequence sequence_;
};
// Checks that commands in the buffer are properly executed, and that the
// status/error stay valid.
TEST_F(CommandBufferHelperTest, TestCommandProcessing) {
// Check initial state of the engine - it should have been configured by the
// helper.
EXPECT_TRUE(parser_ != NULL);
EXPECT_EQ(error::kNoError, GetError());
EXPECT_EQ(0, GetGetOffset());
// Add 3 commands through the helper
AddCommandWithExpect(error::kNoError, 1, 0, NULL);
CommandBufferEntry args1[2];
args1[0].value_uint32 = 3;
args1[1].value_float = 4.f;
AddCommandWithExpect(error::kNoError, 2, 2, args1);
CommandBufferEntry args2[2];
args2[0].value_uint32 = 5;
args2[1].value_float = 6.f;
AddCommandWithExpect(error::kNoError, 3, 2, args2);
helper_->Flush();
// Check that the engine has work to do now.
EXPECT_FALSE(parser_->IsEmpty());
// Wait until it's done.
helper_->Finish();
// Check that the engine has no more work to do.
EXPECT_TRUE(parser_->IsEmpty());
// Check that the commands did happen.
Mock::VerifyAndClearExpectations(api_mock_.get());
// Check the error status.
EXPECT_EQ(error::kNoError, GetError());
}
// Checks that commands in the buffer are properly executed when wrapping the
// buffer, and that the status/error stay valid.
TEST_F(CommandBufferHelperTest, TestCommandWrapping) {
// Add 5 commands of size 3 through the helper to make sure we do wrap.
CommandBufferEntry args1[2];
args1[0].value_uint32 = 3;
args1[1].value_float = 4.f;
for (unsigned int i = 0; i < 5; ++i) {
AddCommandWithExpect(error::kNoError, i + 1, 2, args1);
}
helper_->Finish();
// Check that the commands did happen.
Mock::VerifyAndClearExpectations(api_mock_.get());
// Check the error status.
EXPECT_EQ(error::kNoError, GetError());
}
// Checks that asking for available entries work, and that the parser
// effectively won't use that space.
TEST_F(CommandBufferHelperTest, TestAvailableEntries) {
CommandBufferEntry args[2];
args[0].value_uint32 = 3;
args[1].value_float = 4.f;
// Add 2 commands through the helper - 8 entries
AddCommandWithExpect(error::kNoError, 1, 0, NULL);
AddCommandWithExpect(error::kNoError, 2, 0, NULL);
AddCommandWithExpect(error::kNoError, 3, 2, args);
AddCommandWithExpect(error::kNoError, 4, 2, args);
// Ask for 5 entries.
helper_->WaitForAvailableEntries(5);
CommandBufferOffset put = get_helper_put();
CheckFreeSpace(put, 5);
// Add more commands.
AddCommandWithExpect(error::kNoError, 5, 2, args);
// Wait until everything is done done.
helper_->Finish();
// Check that the commands did happen.
Mock::VerifyAndClearExpectations(api_mock_.get());
// Check the error status.
EXPECT_EQ(error::kNoError, GetError());
}
// Checks that the InsertToken/WaitForToken work.
TEST_F(CommandBufferHelperTest, TestToken) {
CommandBufferEntry args[2];
args[0].value_uint32 = 3;
args[1].value_float = 4.f;
// Add a first command.
AddCommandWithExpect(error::kNoError, 3, 2, args);
// keep track of the buffer position.
CommandBufferOffset command1_put = get_helper_put();
int32 token = helper_->InsertToken();
EXPECT_CALL(*api_mock_.get(), DoCommand(cmd::kSetToken, 1, _))
.WillOnce(DoAll(Invoke(api_mock_.get(), &AsyncAPIMock::SetToken),
Return(error::kNoError)));
// Add another command.
AddCommandWithExpect(error::kNoError, 4, 2, args);
helper_->WaitForToken(token);
// check that the get pointer is beyond the first command.
EXPECT_LE(command1_put, GetGetOffset());
helper_->Finish();
// Check that the commands did happen.
Mock::VerifyAndClearExpectations(api_mock_.get());
// Check the error status.
EXPECT_EQ(error::kNoError, GetError());
}
} // namespace gpu
<commit_msg>Add command buffer test for case where command inserted exactly matches the space left in the command buffer.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Tests for the Command Buffer Helper.
#include "base/at_exit.h"
#include "base/callback.h"
#include "base/message_loop.h"
#include "base/scoped_nsautorelease_pool.h"
#include "gpu/command_buffer/client/cmd_buffer_helper.h"
#include "gpu/command_buffer/service/mocks.h"
#include "gpu/command_buffer/service/command_buffer_service.h"
#include "gpu/command_buffer/service/gpu_processor.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace gpu {
using testing::Return;
using testing::Mock;
using testing::Truly;
using testing::Sequence;
using testing::DoAll;
using testing::Invoke;
using testing::_;
const int32 kNumCommandEntries = 10;
const int32 kCommandBufferSizeBytes =
kNumCommandEntries * sizeof(CommandBufferEntry);
// Test fixture for CommandBufferHelper test - Creates a CommandBufferHelper,
// using a CommandBufferEngine with a mock AsyncAPIInterface for its interface
// (calling it directly, not through the RPC mechanism).
class CommandBufferHelperTest : public testing::Test {
protected:
virtual void SetUp() {
api_mock_.reset(new AsyncAPIMock);
// ignore noops in the mock - we don't want to inspect the internals of the
// helper.
EXPECT_CALL(*api_mock_, DoCommand(0, _, _))
.WillRepeatedly(Return(error::kNoError));
command_buffer_.reset(new CommandBufferService);
command_buffer_->Initialize(kNumCommandEntries);
Buffer ring_buffer = command_buffer_->GetRingBuffer();
parser_ = new CommandParser(ring_buffer.ptr,
ring_buffer.size,
0,
ring_buffer.size,
0,
api_mock_.get());
scoped_refptr<GPUProcessor> gpu_processor(new GPUProcessor(
command_buffer_.get(), NULL, parser_, 1));
command_buffer_->SetPutOffsetChangeCallback(NewCallback(
gpu_processor.get(), &GPUProcessor::ProcessCommands));
api_mock_->set_engine(gpu_processor.get());
helper_.reset(new CommandBufferHelper(command_buffer_.get()));
helper_->Initialize();
}
virtual void TearDown() {
// If the GPUProcessor posts any tasks, this forces them to run.
MessageLoop::current()->RunAllPending();
helper_.release();
}
// Adds a command to the buffer through the helper, while adding it as an
// expected call on the API mock.
void AddCommandWithExpect(error::Error _return,
unsigned int command,
int arg_count,
CommandBufferEntry *args) {
CommandHeader header;
header.size = arg_count + 1;
header.command = command;
CommandBufferEntry* cmds = helper_->GetSpace(arg_count + 1);
CommandBufferOffset put = 0;
cmds[put++].value_header = header;
for (int ii = 0; ii < arg_count; ++ii) {
cmds[put++] = args[ii];
}
EXPECT_CALL(*api_mock_, DoCommand(command, arg_count,
Truly(AsyncAPIMock::IsArgs(arg_count, args))))
.InSequence(sequence_)
.WillOnce(Return(_return));
}
// Checks that the buffer from put to put+size is free in the parser.
void CheckFreeSpace(CommandBufferOffset put, unsigned int size) {
CommandBufferOffset parser_put = parser_->put();
CommandBufferOffset parser_get = parser_->get();
CommandBufferOffset limit = put + size;
if (parser_get > parser_put) {
// "busy" buffer wraps, so "free" buffer is between put (inclusive) and
// get (exclusive).
EXPECT_LE(parser_put, put);
EXPECT_GT(parser_get, limit);
} else {
// "busy" buffer does not wrap, so the "free" buffer is the top side (from
// put to the limit) and the bottom side (from 0 to get).
if (put >= parser_put) {
// we're on the top side, check we are below the limit.
EXPECT_GE(kNumCommandEntries, limit);
} else {
// we're on the bottom side, check we are below get.
EXPECT_GT(parser_get, limit);
}
}
}
int32 GetGetOffset() {
return command_buffer_->GetState().get_offset;
}
int32 GetPutOffset() {
return command_buffer_->GetState().put_offset;
}
error::Error GetError() {
return command_buffer_->GetState().error;
}
CommandBufferOffset get_helper_put() { return helper_->put_; }
base::ScopedNSAutoreleasePool autorelease_pool_;
base::AtExitManager at_exit_manager_;
MessageLoop message_loop_;
scoped_ptr<AsyncAPIMock> api_mock_;
scoped_ptr<CommandBufferService> command_buffer_;
CommandParser* parser_;
scoped_ptr<CommandBufferHelper> helper_;
Sequence sequence_;
};
// Checks that commands in the buffer are properly executed, and that the
// status/error stay valid.
TEST_F(CommandBufferHelperTest, TestCommandProcessing) {
// Check initial state of the engine - it should have been configured by the
// helper.
EXPECT_TRUE(parser_ != NULL);
EXPECT_EQ(error::kNoError, GetError());
EXPECT_EQ(0, GetGetOffset());
// Add 3 commands through the helper
AddCommandWithExpect(error::kNoError, 1, 0, NULL);
CommandBufferEntry args1[2];
args1[0].value_uint32 = 3;
args1[1].value_float = 4.f;
AddCommandWithExpect(error::kNoError, 2, 2, args1);
CommandBufferEntry args2[2];
args2[0].value_uint32 = 5;
args2[1].value_float = 6.f;
AddCommandWithExpect(error::kNoError, 3, 2, args2);
helper_->Flush();
// Check that the engine has work to do now.
EXPECT_FALSE(parser_->IsEmpty());
// Wait until it's done.
helper_->Finish();
// Check that the engine has no more work to do.
EXPECT_TRUE(parser_->IsEmpty());
// Check that the commands did happen.
Mock::VerifyAndClearExpectations(api_mock_.get());
// Check the error status.
EXPECT_EQ(error::kNoError, GetError());
}
// Checks that commands in the buffer are properly executed when wrapping the
// buffer, and that the status/error stay valid.
TEST_F(CommandBufferHelperTest, TestCommandWrapping) {
// Add 5 commands of size 3 through the helper to make sure we do wrap.
CommandBufferEntry args1[2];
args1[0].value_uint32 = 5;
args1[1].value_float = 4.f;
for (unsigned int i = 0; i < 5; ++i) {
AddCommandWithExpect(error::kNoError, i + 1, 2, args1);
}
helper_->Finish();
// Check that the commands did happen.
Mock::VerifyAndClearExpectations(api_mock_.get());
// Check the error status.
EXPECT_EQ(error::kNoError, GetError());
}
// Checks the case where the command inserted exactly matches the space left in
// the command buffer.
TEST_F(CommandBufferHelperTest, TestCommandWrappingExactMultiple) {
const int32 kCommandSize = 5;
const int32 kNumArgs = kCommandSize - 1;
COMPILE_ASSERT(kNumCommandEntries % kCommandSize == 0,
Not_multiple_of_num_command_entries);
CommandBufferEntry args1[kNumArgs];
for (size_t ii = 0; ii < kNumArgs; ++ii) {
args1[0].value_uint32 = ii + 1;
}
for (unsigned int i = 0; i < 5; ++i) {
AddCommandWithExpect(error::kNoError, i + 1, kNumArgs, args1);
}
helper_->Finish();
// Check that the commands did happen.
Mock::VerifyAndClearExpectations(api_mock_.get());
// Check the error status.
EXPECT_EQ(error::kNoError, GetError());
}
// Checks that asking for available entries work, and that the parser
// effectively won't use that space.
TEST_F(CommandBufferHelperTest, TestAvailableEntries) {
CommandBufferEntry args[2];
args[0].value_uint32 = 3;
args[1].value_float = 4.f;
// Add 2 commands through the helper - 8 entries
AddCommandWithExpect(error::kNoError, 1, 0, NULL);
AddCommandWithExpect(error::kNoError, 2, 0, NULL);
AddCommandWithExpect(error::kNoError, 3, 2, args);
AddCommandWithExpect(error::kNoError, 4, 2, args);
// Ask for 5 entries.
helper_->WaitForAvailableEntries(5);
CommandBufferOffset put = get_helper_put();
CheckFreeSpace(put, 5);
// Add more commands.
AddCommandWithExpect(error::kNoError, 5, 2, args);
// Wait until everything is done done.
helper_->Finish();
// Check that the commands did happen.
Mock::VerifyAndClearExpectations(api_mock_.get());
// Check the error status.
EXPECT_EQ(error::kNoError, GetError());
}
// Checks that the InsertToken/WaitForToken work.
TEST_F(CommandBufferHelperTest, TestToken) {
CommandBufferEntry args[2];
args[0].value_uint32 = 3;
args[1].value_float = 4.f;
// Add a first command.
AddCommandWithExpect(error::kNoError, 3, 2, args);
// keep track of the buffer position.
CommandBufferOffset command1_put = get_helper_put();
int32 token = helper_->InsertToken();
EXPECT_CALL(*api_mock_.get(), DoCommand(cmd::kSetToken, 1, _))
.WillOnce(DoAll(Invoke(api_mock_.get(), &AsyncAPIMock::SetToken),
Return(error::kNoError)));
// Add another command.
AddCommandWithExpect(error::kNoError, 4, 2, args);
helper_->WaitForToken(token);
// check that the get pointer is beyond the first command.
EXPECT_LE(command1_put, GetGetOffset());
helper_->Finish();
// Check that the commands did happen.
Mock::VerifyAndClearExpectations(api_mock_.get());
// Check the error status.
EXPECT_EQ(error::kNoError, GetError());
}
} // namespace gpu
<|endoftext|> |
<commit_before>#include "KeyValBase.h"
#include <iostream>
#include <array>
#include <boost/spirit/include/qi.hpp>
#include <boost/fusion/include/std_pair.hpp>
#include "utils.h"
size_t KeyValBase::depth() const
{
return depth_;
}
void KeyValBase::depth(size_t depth) const
{
depth_ = depth;
}
std::string KeyValBase::operator[](const std::string& key) const
{
if (keyvals.count(key) == 0) return "";
return keyvals.at(key);
}
std::string& KeyValBase::operator[](const std::string& key)
{
return keyvals[key];
}
std::string KeyValBase::get(const std::string& key) const
{
return (*this)[key];
}
std::pair<std::string, std::string> KeyValBase::parseKeyval(std::string_view keyval)
{
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
auto trimmed = trim(keyval);
//auto fsplit = trimmed.find_first_of("\"", 1);
//if (fsplit > trimmed.length())
// fsplit = trimmed.length();
//auto left = trimmed.substr(0, fsplit);
//left = trim(left, "\"");
//if (fsplit == trimmed.length())
// return std::make_pair("", "");
//auto esplit = trimmed.find_first_of("\"", fsplit + 1);
//if (esplit == 0 || esplit >= trimmed.length())
// esplit = fsplit;
//auto right = trimmed.substr(esplit + 1);
//right = trim(right, "\"");
//std::string key{ right }, value{ left };
std::pair<std::string, std::string> ret;
if (!qi::parse(trimmed.cbegin(), trimmed.cend(), '"' >> +(qi::char_ - '"') >> '"' >> ' ' >> '"' >> +(qi::char_ - '"') >> '"', ret))
throw std::exception("Failed to parse keyval");
return ret;
}
std::string KeyValBase::toStr(const std::pair<std::string, std::string>& pair, char enclose)
{
return enclose + pair.first + enclose + ' ' + enclose + pair.second + enclose;
}
size_t KeyValBase::parse(std::istream& stream)
{
size_t numparsed = 0;
std::string curline;
while (trim(curline) != "{")
{
getline(stream, curline);
numparsed++;
}
unsigned int depth = 1;
while (getline(stream, curline))
{
numparsed++;
auto trimmedCurline = trim(curline);
if (trimmedCurline == "}")
{
if (--depth == 0)
break;
}
else if (trimmedCurline == "{")
{
++depth;
}
else if (trimmedCurline.find_first_of('"') != std::string::npos)
{
auto [k, v] = parseKeyval(curline);
keyvals[k] = v;
}
else
{
numparsed += parseSpecial(stream, trimmedCurline);
}
}
if (auto it = keyvals.find("id"); it != keyvals.end())
{
this->id_ = atoi(it->second.c_str());
keyvals.erase("id");
}
return numparsed;
}
size_t KeyValBase::parseSpecial(std::istream & stream, std::string_view type)
{
return 0;
}
bool KeyValBase::empty() const
{
return keyvals.empty();
}
void KeyValBase::extraOutput(std::ostream & os) const
{
}
KeyValBase::KeyValBase(std::initializer_list<decltype(keyvals)::value_type> init)
: keyvals(init)
{
}
<commit_msg>Move value when inserting into keyvalues.<commit_after>#include "KeyValBase.h"
#include <iostream>
#include <array>
#include <boost/spirit/include/qi.hpp>
#include <boost/fusion/include/std_pair.hpp>
#include "utils.h"
size_t KeyValBase::depth() const
{
return depth_;
}
void KeyValBase::depth(size_t depth) const
{
depth_ = depth;
}
std::string KeyValBase::operator[](const std::string& key) const
{
if (keyvals.count(key) == 0) return "";
return keyvals.at(key);
}
std::string& KeyValBase::operator[](const std::string& key)
{
return keyvals[key];
}
std::string KeyValBase::get(const std::string& key) const
{
return (*this)[key];
}
std::pair<std::string, std::string> KeyValBase::parseKeyval(std::string_view keyval)
{
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
auto trimmed = trim(keyval);
//auto fsplit = trimmed.find_first_of("\"", 1);
//if (fsplit > trimmed.length())
// fsplit = trimmed.length();
//auto left = trimmed.substr(0, fsplit);
//left = trim(left, "\"");
//if (fsplit == trimmed.length())
// return std::make_pair("", "");
//auto esplit = trimmed.find_first_of("\"", fsplit + 1);
//if (esplit == 0 || esplit >= trimmed.length())
// esplit = fsplit;
//auto right = trimmed.substr(esplit + 1);
//right = trim(right, "\"");
//std::string key{ right }, value{ left };
std::pair<std::string, std::string> ret;
if (!qi::parse(trimmed.cbegin(), trimmed.cend(), '"' >> +(qi::char_ - '"') >> '"' >> ' ' >> '"' >> +(qi::char_ - '"') >> '"', ret))
throw std::exception("Failed to parse keyval");
return ret;
}
std::string KeyValBase::toStr(const std::pair<std::string, std::string>& pair, char enclose)
{
return enclose + pair.first + enclose + ' ' + enclose + pair.second + enclose;
}
size_t KeyValBase::parse(std::istream& stream)
{
size_t numparsed = 0;
std::string curline;
while (trim(curline) != "{")
{
getline(stream, curline);
numparsed++;
}
unsigned int depth = 1;
while (getline(stream, curline))
{
numparsed++;
auto trimmedCurline = trim(curline);
if (trimmedCurline == "}")
{
if (--depth == 0)
break;
}
else if (trimmedCurline == "{")
{
++depth;
}
else if (trimmedCurline.find_first_of('"') != std::string::npos)
{
auto [k, v] = parseKeyval(curline);
keyvals[k] = std::move(v);
}
else
{
numparsed += parseSpecial(stream, trimmedCurline);
}
}
if (auto it = keyvals.find("id"); it != keyvals.end())
{
this->id_ = atoi(it->second.c_str());
keyvals.erase("id");
}
return numparsed;
}
size_t KeyValBase::parseSpecial(std::istream & stream, std::string_view type)
{
return 0;
}
bool KeyValBase::empty() const
{
return keyvals.empty();
}
void KeyValBase::extraOutput(std::ostream & os) const
{
}
KeyValBase::KeyValBase(std::initializer_list<decltype(keyvals)::value_type> init)
: keyvals(init)
{
}
<|endoftext|> |
<commit_before>#include "TileRenderer.h"
#include "components/Options.h"
#include "components/ThreadWorker.h"
#include "graphics/ViewState.h"
#include "projections/ProjectionSurface.h"
#include "projections/PlanarProjectionSurface.h"
#include "renderers/MapRenderer.h"
#include "renderers/drawdatas/TileDrawData.h"
#include "renderers/utils/GLResourceManager.h"
#include "renderers/utils/VTRenderer.h"
#include "utils/Log.h"
#include <vt/Label.h>
#include <vt/LabelCuller.h>
#include <vt/TileTransformer.h>
#include <vt/GLTileRenderer.h>
#include <vt/GLExtensions.h>
#include <cglib/mat.h>
namespace carto {
TileRenderer::TileRenderer() :
_mapRenderer(),
_options(),
_tileTransformer(),
_vtRenderer(),
_interactionMode(false),
_subTileBlending(true),
_labelOrder(0),
_buildingOrder(1),
_rasterFilterMode(vt::RasterFilterMode::BILINEAR),
_horizontalLayerOffset(0),
_viewDir(0, 0, 0),
_mainLightDir(0, 0, 0),
_tiles(),
_mutex()
{
}
TileRenderer::~TileRenderer() {
}
void TileRenderer::setComponents(const std::weak_ptr<Options>& options, const std::weak_ptr<MapRenderer>& mapRenderer) {
std::lock_guard<std::mutex> lock(_mutex);
_options = options;
_mapRenderer = mapRenderer;
_vtRenderer.reset();
}
std::shared_ptr<vt::TileTransformer> TileRenderer::getTileTransformer() const {
std::lock_guard<std::mutex> lock(_mutex);
return _tileTransformer;
}
void TileRenderer::setTileTransformer(const std::shared_ptr<vt::TileTransformer>& tileTransformer) {
std::lock_guard<std::mutex> lock(_mutex);
if (_tileTransformer != tileTransformer) {
_vtRenderer.reset();
}
_tileTransformer = tileTransformer;
}
void TileRenderer::setInteractionMode(bool enabled) {
std::lock_guard<std::mutex> lock(_mutex);
_interactionMode = enabled;
}
void TileRenderer::setSubTileBlending(bool enabled) {
std::lock_guard<std::mutex> lock(_mutex);
_subTileBlending = enabled;
}
void TileRenderer::setLabelOrder(int order) {
std::lock_guard<std::mutex> lock(_mutex);
_labelOrder = order;
}
void TileRenderer::setBuildingOrder(int order) {
std::lock_guard<std::mutex> lock(_mutex);
_buildingOrder = order;
}
void TileRenderer::setRasterFilterMode(vt::RasterFilterMode filterMode) {
std::lock_guard<std::mutex> lock(_mutex);
_rasterFilterMode = filterMode;
}
void TileRenderer::offsetLayerHorizontally(double offset) {
std::lock_guard<std::mutex> lock(_mutex);
_horizontalLayerOffset += offset;
}
bool TileRenderer::onDrawFrame(float deltaSeconds, const ViewState& viewState) {
std::lock_guard<std::mutex> lock(_mutex);
if (!initializeRenderer()) {
return false;
}
std::shared_ptr<vt::GLTileRenderer> tileRenderer = _vtRenderer->getTileRenderer();
if (!tileRenderer) {
return false;
}
cglib::mat4x4<double> modelViewMat = viewState.getModelviewMat() * cglib::translate4_matrix(cglib::vec3<double>(_horizontalLayerOffset, 0, 0));
tileRenderer->setViewState(vt::ViewState(viewState.getProjectionMat(), modelViewMat, viewState.getZoom(), viewState.getAspectRatio(), viewState.getNormalizedResolution()));
tileRenderer->setInteractionMode(_interactionMode);
tileRenderer->setSubTileBlending(_subTileBlending);
tileRenderer->setRasterFilterMode(_rasterFilterMode);
_viewDir = cglib::unit(viewState.getFocusPosNormal());
if (auto options = _options.lock()) {
MapPos internalFocusPos = viewState.getProjectionSurface()->calculateMapPos(viewState.getFocusPos());
_mainLightDir = cglib::vec3<float>::convert(cglib::unit(viewState.getProjectionSurface()->calculateVector(internalFocusPos, options->getMainLightDirection())));
}
tileRenderer->startFrame(deltaSeconds * 3);
bool refresh = false;
refresh = tileRenderer->renderGeometry2D() || refresh;
if (_labelOrder == 0) {
refresh = tileRenderer->renderLabels(true, false) || refresh;
}
if (_buildingOrder == 0) {
refresh = tileRenderer->renderGeometry3D() || refresh;
}
if (_labelOrder == 0) {
refresh = tileRenderer->renderLabels(false, true) || refresh;
}
// Reset GL state to the expected state
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_FALSE);
GLContext::CheckGLError("TileRenderer::onDrawFrame");
return refresh;
}
bool TileRenderer::onDrawFrame3D(float deltaSeconds, const ViewState& viewState) {
std::lock_guard<std::mutex> lock(_mutex);
if (!_vtRenderer) {
return false;
}
std::shared_ptr<vt::GLTileRenderer> tileRenderer = _vtRenderer->getTileRenderer();
if (!tileRenderer) {
return false;
}
bool refresh = false;
if (_labelOrder == 1) {
refresh = tileRenderer->renderLabels(true, false) || refresh;
}
if (_buildingOrder == 1) {
refresh = tileRenderer->renderGeometry3D() || refresh;
}
if (_labelOrder == 1) {
refresh = tileRenderer->renderLabels(false, true) || refresh;
}
tileRenderer->endFrame();
// Reset GL state to the expected state
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_FALSE);
GLContext::CheckGLError("TileRenderer::onDrawFrame3D");
return refresh;
}
bool TileRenderer::cullLabels(vt::LabelCuller& culler, const ViewState& viewState) {
std::shared_ptr<vt::GLTileRenderer> tileRenderer;
cglib::mat4x4<double> modelViewMat;
{
std::lock_guard<std::mutex> lock(_mutex);
if (_vtRenderer) {
tileRenderer = _vtRenderer->getTileRenderer();
}
modelViewMat = viewState.getModelviewMat() * cglib::translate4_matrix(cglib::vec3<double>(_horizontalLayerOffset, 0, 0));
}
if (!tileRenderer) {
return false;
}
culler.setViewState(vt::ViewState(viewState.getProjectionMat(), modelViewMat, viewState.getZoom(), viewState.getAspectRatio(), viewState.getNormalizedResolution()));
tileRenderer->cullLabels(culler);
return true;
}
bool TileRenderer::refreshTiles(const std::vector<std::shared_ptr<TileDrawData> >& drawDatas) {
std::lock_guard<std::mutex> lock(_mutex);
std::map<vt::TileId, std::shared_ptr<const vt::Tile> > tiles;
for (const std::shared_ptr<TileDrawData>& drawData : drawDatas) {
tiles[drawData->getVTTileId()] = drawData->getVTTile();
}
bool changed = (tiles != _tiles) || (_horizontalLayerOffset != 0);
if (!changed) {
return false;
}
if (_vtRenderer) {
if (std::shared_ptr<vt::GLTileRenderer> tileRenderer = _vtRenderer->getTileRenderer()) {
tileRenderer->setVisibleTiles(tiles, _horizontalLayerOffset == 0);
}
}
_tiles = std::move(tiles);
_horizontalLayerOffset = 0;
return true;
}
void TileRenderer::calculateRayIntersectedElements(const cglib::ray3<double>& ray, const ViewState& viewState, float radius, std::vector<std::tuple<vt::TileId, double, long long> >& results) const {
std::lock_guard<std::mutex> lock(_mutex);
if (!_vtRenderer) {
return;
}
std::shared_ptr<vt::GLTileRenderer> tileRenderer = _vtRenderer->getTileRenderer();
if (!tileRenderer) {
return;
}
tileRenderer->findGeometryIntersections(ray, results, radius, true, false);
if (_labelOrder == 0) {
tileRenderer->findLabelIntersections(ray, results, radius, true, false);
}
if (_buildingOrder == 0) {
tileRenderer->findGeometryIntersections(ray, results, radius, false, true);
}
if (_labelOrder == 0) {
tileRenderer->findLabelIntersections(ray, results, radius, false, true);
}
}
void TileRenderer::calculateRayIntersectedElements3D(const cglib::ray3<double>& ray, const ViewState& viewState, float radius, std::vector<std::tuple<vt::TileId, double, long long> >& results) const {
std::lock_guard<std::mutex> lock(_mutex);
if (!_vtRenderer) {
return;
}
std::shared_ptr<vt::GLTileRenderer> tileRenderer = _vtRenderer->getTileRenderer();
if (!tileRenderer) {
return;
}
if (_labelOrder == 1) {
tileRenderer->findLabelIntersections(ray, results, radius, true, false);
}
if (_buildingOrder == 1) {
tileRenderer->findGeometryIntersections(ray, results, radius, false, true);
}
if (_labelOrder == 1) {
tileRenderer->findLabelIntersections(ray, results, radius, false, true);
}
}
void TileRenderer::calculateRayIntersectedBitmaps(const cglib::ray3<double>& ray, const ViewState& viewState, std::vector<std::tuple<vt::TileId, double, vt::TileBitmap, cglib::vec2<float> > >& results) const {
std::lock_guard<std::mutex> lock(_mutex);
if (!_vtRenderer) {
return;
}
std::shared_ptr<vt::GLTileRenderer> tileRenderer = _vtRenderer->getTileRenderer();
if (!tileRenderer) {
return;
}
tileRenderer->findBitmapIntersections(ray, results);
}
bool TileRenderer::initializeRenderer() {
if (_vtRenderer && _vtRenderer->isValid()) {
return true;
}
std::shared_ptr<MapRenderer> mapRenderer = _mapRenderer.lock();
if (!mapRenderer) {
return false; // safety check, should never happen
}
Log::Debug("TileRenderer: Initializing renderer");
_vtRenderer = mapRenderer->getGLResourceManager()->create<VTRenderer>(_tileTransformer);
if (std::shared_ptr<vt::GLTileRenderer> tileRenderer = _vtRenderer->getTileRenderer()) {
tileRenderer->setVisibleTiles(_tiles, _horizontalLayerOffset == 0);
if (!std::dynamic_pointer_cast<PlanarProjectionSurface>(mapRenderer->getProjectionSurface())) {
vt::GLTileRenderer::LightingShader lightingShader2D(true, LIGHTING_SHADER_2D, [this](GLuint shaderProgram, const vt::ViewState& viewState) {
glUniform3fv(glGetUniformLocation(shaderProgram, "u_viewDir"), 1, _viewDir.data());
});
tileRenderer->setLightingShader2D(lightingShader2D);
}
vt::GLTileRenderer::LightingShader lightingShader3D(true, LIGHTING_SHADER_3D, [this](GLuint shaderProgram, const vt::ViewState& viewState) {
if (auto options = _options.lock()) {
const Color& ambientLightColor = options->getAmbientLightColor();
glUniform4f(glGetUniformLocation(shaderProgram, "u_ambientColor"), ambientLightColor.getR() / 255.0f, ambientLightColor.getG() / 255.0f, ambientLightColor.getB() / 255.0f, ambientLightColor.getA() / 255.0f);
const Color& mainLightColor = options->getMainLightColor();
glUniform4f(glGetUniformLocation(shaderProgram, "u_lightColor"), mainLightColor.getR() / 255.0f, mainLightColor.getG() / 255.0f, mainLightColor.getB() / 255.0f, mainLightColor.getA() / 255.0f);
glUniform3fv(glGetUniformLocation(shaderProgram, "u_lightDir"), 1, _mainLightDir.data());
glUniform3fv(glGetUniformLocation(shaderProgram, "u_viewDir"), 1, _viewDir.data());
}
});
tileRenderer->setLightingShader3D(lightingShader3D);
vt::GLTileRenderer::LightingShader lightingShaderNormalMap(false, LIGHTING_SHADER_NORMALMAP, [this](GLuint shaderProgram, const vt::ViewState& viewState) {
if (auto options = _options.lock()) {
const Color& ambientLightColor = options->getAmbientLightColor();
glUniform4f(glGetUniformLocation(shaderProgram, "u_shadowColor"), 0.0f, 0.0f, 0.0f, 1.0f);
glUniform4f(glGetUniformLocation(shaderProgram, "u_highlightColor"), 1.0f, 1.0f, 1.0f, 1.0f);
glUniform3fv(glGetUniformLocation(shaderProgram, "u_lightDir"), 1, _mainLightDir.data());
}
});
tileRenderer->setLightingShaderNormalMap(lightingShaderNormalMap);
}
return _vtRenderer && _vtRenderer->isValid();
}
const std::string TileRenderer::LIGHTING_SHADER_2D = R"GLSL(
uniform vec3 u_viewDir;
vec4 applyLighting(lowp vec4 color, mediump vec3 normal) {
mediump float lighting = max(0.0, dot(normal, u_viewDir)) * 0.5 + 0.5;
return vec4(color.rgb * lighting, color.a);
}
)GLSL";
const std::string TileRenderer::LIGHTING_SHADER_3D = R"GLSL(
uniform vec4 u_ambientColor;
uniform vec4 u_lightColor;
uniform vec3 u_lightDir;
uniform vec3 u_viewDir;
vec4 applyLighting(lowp vec4 color, mediump vec3 normal, highp_opt float height, lowp bool sideVertex) {
if (sideVertex) {
lowp vec3 dimmedColor = color.rgb * (1.0 - 0.5 / (1.0 + height * height));
mediump vec3 lighting = max(0.0, dot(normal, u_lightDir)) * u_lightColor.rgb + u_ambientColor.rgb;
return vec4(dimmedColor.rgb * lighting, color.a);
} else {
mediump float lighting = max(0.0, dot(normal, u_viewDir)) * 0.5 + 0.5;
return vec4(color.rgb * lighting, color.a);
}
}
)GLSL";
const std::string TileRenderer::LIGHTING_SHADER_NORMALMAP = R"GLSL(
uniform vec4 u_shadowColor;
uniform vec4 u_highlightColor;
uniform vec3 u_lightDir;
vec4 applyLighting(lowp vec4 color, mediump vec3 normal, mediump float intensity) {
mediump float lighting = max(0.0, dot(normal, u_lightDir));
lowp vec4 shadeColor = mix(u_shadowColor, u_highlightColor, lighting);
return shadeColor * color * intensity;
}
)GLSL";
}
<commit_msg>Fix lighting shader<commit_after>#include "TileRenderer.h"
#include "components/Options.h"
#include "components/ThreadWorker.h"
#include "graphics/ViewState.h"
#include "projections/ProjectionSurface.h"
#include "projections/PlanarProjectionSurface.h"
#include "renderers/MapRenderer.h"
#include "renderers/drawdatas/TileDrawData.h"
#include "renderers/utils/GLResourceManager.h"
#include "renderers/utils/VTRenderer.h"
#include "utils/Log.h"
#include <vt/Label.h>
#include <vt/LabelCuller.h>
#include <vt/TileTransformer.h>
#include <vt/GLTileRenderer.h>
#include <vt/GLExtensions.h>
#include <cglib/mat.h>
namespace carto {
TileRenderer::TileRenderer() :
_mapRenderer(),
_options(),
_tileTransformer(),
_vtRenderer(),
_interactionMode(false),
_subTileBlending(true),
_labelOrder(0),
_buildingOrder(1),
_rasterFilterMode(vt::RasterFilterMode::BILINEAR),
_horizontalLayerOffset(0),
_viewDir(0, 0, 0),
_mainLightDir(0, 0, 0),
_tiles(),
_mutex()
{
}
TileRenderer::~TileRenderer() {
}
void TileRenderer::setComponents(const std::weak_ptr<Options>& options, const std::weak_ptr<MapRenderer>& mapRenderer) {
std::lock_guard<std::mutex> lock(_mutex);
_options = options;
_mapRenderer = mapRenderer;
_vtRenderer.reset();
}
std::shared_ptr<vt::TileTransformer> TileRenderer::getTileTransformer() const {
std::lock_guard<std::mutex> lock(_mutex);
return _tileTransformer;
}
void TileRenderer::setTileTransformer(const std::shared_ptr<vt::TileTransformer>& tileTransformer) {
std::lock_guard<std::mutex> lock(_mutex);
if (_tileTransformer != tileTransformer) {
_vtRenderer.reset();
}
_tileTransformer = tileTransformer;
}
void TileRenderer::setInteractionMode(bool enabled) {
std::lock_guard<std::mutex> lock(_mutex);
_interactionMode = enabled;
}
void TileRenderer::setSubTileBlending(bool enabled) {
std::lock_guard<std::mutex> lock(_mutex);
_subTileBlending = enabled;
}
void TileRenderer::setLabelOrder(int order) {
std::lock_guard<std::mutex> lock(_mutex);
_labelOrder = order;
}
void TileRenderer::setBuildingOrder(int order) {
std::lock_guard<std::mutex> lock(_mutex);
_buildingOrder = order;
}
void TileRenderer::setRasterFilterMode(vt::RasterFilterMode filterMode) {
std::lock_guard<std::mutex> lock(_mutex);
_rasterFilterMode = filterMode;
}
void TileRenderer::offsetLayerHorizontally(double offset) {
std::lock_guard<std::mutex> lock(_mutex);
_horizontalLayerOffset += offset;
}
bool TileRenderer::onDrawFrame(float deltaSeconds, const ViewState& viewState) {
std::lock_guard<std::mutex> lock(_mutex);
if (!initializeRenderer()) {
return false;
}
std::shared_ptr<vt::GLTileRenderer> tileRenderer = _vtRenderer->getTileRenderer();
if (!tileRenderer) {
return false;
}
cglib::mat4x4<double> modelViewMat = viewState.getModelviewMat() * cglib::translate4_matrix(cglib::vec3<double>(_horizontalLayerOffset, 0, 0));
tileRenderer->setViewState(vt::ViewState(viewState.getProjectionMat(), modelViewMat, viewState.getZoom(), viewState.getAspectRatio(), viewState.getNormalizedResolution()));
tileRenderer->setInteractionMode(_interactionMode);
tileRenderer->setSubTileBlending(_subTileBlending);
tileRenderer->setRasterFilterMode(_rasterFilterMode);
_viewDir = cglib::unit(viewState.getFocusPosNormal());
if (auto options = _options.lock()) {
MapPos internalFocusPos = viewState.getProjectionSurface()->calculateMapPos(viewState.getFocusPos());
_mainLightDir = cglib::vec3<float>::convert(cglib::unit(viewState.getProjectionSurface()->calculateVector(internalFocusPos, options->getMainLightDirection())));
}
tileRenderer->startFrame(deltaSeconds * 3);
bool refresh = false;
refresh = tileRenderer->renderGeometry2D() || refresh;
if (_labelOrder == 0) {
refresh = tileRenderer->renderLabels(true, false) || refresh;
}
if (_buildingOrder == 0) {
refresh = tileRenderer->renderGeometry3D() || refresh;
}
if (_labelOrder == 0) {
refresh = tileRenderer->renderLabels(false, true) || refresh;
}
// Reset GL state to the expected state
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_FALSE);
GLContext::CheckGLError("TileRenderer::onDrawFrame");
return refresh;
}
bool TileRenderer::onDrawFrame3D(float deltaSeconds, const ViewState& viewState) {
std::lock_guard<std::mutex> lock(_mutex);
if (!_vtRenderer) {
return false;
}
std::shared_ptr<vt::GLTileRenderer> tileRenderer = _vtRenderer->getTileRenderer();
if (!tileRenderer) {
return false;
}
bool refresh = false;
if (_labelOrder == 1) {
refresh = tileRenderer->renderLabels(true, false) || refresh;
}
if (_buildingOrder == 1) {
refresh = tileRenderer->renderGeometry3D() || refresh;
}
if (_labelOrder == 1) {
refresh = tileRenderer->renderLabels(false, true) || refresh;
}
tileRenderer->endFrame();
// Reset GL state to the expected state
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_FALSE);
GLContext::CheckGLError("TileRenderer::onDrawFrame3D");
return refresh;
}
bool TileRenderer::cullLabels(vt::LabelCuller& culler, const ViewState& viewState) {
std::shared_ptr<vt::GLTileRenderer> tileRenderer;
cglib::mat4x4<double> modelViewMat;
{
std::lock_guard<std::mutex> lock(_mutex);
if (_vtRenderer) {
tileRenderer = _vtRenderer->getTileRenderer();
}
modelViewMat = viewState.getModelviewMat() * cglib::translate4_matrix(cglib::vec3<double>(_horizontalLayerOffset, 0, 0));
}
if (!tileRenderer) {
return false;
}
culler.setViewState(vt::ViewState(viewState.getProjectionMat(), modelViewMat, viewState.getZoom(), viewState.getAspectRatio(), viewState.getNormalizedResolution()));
tileRenderer->cullLabels(culler);
return true;
}
bool TileRenderer::refreshTiles(const std::vector<std::shared_ptr<TileDrawData> >& drawDatas) {
std::lock_guard<std::mutex> lock(_mutex);
std::map<vt::TileId, std::shared_ptr<const vt::Tile> > tiles;
for (const std::shared_ptr<TileDrawData>& drawData : drawDatas) {
tiles[drawData->getVTTileId()] = drawData->getVTTile();
}
bool changed = (tiles != _tiles) || (_horizontalLayerOffset != 0);
if (!changed) {
return false;
}
if (_vtRenderer) {
if (std::shared_ptr<vt::GLTileRenderer> tileRenderer = _vtRenderer->getTileRenderer()) {
tileRenderer->setVisibleTiles(tiles, _horizontalLayerOffset == 0);
}
}
_tiles = std::move(tiles);
_horizontalLayerOffset = 0;
return true;
}
void TileRenderer::calculateRayIntersectedElements(const cglib::ray3<double>& ray, const ViewState& viewState, float radius, std::vector<std::tuple<vt::TileId, double, long long> >& results) const {
std::lock_guard<std::mutex> lock(_mutex);
if (!_vtRenderer) {
return;
}
std::shared_ptr<vt::GLTileRenderer> tileRenderer = _vtRenderer->getTileRenderer();
if (!tileRenderer) {
return;
}
tileRenderer->findGeometryIntersections(ray, results, radius, true, false);
if (_labelOrder == 0) {
tileRenderer->findLabelIntersections(ray, results, radius, true, false);
}
if (_buildingOrder == 0) {
tileRenderer->findGeometryIntersections(ray, results, radius, false, true);
}
if (_labelOrder == 0) {
tileRenderer->findLabelIntersections(ray, results, radius, false, true);
}
}
void TileRenderer::calculateRayIntersectedElements3D(const cglib::ray3<double>& ray, const ViewState& viewState, float radius, std::vector<std::tuple<vt::TileId, double, long long> >& results) const {
std::lock_guard<std::mutex> lock(_mutex);
if (!_vtRenderer) {
return;
}
std::shared_ptr<vt::GLTileRenderer> tileRenderer = _vtRenderer->getTileRenderer();
if (!tileRenderer) {
return;
}
if (_labelOrder == 1) {
tileRenderer->findLabelIntersections(ray, results, radius, true, false);
}
if (_buildingOrder == 1) {
tileRenderer->findGeometryIntersections(ray, results, radius, false, true);
}
if (_labelOrder == 1) {
tileRenderer->findLabelIntersections(ray, results, radius, false, true);
}
}
void TileRenderer::calculateRayIntersectedBitmaps(const cglib::ray3<double>& ray, const ViewState& viewState, std::vector<std::tuple<vt::TileId, double, vt::TileBitmap, cglib::vec2<float> > >& results) const {
std::lock_guard<std::mutex> lock(_mutex);
if (!_vtRenderer) {
return;
}
std::shared_ptr<vt::GLTileRenderer> tileRenderer = _vtRenderer->getTileRenderer();
if (!tileRenderer) {
return;
}
tileRenderer->findBitmapIntersections(ray, results);
}
bool TileRenderer::initializeRenderer() {
if (_vtRenderer && _vtRenderer->isValid()) {
return true;
}
std::shared_ptr<MapRenderer> mapRenderer = _mapRenderer.lock();
if (!mapRenderer) {
return false; // safety check, should never happen
}
Log::Debug("TileRenderer: Initializing renderer");
_vtRenderer = mapRenderer->getGLResourceManager()->create<VTRenderer>(_tileTransformer);
if (std::shared_ptr<vt::GLTileRenderer> tileRenderer = _vtRenderer->getTileRenderer()) {
tileRenderer->setVisibleTiles(_tiles, _horizontalLayerOffset == 0);
if (!std::dynamic_pointer_cast<PlanarProjectionSurface>(mapRenderer->getProjectionSurface())) {
vt::GLTileRenderer::LightingShader lightingShader2D(true, LIGHTING_SHADER_2D, [this](GLuint shaderProgram, const vt::ViewState& viewState) {
glUniform3fv(glGetUniformLocation(shaderProgram, "u_viewDir"), 1, _viewDir.data());
});
tileRenderer->setLightingShader2D(lightingShader2D);
}
vt::GLTileRenderer::LightingShader lightingShader3D(true, LIGHTING_SHADER_3D, [this](GLuint shaderProgram, const vt::ViewState& viewState) {
if (auto options = _options.lock()) {
const Color& ambientLightColor = options->getAmbientLightColor();
glUniform4f(glGetUniformLocation(shaderProgram, "u_ambientColor"), ambientLightColor.getR() / 255.0f, ambientLightColor.getG() / 255.0f, ambientLightColor.getB() / 255.0f, ambientLightColor.getA() / 255.0f);
const Color& mainLightColor = options->getMainLightColor();
glUniform4f(glGetUniformLocation(shaderProgram, "u_lightColor"), mainLightColor.getR() / 255.0f, mainLightColor.getG() / 255.0f, mainLightColor.getB() / 255.0f, mainLightColor.getA() / 255.0f);
glUniform3fv(glGetUniformLocation(shaderProgram, "u_lightDir"), 1, _mainLightDir.data());
glUniform3fv(glGetUniformLocation(shaderProgram, "u_viewDir"), 1, _viewDir.data());
}
});
tileRenderer->setLightingShader3D(lightingShader3D);
vt::GLTileRenderer::LightingShader lightingShaderNormalMap(false, LIGHTING_SHADER_NORMALMAP, [this](GLuint shaderProgram, const vt::ViewState& viewState) {
if (auto options = _options.lock()) {
const Color& ambientLightColor = options->getAmbientLightColor();
glUniform4f(glGetUniformLocation(shaderProgram, "u_shadowColor"), 0.0f, 0.0f, 0.0f, 1.0f);
glUniform4f(glGetUniformLocation(shaderProgram, "u_highlightColor"), 1.0f, 1.0f, 1.0f, 1.0f);
glUniform3fv(glGetUniformLocation(shaderProgram, "u_lightDir"), 1, _mainLightDir.data());
}
});
tileRenderer->setLightingShaderNormalMap(lightingShaderNormalMap);
}
return _vtRenderer && _vtRenderer->isValid();
}
const std::string TileRenderer::LIGHTING_SHADER_2D = R"GLSL(
uniform vec3 u_viewDir;
vec4 applyLighting(lowp vec4 color, mediump vec3 normal) {
mediump float lighting = max(0.0, dot(normal, u_viewDir)) * 0.5 + 0.5;
return vec4(color.rgb * lighting, color.a);
}
)GLSL";
const std::string TileRenderer::LIGHTING_SHADER_3D = R"GLSL(
uniform vec4 u_ambientColor;
uniform vec4 u_lightColor;
uniform vec3 u_lightDir;
uniform vec3 u_viewDir;
vec4 applyLighting(lowp vec4 color, mediump vec3 normal, highp_opt float height, bool sideVertex) {
if (sideVertex) {
lowp vec3 dimmedColor = color.rgb * (1.0 - 0.5 / (1.0 + height * height));
mediump vec3 lighting = max(0.0, dot(normal, u_lightDir)) * u_lightColor.rgb + u_ambientColor.rgb;
return vec4(dimmedColor.rgb * lighting, color.a);
} else {
mediump float lighting = max(0.0, dot(normal, u_viewDir)) * 0.5 + 0.5;
return vec4(color.rgb * lighting, color.a);
}
}
)GLSL";
const std::string TileRenderer::LIGHTING_SHADER_NORMALMAP = R"GLSL(
uniform vec4 u_shadowColor;
uniform vec4 u_highlightColor;
uniform vec3 u_lightDir;
vec4 applyLighting(lowp vec4 color, mediump vec3 normal, mediump float intensity) {
mediump float lighting = max(0.0, dot(normal, u_lightDir));
lowp vec4 shadeColor = mix(u_shadowColor, u_highlightColor, lighting);
return shadeColor * color * intensity;
}
)GLSL";
}
<|endoftext|> |
<commit_before>/*****************************************************************************
* Project: BaBar detector at the SLAC PEP-II B-factory
* Package: RooFitModels
* File:
* Authors:
* Jim Smith, jgsmith@pizero.colorado.edu
* History:
* 08-Jul-2002 JGS Created initial version
*
*****************************************************************************/
// -- CLASS DESCRIPTION [PDF] --
// Implement standard CP physics model with S and C (no mention of lambda)
// Suitably stolen and modified from RooBCPEffDecay
#include <iostream.h>
#include "RooFitCore/RooRealVar.hh"
#include "RooFitCore/RooRandom.hh"
#include "RooFitModels/RooBCPGenDecay.hh"
ClassImp(RooBCPGenDecay)
;
RooBCPGenDecay::RooBCPGenDecay(const char *name, const char *title,
RooRealVar& t, RooAbsCategory& tag,
RooAbsReal& tau, RooAbsReal& dm,
RooAbsReal& avgMistag,
RooAbsReal& a, RooAbsReal& b,
RooAbsReal& delMistag,
RooAbsReal& mu,
const RooResolutionModel& model, DecayType type) :
RooConvolutedPdf(name,title,model,t),
_avgC("C","Coefficient of cos term",this,a),
_avgS("S","Coefficient of cos term",this,b),
_avgMistag("avgMistag","Average mistag rate",this,avgMistag),
_delMistag("delMistag","Delta mistag rate",this,delMistag),
_mu("mu","Tagg efficiency difference",this,mu),
_tag("tag","CP state",this,tag),
_tau("tau","decay time",this,tau),
_dm("dm","mixing frequency",this,dm),
_t("t","time",this,t),
_type(type),
_genB0Frac(0)
{
// Constructor
switch(type) {
case SingleSided:
_basisExp = declareBasis("exp(-@0/@1)",RooArgList(tau,dm)) ;
_basisSin = declareBasis("exp(-@0/@1)*sin(@0*@2)",RooArgList(tau,dm)) ;
_basisCos = declareBasis("exp(-@0/@1)*cos(@0*@2)",RooArgList(tau,dm)) ;
break ;
case Flipped:
_basisExp = declareBasis("exp(@0)/@1)",RooArgList(tau,dm)) ;
_basisSin = declareBasis("exp(@0/@1)*sin(@0*@2)",RooArgList(tau,dm)) ;
_basisCos = declareBasis("exp(@0/@1)*cos(@0*@2)",RooArgList(tau,dm)) ;
break ;
case DoubleSided:
_basisExp = declareBasis("exp(-abs(@0)/@1)",RooArgList(tau,dm)) ;
_basisSin = declareBasis("exp(-abs(@0)/@1)*sin(@0*@2)",RooArgList(tau,dm)) ;
_basisCos = declareBasis("exp(-abs(@0)/@1)*cos(@0*@2)",RooArgList(tau,dm)) ;
break ;
}
}
RooBCPGenDecay::RooBCPGenDecay(const RooBCPGenDecay& other, const char* name) :
RooConvolutedPdf(other,name),
_avgC("C",this,other._avgC),
_avgS("S",this,other._avgS),
_avgMistag("avgMistag",this,other._avgMistag),
_delMistag("delMistag",this,other._delMistag),
_mu("mu",this,other._mu),
_tag("tag",this,other._tag),
_tau("tau",this,other._tau),
_dm("dm",this,other._dm),
_t("t",this,other._t),
_type(other._type),
_basisExp(other._basisExp),
_basisSin(other._basisSin),
_basisCos(other._basisCos),
_genB0Frac(other._genB0Frac)
{
// Copy constructor
}
RooBCPGenDecay::~RooBCPGenDecay()
{
// Destructor
}
Double_t RooBCPGenDecay::coefficient(Int_t basisIndex) const
{
// B0 : _tag = +1
// B0bar : _tag = -1
if (basisIndex==_basisExp) {
//exp term: (1 -/+ dw + mu*_tag*w)
return (1 - _tag*_delMistag + _mu*_tag*(1. - 2.*_avgMistag)) ;
// = 1 + _tag*deltaDil/2 + _mu*avgDil
}
if (basisIndex==_basisSin) {
//sin term: -(+/- (1-2w) + _mu*(1 +/- delw))*S
return (_tag*(1-2*_avgMistag) + _mu*(1. + _tag*_delMistag))*_avgS ;
// = (_tag*avgDil + _mu*(1 + tag*deltaDil/2)) * S
}
if (basisIndex==_basisCos) {
//cos term: (+/- (1-2w) + _mu*(1 +/- delw))*C
return 1.*(_tag*(1-2*_avgMistag) + _mu*(1. + _tag*_delMistag))*_avgC ;
// = -(_tag*avgDil + _mu*(1 + _tag*deltaDil/2) )* C
}
return 0 ;
}
Int_t RooBCPGenDecay::getCoefAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars) const
{
if (matchArgs(allVars,analVars,_tag)) return 1 ;
return 0 ;
}
Double_t RooBCPGenDecay::coefAnalyticalIntegral(Int_t basisIndex, Int_t code) const
{
switch(code) {
// No integration
case 0: return coefficient(basisIndex) ;
// Integration over 'tag'
case 1:
if (basisIndex==_basisExp) {
return 2 ;
}
if (basisIndex==_basisSin || basisIndex==_basisCos) {
return 0 ;
}
default:
assert(0) ;
}
return 0 ;
}
Int_t RooBCPGenDecay::getGenerator(const RooArgSet& directVars, RooArgSet &generateVars, Bool_t staticInitOK) const
{
if (staticInitOK) {
if (matchArgs(directVars,generateVars,_t,_tag)) return 2 ;
}
if (matchArgs(directVars,generateVars,_t)) return 1 ;
return 0 ;
}
void RooBCPGenDecay::initGenerator(Int_t code)
{
if (code==2) {
// Calculate the fraction of mixed events to generate
Double_t sumInt = RooRealIntegral("sumInt","sum integral",*this,RooArgSet(_t.arg(),_tag.arg())).getVal() ;
_tag = 1 ;
Double_t b0Int = RooRealIntegral("mixInt","mix integral",*this,RooArgSet(_t.arg())).getVal() ;
_genB0Frac = b0Int/sumInt ;
}
}
void RooBCPGenDecay::generateEvent(Int_t code)
{
// Generate mix-state dependent
if (code==2) {
Double_t rand = RooRandom::uniform() ;
_tag = (rand<=_genB0Frac) ? 1 : -1 ;
}
// Generate delta-t dependent
while(1) {
Double_t rand = RooRandom::uniform() ;
Double_t tval(0) ;
switch(_type) {
case SingleSided:
tval = -_tau*log(rand);
break ;
case Flipped:
tval= +_tau*log(rand);
break ;
case DoubleSided:
tval = (rand<=0.5) ? -_tau*log(2*rand) : +_tau*log(2*(rand-0.5)) ;
break ;
}
// Accept event if T is in generated range
Double_t maxDil = 1.0 ;
// 2 in next line is conservative and inefficient - allows for delMistag=1!
Double_t maxAcceptProb = 2 + fabs(maxDil*_avgS) + fabs(maxDil*_avgC);
Double_t acceptProb = (1-_tag*_delMistag + _mu*_tag*(1. - 2.*_avgMistag))
+ (_tag*(1-2*_avgMistag) + _mu*(1. + _tag*_delMistag))*_avgS*sin(_dm*tval)
- (_tag*(1-2*_avgMistag) + _mu*(1. + _tag*_delMistag))*_avgC*cos(_dm*tval);
Bool_t accept = maxAcceptProb*RooRandom::uniform() < acceptProb ? kTRUE : kFALSE ;
if (tval<_t.max() && tval>_t.min() && accept) {
_t = tval ;
break ;
}
}
}
<commit_msg>Fix some sign errors in implementation of mu<commit_after>/*****************************************************************************
* Project: BaBar detector at the SLAC PEP-II B-factory
* Package: RooFitModels
* File:
* Authors:
* Jim Smith, jgsmith@pizero.colorado.edu
* History:
* 08-Jul-2002 JGS Created initial version
*
*****************************************************************************/
// -- CLASS DESCRIPTION [PDF] --
// Implement standard CP physics model with S and C (no mention of lambda)
// Suitably stolen and modified from RooBCPEffDecay
#include <iostream.h>
#include "RooFitCore/RooRealVar.hh"
#include "RooFitCore/RooRandom.hh"
#include "RooFitModels/RooBCPGenDecay.hh"
ClassImp(RooBCPGenDecay)
;
RooBCPGenDecay::RooBCPGenDecay(const char *name, const char *title,
RooRealVar& t, RooAbsCategory& tag,
RooAbsReal& tau, RooAbsReal& dm,
RooAbsReal& avgMistag,
RooAbsReal& a, RooAbsReal& b,
RooAbsReal& delMistag,
RooAbsReal& mu,
const RooResolutionModel& model, DecayType type) :
RooConvolutedPdf(name,title,model,t),
_avgC("C","Coefficient of cos term",this,a),
_avgS("S","Coefficient of cos term",this,b),
_avgMistag("avgMistag","Average mistag rate",this,avgMistag),
_delMistag("delMistag","Delta mistag rate",this,delMistag),
_mu("mu","Tagg efficiency difference",this,mu),
_tag("tag","CP state",this,tag),
_tau("tau","decay time",this,tau),
_dm("dm","mixing frequency",this,dm),
_t("t","time",this,t),
_type(type),
_genB0Frac(0)
{
// Constructor
switch(type) {
case SingleSided:
_basisExp = declareBasis("exp(-@0/@1)",RooArgList(tau,dm)) ;
_basisSin = declareBasis("exp(-@0/@1)*sin(@0*@2)",RooArgList(tau,dm)) ;
_basisCos = declareBasis("exp(-@0/@1)*cos(@0*@2)",RooArgList(tau,dm)) ;
break ;
case Flipped:
_basisExp = declareBasis("exp(@0)/@1)",RooArgList(tau,dm)) ;
_basisSin = declareBasis("exp(@0/@1)*sin(@0*@2)",RooArgList(tau,dm)) ;
_basisCos = declareBasis("exp(@0/@1)*cos(@0*@2)",RooArgList(tau,dm)) ;
break ;
case DoubleSided:
_basisExp = declareBasis("exp(-abs(@0)/@1)",RooArgList(tau,dm)) ;
_basisSin = declareBasis("exp(-abs(@0)/@1)*sin(@0*@2)",RooArgList(tau,dm)) ;
_basisCos = declareBasis("exp(-abs(@0)/@1)*cos(@0*@2)",RooArgList(tau,dm)) ;
break ;
}
}
RooBCPGenDecay::RooBCPGenDecay(const RooBCPGenDecay& other, const char* name) :
RooConvolutedPdf(other,name),
_avgC("C",this,other._avgC),
_avgS("S",this,other._avgS),
_avgMistag("avgMistag",this,other._avgMistag),
_delMistag("delMistag",this,other._delMistag),
_mu("mu",this,other._mu),
_tag("tag",this,other._tag),
_tau("tau",this,other._tau),
_dm("dm",this,other._dm),
_t("t",this,other._t),
_type(other._type),
_basisExp(other._basisExp),
_basisSin(other._basisSin),
_basisCos(other._basisCos),
_genB0Frac(other._genB0Frac)
{
// Copy constructor
}
RooBCPGenDecay::~RooBCPGenDecay()
{
// Destructor
}
Double_t RooBCPGenDecay::coefficient(Int_t basisIndex) const
{
// B0 : _tag = +1
// B0bar : _tag = -1
if (basisIndex==_basisExp) {
//exp term: (1 -/+ dw + mu*_tag*w)
return (1 - _tag*_delMistag + _mu*_tag*(1. - 2.*_avgMistag)) ;
// = 1 + _tag*deltaDil/2 + _mu*avgDil
}
if (basisIndex==_basisSin) {
//sin term: (+/- (1-2w) + _mu*(1 -/+ delw))*S
return (_tag*(1-2*_avgMistag) + _mu*(1. - _tag*_delMistag))*_avgS ;
// = (_tag*avgDil + _mu*(1 + tag*deltaDil/2)) * S
}
if (basisIndex==_basisCos) {
//cos term: -(+/- (1-2w) + _mu*(1 -/+ delw))*C
return -1.*(_tag*(1-2*_avgMistag) + _mu*(1. - _tag*_delMistag))*_avgC ;
// = -(_tag*avgDil + _mu*(1 + _tag*deltaDil/2) )* C
}
return 0 ;
}
Int_t RooBCPGenDecay::getCoefAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars) const
{
if (matchArgs(allVars,analVars,_tag)) return 1 ;
return 0 ;
}
Double_t RooBCPGenDecay::coefAnalyticalIntegral(Int_t basisIndex, Int_t code) const
{
switch(code) {
// No integration
case 0: return coefficient(basisIndex) ;
// Integration over 'tag'
case 1:
if (basisIndex==_basisExp) {
return 2 ;
}
if (basisIndex==_basisSin || basisIndex==_basisCos) {
return 0 ;
}
default:
assert(0) ;
}
return 0 ;
}
Int_t RooBCPGenDecay::getGenerator(const RooArgSet& directVars, RooArgSet &generateVars, Bool_t staticInitOK) const
{
if (staticInitOK) {
if (matchArgs(directVars,generateVars,_t,_tag)) return 2 ;
}
if (matchArgs(directVars,generateVars,_t)) return 1 ;
return 0 ;
}
void RooBCPGenDecay::initGenerator(Int_t code)
{
if (code==2) {
// Calculate the fraction of mixed events to generate
Double_t sumInt = RooRealIntegral("sumInt","sum integral",*this,RooArgSet(_t.arg(),_tag.arg())).getVal() ;
_tag = 1 ;
Double_t b0Int = RooRealIntegral("mixInt","mix integral",*this,RooArgSet(_t.arg())).getVal() ;
_genB0Frac = b0Int/sumInt ;
}
}
void RooBCPGenDecay::generateEvent(Int_t code)
{
// Generate mix-state dependent
if (code==2) {
Double_t rand = RooRandom::uniform() ;
_tag = (rand<=_genB0Frac) ? 1 : -1 ;
}
// Generate delta-t dependent
while(1) {
Double_t rand = RooRandom::uniform() ;
Double_t tval(0) ;
switch(_type) {
case SingleSided:
tval = -_tau*log(rand);
break ;
case Flipped:
tval= +_tau*log(rand);
break ;
case DoubleSided:
tval = (rand<=0.5) ? -_tau*log(2*rand) : +_tau*log(2*(rand-0.5)) ;
break ;
}
// Accept event if T is in generated range
Double_t maxDil = 1.0 ;
// 2 in next line is conservative and inefficient - allows for delMistag=1!
Double_t maxAcceptProb = 2 + fabs(maxDil*_avgS) + fabs(maxDil*_avgC);
Double_t acceptProb = (1-_tag*_delMistag + _mu*_tag*(1. - 2.*_avgMistag))
+ (_tag*(1-2*_avgMistag) + _mu*(1. - _tag*_delMistag))*_avgS*sin(_dm*tval)
- (_tag*(1-2*_avgMistag) + _mu*(1. - _tag*_delMistag))*_avgC*cos(_dm*tval);
Bool_t accept = maxAcceptProb*RooRandom::uniform() < acceptProb ? kTRUE : kFALSE ;
if (tval<_t.max() && tval>_t.min() && accept) {
_t = tval ;
break ;
}
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2020 by Robert Bosch GmbH, Apex.AI Inc. 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 "iceoryx_posh/roudi/roudi_cmd_line_parser.hpp"
#include "iceoryx_posh/internal/log/posh_logging.hpp"
#include "iceoryx_utils/cxx/convert.hpp"
#include "iceoryx_versions.hpp"
#include "iceoryx_utils/platform/getopt.hpp"
#include <iostream>
namespace iox
{
namespace config
{
cxx::expected<CmdLineArgs_t, CmdLineParserResult>
CmdLineParser::parse(int argc, char* argv[], const CmdLineArgumentParsingMode cmdLineParsingMode) noexcept
{
constexpr option longOptions[] = {{"help", no_argument, nullptr, 'h'},
{"version", no_argument, nullptr, 'v'},
{"monitoring-mode", required_argument, nullptr, 'm'},
{"log-level", required_argument, nullptr, 'l'},
{"unique-roudi-id", required_argument, nullptr, 'u'},
{"compatibility", required_argument, nullptr, 'x'},
{"kill-delay", required_argument, nullptr, 'k'},
{nullptr, 0, nullptr, 0}};
// colon after shortOption means it requires an argument, two colons mean optional argument
constexpr const char* shortOptions = "hvm:l:u:x:k:";
int32_t index;
int32_t opt{-1};
while ((opt = getopt_long(argc, argv, shortOptions, longOptions, &index), opt != -1))
{
switch (opt)
{
case 'h':
std::cout << "Usage: " << argv[0] << " [options]" << std::endl;
std::cout << "Options:" << std::endl;
std::cout << "-h, --help Display help." << std::endl;
std::cout << "-v, --version Display version." << std::endl;
std::cout << "-u, --unique-roudi-id <INT> Set the unique RouDi id." << std::endl;
std::cout << "-m, --monitoring-mode <MODE> Set process alive monitoring mode." << std::endl;
std::cout << " <MODE> {on, off}" << std::endl;
std::cout << " default = 'on'" << std::endl;
std::cout << " on: enables monitoring for all processes" << std::endl;
std::cout << " off: disables monitoring for all processes" << std::endl;
std::cout << "-l, --log-level <LEVEL> Set log level." << std::endl;
std::cout << " <LEVEL> {off, fatal, error, warning, info, debug, verbose}"
<< std::endl;
std::cout << "-x, --compatibility Set compatibility check level between runtime and RouDi."
<< std::endl;
std::cout << " off: no check" << std::endl;
std::cout << " major: same major version " << std::endl;
std::cout << " minor: same minor version + major check" << std::endl;
std::cout << " patch: same patch version + minor check" << std::endl;
std::cout << " commitId: same commit ID + patch check" << std::endl;
std::cout << " buildDate: same build date + commId check" << std::endl;
std::cout << "-k, --kill-delay <UINT> Sets the delay when RouDi sends SIG_KILL, if apps"
<< std::endl;
std::cout << " have't responded after trying SIG_TERM first, in seconds."
<< std::endl;
m_run = false;
break;
case 'v':
std::cout << "RouDi version: " << ICEORYX_LATEST_RELEASE_VERSION << std::endl;
std::cout << "Build date: " << ICEORYX_BUILDDATE << std::endl;
std::cout << "Commit ID: " << ICEORYX_SHA1 << std::endl;
m_run = false;
break;
case 'u':
{
uint16_t roudiId{0u};
constexpr uint64_t MAX_ROUDI_ID = ((1 << 16) - 1);
if (!cxx::convert::fromString(optarg, roudiId))
{
LogError() << "The RouDi id must be in the range of [0, " << MAX_ROUDI_ID << "]";
m_run = false;
}
m_uniqueRouDiId.emplace(roudiId);
break;
}
case 'm':
{
if (strcmp(optarg, "on") == 0)
{
m_monitoringMode = roudi::MonitoringMode::ON;
}
else if (strcmp(optarg, "off") == 0)
{
m_monitoringMode = roudi::MonitoringMode::OFF;
}
else
{
m_run = false;
LogError() << "Options for monitoring-mode are 'on' and 'off'!";
}
break;
}
case 'l':
{
if (strcmp(optarg, "off") == 0)
{
m_logLevel = iox::log::LogLevel::kOff;
}
else if (strcmp(optarg, "fatal") == 0)
{
m_logLevel = iox::log::LogLevel::kFatal;
}
else if (strcmp(optarg, "error") == 0)
{
m_logLevel = iox::log::LogLevel::kError;
}
else if (strcmp(optarg, "warning") == 0)
{
m_logLevel = iox::log::LogLevel::kWarn;
}
else if (strcmp(optarg, "info") == 0)
{
m_logLevel = iox::log::LogLevel::kInfo;
}
else if (strcmp(optarg, "debug") == 0)
{
m_logLevel = iox::log::LogLevel::kDebug;
}
else if (strcmp(optarg, "verbose") == 0)
{
m_logLevel = iox::log::LogLevel::kVerbose;
}
else
{
m_run = false;
LogError() << "Options for log-level are 'off', 'fatal', 'error', 'warning', 'info', 'debug' and "
"'verbose'!";
}
break;
}
case 'k':
{
uint32_t processKillDelayInSeconds{0u};
constexpr uint64_t MAX_PROCESS_KILL_DELAY = std::numeric_limits<uint32_t>::max();
if (!cxx::convert::fromString(optarg, processKillDelayInSeconds))
{
LogError() << "The process kill delay must be in the range of [0, " << MAX_PROCESS_KILL_DELAY << "]";
m_run = false;
}
else
{
m_processKillDelay =
units::Duration::fromSeconds(static_cast<unsigned long long int>(processKillDelayInSeconds));
}
break;
}
case 'x':
{
if (strcmp(optarg, "off") == 0)
{
m_compatibilityCheckLevel = iox::version::CompatibilityCheckLevel::OFF;
}
else if (strcmp(optarg, "major") == 0)
{
m_compatibilityCheckLevel = iox::version::CompatibilityCheckLevel::MAJOR;
}
else if (strcmp(optarg, "minor") == 0)
{
m_compatibilityCheckLevel = iox::version::CompatibilityCheckLevel::MINOR;
}
else if (strcmp(optarg, "patch") == 0)
{
m_compatibilityCheckLevel = iox::version::CompatibilityCheckLevel::PATCH;
}
else if (strcmp(optarg, "commitId") == 0)
{
m_compatibilityCheckLevel = iox::version::CompatibilityCheckLevel::COMMIT_ID;
}
else if (strcmp(optarg, "buildDate") == 0)
{
m_compatibilityCheckLevel = iox::version::CompatibilityCheckLevel::BUILD_DATE;
}
else
{
m_run = false;
LogError()
<< "Options for compatibility are 'off', 'major', 'minor', 'patch', 'commitId' and 'buildDate'!";
}
break;
}
default:
{
// CmdLineParser did not understand the parameters, don't run
m_run = false;
return cxx::error<CmdLineParserResult>(CmdLineParserResult::UNKNOWN_OPTION_USED);
}
};
if (cmdLineParsingMode == CmdLineArgumentParsingMode::ONE)
{
break;
}
}
return cxx::success<CmdLineArgs_t>(CmdLineArgs_t{
m_monitoringMode, m_logLevel, m_compatibilityCheckLevel, m_processKillDelay, m_uniqueRouDiId, m_run, ""});
} // namespace roudi
} // namespace config
} // namespace iox
<commit_msg>iox-#536 removed another unnecessary static_cast<commit_after>// Copyright (c) 2020 by Robert Bosch GmbH, Apex.AI Inc. 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 "iceoryx_posh/roudi/roudi_cmd_line_parser.hpp"
#include "iceoryx_posh/internal/log/posh_logging.hpp"
#include "iceoryx_utils/cxx/convert.hpp"
#include "iceoryx_versions.hpp"
#include "iceoryx_utils/platform/getopt.hpp"
#include <iostream>
namespace iox
{
namespace config
{
cxx::expected<CmdLineArgs_t, CmdLineParserResult>
CmdLineParser::parse(int argc, char* argv[], const CmdLineArgumentParsingMode cmdLineParsingMode) noexcept
{
constexpr option longOptions[] = {{"help", no_argument, nullptr, 'h'},
{"version", no_argument, nullptr, 'v'},
{"monitoring-mode", required_argument, nullptr, 'm'},
{"log-level", required_argument, nullptr, 'l'},
{"unique-roudi-id", required_argument, nullptr, 'u'},
{"compatibility", required_argument, nullptr, 'x'},
{"kill-delay", required_argument, nullptr, 'k'},
{nullptr, 0, nullptr, 0}};
// colon after shortOption means it requires an argument, two colons mean optional argument
constexpr const char* shortOptions = "hvm:l:u:x:k:";
int32_t index;
int32_t opt{-1};
while ((opt = getopt_long(argc, argv, shortOptions, longOptions, &index), opt != -1))
{
switch (opt)
{
case 'h':
std::cout << "Usage: " << argv[0] << " [options]" << std::endl;
std::cout << "Options:" << std::endl;
std::cout << "-h, --help Display help." << std::endl;
std::cout << "-v, --version Display version." << std::endl;
std::cout << "-u, --unique-roudi-id <INT> Set the unique RouDi id." << std::endl;
std::cout << "-m, --monitoring-mode <MODE> Set process alive monitoring mode." << std::endl;
std::cout << " <MODE> {on, off}" << std::endl;
std::cout << " default = 'on'" << std::endl;
std::cout << " on: enables monitoring for all processes" << std::endl;
std::cout << " off: disables monitoring for all processes" << std::endl;
std::cout << "-l, --log-level <LEVEL> Set log level." << std::endl;
std::cout << " <LEVEL> {off, fatal, error, warning, info, debug, verbose}"
<< std::endl;
std::cout << "-x, --compatibility Set compatibility check level between runtime and RouDi."
<< std::endl;
std::cout << " off: no check" << std::endl;
std::cout << " major: same major version " << std::endl;
std::cout << " minor: same minor version + major check" << std::endl;
std::cout << " patch: same patch version + minor check" << std::endl;
std::cout << " commitId: same commit ID + patch check" << std::endl;
std::cout << " buildDate: same build date + commId check" << std::endl;
std::cout << "-k, --kill-delay <UINT> Sets the delay when RouDi sends SIG_KILL, if apps"
<< std::endl;
std::cout << " have't responded after trying SIG_TERM first, in seconds."
<< std::endl;
m_run = false;
break;
case 'v':
std::cout << "RouDi version: " << ICEORYX_LATEST_RELEASE_VERSION << std::endl;
std::cout << "Build date: " << ICEORYX_BUILDDATE << std::endl;
std::cout << "Commit ID: " << ICEORYX_SHA1 << std::endl;
m_run = false;
break;
case 'u':
{
uint16_t roudiId{0u};
constexpr uint64_t MAX_ROUDI_ID = ((1 << 16) - 1);
if (!cxx::convert::fromString(optarg, roudiId))
{
LogError() << "The RouDi id must be in the range of [0, " << MAX_ROUDI_ID << "]";
m_run = false;
}
m_uniqueRouDiId.emplace(roudiId);
break;
}
case 'm':
{
if (strcmp(optarg, "on") == 0)
{
m_monitoringMode = roudi::MonitoringMode::ON;
}
else if (strcmp(optarg, "off") == 0)
{
m_monitoringMode = roudi::MonitoringMode::OFF;
}
else
{
m_run = false;
LogError() << "Options for monitoring-mode are 'on' and 'off'!";
}
break;
}
case 'l':
{
if (strcmp(optarg, "off") == 0)
{
m_logLevel = iox::log::LogLevel::kOff;
}
else if (strcmp(optarg, "fatal") == 0)
{
m_logLevel = iox::log::LogLevel::kFatal;
}
else if (strcmp(optarg, "error") == 0)
{
m_logLevel = iox::log::LogLevel::kError;
}
else if (strcmp(optarg, "warning") == 0)
{
m_logLevel = iox::log::LogLevel::kWarn;
}
else if (strcmp(optarg, "info") == 0)
{
m_logLevel = iox::log::LogLevel::kInfo;
}
else if (strcmp(optarg, "debug") == 0)
{
m_logLevel = iox::log::LogLevel::kDebug;
}
else if (strcmp(optarg, "verbose") == 0)
{
m_logLevel = iox::log::LogLevel::kVerbose;
}
else
{
m_run = false;
LogError() << "Options for log-level are 'off', 'fatal', 'error', 'warning', 'info', 'debug' and "
"'verbose'!";
}
break;
}
case 'k':
{
uint32_t processKillDelayInSeconds{0u};
constexpr uint64_t MAX_PROCESS_KILL_DELAY = std::numeric_limits<uint32_t>::max();
if (!cxx::convert::fromString(optarg, processKillDelayInSeconds))
{
LogError() << "The process kill delay must be in the range of [0, " << MAX_PROCESS_KILL_DELAY << "]";
m_run = false;
}
else
{
m_processKillDelay =
units::Duration::fromSeconds(processKillDelayInSeconds);
}
break;
}
case 'x':
{
if (strcmp(optarg, "off") == 0)
{
m_compatibilityCheckLevel = iox::version::CompatibilityCheckLevel::OFF;
}
else if (strcmp(optarg, "major") == 0)
{
m_compatibilityCheckLevel = iox::version::CompatibilityCheckLevel::MAJOR;
}
else if (strcmp(optarg, "minor") == 0)
{
m_compatibilityCheckLevel = iox::version::CompatibilityCheckLevel::MINOR;
}
else if (strcmp(optarg, "patch") == 0)
{
m_compatibilityCheckLevel = iox::version::CompatibilityCheckLevel::PATCH;
}
else if (strcmp(optarg, "commitId") == 0)
{
m_compatibilityCheckLevel = iox::version::CompatibilityCheckLevel::COMMIT_ID;
}
else if (strcmp(optarg, "buildDate") == 0)
{
m_compatibilityCheckLevel = iox::version::CompatibilityCheckLevel::BUILD_DATE;
}
else
{
m_run = false;
LogError()
<< "Options for compatibility are 'off', 'major', 'minor', 'patch', 'commitId' and 'buildDate'!";
}
break;
}
default:
{
// CmdLineParser did not understand the parameters, don't run
m_run = false;
return cxx::error<CmdLineParserResult>(CmdLineParserResult::UNKNOWN_OPTION_USED);
}
};
if (cmdLineParsingMode == CmdLineArgumentParsingMode::ONE)
{
break;
}
}
return cxx::success<CmdLineArgs_t>(CmdLineArgs_t{
m_monitoringMode, m_logLevel, m_compatibilityCheckLevel, m_processKillDelay, m_uniqueRouDiId, m_run, ""});
} // namespace roudi
} // namespace config
} // namespace iox
<|endoftext|> |
<commit_before>// Copyright (c) 2014-2018 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/
#ifndef TAO_PEGTL_INPUT_ERROR_HPP
#define TAO_PEGTL_INPUT_ERROR_HPP
#include <cerrno>
#include <sstream>
#include <stdexcept>
#include "config.hpp"
// In PEGTL 3 input_error was changed to std::system_error and
// std::filesystem::filesystem_error (the latter is derived from the former).
// Here we half-backported it - input_error is replaced with system_error.
#if 0
namespace tao
{
namespace TAO_PEGTL_NAMESPACE
{
struct input_error
: std::runtime_error
{
input_error( const std::string& message, const int in_errorno )
: std::runtime_error( message ),
errorno( in_errorno )
{
}
int errorno;
};
} // namespace TAO_PEGTL_NAMESPACE
} // namespace tao
#endif
#define TAO_PEGTL_INTERNAL_UNWRAP( ... ) __VA_ARGS__
#define TAO_PEGTL_THROW_INPUT_ERROR( MESSAGE ) \
do { \
const int errorno = errno; \
std::ostringstream oss; \
oss << TAO_PEGTL_INTERNAL_UNWRAP( MESSAGE ) << " errno " << errorno; \
throw std::system_error( errorno, std::system_category(), oss.str() ); \
} while( false )
#endif
<commit_msg>missing header in a previous commit<commit_after>// Copyright (c) 2014-2018 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/
#ifndef TAO_PEGTL_INPUT_ERROR_HPP
#define TAO_PEGTL_INPUT_ERROR_HPP
#include <cerrno>
#include <sstream>
#include <stdexcept>
#include <system_error>
#include "config.hpp"
// In PEGTL 3 input_error was changed to std::system_error and
// std::filesystem::filesystem_error (the latter is derived from the former).
// Here we half-backported it - input_error is replaced with system_error.
#if 0
namespace tao
{
namespace TAO_PEGTL_NAMESPACE
{
struct input_error
: std::runtime_error
{
input_error( const std::string& message, const int in_errorno )
: std::runtime_error( message ),
errorno( in_errorno )
{
}
int errorno;
};
} // namespace TAO_PEGTL_NAMESPACE
} // namespace tao
#endif
#define TAO_PEGTL_INTERNAL_UNWRAP( ... ) __VA_ARGS__
#define TAO_PEGTL_THROW_INPUT_ERROR( MESSAGE ) \
do { \
const int errorno = errno; \
std::ostringstream oss; \
oss << TAO_PEGTL_INTERNAL_UNWRAP( MESSAGE ) << " errno " << errorno; \
throw std::system_error( errorno, std::system_category(), oss.str() ); \
} while( false )
#endif
<|endoftext|> |
<commit_before>#include "ModI2CHost.h"
CModI2CHost::CModI2CHost(void)
{
// nothing
}
void CModI2CHost::Begin(void)
{
CModTemplate::Begin();
ModGUID = 8; // GUID of this sspecific mod
if (Global.HasUSB) // i2c host only activates if this device is plugged into the PC
{
Wire.begin();
}
}
void CModI2CHost::LoadData(void)
{
CModTemplate::LoadData();
if (Global.HasUSB)
{
}
}
void CModI2CHost::Loop(void)
{
CModTemplate::Loop();
if (Global.HasUSB)
{
// syncs templayer value with guest
if (Global.TempLayer != I2CTempLayer)
{
SetTempLayer();
I2CTempLayer = Global.TempLayer;
}
if (Global.LEDBrightness != I2CLEDBrightness)
{
SetSubLEDBrightness();
I2CLEDBrightness = Global.LEDBrightness;
}
if (Global.RefreshDelay != I2CRefresh)
{
SetSubRefreshRate();
I2CRefresh = Global.RefreshDelay;
}
// gets keystrokes from guest
Wire.requestFrom(8, 32);
bool hasInput = true;
byte keyData[8];
byte keyType[8];
byte keyMode[8];
byte keyX[8];
byte keyY[8];
byte keyIndex = 0;
while (hasInput)
{
if (Wire.available()) // need to put ifs in here so trailing bytes are left out
{
byte tempByte = Wire.read();
keyX[keyIndex] = tempByte & 0x0f; // bitwise structure is YYYYXXXX
keyY[keyIndex] = tempByte >> 4;
}
else
{
hasInput = false;
}
if (Wire.available()) // need to put ifs in here so trailing bytes are left out
{
keyData[keyIndex] = Wire.read();
}
else
{
hasInput = false;
}
if (Wire.available()) // need to put ifs in here so trailing bytes are left out
{
keyType[keyIndex] = Wire.read();
}
else
{
hasInput = false;
}
if (Wire.available()) // need to put ifs in here so trailing bytes are left out
{
keyMode[keyIndex] = Wire.read();
keyIndex++;
}
else
{
hasInput = false;
}
}
for (byte i = 0; i < keyIndex; i++)
{
if (keyMode[i] == 1) // release key
{
Animus.ReleaseKey(keyData[i], keyType[i]);
}
else if (keyMode[i] == 5) // press key
{
Animus.PrePress(keyData[i], keyType[i]);
if (Global.TempLayer != I2CTempLayer)
{
SetTempLayer();
I2CTempLayer = Global.TempLayer;
Wire.beginTransmission(8);
Wire.write(6);
Wire.write(keyX[i]);
Wire.write(keyY[i]);
Wire.endTransmission();
Wire.requestFrom(8, 2);
if (Wire.available()) // need to put ifs in here so trailing bytes are left out
{
keyData[i] = Wire.read();
}
if (Wire.available()) // need to put ifs in here so trailing bytes are left out
{
keyType[i] = Wire.read();
}
}
Animus.PressKey(keyData[i], keyType[i]);
}
}
}
if (Animus.Async1MSDelay())
{
if (Global.HasUSB)
{
}
}
}
void CModI2CHost::PressCoords(byte x, byte y)
{
CModTemplate::PressCoords(x, y);
if (Global.HasUSB)
{
}
}
void CModI2CHost::PrePress(byte val, byte type)
{
CModTemplate::PrePress(val, type);
if (Global.HasUSB)
{
}
}
void CModI2CHost::PressKey(byte val, byte type)
{
CModTemplate::PressKey(val, type);
if (Global.HasUSB)
{
}
}
void CModI2CHost::ReleaseKey(byte val, byte type)
{
CModTemplate::ReleaseKey(val, type);
if (Global.HasUSB)
{
}
}
void CModI2CHost::SerialComms(byte mode) // holy shit this is complicated
{
CModTemplate::SerialComms(mode);
// serial communication
if (Global.HasUSB)
{
if (Comms.mode == 6) // write to guest eeprom starting at addr = 0 or 900, ending at first short read from serial
{
EEPROM.update(0, 5);
if (Serial.available()) //TODO I might want to work in a timeout or fail check for this
{
if (SerialLoaderByteStatus == 0) // if this is the first time mode 6 has made contact
{
EEPROMPacket[0] = (byte)Serial.read();
SerialLoaderByteStatus = 1;
EEPROM.update(0, 6);
}
else if (SerialLoaderByteStatus == 1) // if this is the second time mode 6 has made contact
{
EEPROMPacket[1] = (byte)Serial.read();
SerialLoaderByteStatus = 2;
EEPROM.update(2, 5);
}
else if (SerialLoaderByteStatus == 2) // if status is 2, get packet size
{
EEPROMPacketSize = (byte)Serial.read();
SerialLoaderByteStatus = 3;
EEPROM.update(4, 5);
}
else if (SerialLoaderByteStatus == 3) // if mode 6 has obtained the start address and package length
{
if (EEPROMPacketSize > 0)
{
EEPROMPacket[EEPROMPacketIndex] = (byte)Serial.read();
EEPROMPacketIndex++;
EEPROMPacketSize--;
EEPROM.update(6, 5);
}
if (EEPROMPacketSize <= 0)
{
EEPROM.update(8, 5);
SetSubEEPROM();
EEPROM.update(10, 5);
EEPROMPacketIndex = 2;
SerialLoaderByteStatus = 0;
Comms.mode = 0;
}
}
}
}
}
}
// first byte is the type of the packet
// second byte always sends the templayer
// third byte forward is the data of the packet
/*
type 0 does nothing
type 1 sends templayer (templayer)
type 2 is a full reflash type that writes sub eeprom from 0 to 1024 (byte0, byte1, byte2, ...)
type 3 writes sub eeprom starting from 900 (byte0, byte1, byte2, ...)
type 4 changes the LED setting (brightness)
type 5 changes the refresh rate (refresh)
*/
void CModI2CHost::SetTempLayer()
{
Wire.beginTransmission(8);
Wire.write(1);
Wire.write(Global.TempLayer);
Wire.endTransmission();
}
void CModI2CHost::SetSubEEPROM(void)
{
Wire.beginTransmission(8);
Wire.write(2);
Wire.write(EEPROMPacket, EEPROMPacketIndex);
Wire.endTransmission();
}
void CModI2CHost::SetSubLEDBrightness(void)
{
Wire.beginTransmission(8);
Wire.write(4);
Wire.write(Global.LEDBrightness);
Wire.endTransmission();
}
void CModI2CHost::SetSubRefreshRate(void)
{
Wire.beginTransmission(8);
Wire.write(5);
Wire.write(Global.RefreshDelay);
Wire.endTransmission();
}
CModI2CHost ModI2CHost;
<commit_msg>remove: cleanup debug messages<commit_after>#include "ModI2CHost.h"
CModI2CHost::CModI2CHost(void)
{
// nothing
}
void CModI2CHost::Begin(void)
{
CModTemplate::Begin();
ModGUID = 8; // GUID of this sspecific mod
if (Global.HasUSB) // i2c host only activates if this device is plugged into the PC
{
Wire.begin();
}
}
void CModI2CHost::LoadData(void)
{
CModTemplate::LoadData();
if (Global.HasUSB)
{
}
}
void CModI2CHost::Loop(void)
{
CModTemplate::Loop();
if (Global.HasUSB)
{
// syncs templayer value with guest
if (Global.TempLayer != I2CTempLayer)
{
SetTempLayer();
I2CTempLayer = Global.TempLayer;
}
if (Global.LEDBrightness != I2CLEDBrightness)
{
SetSubLEDBrightness();
I2CLEDBrightness = Global.LEDBrightness;
}
if (Global.RefreshDelay != I2CRefresh)
{
SetSubRefreshRate();
I2CRefresh = Global.RefreshDelay;
}
// gets keystrokes from guest
Wire.requestFrom(8, 32);
bool hasInput = true;
byte keyData[8];
byte keyType[8];
byte keyMode[8];
byte keyX[8];
byte keyY[8];
byte keyIndex = 0;
while (hasInput)
{
if (Wire.available()) // need to put ifs in here so trailing bytes are left out
{
byte tempByte = Wire.read();
keyX[keyIndex] = tempByte & 0x0f; // bitwise structure is YYYYXXXX
keyY[keyIndex] = tempByte >> 4;
}
else
{
hasInput = false;
}
if (Wire.available()) // need to put ifs in here so trailing bytes are left out
{
keyData[keyIndex] = Wire.read();
}
else
{
hasInput = false;
}
if (Wire.available()) // need to put ifs in here so trailing bytes are left out
{
keyType[keyIndex] = Wire.read();
}
else
{
hasInput = false;
}
if (Wire.available()) // need to put ifs in here so trailing bytes are left out
{
keyMode[keyIndex] = Wire.read();
keyIndex++;
}
else
{
hasInput = false;
}
}
for (byte i = 0; i < keyIndex; i++)
{
if (keyMode[i] == 1) // release key
{
Animus.ReleaseKey(keyData[i], keyType[i]);
}
else if (keyMode[i] == 5) // press key
{
Animus.PrePress(keyData[i], keyType[i]);
if (Global.TempLayer != I2CTempLayer)
{
SetTempLayer();
I2CTempLayer = Global.TempLayer;
Wire.beginTransmission(8);
Wire.write(6);
Wire.write(keyX[i]);
Wire.write(keyY[i]);
Wire.endTransmission();
Wire.requestFrom(8, 2);
if (Wire.available()) // need to put ifs in here so trailing bytes are left out
{
keyData[i] = Wire.read();
}
if (Wire.available()) // need to put ifs in here so trailing bytes are left out
{
keyType[i] = Wire.read();
}
}
Animus.PressKey(keyData[i], keyType[i]);
}
}
}
if (Animus.Async1MSDelay())
{
if (Global.HasUSB)
{
}
}
}
void CModI2CHost::PressCoords(byte x, byte y)
{
CModTemplate::PressCoords(x, y);
if (Global.HasUSB)
{
}
}
void CModI2CHost::PrePress(byte val, byte type)
{
CModTemplate::PrePress(val, type);
if (Global.HasUSB)
{
}
}
void CModI2CHost::PressKey(byte val, byte type)
{
CModTemplate::PressKey(val, type);
if (Global.HasUSB)
{
}
}
void CModI2CHost::ReleaseKey(byte val, byte type)
{
CModTemplate::ReleaseKey(val, type);
if (Global.HasUSB)
{
}
}
void CModI2CHost::SerialComms(byte mode) // holy shit this is complicated
{
CModTemplate::SerialComms(mode);
// serial communication
if (Global.HasUSB)
{
if (Comms.mode == 6) // write to guest eeprom starting at addr = 0 or 900, ending at first short read from serial
{
EEPROM.update(0, 5);
if (Serial.available()) //TODO I might want to work in a timeout or fail check for this
{
if (SerialLoaderByteStatus == 0) // if this is the first time mode 6 has made contact
{
EEPROMPacket[0] = (byte)Serial.read();
SerialLoaderByteStatus = 1;
}
else if (SerialLoaderByteStatus == 1) // if this is the second time mode 6 has made contact
{
EEPROMPacket[1] = (byte)Serial.read();
SerialLoaderByteStatus = 2;
}
else if (SerialLoaderByteStatus == 2) // if status is 2, get packet size
{
EEPROMPacketSize = (byte)Serial.read();
SerialLoaderByteStatus = 3;
}
else if (SerialLoaderByteStatus == 3) // if mode 6 has obtained the start address and package length
{
if (EEPROMPacketSize > 0)
{
EEPROMPacket[EEPROMPacketIndex] = (byte)Serial.read();
EEPROMPacketIndex++;
EEPROMPacketSize--;
}
if (EEPROMPacketSize <= 0)
{
SetSubEEPROM();
EEPROMPacketIndex = 2;
SerialLoaderByteStatus = 0;
Comms.mode = 0;
}
}
}
}
}
}
void CModI2CHost::SetTempLayer()
{
Wire.beginTransmission(8);
Wire.write(1);
Wire.write(Global.TempLayer);
Wire.endTransmission();
}
void CModI2CHost::SetSubEEPROM(void)
{
Wire.beginTransmission(8);
Wire.write(2);
Wire.write(EEPROMPacket, EEPROMPacketIndex);
Wire.endTransmission();
}
void CModI2CHost::SetSubLEDBrightness(void)
{
Wire.beginTransmission(8);
Wire.write(4);
Wire.write(Global.LEDBrightness);
Wire.endTransmission();
}
void CModI2CHost::SetSubRefreshRate(void)
{
Wire.beginTransmission(8);
Wire.write(5);
Wire.write(Global.RefreshDelay);
Wire.endTransmission();
}
CModI2CHost ModI2CHost;
<|endoftext|> |
<commit_before>/* This file is part of Mapnik (c++ mapping toolkit)
* Copyright (C) 2005 Artem Pavlenko
*
* Mapnik 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 any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "dbffile.hpp"
#include "utils.hpp"
#include <string>
dbf_file::dbf_file()
: num_records_(0),
num_fields_(0),
record_length_(0),
record_(0) {}
dbf_file::dbf_file(const char* file_name)
:num_records_(0),
num_fields_(0),
record_length_(0),
record_(0)
{
file_.open(file_name);
if (file_.is_open())
{
read_header();
}
}
dbf_file::~dbf_file()
{
::operator delete(record_);
file_.close();
}
bool dbf_file::open(const std::string& file_name)
{
file_.open(file_name.c_str());
if (file_.is_open())
read_header();
return file_?true:false;
}
bool dbf_file::is_open()
{
return file_.is_open();
}
void dbf_file::close()
{
if (file_ && file_.is_open())
file_.close();
}
int dbf_file::num_records() const
{
return num_records_;
}
int dbf_file::num_fields() const
{
return num_fields_;
}
void dbf_file::move_to(int index)
{
if (index>0 && index<=num_records_)
{
long pos=(num_fields_<<5)+34+(index-1)*(record_length_+1);
file_.seekg(pos,std::ios::beg);
file_.read(record_,record_length_);
}
}
std::string dbf_file::string_value(int col) const
{
if (col>=0 && col<num_fields_)
{
return std::string(record_+fields_[col].offset_,fields_[col].length_);
}
return "";
}
const field_descriptor& dbf_file::descriptor(int col) const
{
assert(col>=0 && col<num_fields_);
return fields_[col];
}
void dbf_file::add_attribute(int col,Feature const& f) const throw()
{
if (col>=0 && col<num_fields_)
{
std::string name=fields_[col].name_;
std::string str=trim(std::string(record_+fields_[col].offset_,fields_[col].length_));
switch (fields_[col].type_)
{
case 'C':
case 'D'://todo handle date?
case 'M':
case 'L':
f[name] = str;
break;
case 'N':
case 'F':
{
if (str[0]=='*')
{
boost::put(f,name,0);
break;
}
if (fields_[col].dec_>0)
{
double d;
fromString(str,d);
boost::put(f,name,d);
}
else
{
int i;
fromString(str,i);
boost::put(f,name,i);
}
break;
}
}
}
}
void dbf_file::read_header()
{
char c=file_.get();
if (c=='\3' || c=='\131')
{
skip(3);
num_records_=read_int();
assert(num_records_>0);
num_fields_=read_short();
assert(num_fields_>0);
num_fields_=(num_fields_-33)/32;
skip(22);
int offset=0;
char name[11];
memset(&name,0,11);
fields_.reserve(num_fields_);
for (int i=0;i<num_fields_;++i)
{
field_descriptor desc;
desc.index_=i;
file_.read(name,10);
desc.name_=trim_left(name);
skip(1);
desc.type_=file_.get();
skip(4);
desc.length_=file_.get();
desc.dec_=file_.get();
skip(14);
desc.offset_=offset;
offset+=desc.length_;
fields_.push_back(desc);
}
record_length_=offset;
if (record_length_>0)
{
record_=static_cast<char*>(::operator new (sizeof(char)*record_length_));
}
}
}
int dbf_file::read_short()
{
char b[2];
file_.read(b,2);
return (b[0] & 0xff) | (b[1] & 0xff) << 8;
}
int dbf_file::read_int()
{
char b[4];
file_.read(b,4);
return (b[0] & 0xff) | (b[1] & 0xff) << 8 |
(b[2] & 0xff) << 16 | (b[3] & 0xff) <<24;
}
void dbf_file::skip(int bytes)
{
file_.seekg(bytes,std::ios::cur);
}
<commit_msg>added explicit flags ios::in|ios::binary for win32 compat<commit_after>/* This file is part of Mapnik (c++ mapping toolkit)
* Copyright (C) 2005 Artem Pavlenko
*
* Mapnik 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 any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "dbffile.hpp"
#include "utils.hpp"
#include <boost/algorithm/string.hpp>
#include <string>
dbf_file::dbf_file()
: num_records_(0),
num_fields_(0),
record_length_(0),
record_(0) {}
dbf_file::dbf_file(const char* file_name)
:num_records_(0),
num_fields_(0),
record_length_(0),
record_(0)
{
file_.open(file_name);
if (file_.is_open())
{
read_header();
}
}
dbf_file::~dbf_file()
{
::operator delete(record_);
file_.close();
}
bool dbf_file::open(const std::string& file_name)
{
file_.open(file_name.c_str(),std::ios::in|std::ios::binary);
if (file_.is_open())
read_header();
return file_?true:false;
}
bool dbf_file::is_open()
{
return file_.is_open();
}
void dbf_file::close()
{
if (file_ && file_.is_open())
file_.close();
}
int dbf_file::num_records() const
{
return num_records_;
}
int dbf_file::num_fields() const
{
return num_fields_;
}
void dbf_file::move_to(int index)
{
if (index>0 && index<=num_records_)
{
long pos=(num_fields_<<5)+34+(index-1)*(record_length_+1);
file_.seekg(pos,std::ios::beg);
file_.read(record_,record_length_);
}
}
std::string dbf_file::string_value(int col) const
{
if (col>=0 && col<num_fields_)
{
return std::string(record_+fields_[col].offset_,fields_[col].length_);
}
return "";
}
const field_descriptor& dbf_file::descriptor(int col) const
{
assert(col>=0 && col<num_fields_);
return fields_[col];
}
void dbf_file::add_attribute(int col,Feature const& f) const throw()
{
if (col>=0 && col<num_fields_)
{
std::string name=fields_[col].name_;
std::string str=boost::trim_copy(std::string(record_+fields_[col].offset_,fields_[col].length_));
switch (fields_[col].type_)
{
case 'C':
case 'D'://todo handle date?
case 'M':
case 'L':
f[name] = str;
break;
case 'N':
case 'F':
{
if (str[0]=='*')
{
boost::put(f,name,0);
break;
}
if (fields_[col].dec_>0)
{
double d;
fromString(str,d);
boost::put(f,name,d);
}
else
{
int i;
fromString(str,i);
boost::put(f,name,i);
}
break;
}
}
}
}
void dbf_file::read_header()
{
char c=file_.get();
if (c=='\3' || c=='\131')
{
skip(3);
num_records_=read_int();
assert(num_records_>0);
num_fields_=read_short();
assert(num_fields_>0);
num_fields_=(num_fields_-33)/32;
skip(22);
int offset=0;
char name[11];
memset(&name,0,11);
fields_.reserve(num_fields_);
for (int i=0;i<num_fields_;++i)
{
field_descriptor desc;
desc.index_=i;
file_.read(name,10);
desc.name_=boost::trim_left_copy(std::string(name));
std::clog << "name=" << name << std::endl;
skip(1);
desc.type_=file_.get();
skip(4);
desc.length_=file_.get();
desc.dec_=file_.get();
skip(14);
desc.offset_=offset;
offset+=desc.length_;
fields_.push_back(desc);
}
record_length_=offset;
if (record_length_>0)
{
record_=static_cast<char*>(::operator new (sizeof(char)*record_length_));
}
}
}
int dbf_file::read_short()
{
char b[2];
file_.read(b,2);
return (b[0] & 0xff) | (b[1] & 0xff) << 8;
}
int dbf_file::read_int()
{
char b[4];
file_.read(b,4);
return (b[0] & 0xff) | (b[1] & 0xff) << 8 |
(b[2] & 0xff) << 16 | (b[3] & 0xff) <<24;
}
void dbf_file::skip(int bytes)
{
file_.seekg(bytes,std::ios::cur);
}
<|endoftext|> |
<commit_before>/**
* PANDA 3D SOFTWARE
* Copyright (c) Carnegie Mellon University. All rights reserved.
*
* All use of this software is subject to the terms of the revised BSD
* license. You should have received a copy of this license along
* with this source code in a file named "LICENSE."
*
* @file virtualFileSimple.cxx
* @author drose
* @date 2002-08-03
*/
#include "virtualFileSimple.h"
#include "virtualFileMount.h"
#include "virtualFileList.h"
#include "dcast.h"
TypeHandle VirtualFileSimple::_type_handle;
/**
* Returns the VirtualFileSystem this file is associated with.
*/
VirtualFileSystem *VirtualFileSimple::
get_file_system() const {
return _mount->get_file_system();
}
/**
* Returns the full pathname to this file within the virtual file system.
*/
Filename VirtualFileSimple::
get_filename() const {
string mount_point = _mount->get_mount_point();
if (_local_filename.empty()) {
if (mount_point.empty()) {
return "/";
} else {
return string("/") + mount_point;
}
} else {
if (mount_point.empty()) {
return string("/") + _local_filename.get_fullpath();
} else {
return string("/") + mount_point + string("/") + _local_filename.get_fullpath();
}
}
}
/**
* Returns true if this file exists, false otherwise.
*/
bool VirtualFileSimple::
has_file() const {
return _mount->has_file(_local_filename);
}
/**
* Returns true if this file represents a directory (and scan_directory() may
* be called), false otherwise.
*/
bool VirtualFileSimple::
is_directory() const {
return _mount->is_directory(_local_filename);
}
/**
* Returns true if this file represents a regular file (and read_file() may be
* called), false otherwise.
*/
bool VirtualFileSimple::
is_regular_file() const {
return _mount->is_regular_file(_local_filename);
}
/**
* Returns true if this file represents a writable regular file (and
* write_file() may be called), false otherwise.
*/
bool VirtualFileSimple::
is_writable() const {
return _mount->is_writable(_local_filename);
}
/**
* Attempts to delete this file or directory. This can remove a single file
* or an empty directory. It will not remove a nonempty directory. Returns
* true on success, false on failure.
*/
bool VirtualFileSimple::
delete_file() {
return _mount->delete_file(_local_filename);
}
/**
* Attempts to move or rename this file or directory. If the original file is
* an ordinary file, it will quietly replace any already-existing file in the
* new filename (but not a directory). If the original file is a directory,
* the new filename must not already exist.
*
* If the file is a directory, the new filename must be within the same mount
* point. If the file is an ordinary file, the new filename may be anywhere;
* but if it is not within the same mount point then the rename operation is
* automatically performed as a two-step copy-and-delete operation.
*/
bool VirtualFileSimple::
rename_file(VirtualFile *new_file) {
if (new_file->is_of_type(VirtualFileSimple::get_class_type())) {
VirtualFileSimple *new_file_simple = DCAST(VirtualFileSimple, new_file);
if (new_file_simple->_mount == _mount) {
// Same mount pount.
if (_mount->rename_file(_local_filename, new_file_simple->_local_filename)) {
return true;
}
}
}
// Different mount point, or the mount doesn't support renaming. Do it by
// hand.
if (is_regular_file() && !new_file->is_directory()) {
// copy-and-delete.
new_file->delete_file();
if (copy_file(new_file)) {
delete_file();
return true;
}
}
return false;
}
/**
* Attempts to copy the contents of this file to the indicated file. Returns
* true on success, false on failure.
*/
bool VirtualFileSimple::
copy_file(VirtualFile *new_file) {
if (new_file->is_of_type(VirtualFileSimple::get_class_type())) {
VirtualFileSimple *new_file_simple = DCAST(VirtualFileSimple, new_file);
if (new_file_simple->_mount == _mount) {
// Same mount pount.
if (_mount->copy_file(_local_filename, new_file_simple->_local_filename)) {
return true;
}
}
}
// Different mount point, or the mount doesn't support copying. Do it by
// hand.
ostream *out = new_file->open_write_file(false, true);
istream *in = open_read_file(false);
static const size_t buffer_size = 4096;
char buffer[buffer_size];
in->read(buffer, buffer_size);
size_t count = in->gcount();
while (count != 0) {
out->write(buffer, count);
if (out->fail()) {
new_file->close_write_file(out);
close_read_file(in);
new_file->delete_file();
return false;
}
in->read(buffer, buffer_size);
count = in->gcount();
}
if (!in->eof()) {
new_file->close_write_file(out);
close_read_file(in);
new_file->delete_file();
return false;
}
new_file->close_write_file(out);
close_read_file(in);
return true;
}
/**
* Opens the file for reading. Returns a newly allocated istream on success
* (which you should eventually delete when you are done reading). Returns
* NULL on failure.
*
* If auto_unwrap is true, an explicitly-named .pz/.gz file is automatically
* decompressed and the decompressed contents are returned. This is different
* than vfs-implicit-pz, which will automatically decompress a file if the
* extension .pz is *not* given.
*/
istream *VirtualFileSimple::
open_read_file(bool auto_unwrap) const {
// Will we be automatically unwrapping a .pz file?
bool do_uncompress = (_implicit_pz_file ||
(auto_unwrap && (_local_filename.get_extension() == "pz" ||
_local_filename.get_extension() == "gz")));
Filename local_filename(_local_filename);
if (do_uncompress) {
// .pz files are always binary, of course.
local_filename.set_binary();
}
return _mount->open_read_file(local_filename, do_uncompress);
}
/**
* Closes a file opened by a previous call to open_read_file(). This really
* just deletes the istream pointer, but it is recommended to use this
* interface instead of deleting it explicitly, to help work around compiler
* issues.
*/
void VirtualFileSimple::
close_read_file(istream *stream) const {
_mount->close_read_file(stream);
}
/**
* Opens the file for writing. Returns a newly allocated ostream on success
* (which you should eventually delete when you are done writing). Returns
* NULL on failure.
*
* If auto_wrap is true, an explicitly-named .pz file is automatically
* compressed while writing. If truncate is true, the file is truncated to
* zero length before writing.
*/
ostream *VirtualFileSimple::
open_write_file(bool auto_wrap, bool truncate) {
// Will we be automatically wrapping a .pz file?
bool do_compress = (_implicit_pz_file || (auto_wrap && _local_filename.get_extension() == "pz"));
Filename local_filename(_local_filename);
if (do_compress) {
// .pz files are always binary, of course.
local_filename.set_binary();
}
return _mount->open_write_file(local_filename, do_compress, truncate);
}
/**
* Works like open_write_file(), but the file is opened in append mode. Like
* open_write_file, the returned pointer should eventually be passed to
* close_write_file().
*/
ostream *VirtualFileSimple::
open_append_file() {
return _mount->open_append_file(_local_filename);
}
/**
* Closes a file opened by a previous call to open_write_file(). This really
* just deletes the ostream pointer, but it is recommended to use this
* interface instead of deleting it explicitly, to help work around compiler
* issues.
*/
void VirtualFileSimple::
close_write_file(ostream *stream) {
_mount->close_write_file(stream);
}
/**
* Opens the file for writing. Returns a newly allocated iostream on success
* (which you should eventually delete when you are done writing). Returns
* NULL on failure.
*/
iostream *VirtualFileSimple::
open_read_write_file(bool truncate) {
return _mount->open_read_write_file(_local_filename, truncate);
}
/**
* Works like open_read_write_file(), but the file is opened in append mode.
* Like open_read_write_file, the returned pointer should eventually be passed
* to close_read_write_file().
*/
iostream *VirtualFileSimple::
open_read_append_file() {
return _mount->open_read_append_file(_local_filename);
}
/**
* Closes a file opened by a previous call to open_read_write_file(). This
* really just deletes the iostream pointer, but it is recommended to use this
* interface instead of deleting it explicitly, to help work around compiler
* issues.
*/
void VirtualFileSimple::
close_read_write_file(iostream *stream) {
_mount->close_read_write_file(stream);
}
/**
* Returns the current size on disk (or wherever it is) of the already-open
* file. Pass in the stream that was returned by open_read_file(); some
* implementations may require this stream to determine the size.
*/
streamsize VirtualFileSimple::
get_file_size(istream *stream) const {
return _mount->get_file_size(_local_filename, stream);
}
/**
* Returns the current size on disk (or wherever it is) of the file before it
* has been opened.
*/
streamsize VirtualFileSimple::
get_file_size() const {
return _mount->get_file_size(_local_filename);
}
/**
* Returns a time_t value that represents the time the file was last modified,
* to within whatever precision the operating system records this information
* (on a Windows95 system, for instance, this may only be accurate to within 2
* seconds).
*
* If the timestamp cannot be determined, either because it is not supported
* by the operating system or because there is some error (such as file not
* found), returns 0.
*/
time_t VirtualFileSimple::
get_timestamp() const {
return _mount->get_timestamp(_local_filename);
}
/**
* Populates the SubfileInfo structure with the data representing where the
* file actually resides on disk, if this is knowable. Returns true if the
* file might reside on disk, and the info is populated, or false if it does
* not (or it is not known where the file resides), in which case the info is
* meaningless.
*/
bool VirtualFileSimple::
get_system_info(SubfileInfo &info) {
return _mount->get_system_info(_local_filename, info);
}
/**
* See Filename::atomic_compare_and_exchange_contents().
*/
bool VirtualFileSimple::
atomic_compare_and_exchange_contents(string &orig_contents,
const string &old_contents,
const string &new_contents) {
return _mount->atomic_compare_and_exchange_contents(_local_filename, orig_contents, old_contents, new_contents);
}
/**
* See Filename::atomic_read_contents().
*/
bool VirtualFileSimple::
atomic_read_contents(string &contents) const {
return _mount->atomic_read_contents(_local_filename, contents);
}
/**
* Fills up the indicated pvector with the contents of the file, if it is a
* regular file. Returns true on success, false otherwise.
*/
bool VirtualFileSimple::
read_file(pvector<unsigned char> &result, bool auto_unwrap) const {
// Will we be automatically unwrapping a .pz file?
bool do_uncompress = (_implicit_pz_file ||
(auto_unwrap && (_local_filename.get_extension() == "pz" ||
_local_filename.get_extension() == "gz")));
Filename local_filename(_local_filename);
if (do_uncompress) {
// .pz files are always binary, of course.
local_filename.set_binary();
}
return _mount->read_file(local_filename, do_uncompress, result);
}
/**
* Writes the indicated data to the file, if it is writable. Returns true on
* success, false otherwise.
*/
bool VirtualFileSimple::
write_file(const unsigned char *data, size_t data_size, bool auto_wrap) {
// Will we be automatically wrapping a .pz file?
bool do_compress = (_implicit_pz_file || (auto_wrap && _local_filename.get_extension() == "pz"));
Filename local_filename(_local_filename);
if (do_compress) {
// .pz files are always binary, of course.
local_filename.set_binary();
}
return _mount->write_file(local_filename, do_compress, data, data_size);
}
/**
* Fills file_list up with the list of files that are within this directory,
* excluding those whose basenames are listed in mount_points. Returns true
* if successful, false if the file is not a directory or the directory cannot
* be read.
*/
bool VirtualFileSimple::
scan_local_directory(VirtualFileList *file_list,
const ov_set<string> &mount_points) const {
vector_string names;
if (!_mount->scan_directory(names, _local_filename)) {
return false;
}
// Now the scan above gave us a list of basenames. Turn these back into
// VirtualFile pointers.
// Each of the files returned by the mount will be just a simple file within
// the same mount tree, unless it is shadowed by a mount point listed in
// mount_points.
vector_string::const_iterator ni;
for (ni = names.begin(); ni != names.end(); ++ni) {
const string &basename = (*ni);
if (mount_points.find(basename) == mount_points.end()) {
Filename filename(_local_filename, basename);
VirtualFileSimple *file = new VirtualFileSimple(_mount, filename, false, 0);
file_list->add_file(file);
}
}
return true;
}
<commit_msg>vfs: don't crash if copy_file can't open output file (LP 1687283)<commit_after>/**
* PANDA 3D SOFTWARE
* Copyright (c) Carnegie Mellon University. All rights reserved.
*
* All use of this software is subject to the terms of the revised BSD
* license. You should have received a copy of this license along
* with this source code in a file named "LICENSE."
*
* @file virtualFileSimple.cxx
* @author drose
* @date 2002-08-03
*/
#include "virtualFileSimple.h"
#include "virtualFileMount.h"
#include "virtualFileList.h"
#include "dcast.h"
TypeHandle VirtualFileSimple::_type_handle;
/**
* Returns the VirtualFileSystem this file is associated with.
*/
VirtualFileSystem *VirtualFileSimple::
get_file_system() const {
return _mount->get_file_system();
}
/**
* Returns the full pathname to this file within the virtual file system.
*/
Filename VirtualFileSimple::
get_filename() const {
string mount_point = _mount->get_mount_point();
if (_local_filename.empty()) {
if (mount_point.empty()) {
return "/";
} else {
return string("/") + mount_point;
}
} else {
if (mount_point.empty()) {
return string("/") + _local_filename.get_fullpath();
} else {
return string("/") + mount_point + string("/") + _local_filename.get_fullpath();
}
}
}
/**
* Returns true if this file exists, false otherwise.
*/
bool VirtualFileSimple::
has_file() const {
return _mount->has_file(_local_filename);
}
/**
* Returns true if this file represents a directory (and scan_directory() may
* be called), false otherwise.
*/
bool VirtualFileSimple::
is_directory() const {
return _mount->is_directory(_local_filename);
}
/**
* Returns true if this file represents a regular file (and read_file() may be
* called), false otherwise.
*/
bool VirtualFileSimple::
is_regular_file() const {
return _mount->is_regular_file(_local_filename);
}
/**
* Returns true if this file represents a writable regular file (and
* write_file() may be called), false otherwise.
*/
bool VirtualFileSimple::
is_writable() const {
return _mount->is_writable(_local_filename);
}
/**
* Attempts to delete this file or directory. This can remove a single file
* or an empty directory. It will not remove a nonempty directory. Returns
* true on success, false on failure.
*/
bool VirtualFileSimple::
delete_file() {
return _mount->delete_file(_local_filename);
}
/**
* Attempts to move or rename this file or directory. If the original file is
* an ordinary file, it will quietly replace any already-existing file in the
* new filename (but not a directory). If the original file is a directory,
* the new filename must not already exist.
*
* If the file is a directory, the new filename must be within the same mount
* point. If the file is an ordinary file, the new filename may be anywhere;
* but if it is not within the same mount point then the rename operation is
* automatically performed as a two-step copy-and-delete operation.
*/
bool VirtualFileSimple::
rename_file(VirtualFile *new_file) {
if (new_file->is_of_type(VirtualFileSimple::get_class_type())) {
VirtualFileSimple *new_file_simple = DCAST(VirtualFileSimple, new_file);
if (new_file_simple->_mount == _mount) {
// Same mount pount.
if (_mount->rename_file(_local_filename, new_file_simple->_local_filename)) {
return true;
}
}
}
// Different mount point, or the mount doesn't support renaming. Do it by
// hand.
if (is_regular_file() && !new_file->is_directory()) {
// copy-and-delete.
new_file->delete_file();
if (copy_file(new_file)) {
delete_file();
return true;
}
}
return false;
}
/**
* Attempts to copy the contents of this file to the indicated file. Returns
* true on success, false on failure.
*/
bool VirtualFileSimple::
copy_file(VirtualFile *new_file) {
if (new_file->is_of_type(VirtualFileSimple::get_class_type())) {
VirtualFileSimple *new_file_simple = DCAST(VirtualFileSimple, new_file);
if (new_file_simple->_mount == _mount) {
// Same mount pount.
if (_mount->copy_file(_local_filename, new_file_simple->_local_filename)) {
return true;
}
}
}
// Different mount point, or the mount doesn't support copying. Do it by
// hand.
ostream *out = new_file->open_write_file(false, true);
if (out == nullptr) {
return false;
}
istream *in = open_read_file(false);
if (in == nullptr) {
new_file->close_write_file(out);
new_file->delete_file();
return false;
}
static const size_t buffer_size = 4096;
char buffer[buffer_size];
in->read(buffer, buffer_size);
size_t count = in->gcount();
while (count != 0) {
out->write(buffer, count);
if (out->fail()) {
new_file->close_write_file(out);
close_read_file(in);
new_file->delete_file();
return false;
}
in->read(buffer, buffer_size);
count = in->gcount();
}
if (!in->eof()) {
new_file->close_write_file(out);
close_read_file(in);
new_file->delete_file();
return false;
}
new_file->close_write_file(out);
close_read_file(in);
return true;
}
/**
* Opens the file for reading. Returns a newly allocated istream on success
* (which you should eventually delete when you are done reading). Returns
* NULL on failure.
*
* If auto_unwrap is true, an explicitly-named .pz/.gz file is automatically
* decompressed and the decompressed contents are returned. This is different
* than vfs-implicit-pz, which will automatically decompress a file if the
* extension .pz is *not* given.
*/
istream *VirtualFileSimple::
open_read_file(bool auto_unwrap) const {
// Will we be automatically unwrapping a .pz file?
bool do_uncompress = (_implicit_pz_file ||
(auto_unwrap && (_local_filename.get_extension() == "pz" ||
_local_filename.get_extension() == "gz")));
Filename local_filename(_local_filename);
if (do_uncompress) {
// .pz files are always binary, of course.
local_filename.set_binary();
}
return _mount->open_read_file(local_filename, do_uncompress);
}
/**
* Closes a file opened by a previous call to open_read_file(). This really
* just deletes the istream pointer, but it is recommended to use this
* interface instead of deleting it explicitly, to help work around compiler
* issues.
*/
void VirtualFileSimple::
close_read_file(istream *stream) const {
_mount->close_read_file(stream);
}
/**
* Opens the file for writing. Returns a newly allocated ostream on success
* (which you should eventually delete when you are done writing). Returns
* NULL on failure.
*
* If auto_wrap is true, an explicitly-named .pz file is automatically
* compressed while writing. If truncate is true, the file is truncated to
* zero length before writing.
*/
ostream *VirtualFileSimple::
open_write_file(bool auto_wrap, bool truncate) {
// Will we be automatically wrapping a .pz file?
bool do_compress = (_implicit_pz_file || (auto_wrap && _local_filename.get_extension() == "pz"));
Filename local_filename(_local_filename);
if (do_compress) {
// .pz files are always binary, of course.
local_filename.set_binary();
}
return _mount->open_write_file(local_filename, do_compress, truncate);
}
/**
* Works like open_write_file(), but the file is opened in append mode. Like
* open_write_file, the returned pointer should eventually be passed to
* close_write_file().
*/
ostream *VirtualFileSimple::
open_append_file() {
return _mount->open_append_file(_local_filename);
}
/**
* Closes a file opened by a previous call to open_write_file(). This really
* just deletes the ostream pointer, but it is recommended to use this
* interface instead of deleting it explicitly, to help work around compiler
* issues.
*/
void VirtualFileSimple::
close_write_file(ostream *stream) {
_mount->close_write_file(stream);
}
/**
* Opens the file for writing. Returns a newly allocated iostream on success
* (which you should eventually delete when you are done writing). Returns
* NULL on failure.
*/
iostream *VirtualFileSimple::
open_read_write_file(bool truncate) {
return _mount->open_read_write_file(_local_filename, truncate);
}
/**
* Works like open_read_write_file(), but the file is opened in append mode.
* Like open_read_write_file, the returned pointer should eventually be passed
* to close_read_write_file().
*/
iostream *VirtualFileSimple::
open_read_append_file() {
return _mount->open_read_append_file(_local_filename);
}
/**
* Closes a file opened by a previous call to open_read_write_file(). This
* really just deletes the iostream pointer, but it is recommended to use this
* interface instead of deleting it explicitly, to help work around compiler
* issues.
*/
void VirtualFileSimple::
close_read_write_file(iostream *stream) {
_mount->close_read_write_file(stream);
}
/**
* Returns the current size on disk (or wherever it is) of the already-open
* file. Pass in the stream that was returned by open_read_file(); some
* implementations may require this stream to determine the size.
*/
streamsize VirtualFileSimple::
get_file_size(istream *stream) const {
return _mount->get_file_size(_local_filename, stream);
}
/**
* Returns the current size on disk (or wherever it is) of the file before it
* has been opened.
*/
streamsize VirtualFileSimple::
get_file_size() const {
return _mount->get_file_size(_local_filename);
}
/**
* Returns a time_t value that represents the time the file was last modified,
* to within whatever precision the operating system records this information
* (on a Windows95 system, for instance, this may only be accurate to within 2
* seconds).
*
* If the timestamp cannot be determined, either because it is not supported
* by the operating system or because there is some error (such as file not
* found), returns 0.
*/
time_t VirtualFileSimple::
get_timestamp() const {
return _mount->get_timestamp(_local_filename);
}
/**
* Populates the SubfileInfo structure with the data representing where the
* file actually resides on disk, if this is knowable. Returns true if the
* file might reside on disk, and the info is populated, or false if it does
* not (or it is not known where the file resides), in which case the info is
* meaningless.
*/
bool VirtualFileSimple::
get_system_info(SubfileInfo &info) {
return _mount->get_system_info(_local_filename, info);
}
/**
* See Filename::atomic_compare_and_exchange_contents().
*/
bool VirtualFileSimple::
atomic_compare_and_exchange_contents(string &orig_contents,
const string &old_contents,
const string &new_contents) {
return _mount->atomic_compare_and_exchange_contents(_local_filename, orig_contents, old_contents, new_contents);
}
/**
* See Filename::atomic_read_contents().
*/
bool VirtualFileSimple::
atomic_read_contents(string &contents) const {
return _mount->atomic_read_contents(_local_filename, contents);
}
/**
* Fills up the indicated pvector with the contents of the file, if it is a
* regular file. Returns true on success, false otherwise.
*/
bool VirtualFileSimple::
read_file(pvector<unsigned char> &result, bool auto_unwrap) const {
// Will we be automatically unwrapping a .pz file?
bool do_uncompress = (_implicit_pz_file ||
(auto_unwrap && (_local_filename.get_extension() == "pz" ||
_local_filename.get_extension() == "gz")));
Filename local_filename(_local_filename);
if (do_uncompress) {
// .pz files are always binary, of course.
local_filename.set_binary();
}
return _mount->read_file(local_filename, do_uncompress, result);
}
/**
* Writes the indicated data to the file, if it is writable. Returns true on
* success, false otherwise.
*/
bool VirtualFileSimple::
write_file(const unsigned char *data, size_t data_size, bool auto_wrap) {
// Will we be automatically wrapping a .pz file?
bool do_compress = (_implicit_pz_file || (auto_wrap && _local_filename.get_extension() == "pz"));
Filename local_filename(_local_filename);
if (do_compress) {
// .pz files are always binary, of course.
local_filename.set_binary();
}
return _mount->write_file(local_filename, do_compress, data, data_size);
}
/**
* Fills file_list up with the list of files that are within this directory,
* excluding those whose basenames are listed in mount_points. Returns true
* if successful, false if the file is not a directory or the directory cannot
* be read.
*/
bool VirtualFileSimple::
scan_local_directory(VirtualFileList *file_list,
const ov_set<string> &mount_points) const {
vector_string names;
if (!_mount->scan_directory(names, _local_filename)) {
return false;
}
// Now the scan above gave us a list of basenames. Turn these back into
// VirtualFile pointers.
// Each of the files returned by the mount will be just a simple file within
// the same mount tree, unless it is shadowed by a mount point listed in
// mount_points.
vector_string::const_iterator ni;
for (ni = names.begin(); ni != names.end(); ++ni) {
const string &basename = (*ni);
if (mount_points.find(basename) == mount_points.end()) {
Filename filename(_local_filename, basename);
VirtualFileSimple *file = new VirtualFileSimple(_mount, filename, false, 0);
file_list->add_file(file);
}
}
return true;
}
<|endoftext|> |
<commit_before>/*
Copyright (C) 2013 Martin Klapetek <mklapetek@kde.org>
Copyright (C) 2014 David Edmundson <davidedmundson@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.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 "im-persons-data-source.h"
#include <TelepathyQt/AccountManager>
#include <TelepathyQt/AccountFactory>
#include <TelepathyQt/ContactManager>
#include <TelepathyQt/PendingOperation>
#include <TelepathyQt/PendingReady>
#include <TelepathyQt/Presence>
#include <TelepathyQt/Utils>
#include "KTp/contact-factory.h"
#include "KTp/global-contact-manager.h"
#include "KTp/types.h"
#include "debug.h"
#include <KPeopleBackend/AllContactsMonitor>
#include <KPluginFactory>
#include <KPluginLoader>
#include <KConfig>
#include <KConfigGroup>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QPixmap>
using namespace KPeople;
class KTpAllContacts : public AllContactsMonitor
{
Q_OBJECT
public:
KTpAllContacts();
~KTpAllContacts();
virtual QMap<QString, AbstractContact::Ptr> contacts() Q_DECL_OVERRIDE;
private Q_SLOTS:
void loadCache(const QString &accountId = QString());
void onAccountManagerReady(Tp::PendingOperation *op);
void onContactChanged();
void onContactInvalidated();
void onAllKnownContactsChanged(const Tp::Contacts &contactsAdded, const Tp::Contacts &contactsRemoved);
void onAccountCurrentPresenceChanged(const Tp::Presence ¤tPresence);
private:
QString createUri(const KTp::ContactPtr &contact) const;
//presence names indexed by ConnectionPresenceType
QHash<QString, KTp::ContactPtr> m_contacts;
QMap<QString, AbstractContact::Ptr> m_contactVCards;
};
class TelepathyContact : public KPeople::AbstractContact
{
public:
virtual QVariant customProperty(const QString &key) const Q_DECL_OVERRIDE
{
// Check if the contact is valid first
if (m_contact && m_contact->manager() && m_contact->manager()->connection() && m_account) {
if (key == AbstractContact::NameProperty)
return m_contact->alias();
else if(key == AbstractContact::GroupsProperty)
return m_contact->groups();
else if(key == S_KPEOPLE_PROPERTY_CONTACT_ID)
return m_contact->id();
else if(key == S_KPEOPLE_PROPERTY_ACCOUNT_PATH)
return m_account->objectPath();
else if(key == S_KPEOPLE_PROPERTY_PRESENCE)
return s_presenceStrings.value(m_contact->presence().type());
else if (key == AbstractContact::PictureProperty)
return m_contact->avatarPixmap();
}
return m_properties[key];
}
void insertProperty(const QString &key, const QVariant &value)
{
m_properties[key] = value;
}
void setContact(const KTp::ContactPtr &contact)
{
m_contact = contact;
}
void setAccount(const Tp::AccountPtr &account)
{
m_account = account;
}
private:
KTp::ContactPtr m_contact;
Tp::AccountPtr m_account;
QVariantMap m_properties;
};
KTpAllContacts::KTpAllContacts()
{
Tp::registerTypes();
loadCache();
}
KTpAllContacts::~KTpAllContacts()
{
}
void KTpAllContacts::loadCache(const QString &accountId)
{
QSqlDatabase db = QSqlDatabase::addDatabase(QLatin1String("QSQLITE"), QLatin1String("ktpCache"));
QString path = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1String("/ktp");
QDir().mkpath(path);
db.setDatabaseName(path+QStringLiteral("/cache.db"));
if (!db.open()) {
qWarning() << "couldn't open database" << db.databaseName();
}
QSqlQuery query(db);
query.exec(QLatin1String("SELECT DISTINCT groupName FROM groups ORDER BY groupId;"));
QStringList groupsList;
while (query.next()) {
groupsList.append(query.value(0).toString());
}
QString queryPrep = QStringLiteral("SELECT accountId, contactId, alias, avatarFileName, isBlocked");
if (!groupsList.isEmpty()) {
queryPrep.append(QStringLiteral(", groupsIds"));
}
queryPrep.append(QStringLiteral(" FROM contacts"));
if (!accountId.isEmpty()) {
queryPrep.append(QStringLiteral(" WHERE accountId = ?;"));
query.prepare(queryPrep);
query.bindValue(0, accountId);
} else {
queryPrep.append(QStringLiteral(";"));
query.prepare(queryPrep);
}
query.exec();
KConfig config(QLatin1String("ktelepathy-avatarsrc"));
QString cacheDir = QString::fromLatin1(qgetenv("XDG_CACHE_HOME"));
if (cacheDir.isEmpty()) {
cacheDir = QStringLiteral("%1/.cache").arg(QLatin1String(qgetenv("HOME")));
}
while (query.next()) {
QExplicitlySharedDataPointer<TelepathyContact> addressee(new TelepathyContact);
const QString accountId = query.value(0).toString();
const QString contactId = query.value(1).toString();
QString avatarFileName = query.value(3).toString();
addressee->insertProperty(AbstractContact::NameProperty, query.value(2).toString());
if (avatarFileName.isEmpty()) {
KConfigGroup avatarTokenGroup = config.group(contactId);
QString avatarToken = avatarTokenGroup.readEntry(QLatin1String("avatarToken"));
//only bother loading the pixmap if the token is not empty
if (!avatarToken.isEmpty()) {
// the accountId is in form of "connection manager name / protocol / username...",
// so let's look for the first / after the very first / (ie. second /)
QString path = QStringLiteral("%1/telepathy/avatars/%2").
arg(cacheDir).arg(accountId.left(accountId.indexOf(QLatin1Char('/'), accountId.indexOf(QLatin1Char('/')) + 1)));
avatarFileName = QStringLiteral("%1/%2").arg(path).arg(Tp::escapeAsIdentifier(avatarToken));
}
}
addressee->insertProperty(AbstractContact::PictureProperty, QUrl::fromLocalFile(avatarFileName));
addressee->insertProperty(S_KPEOPLE_PROPERTY_IS_BLOCKED, query.value(4).toBool());
if (!groupsList.isEmpty()) {
QVariantList contactGroups;
Q_FOREACH (const QString &groupIdStr, query.value(5).toString().split(QLatin1Char('/'))) {
bool convSuccess;
int groupId = groupIdStr.toInt(&convSuccess);
if ((!convSuccess) || (groupId >= groupsList.count()))
continue;
contactGroups.append(groupsList.at(groupId));
}
addressee->insertProperty(AbstractContact::GroupsProperty, contactGroups);
}
addressee->insertProperty(S_KPEOPLE_PROPERTY_CONTACT_ID, contactId);
addressee->insertProperty(S_KPEOPLE_PROPERTY_ACCOUNT_PATH, TP_QT_ACCOUNT_OBJECT_PATH_BASE + QLatin1Char('/') + accountId);
addressee->insertProperty(S_KPEOPLE_PROPERTY_PRESENCE, s_presenceStrings[Tp::ConnectionPresenceTypeOffline]);
const QString uri = QLatin1String("ktp://") + accountId + QLatin1Char('?') + contactId;
QMap<QString, AbstractContact::Ptr>::const_iterator it = m_contactVCards.constFind(uri);
if (it != m_contactVCards.constEnd()) {
Q_EMIT contactChanged(uri, addressee);
} else {
Q_EMIT contactAdded(uri, addressee);
}
m_contactVCards[uri] = addressee;
}
//now start fetching the up-to-date information
connect(KTp::accountManager()->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)),
this, SLOT(onAccountManagerReady(Tp::PendingOperation*)), Qt::UniqueConnection);
emitInitialFetchComplete(true);
}
QString KTpAllContacts::createUri(const KTp::ContactPtr &contact) const
{
// so real ID will look like
// ktp://gabble/jabber/blah/asdfjwer?foo@bar.com
// ? is used as it is not a valid character in the dbus path that makes up the account UID
return QLatin1String("ktp://") + contact->accountUniqueIdentifier() + QLatin1Char('?') + contact->id();
}
void KTpAllContacts::onAccountManagerReady(Tp::PendingOperation *op)
{
if (op->isError()) {
qCWarning(KTP_KPEOPLE) << "Failed to initialize AccountManager:" << op->errorName();
qCWarning(KTP_KPEOPLE) << op->errorMessage();
return;
}
qCDebug(KTP_KPEOPLE) << "Account manager ready";
Q_FOREACH (const Tp::AccountPtr &account, KTp::accountManager()->allAccounts()) {
connect(account.data(), &Tp::Account::currentPresenceChanged, this, &KTpAllContacts::onAccountCurrentPresenceChanged);
}
connect(KTp::contactManager(), SIGNAL(allKnownContactsChanged(Tp::Contacts,Tp::Contacts)),
this, SLOT(onAllKnownContactsChanged(Tp::Contacts,Tp::Contacts)));
onAllKnownContactsChanged(KTp::contactManager()->allKnownContacts(), Tp::Contacts());
}
void KTpAllContacts::onAccountCurrentPresenceChanged(const Tp::Presence ¤tPresence)
{
Tp::Account *account = qobject_cast<Tp::Account*>(sender());
if (!account) {
return;
}
if (currentPresence.type() == Tp::ConnectionPresenceTypeOffline) {
loadCache(account->uniqueIdentifier());
}
}
void KTpAllContacts::onAllKnownContactsChanged(const Tp::Contacts &contactsAdded, const Tp::Contacts &contactsRemoved)
{
if (!m_contacts.isEmpty()) {
Q_FOREACH (const Tp::ContactPtr &c, contactsRemoved) {
const KTp::ContactPtr &contact = KTp::ContactPtr::qObjectCast(c);
const QString uri = createUri(contact);
m_contacts.remove(uri);
m_contactVCards.remove(uri);
Q_EMIT contactRemoved(uri);
}
}
Q_FOREACH (const Tp::ContactPtr &contact, contactsAdded) {
KTp::ContactPtr ktpContact = KTp::ContactPtr::qObjectCast(contact);
const QString uri = createUri(ktpContact);
AbstractContact::Ptr vcard = m_contactVCards.value(uri);
bool added = false;
if (!vcard) {
vcard = AbstractContact::Ptr(new TelepathyContact);
m_contactVCards[uri] = vcard;
added = true;
}
static_cast<TelepathyContact*>(vcard.data())->setContact(ktpContact);
static_cast<TelepathyContact*>(vcard.data())->setAccount(KTp::contactManager()->accountForContact(ktpContact));
m_contacts.insert(uri, ktpContact);
if (added) {
Q_EMIT contactAdded(uri, vcard);
} else {
Q_EMIT contactChanged(uri, vcard);
}
connect(ktpContact.data(), SIGNAL(presenceChanged(Tp::Presence)),
this, SLOT(onContactChanged()));
connect(ktpContact.data(), SIGNAL(capabilitiesChanged(Tp::ContactCapabilities)),
this, SLOT(onContactChanged()));
connect(ktpContact.data(), SIGNAL(invalidated()),
this, SLOT(onContactInvalidated()));
connect(ktpContact.data(), SIGNAL(avatarDataChanged(Tp::AvatarData)),
this, SLOT(onContactChanged()));
connect(ktpContact.data(), SIGNAL(addedToGroup(QString)),
this, SLOT(onContactChanged()));
connect(ktpContact.data(), SIGNAL(removedFromGroup(QString)),
this, SLOT(onContactChanged()));
}
}
void KTpAllContacts::onContactChanged()
{
const KTp::ContactPtr contact(qobject_cast<KTp::Contact*>(sender()));
const QString uri = createUri(contact);
Q_EMIT contactChanged(uri, m_contactVCards.value(uri));
}
void KTpAllContacts::onContactInvalidated()
{
const KTp::ContactPtr contact(qobject_cast<KTp::Contact*>(sender()));
const QString uri = createUri(contact);
m_contacts.remove(uri);
//set to offline and emit changed
AbstractContact::Ptr vcard = m_contactVCards[uri];
TelepathyContact *tpContact = static_cast<TelepathyContact*>(vcard.data());
tpContact->insertProperty(S_KPEOPLE_PROPERTY_PRESENCE, QStringLiteral("offline"));
Q_EMIT contactChanged(uri, vcard);
}
QMap<QString, AbstractContact::Ptr> KTpAllContacts::contacts()
{
return m_contactVCards;
}
IMPersonsDataSource::IMPersonsDataSource(QObject *parent, const QVariantList &args)
: BasePersonsDataSource(parent)
{
Q_UNUSED(args);
}
IMPersonsDataSource::~IMPersonsDataSource()
{
}
QString IMPersonsDataSource::sourcePluginId() const
{
return QStringLiteral("ktp");
}
AllContactsMonitor* IMPersonsDataSource::createAllContactsMonitor()
{
return new KTpAllContacts();
}
K_PLUGIN_FACTORY( IMPersonsDataSourceFactory, registerPlugin<IMPersonsDataSource>(); )
K_EXPORT_PLUGIN( IMPersonsDataSourceFactory("im_persons_data_source_plugin") )
#include "im-persons-data-source.moc"
<commit_msg>Don't create null fields if uri is not available<commit_after>/*
Copyright (C) 2013 Martin Klapetek <mklapetek@kde.org>
Copyright (C) 2014 David Edmundson <davidedmundson@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.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 "im-persons-data-source.h"
#include <TelepathyQt/AccountManager>
#include <TelepathyQt/AccountFactory>
#include <TelepathyQt/ContactManager>
#include <TelepathyQt/PendingOperation>
#include <TelepathyQt/PendingReady>
#include <TelepathyQt/Presence>
#include <TelepathyQt/Utils>
#include "KTp/contact-factory.h"
#include "KTp/global-contact-manager.h"
#include "KTp/types.h"
#include "debug.h"
#include <KPeopleBackend/AllContactsMonitor>
#include <KPluginFactory>
#include <KPluginLoader>
#include <KConfig>
#include <KConfigGroup>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QPixmap>
using namespace KPeople;
class KTpAllContacts : public AllContactsMonitor
{
Q_OBJECT
public:
KTpAllContacts();
~KTpAllContacts();
virtual QMap<QString, AbstractContact::Ptr> contacts() Q_DECL_OVERRIDE;
private Q_SLOTS:
void loadCache(const QString &accountId = QString());
void onAccountManagerReady(Tp::PendingOperation *op);
void onContactChanged();
void onContactInvalidated();
void onAllKnownContactsChanged(const Tp::Contacts &contactsAdded, const Tp::Contacts &contactsRemoved);
void onAccountCurrentPresenceChanged(const Tp::Presence ¤tPresence);
private:
QString createUri(const KTp::ContactPtr &contact) const;
//presence names indexed by ConnectionPresenceType
QHash<QString, KTp::ContactPtr> m_contacts;
QMap<QString, AbstractContact::Ptr> m_contactVCards;
};
class TelepathyContact : public KPeople::AbstractContact
{
public:
virtual QVariant customProperty(const QString &key) const Q_DECL_OVERRIDE
{
// Check if the contact is valid first
if (m_contact && m_contact->manager() && m_contact->manager()->connection() && m_account) {
if (key == AbstractContact::NameProperty)
return m_contact->alias();
else if(key == AbstractContact::GroupsProperty)
return m_contact->groups();
else if(key == S_KPEOPLE_PROPERTY_CONTACT_ID)
return m_contact->id();
else if(key == S_KPEOPLE_PROPERTY_ACCOUNT_PATH)
return m_account->objectPath();
else if(key == S_KPEOPLE_PROPERTY_PRESENCE)
return s_presenceStrings.value(m_contact->presence().type());
else if (key == AbstractContact::PictureProperty)
return m_contact->avatarPixmap();
}
return m_properties[key];
}
void insertProperty(const QString &key, const QVariant &value)
{
m_properties[key] = value;
}
void setContact(const KTp::ContactPtr &contact)
{
m_contact = contact;
}
void setAccount(const Tp::AccountPtr &account)
{
m_account = account;
}
private:
KTp::ContactPtr m_contact;
Tp::AccountPtr m_account;
QVariantMap m_properties;
};
KTpAllContacts::KTpAllContacts()
{
Tp::registerTypes();
loadCache();
}
KTpAllContacts::~KTpAllContacts()
{
}
void KTpAllContacts::loadCache(const QString &accountId)
{
QSqlDatabase db = QSqlDatabase::addDatabase(QLatin1String("QSQLITE"), QLatin1String("ktpCache"));
QString path = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1String("/ktp");
QDir().mkpath(path);
db.setDatabaseName(path+QStringLiteral("/cache.db"));
if (!db.open()) {
qWarning() << "couldn't open database" << db.databaseName();
}
QSqlQuery query(db);
query.exec(QLatin1String("SELECT DISTINCT groupName FROM groups ORDER BY groupId;"));
QStringList groupsList;
while (query.next()) {
groupsList.append(query.value(0).toString());
}
QString queryPrep = QStringLiteral("SELECT accountId, contactId, alias, avatarFileName, isBlocked");
if (!groupsList.isEmpty()) {
queryPrep.append(QStringLiteral(", groupsIds"));
}
queryPrep.append(QStringLiteral(" FROM contacts"));
if (!accountId.isEmpty()) {
queryPrep.append(QStringLiteral(" WHERE accountId = ?;"));
query.prepare(queryPrep);
query.bindValue(0, accountId);
} else {
queryPrep.append(QStringLiteral(";"));
query.prepare(queryPrep);
}
query.exec();
KConfig config(QLatin1String("ktelepathy-avatarsrc"));
QString cacheDir = QString::fromLatin1(qgetenv("XDG_CACHE_HOME"));
if (cacheDir.isEmpty()) {
cacheDir = QStringLiteral("%1/.cache").arg(QLatin1String(qgetenv("HOME")));
}
while (query.next()) {
QExplicitlySharedDataPointer<TelepathyContact> addressee(new TelepathyContact);
const QString accountId = query.value(0).toString();
const QString contactId = query.value(1).toString();
QString avatarFileName = query.value(3).toString();
addressee->insertProperty(AbstractContact::NameProperty, query.value(2).toString());
if (avatarFileName.isEmpty()) {
KConfigGroup avatarTokenGroup = config.group(contactId);
QString avatarToken = avatarTokenGroup.readEntry(QLatin1String("avatarToken"));
//only bother loading the pixmap if the token is not empty
if (!avatarToken.isEmpty()) {
// the accountId is in form of "connection manager name / protocol / username...",
// so let's look for the first / after the very first / (ie. second /)
QString path = QStringLiteral("%1/telepathy/avatars/%2").
arg(cacheDir).arg(accountId.left(accountId.indexOf(QLatin1Char('/'), accountId.indexOf(QLatin1Char('/')) + 1)));
avatarFileName = QStringLiteral("%1/%2").arg(path).arg(Tp::escapeAsIdentifier(avatarToken));
}
}
addressee->insertProperty(AbstractContact::PictureProperty, QUrl::fromLocalFile(avatarFileName));
addressee->insertProperty(S_KPEOPLE_PROPERTY_IS_BLOCKED, query.value(4).toBool());
if (!groupsList.isEmpty()) {
QVariantList contactGroups;
Q_FOREACH (const QString &groupIdStr, query.value(5).toString().split(QLatin1Char('/'))) {
bool convSuccess;
int groupId = groupIdStr.toInt(&convSuccess);
if ((!convSuccess) || (groupId >= groupsList.count()))
continue;
contactGroups.append(groupsList.at(groupId));
}
addressee->insertProperty(AbstractContact::GroupsProperty, contactGroups);
}
addressee->insertProperty(S_KPEOPLE_PROPERTY_CONTACT_ID, contactId);
addressee->insertProperty(S_KPEOPLE_PROPERTY_ACCOUNT_PATH, TP_QT_ACCOUNT_OBJECT_PATH_BASE + QLatin1Char('/') + accountId);
addressee->insertProperty(S_KPEOPLE_PROPERTY_PRESENCE, s_presenceStrings[Tp::ConnectionPresenceTypeOffline]);
const QString uri = QLatin1String("ktp://") + accountId + QLatin1Char('?') + contactId;
QMap<QString, AbstractContact::Ptr>::const_iterator it = m_contactVCards.constFind(uri);
if (it != m_contactVCards.constEnd()) {
Q_EMIT contactChanged(uri, addressee);
} else {
Q_EMIT contactAdded(uri, addressee);
}
m_contactVCards[uri] = addressee;
}
//now start fetching the up-to-date information
connect(KTp::accountManager()->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)),
this, SLOT(onAccountManagerReady(Tp::PendingOperation*)), Qt::UniqueConnection);
emitInitialFetchComplete(true);
}
QString KTpAllContacts::createUri(const KTp::ContactPtr &contact) const
{
// so real ID will look like
// ktp://gabble/jabber/blah/asdfjwer?foo@bar.com
// ? is used as it is not a valid character in the dbus path that makes up the account UID
return QLatin1String("ktp://") + contact->accountUniqueIdentifier() + QLatin1Char('?') + contact->id();
}
void KTpAllContacts::onAccountManagerReady(Tp::PendingOperation *op)
{
if (op->isError()) {
qCWarning(KTP_KPEOPLE) << "Failed to initialize AccountManager:" << op->errorName();
qCWarning(KTP_KPEOPLE) << op->errorMessage();
return;
}
qCDebug(KTP_KPEOPLE) << "Account manager ready";
Q_FOREACH (const Tp::AccountPtr &account, KTp::accountManager()->allAccounts()) {
connect(account.data(), &Tp::Account::currentPresenceChanged, this, &KTpAllContacts::onAccountCurrentPresenceChanged);
}
connect(KTp::contactManager(), SIGNAL(allKnownContactsChanged(Tp::Contacts,Tp::Contacts)),
this, SLOT(onAllKnownContactsChanged(Tp::Contacts,Tp::Contacts)));
onAllKnownContactsChanged(KTp::contactManager()->allKnownContacts(), Tp::Contacts());
}
void KTpAllContacts::onAccountCurrentPresenceChanged(const Tp::Presence ¤tPresence)
{
Tp::Account *account = qobject_cast<Tp::Account*>(sender());
if (!account) {
return;
}
if (currentPresence.type() == Tp::ConnectionPresenceTypeOffline) {
loadCache(account->uniqueIdentifier());
}
}
void KTpAllContacts::onAllKnownContactsChanged(const Tp::Contacts &contactsAdded, const Tp::Contacts &contactsRemoved)
{
if (!m_contacts.isEmpty()) {
Q_FOREACH (const Tp::ContactPtr &c, contactsRemoved) {
const KTp::ContactPtr &contact = KTp::ContactPtr::qObjectCast(c);
const QString uri = createUri(contact);
m_contacts.remove(uri);
m_contactVCards.remove(uri);
Q_EMIT contactRemoved(uri);
}
}
Q_FOREACH (const Tp::ContactPtr &contact, contactsAdded) {
KTp::ContactPtr ktpContact = KTp::ContactPtr::qObjectCast(contact);
const QString uri = createUri(ktpContact);
AbstractContact::Ptr vcard = m_contactVCards.value(uri);
bool added = false;
if (!vcard) {
vcard = AbstractContact::Ptr(new TelepathyContact);
m_contactVCards[uri] = vcard;
added = true;
}
static_cast<TelepathyContact*>(vcard.data())->setContact(ktpContact);
static_cast<TelepathyContact*>(vcard.data())->setAccount(KTp::contactManager()->accountForContact(ktpContact));
m_contacts.insert(uri, ktpContact);
if (added) {
Q_EMIT contactAdded(uri, vcard);
} else {
Q_EMIT contactChanged(uri, vcard);
}
connect(ktpContact.data(), SIGNAL(presenceChanged(Tp::Presence)),
this, SLOT(onContactChanged()));
connect(ktpContact.data(), SIGNAL(capabilitiesChanged(Tp::ContactCapabilities)),
this, SLOT(onContactChanged()));
connect(ktpContact.data(), SIGNAL(invalidated()),
this, SLOT(onContactInvalidated()));
connect(ktpContact.data(), SIGNAL(avatarDataChanged(Tp::AvatarData)),
this, SLOT(onContactChanged()));
connect(ktpContact.data(), SIGNAL(addedToGroup(QString)),
this, SLOT(onContactChanged()));
connect(ktpContact.data(), SIGNAL(removedFromGroup(QString)),
this, SLOT(onContactChanged()));
}
}
void KTpAllContacts::onContactChanged()
{
const KTp::ContactPtr contact(qobject_cast<KTp::Contact*>(sender()));
const QString uri = createUri(contact);
Q_EMIT contactChanged(uri, m_contactVCards.value(uri));
}
void KTpAllContacts::onContactInvalidated()
{
const KTp::ContactPtr contact(qobject_cast<KTp::Contact*>(sender()));
const QString uri = createUri(contact);
m_contacts.remove(uri);
//set to offline and emit changed
AbstractContact::Ptr vcard = m_contactVCards.value(uri);
TelepathyContact *tpContact = static_cast<TelepathyContact*>(vcard.data());
tpContact->insertProperty(S_KPEOPLE_PROPERTY_PRESENCE, QStringLiteral("offline"));
Q_EMIT contactChanged(uri, vcard);
}
QMap<QString, AbstractContact::Ptr> KTpAllContacts::contacts()
{
return m_contactVCards;
}
IMPersonsDataSource::IMPersonsDataSource(QObject *parent, const QVariantList &args)
: BasePersonsDataSource(parent)
{
Q_UNUSED(args);
}
IMPersonsDataSource::~IMPersonsDataSource()
{
}
QString IMPersonsDataSource::sourcePluginId() const
{
return QStringLiteral("ktp");
}
AllContactsMonitor* IMPersonsDataSource::createAllContactsMonitor()
{
return new KTpAllContacts();
}
K_PLUGIN_FACTORY( IMPersonsDataSourceFactory, registerPlugin<IMPersonsDataSource>(); )
K_EXPORT_PLUGIN( IMPersonsDataSourceFactory("im_persons_data_source_plugin") )
#include "im-persons-data-source.moc"
<|endoftext|> |
<commit_before>#pragma once
#include "util.cpp"
//return intervals during which the satellite can photograph the object
//ignoring the photos the satellite should already take
vector<pair<ll, ll>> possible_intervals(Input& input, Satellite& satellite, Object& object) {
vector<pair<ll, ll>> ret(1);
ret[0] = make_pair(0, input.t-1);
return ret;
}
<commit_msg>Added possible intervals function<commit_after>#pragma once
#include "util.cpp"
#include <cmath>
const int ROTATION = -15;
const int LOW_LAT = -324000;
const int UP_LAT = 324000;
const int LOW_LON = -648000;
const int UP_LON = 647999;
const int INTERV_LON = UP_LON - LOW_LON;
const int INVER_LAT = UP_LAT - LOW_LAT;
double checkBounds_x(double x)
{
if (x < LOW_LON)
return x + INTERV_LON;
else if (x > LOW_LON)
return x - INTERV_LON;
return x;
}
double projectUp(ll x, ll y, double v, int x_speed)
{
double t = 1.0 * (UP_LON - y) / abs(v);
double pos = x + t * x_speed;
return checkBounds_x(pos);
}
double projectDown(ll x, ll y, double v, int x_speed)
{
double t = 1.0 * (y - LOW_LON) / abs(v);
double pos = x + t * x_speed;
return checkBounds_x(pos);
}
double distX(double x1, double x2)
{
if (x1 > x2)
swap(x1, x2);
return min(x2 - x1, x1 - LOW_LON + UP_LON - x2);
}
//return intervals during which the satellite can photograph the object
//ignoring the photos the satellite should already take
vector<pair<ll, ll>> possible_intervals(Input& input, Satellite& satellite, Object& object)
{
double crossTime = 1.0 * INVER_LAT / abs(satellite.v);
double crossLen = crossTime * ROTATION;
vector<double> up_positions;
vector<double> down_positions;
vector<double> up_times;
vector<double> down_times;
bool isUp;
double time;
double len;
if (satellite.v > 0)
{
len = projectUp(satellite.lon, satellite.lat, satellite.v, ROTATION);
up_positions.push_back(len);
time = (UP_LAT - satellite.lat) / satellite.v;
up_times.push_back(time);
isUp = true;
}
else
{
len = projectDown(satellite.lon, satellite.lat, satellite.v, ROTATION);
down_positions.push_back(len);
time = (satellite.lat - LOW_LAT) / satellite.v;
down_times.push_back(time);
isUp = false;
}
while (time + crossTime < input.t)
{
time += crossTime;
len = checkBounds_x(len + crossLen);
isUp = !isUp;
if (isUp)
{
up_positions.push_back(len);
up_times.push_back(time);
}
else
{
down_positions.push_back(len);
down_times.push_back(time);
}
}
// project object
double obj_up_pos = projectUp(object.lon, object.lat, satellite.v, -ROTATION);
double obj_down_pos = projectDown(object.lon, object.lat, satellite.v, ROTATION);
vector<pair<ll, ll>> intervals;
for (int i = 0; i < up_positions.size(); i++)
{
if (distX(obj_up_pos, up_positions[i]) < satellite.d)
{
double t_star = up_times[i] + 1.0 * (UP_LAT - object.lat) / satellite.v;
intervals.push_back(make_pair(floor(t_star), ceil(t_star)));
}
}
for (int i = 0; i < down_positions.size(); i++)
{
if (distX(obj_down_pos, down_positions[i]) < satellite.d)
{
double t_star = down_times[i] + 1.0 * (object.lat - LOW_LAT) / satellite.v;
intervals.push_back(make_pair(floor(t_star), ceil(t_star)));
}
}
return intervals;
}
<|endoftext|> |
<commit_before><commit_msg>nitpick: avoid triple redirection inside loop, fdo#75264 related<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: acredlin.hxx,v $
*
* $Revision: 1.1.1.1 $
*
* last change: $Author: hr $ $Date: 2000-09-18 16:44:57 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef SC_ACREDLIN_HXX
#define SC_ACREDLIN_HXX
#ifndef VCL
#endif
#ifndef _MOREBTN_HXX //autogen
#include <vcl/morebtn.hxx>
#endif
#ifndef _COMBOBOX_HXX //autogen
#include <vcl/combobox.hxx>
#endif
#ifndef _GROUP_HXX //autogen
#include <vcl/group.hxx>
#endif
#ifndef _HEADBAR_HXX //autogen
#include <svtools/headbar.hxx>
#endif
#ifndef _SVTABBX_HXX //autogen
#include <svtools/svtabbx.hxx>
#endif
#ifndef SC_RANGENAM_HXX
#include "rangenam.hxx"
#endif
#ifndef SC_ANYREFDG_HXX
#include "anyrefdg.hxx"
#endif
#ifndef _SV_LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif
#ifndef _SVX_ACREDLIN_HXX
#include <svx/ctredlin.hxx>
#endif
#ifndef _SVX_SIMPTABL_HXX
#include <svx/simptabl.hxx>
#endif
#ifndef _SVARRAY_HXX
#define _SVARRAY_HXX
#include <svtools/svarray.hxx>
#endif
#ifndef SC_CHGTRACK_HXX
#include "chgtrack.hxx"
#endif
#ifndef SC_CHGVISET_HXX
#include "chgviset.hxx"
#endif
#ifndef _SV_TIMER_HXX //autogen
#include <vcl/timer.hxx>
#endif
class ScViewData;
class ScDocument;
#define FLT_DATE_BEFORE 0
#define FLT_DATE_SINCE 1
#define FLT_DATE_EQUAL 2
#define FLT_DATE_NOTEQUAL 3
#define FLT_DATE_BETWEEN 4
#define FLT_DATE_SAVE 5
class ScViewEntryPtr
{
private:
String* pAction;
String* pPos;
String* pAuthor;
String* pDate;
String* pComment;
void* pData;
public:
String* GetpAction() {return pAction; }
String* GetpPos() {return pPos; }
String* GetpAuthor() {return pAuthor; }
String* GetpDate() {return pDate; }
String* GetpComment() {return pComment;}
void* GetpData() {return pData; }
void SetpAction (String* pString) {pAction= pString;}
void SetpPos (String* pString) {pPos = pString;}
void SetpAuthor (String* pString) {pAuthor= pString;}
void SetpDate (String* pString) {pDate = pString;}
void SetpComment(String* pString) {pComment=pString;}
void SetpData (void* pdata) {pData =pdata;}
};
class ScViewEntryPtrList
{
ScViewEntryPtrList* pNext;
ScViewEntryPtrList* pLast;
ScViewEntryPtr* pData;
};
class ScRedlinData : public RedlinData
{
public:
ScRedlinData();
~ScRedlinData();
USHORT nTable;
USHORT nCol;
USHORT nRow;
ULONG nActionNo;
ULONG nInfo;
BOOL bIsRejectable;
BOOL bIsAcceptable;
};
typedef long LExpNum;
//@ Expand-Entrys nicht eindeutig, daher gestrichen
//DECLARE_TABLE( ScChgTrackExps, LExpNum)
//==================================================================
class ScAcceptChgDlg : public SfxModelessDialog
{
private:
Timer aSelectionTimer;
Timer aReOpenTimer;
SvxAcceptChgCtr aAcceptChgCtr;
ScViewData* pViewData;
ScDocument* pDoc;
ScRangeName aLocalRangeName;
Selection theCurSel;
SvxTPFilter* pTPFilter;
SvxTPView* pTPView;
SvxRedlinTable* pTheView;
Size MinSize;
ScRangeList aRangeList;
ScChangeViewSettings aChangeViewSet;
International aInter;
String aStrInsertCols;
String aStrInsertRows;
String aStrInsertTabs;
String aStrDeleteCols;
String aStrDeleteRows;
String aStrDeleteTabs;
String aStrMove;
String aStrContent;
String aStrReject;
String aUnknown;
String aStrAllAccepted;
String aStrAllRejected;
String aStrNoEntry;
String aStrContentWithChild;
String aStrChildContent;
String aStrChildOrgContent;
String aStrEmpty;
Bitmap aExpBmp;
Bitmap aCollBmp;
Bitmap aCloseBmp;
Bitmap aOpenBmp;
Bitmap aEndBmp;
Bitmap aErrorBmp;
ULONG nAcceptCount;
ULONG nRejectCount;
BOOL bAcceptEnableFlag;
BOOL bRejectEnableFlag;
BOOL bNeedsUpdate;
BOOL bIgnoreMsg;
BOOL bNoSelection;
BOOL bHasFilterEntry;
BOOL bUseColor;
//ScChgTrackExps aExpandArray;
void Init();
void InitFilter();
void SetMyStaticData();
DECL_LINK( FilterHandle, SvxTPFilter* );
DECL_LINK( RefHandle, SvxTPFilter* );
DECL_LINK( FilterModified, SvxTPFilter* );
DECL_LINK( MinSizeHandle, SvxAcceptChgCtr*);
DECL_LINK( RejectHandle, SvxTPView*);
DECL_LINK( AcceptHandle, SvxTPView*);
DECL_LINK( RejectAllHandle, SvxTPView*);
DECL_LINK( AcceptAllHandle, SvxTPView*);
DECL_LINK( ExpandingHandle, SvxRedlinTable*);
DECL_LINK( SelectHandle, SvxRedlinTable*);
DECL_LINK( RefInfoHandle, String*);
DECL_LINK( UpdateSelectionHdl, Timer*);
DECL_LINK( ChgTrackModHdl, ScChangeTrack*);
DECL_LINK( CommandHdl, Control*);
DECL_LINK( ReOpenTimerHdl, Timer*);
DECL_LINK( ColCompareHdl, SvSortData*);
protected:
virtual void Resize();
virtual BOOL Close();
void RejectFiltered();
void AcceptFiltered();
BOOL IsValidAction(const ScChangeAction* pScChangeAction);
String* MakeTypeString(ScChangeActionType eType);
SvLBoxEntry* InsertChangeAction(const ScChangeAction* pScChangeAction,ScChangeActionState eState,
SvLBoxEntry* pParent=NULL,BOOL bDelMaster=FALSE,
BOOL bDisabled=FALSE,ULONG nPos=LIST_APPEND);
SvLBoxEntry* InsertFilteredAction(const ScChangeAction* pScChangeAction,ScChangeActionState eState,
SvLBoxEntry* pParent=NULL,BOOL bDelMaster=FALSE,
BOOL bDisabled=FALSE,ULONG nPos=LIST_APPEND);
SvLBoxEntry* InsertChangeActionContent(const ScChangeActionContent* pScChangeAction,
SvLBoxEntry* pParent,ULONG nSpecial);
void GetDependents( const ScChangeAction* pScChangeAction,
ScChangeActionTable& aActionTable,
SvLBoxEntry* pEntry);
BOOL InsertContentChilds(ScChangeActionTable* pActionTable,SvLBoxEntry* pParent);
BOOL InsertAcceptedORejected(SvLBoxEntry* pParent);
BOOL InsertDeletedChilds(const ScChangeAction *pChangeAction, ScChangeActionTable* pActionTable,
SvLBoxEntry* pParent);
BOOL InsertChilds(ScChangeActionTable* pActionTable,SvLBoxEntry* pParent);
void AppendChanges(ScChangeTrack* pChanges,ULONG nStartAction, ULONG nEndAction,
ULONG nPos=LIST_APPEND);
void RemoveEntrys(ULONG nStartAction,ULONG nEndAction);
void UpdateEntrys(ScChangeTrack* pChgTrack, ULONG nStartAction,ULONG nEndAction);
void UpdateView();
void ClearView();
BOOL Expand(ScChangeTrack* pChanges,const ScChangeAction* pScChangeAction,
SvLBoxEntry* pEntry, BOOL bFilter=FALSE);
public:
ScAcceptChgDlg( SfxBindings* pB, SfxChildWindow* pCW, Window* pParent,
ScViewData* ptrViewData);
~ScAcceptChgDlg();
void ReInit(ScViewData* ptrViewData);
virtual long PreNotify( NotifyEvent& rNEvt );
void Initialize (SfxChildWinInfo* pInfo);
virtual void FillInfo(SfxChildWinInfo&) const;
};
#endif // SC_NAMEDLG_HXX
<commit_msg>del: International<commit_after>/*************************************************************************
*
* $RCSfile: acredlin.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: er $ $Date: 2001-03-14 14:34:29 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef SC_ACREDLIN_HXX
#define SC_ACREDLIN_HXX
#ifndef VCL
#endif
#ifndef _MOREBTN_HXX //autogen
#include <vcl/morebtn.hxx>
#endif
#ifndef _COMBOBOX_HXX //autogen
#include <vcl/combobox.hxx>
#endif
#ifndef _GROUP_HXX //autogen
#include <vcl/group.hxx>
#endif
#ifndef _HEADBAR_HXX //autogen
#include <svtools/headbar.hxx>
#endif
#ifndef _SVTABBX_HXX //autogen
#include <svtools/svtabbx.hxx>
#endif
#ifndef SC_RANGENAM_HXX
#include "rangenam.hxx"
#endif
#ifndef SC_ANYREFDG_HXX
#include "anyrefdg.hxx"
#endif
#ifndef _SV_LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif
#ifndef _SVX_ACREDLIN_HXX
#include <svx/ctredlin.hxx>
#endif
#ifndef _SVX_SIMPTABL_HXX
#include <svx/simptabl.hxx>
#endif
#ifndef _SVARRAY_HXX
#define _SVARRAY_HXX
#include <svtools/svarray.hxx>
#endif
#ifndef SC_CHGTRACK_HXX
#include "chgtrack.hxx"
#endif
#ifndef SC_CHGVISET_HXX
#include "chgviset.hxx"
#endif
#ifndef _SV_TIMER_HXX //autogen
#include <vcl/timer.hxx>
#endif
class ScViewData;
class ScDocument;
#define FLT_DATE_BEFORE 0
#define FLT_DATE_SINCE 1
#define FLT_DATE_EQUAL 2
#define FLT_DATE_NOTEQUAL 3
#define FLT_DATE_BETWEEN 4
#define FLT_DATE_SAVE 5
class ScViewEntryPtr
{
private:
String* pAction;
String* pPos;
String* pAuthor;
String* pDate;
String* pComment;
void* pData;
public:
String* GetpAction() {return pAction; }
String* GetpPos() {return pPos; }
String* GetpAuthor() {return pAuthor; }
String* GetpDate() {return pDate; }
String* GetpComment() {return pComment;}
void* GetpData() {return pData; }
void SetpAction (String* pString) {pAction= pString;}
void SetpPos (String* pString) {pPos = pString;}
void SetpAuthor (String* pString) {pAuthor= pString;}
void SetpDate (String* pString) {pDate = pString;}
void SetpComment(String* pString) {pComment=pString;}
void SetpData (void* pdata) {pData =pdata;}
};
class ScViewEntryPtrList
{
ScViewEntryPtrList* pNext;
ScViewEntryPtrList* pLast;
ScViewEntryPtr* pData;
};
class ScRedlinData : public RedlinData
{
public:
ScRedlinData();
~ScRedlinData();
USHORT nTable;
USHORT nCol;
USHORT nRow;
ULONG nActionNo;
ULONG nInfo;
BOOL bIsRejectable;
BOOL bIsAcceptable;
};
typedef long LExpNum;
//@ Expand-Entrys nicht eindeutig, daher gestrichen
//DECLARE_TABLE( ScChgTrackExps, LExpNum)
//==================================================================
class ScAcceptChgDlg : public SfxModelessDialog
{
private:
Timer aSelectionTimer;
Timer aReOpenTimer;
SvxAcceptChgCtr aAcceptChgCtr;
ScViewData* pViewData;
ScDocument* pDoc;
ScRangeName aLocalRangeName;
Selection theCurSel;
SvxTPFilter* pTPFilter;
SvxTPView* pTPView;
SvxRedlinTable* pTheView;
Size MinSize;
ScRangeList aRangeList;
ScChangeViewSettings aChangeViewSet;
String aStrInsertCols;
String aStrInsertRows;
String aStrInsertTabs;
String aStrDeleteCols;
String aStrDeleteRows;
String aStrDeleteTabs;
String aStrMove;
String aStrContent;
String aStrReject;
String aUnknown;
String aStrAllAccepted;
String aStrAllRejected;
String aStrNoEntry;
String aStrContentWithChild;
String aStrChildContent;
String aStrChildOrgContent;
String aStrEmpty;
Bitmap aExpBmp;
Bitmap aCollBmp;
Bitmap aCloseBmp;
Bitmap aOpenBmp;
Bitmap aEndBmp;
Bitmap aErrorBmp;
ULONG nAcceptCount;
ULONG nRejectCount;
BOOL bAcceptEnableFlag;
BOOL bRejectEnableFlag;
BOOL bNeedsUpdate;
BOOL bIgnoreMsg;
BOOL bNoSelection;
BOOL bHasFilterEntry;
BOOL bUseColor;
//ScChgTrackExps aExpandArray;
void Init();
void InitFilter();
void SetMyStaticData();
DECL_LINK( FilterHandle, SvxTPFilter* );
DECL_LINK( RefHandle, SvxTPFilter* );
DECL_LINK( FilterModified, SvxTPFilter* );
DECL_LINK( MinSizeHandle, SvxAcceptChgCtr*);
DECL_LINK( RejectHandle, SvxTPView*);
DECL_LINK( AcceptHandle, SvxTPView*);
DECL_LINK( RejectAllHandle, SvxTPView*);
DECL_LINK( AcceptAllHandle, SvxTPView*);
DECL_LINK( ExpandingHandle, SvxRedlinTable*);
DECL_LINK( SelectHandle, SvxRedlinTable*);
DECL_LINK( RefInfoHandle, String*);
DECL_LINK( UpdateSelectionHdl, Timer*);
DECL_LINK( ChgTrackModHdl, ScChangeTrack*);
DECL_LINK( CommandHdl, Control*);
DECL_LINK( ReOpenTimerHdl, Timer*);
DECL_LINK( ColCompareHdl, SvSortData*);
protected:
virtual void Resize();
virtual BOOL Close();
void RejectFiltered();
void AcceptFiltered();
BOOL IsValidAction(const ScChangeAction* pScChangeAction);
String* MakeTypeString(ScChangeActionType eType);
SvLBoxEntry* InsertChangeAction(const ScChangeAction* pScChangeAction,ScChangeActionState eState,
SvLBoxEntry* pParent=NULL,BOOL bDelMaster=FALSE,
BOOL bDisabled=FALSE,ULONG nPos=LIST_APPEND);
SvLBoxEntry* InsertFilteredAction(const ScChangeAction* pScChangeAction,ScChangeActionState eState,
SvLBoxEntry* pParent=NULL,BOOL bDelMaster=FALSE,
BOOL bDisabled=FALSE,ULONG nPos=LIST_APPEND);
SvLBoxEntry* InsertChangeActionContent(const ScChangeActionContent* pScChangeAction,
SvLBoxEntry* pParent,ULONG nSpecial);
void GetDependents( const ScChangeAction* pScChangeAction,
ScChangeActionTable& aActionTable,
SvLBoxEntry* pEntry);
BOOL InsertContentChilds(ScChangeActionTable* pActionTable,SvLBoxEntry* pParent);
BOOL InsertAcceptedORejected(SvLBoxEntry* pParent);
BOOL InsertDeletedChilds(const ScChangeAction *pChangeAction, ScChangeActionTable* pActionTable,
SvLBoxEntry* pParent);
BOOL InsertChilds(ScChangeActionTable* pActionTable,SvLBoxEntry* pParent);
void AppendChanges(ScChangeTrack* pChanges,ULONG nStartAction, ULONG nEndAction,
ULONG nPos=LIST_APPEND);
void RemoveEntrys(ULONG nStartAction,ULONG nEndAction);
void UpdateEntrys(ScChangeTrack* pChgTrack, ULONG nStartAction,ULONG nEndAction);
void UpdateView();
void ClearView();
BOOL Expand(ScChangeTrack* pChanges,const ScChangeAction* pScChangeAction,
SvLBoxEntry* pEntry, BOOL bFilter=FALSE);
public:
ScAcceptChgDlg( SfxBindings* pB, SfxChildWindow* pCW, Window* pParent,
ScViewData* ptrViewData);
~ScAcceptChgDlg();
void ReInit(ScViewData* ptrViewData);
virtual long PreNotify( NotifyEvent& rNEvt );
void Initialize (SfxChildWinInfo* pInfo);
virtual void FillInfo(SfxChildWinInfo&) const;
};
#endif // SC_NAMEDLG_HXX
<|endoftext|> |
<commit_before><commit_msg>tdf#91015 - CSV dialog crasher.<commit_after><|endoftext|> |
<commit_before>/*************************************************************************/
/* remote_transform.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "remote_transform.h"
void RemoteTransform::_update_cache() {
cache = 0;
if (has_node(remote_node)) {
Node *node = get_node(remote_node);
if (!node || this == node || node->is_a_parent_of(this) || this->is_a_parent_of(node)) {
return;
}
cache = node->get_instance_id();
}
}
void RemoteTransform::_update_remote() {
if (!is_inside_tree())
return;
if (!cache)
return;
Spatial *n = Object::cast_to<Spatial>(ObjectDB::get_instance(cache));
if (!n)
return;
if (!n->is_inside_tree())
return;
//todo make faster
if (use_global_coordinates) {
if (update_remote_position && update_remote_rotation && update_remote_scale) {
n->set_global_transform(get_global_transform());
} else {
Transform n_trans = n->get_global_transform();
Transform our_trans = get_global_transform();
if (!update_remote_position)
our_trans.set_origin(n_trans.get_origin());
n->set_global_transform(our_trans);
if (!update_remote_rotation)
n->set_rotation(n_trans.basis.get_rotation());
if (!update_remote_scale)
n->set_scale(n_trans.basis.get_scale());
}
} else {
if (update_remote_position && update_remote_rotation && update_remote_scale) {
n->set_global_transform(get_global_transform());
} else {
Transform n_trans = n->get_transform();
Transform our_trans = get_transform();
if (!update_remote_position)
our_trans.set_origin(n_trans.get_origin());
n->set_transform(our_trans);
if (!update_remote_rotation)
n->set_rotation(n_trans.basis.get_rotation());
if (!update_remote_scale)
n->set_scale(n_trans.basis.get_scale());
}
}
}
void RemoteTransform::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_READY: {
_update_cache();
} break;
case NOTIFICATION_TRANSFORM_CHANGED: {
if (!is_inside_tree())
break;
if (cache) {
_update_remote();
}
} break;
}
}
void RemoteTransform::set_remote_node(const NodePath &p_remote_node) {
remote_node = p_remote_node;
if (is_inside_tree()) {
_update_cache();
_update_remote();
}
update_configuration_warning();
}
NodePath RemoteTransform::get_remote_node() const {
return remote_node;
}
void RemoteTransform::set_use_global_coordinates(const bool p_enable) {
use_global_coordinates = p_enable;
}
bool RemoteTransform::get_use_global_coordinates() const {
return use_global_coordinates;
}
void RemoteTransform::set_update_position(const bool p_update) {
update_remote_position = p_update;
_update_remote();
}
bool RemoteTransform::get_update_position() const {
return update_remote_position;
}
void RemoteTransform::set_update_rotation(const bool p_update) {
update_remote_rotation = p_update;
_update_remote();
}
bool RemoteTransform::get_update_rotation() const {
return update_remote_rotation;
}
void RemoteTransform::set_update_scale(const bool p_update) {
update_remote_scale = p_update;
_update_remote();
}
bool RemoteTransform::get_update_scale() const {
return update_remote_scale;
}
String RemoteTransform::get_configuration_warning() const {
if (!has_node(remote_node) || !Object::cast_to<Spatial>(get_node(remote_node))) {
return TTR("Path property must point to a valid Spatial node to work.");
}
return String();
}
void RemoteTransform::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_remote_node", "path"), &RemoteTransform::set_remote_node);
ClassDB::bind_method(D_METHOD("get_remote_node"), &RemoteTransform::get_remote_node);
ClassDB::bind_method(D_METHOD("set_use_global_coordinates", "use_global_coordinates"), &RemoteTransform::set_use_global_coordinates);
ClassDB::bind_method(D_METHOD("get_use_global_coordinates"), &RemoteTransform::get_use_global_coordinates);
ClassDB::bind_method(D_METHOD("set_update_position", "update_remote_position"), &RemoteTransform::set_update_position);
ClassDB::bind_method(D_METHOD("get_update_position"), &RemoteTransform::get_update_position);
ClassDB::bind_method(D_METHOD("set_update_rotation", "update_remote_rotation"), &RemoteTransform::set_update_rotation);
ClassDB::bind_method(D_METHOD("get_update_rotation"), &RemoteTransform::get_update_rotation);
ClassDB::bind_method(D_METHOD("set_update_scale", "update_remote_scale"), &RemoteTransform::set_update_scale);
ClassDB::bind_method(D_METHOD("get_update_scale"), &RemoteTransform::get_update_scale);
ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "remote_path", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Spatial"), "set_remote_node", "get_remote_node");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_global_coordinates"), "set_use_global_coordinates", "get_use_global_coordinates");
ADD_GROUP("Update", "update_");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "update_position"), "set_update_position", "get_update_position");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "update_rotation"), "set_update_rotation", "get_update_rotation");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "update_scale"), "set_update_scale", "get_update_scale");
}
RemoteTransform::RemoteTransform() {
use_global_coordinates = true;
update_remote_position = true;
update_remote_rotation = true;
update_remote_scale = true;
cache = 0;
set_notify_transform(true);
}
<commit_msg>Fix properties update in remote transform<commit_after>/*************************************************************************/
/* remote_transform.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "remote_transform.h"
void RemoteTransform::_update_cache() {
cache = 0;
if (has_node(remote_node)) {
Node *node = get_node(remote_node);
if (!node || this == node || node->is_a_parent_of(this) || this->is_a_parent_of(node)) {
return;
}
cache = node->get_instance_id();
}
}
void RemoteTransform::_update_remote() {
if (!is_inside_tree())
return;
if (!cache)
return;
Spatial *n = Object::cast_to<Spatial>(ObjectDB::get_instance(cache));
if (!n)
return;
if (!n->is_inside_tree())
return;
//todo make faster
if (use_global_coordinates) {
if (update_remote_position && update_remote_rotation && update_remote_scale) {
n->set_global_transform(get_global_transform());
} else {
Transform our_trans = get_global_transform();
if (update_remote_rotation)
n->set_rotation(our_trans.basis.get_rotation());
if (update_remote_scale)
n->set_scale(our_trans.basis.get_scale());
if (update_remote_position) {
Transform n_trans = n->get_global_transform();
n_trans.set_origin(our_trans.get_origin());
n->set_global_transform(n_trans);
}
}
} else {
if (update_remote_position && update_remote_rotation && update_remote_scale) {
n->set_transform(get_transform());
} else {
Transform our_trans = get_transform();
if (update_remote_rotation)
n->set_rotation(our_trans.basis.get_rotation());
if (update_remote_scale)
n->set_scale(our_trans.basis.get_scale());
if (update_remote_position) {
Transform n_trans = n->get_transform();
n_trans.set_origin(our_trans.get_origin());
n->set_transform(n_trans);
}
}
}
}
void RemoteTransform::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_READY: {
_update_cache();
} break;
case NOTIFICATION_TRANSFORM_CHANGED: {
if (!is_inside_tree())
break;
if (cache) {
_update_remote();
}
} break;
}
}
void RemoteTransform::set_remote_node(const NodePath &p_remote_node) {
remote_node = p_remote_node;
if (is_inside_tree()) {
_update_cache();
_update_remote();
}
update_configuration_warning();
}
NodePath RemoteTransform::get_remote_node() const {
return remote_node;
}
void RemoteTransform::set_use_global_coordinates(const bool p_enable) {
use_global_coordinates = p_enable;
}
bool RemoteTransform::get_use_global_coordinates() const {
return use_global_coordinates;
}
void RemoteTransform::set_update_position(const bool p_update) {
update_remote_position = p_update;
_update_remote();
}
bool RemoteTransform::get_update_position() const {
return update_remote_position;
}
void RemoteTransform::set_update_rotation(const bool p_update) {
update_remote_rotation = p_update;
_update_remote();
}
bool RemoteTransform::get_update_rotation() const {
return update_remote_rotation;
}
void RemoteTransform::set_update_scale(const bool p_update) {
update_remote_scale = p_update;
_update_remote();
}
bool RemoteTransform::get_update_scale() const {
return update_remote_scale;
}
String RemoteTransform::get_configuration_warning() const {
if (!has_node(remote_node) || !Object::cast_to<Spatial>(get_node(remote_node))) {
return TTR("Path property must point to a valid Spatial node to work.");
}
return String();
}
void RemoteTransform::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_remote_node", "path"), &RemoteTransform::set_remote_node);
ClassDB::bind_method(D_METHOD("get_remote_node"), &RemoteTransform::get_remote_node);
ClassDB::bind_method(D_METHOD("set_use_global_coordinates", "use_global_coordinates"), &RemoteTransform::set_use_global_coordinates);
ClassDB::bind_method(D_METHOD("get_use_global_coordinates"), &RemoteTransform::get_use_global_coordinates);
ClassDB::bind_method(D_METHOD("set_update_position", "update_remote_position"), &RemoteTransform::set_update_position);
ClassDB::bind_method(D_METHOD("get_update_position"), &RemoteTransform::get_update_position);
ClassDB::bind_method(D_METHOD("set_update_rotation", "update_remote_rotation"), &RemoteTransform::set_update_rotation);
ClassDB::bind_method(D_METHOD("get_update_rotation"), &RemoteTransform::get_update_rotation);
ClassDB::bind_method(D_METHOD("set_update_scale", "update_remote_scale"), &RemoteTransform::set_update_scale);
ClassDB::bind_method(D_METHOD("get_update_scale"), &RemoteTransform::get_update_scale);
ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "remote_path", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Spatial"), "set_remote_node", "get_remote_node");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_global_coordinates"), "set_use_global_coordinates", "get_use_global_coordinates");
ADD_GROUP("Update", "update_");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "update_position"), "set_update_position", "get_update_position");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "update_rotation"), "set_update_rotation", "get_update_rotation");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "update_scale"), "set_update_scale", "get_update_scale");
}
RemoteTransform::RemoteTransform() {
use_global_coordinates = true;
update_remote_position = true;
update_remote_rotation = true;
update_remote_scale = true;
cache = 0;
set_notify_transform(true);
}
<|endoftext|> |
<commit_before>#include <sstream> // ostringstream
#include <iomanip> // std::setw
#include <stdio.h> // printf
#include "allocore/math/al_Constants.hpp"
#include "allocore/system/al_Time.hpp"
/* Windows */
#if defined(AL_WINDOWS)
#include <windows.h>
/*
Info on Windows timing:
http://windowstimestamp.com/description
*/
/*
// singleton object to force init/quit of timing
static struct TimeSingleton{
TimeSingleton(){ timeBeginPeriod(1); }
~TimeSingleton(){ timeEndPeriod(1); }
} timeSingleton;
// interface to Windows API
static DWORD time_ms(){ return timeGetTime(); }
static void sleep_ms(unsigned long long ms){ Sleep(DWORD(ms)); }
// allocore definitions
al_sec al_time(){ return time_ms() * 1e-3; }
al_nsec al_time_nsec(){ return al_nsec(time_ms()) * al_nsec(1e6); }
void al_sleep(al_sec v){ sleep_ms(v * 1e3); }
void al_sleep_nsec(al_nsec v){ sleep_ms(v / 1e6); }
//*/
//*
static void sleep_ms(unsigned long long ms){ Sleep(DWORD(ms)); }
// Method to supposedly get microsecond sleep
// From: http://blogs.msdn.com/b/cellfish/archive/2008/09/17/sleep-less-than-one-millisecond.aspx
/*
#include <Winsock2.h> // SOCKET
static int sleep_us(long usec){
static bool first = true;
if(first){
first = false;
WORD wVersionRequested = MAKEWORD(1,0);
WSADATA wsaData;
WSAStartup(wVersionRequested, &wsaData);
}
struct timeval tv;
fd_set dummy;
SOCKET s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
FD_ZERO(&dummy);
FD_SET(s, &dummy);
tv.tv_sec = usec/1000000L;
tv.tv_usec = usec%1000000L;
return select(0, 0, 0, &dummy, &tv);
}*/
// system time as 100-nanosecond interval
al_nsec system_time_100ns(){
SYSTEMTIME st;
GetSystemTime(&st);
//printf("%d/%d/%d %d:%d:%d\n", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
FILETIME time;
SystemTimeToFileTime(&st, &time);
//GetSystemTimeAsFileTime(&time);
ULARGE_INTEGER timeULI = {{time.dwLowDateTime, time.dwHighDateTime}};
al_nsec res = timeULI.QuadPart; // in 100-nanosecond intervals
res -= al_nsec(116444736000000000); // convert epoch from 1601 to 1970
return res;
}
al_nsec steady_time_us(){
// Windows 10 and above
//PULONGLONG time;
//QueryInterruptTimePrecise(&time);
LARGE_INTEGER freq; // ticks/second
LARGE_INTEGER time; // tick count
QueryPerformanceFrequency(&freq);
QueryPerformanceCounter(&time);
// convert ticks to microseconds
time.QuadPart *= 1000000;
time.QuadPart /= freq.QuadPart;
return al_nsec(time.QuadPart);
}
al_sec al_system_time(){ return system_time_100ns() * 1e-7; }
al_nsec al_system_time_nsec(){ return system_time_100ns() * al_nsec(100); }
al_sec al_steady_time(){ return steady_time_us() * 1e-6; }
al_nsec al_steady_time_nsec(){ return steady_time_us() * al_nsec(1e3); }
void al_sleep(al_sec v){ sleep_ms(v * 1e3); }
void al_sleep_nsec(al_nsec v){ sleep_ms(v / 1e6); }
//void al_sleep(al_sec v){ sleep_us(v * 1e6); }
//void al_sleep_nsec(al_nsec v){ sleep_us(v / 1e3); }
//*/
/* Posix (Mac, Linux) */
#else
#include <time.h> // nanosleep, clock_gettime
#include <sys/time.h> // gettimeofday
#include <unistd.h> // _POSIX_TIMERS
al_sec al_system_time(){
timeval t;
gettimeofday(&t, NULL);
return al_sec(t.tv_sec) + al_sec(t.tv_usec) * 1e-6;
}
al_nsec al_system_time_nsec(){
timeval t;
gettimeofday(&t, NULL);
return al_nsec(t.tv_sec) * al_nsec(1e9) + al_nsec(t.tv_usec) * al_nsec(1e3);
}
#ifdef AL_OSX
#include <mach/mach_time.h>
// Code from:
// http://stackoverflow.com/questions/23378063/how-can-i-use-mach-absolute-time-without-overflowing
al_sec al_steady_time(){
return al_steady_time_nsec() * 1e-9;
}
al_nsec al_steady_time_nsec(){
uint64_t now = mach_absolute_time();
static struct Data {
Data(uint64_t bias_) : bias(bias_) {
mach_timebase_info(&tb);
if (tb.denom > 1024) {
double frac = (double)tb.numer/tb.denom;
tb.denom = 1024;
tb.numer = tb.denom * frac + 0.5;
}
}
mach_timebase_info_data_t tb;
uint64_t bias;
} data(now);
return (now - data.bias) * data.tb.numer / data.tb.denom;
}
// Posix timers available?
#elif _POSIX_TIMERS > 0 && defined(_POSIX_MONOTONIC_CLOCK)
al_sec al_steady_time(){
struct timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
return al_sec(t.tv_sec) + al_sec(t.tv_nsec) * 1e-9;
}
al_nsec al_steady_time_nsec(){
struct timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
return al_nsec(t.tv_sec) * al_nsec(1e9) + al_nsec(t.tv_nsec);
}
// Otherwise fallback to system time
#else
al_sec al_steady_time(){
return al_system_time();
}
al_nsec al_steady_time_nsec(){
return al_system_time_nsec();
}
#endif
void al_sleep(al_sec v) {
time_t sec = (time_t)v;
al_nsec nsec = al_time_s2ns * (v - (al_sec)sec);
timespec tspec = { sec, nsec };
while (nanosleep(&tspec, &tspec) == -1)
continue;
}
void al_sleep_nsec(al_nsec v) {
al_sleep((al_sec)v * al_time_ns2s);
}
#endif
/* end platform specific */
void al_sleep_until(al_sec target) {
al_sec dt = target - al_time();
if (dt > 0) al_sleep(dt);
}
al_sec al_time(){ return al_system_time(); }
al_nsec al_time_nsec(){ return al_system_time_nsec(); }
namespace al {
std::string toTimecode(al_nsec t, const std::string& format){
unsigned day = t/(al_nsec(1000000000) * 60 * 60 * 24); // basically for overflow
unsigned hrs = t/(al_nsec(1000000000) * 60 * 60) % 24;
unsigned min = t/(al_nsec(1000000000) * 60) % 60;
unsigned sec = t/(al_nsec(1000000000)) % 60;
unsigned msc = t/(al_nsec(1000000)) % 1000;
unsigned usc = t/(al_nsec(1000)) % 1000;
std::ostringstream s;
s.fill('0');
for(unsigned i=0; i<format.size(); ++i){
const auto c = format[i];
switch(c){
case 'D': s << day; break;
case 'H': s << std::setw(2) << hrs; break;
case 'M': s << std::setw(2) << min; break;
case 'S': s << std::setw(2) << sec; break;
case 'm': s << std::setw(3) << msc; break;
case 'u': s << std::setw(3) << usc; break;
default: s << c;
}
}
return s.str();
}
std::string timecodeNow(const std::string& format){
return toTimecode(al_system_time_nsec(), format);
}
void Timer::print() const {
auto t = getTime();
auto dt = t-mStart;
double dtSec = al_time_ns2s * dt;
printf("%g sec (%g ms) elapsed\n", dtSec, dtSec*1000.);
}
void DelayLockedLoop :: setBandwidth(double bandwidth) {
double F = 1./tperiod; // step rate
double omega = M_PI * 2.8 * bandwidth/F;
mB = omega * sqrt(2.); // 1st-order weight
mC = omega * omega; // 2nd-order weight
}
void DelayLockedLoop :: step(al_sec realtime) {
if (mReset) {
// The first iteration sets initial conditions.
// init loop
t2 = tperiod;
t0 = realtime;
t1 = t0 + t2; // t1 is ideally the timestamp of the next block start
// subsequent iterations use the other branch:
mReset = false;
} else {
// read timer and calculate loop error
// e.g. if t1 underestimated, terr will be
al_sec terr = realtime - t1;
// update loop
t0 = t1; // 0th-order (distance)
t1 += mB * terr + t2; // integration of 1st-order (velocity)
t2 += mC * terr; // integration of 2nd-order (acceleration)
}
// // now t0 is the current system time, and t1 is the estimated system time at the next step
// //
// al_sec tper_estimate = t1-t0; // estimated real duration between this step & the next one
// double factor = tperiod/tper_estimate; // <1 if we are too slow, >1 if we are too fast
// double real_rate = 1./tper_estimate;
// al_sec tper_estimate2 = t2; // estimated real duration between this step & the next one
// double factor2 = 1./t2; // <1 if we are too slow, >1 if we are too fast
// printf("factor %f %f rate %f\n", factor, factor2, real_rate);
}
} // al::
<commit_msg>Fix narrowing error in initializer<commit_after>#include <sstream> // ostringstream
#include <iomanip> // std::setw
#include <stdio.h> // printf
#include "allocore/math/al_Constants.hpp"
#include "allocore/system/al_Time.hpp"
/* Windows */
#if defined(AL_WINDOWS)
#include <windows.h>
/*
Info on Windows timing:
http://windowstimestamp.com/description
*/
/*
// singleton object to force init/quit of timing
static struct TimeSingleton{
TimeSingleton(){ timeBeginPeriod(1); }
~TimeSingleton(){ timeEndPeriod(1); }
} timeSingleton;
// interface to Windows API
static DWORD time_ms(){ return timeGetTime(); }
static void sleep_ms(unsigned long long ms){ Sleep(DWORD(ms)); }
// allocore definitions
al_sec al_time(){ return time_ms() * 1e-3; }
al_nsec al_time_nsec(){ return al_nsec(time_ms()) * al_nsec(1e6); }
void al_sleep(al_sec v){ sleep_ms(v * 1e3); }
void al_sleep_nsec(al_nsec v){ sleep_ms(v / 1e6); }
//*/
//*
static void sleep_ms(unsigned long long ms){ Sleep(DWORD(ms)); }
// Method to supposedly get microsecond sleep
// From: http://blogs.msdn.com/b/cellfish/archive/2008/09/17/sleep-less-than-one-millisecond.aspx
/*
#include <Winsock2.h> // SOCKET
static int sleep_us(long usec){
static bool first = true;
if(first){
first = false;
WORD wVersionRequested = MAKEWORD(1,0);
WSADATA wsaData;
WSAStartup(wVersionRequested, &wsaData);
}
struct timeval tv;
fd_set dummy;
SOCKET s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
FD_ZERO(&dummy);
FD_SET(s, &dummy);
tv.tv_sec = usec/1000000L;
tv.tv_usec = usec%1000000L;
return select(0, 0, 0, &dummy, &tv);
}*/
// system time as 100-nanosecond interval
al_nsec system_time_100ns(){
SYSTEMTIME st;
GetSystemTime(&st);
//printf("%d/%d/%d %d:%d:%d\n", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
FILETIME time;
SystemTimeToFileTime(&st, &time);
//GetSystemTimeAsFileTime(&time);
ULARGE_INTEGER timeULI = {{time.dwLowDateTime, time.dwHighDateTime}};
al_nsec res = timeULI.QuadPart; // in 100-nanosecond intervals
res -= al_nsec(116444736000000000); // convert epoch from 1601 to 1970
return res;
}
al_nsec steady_time_us(){
// Windows 10 and above
//PULONGLONG time;
//QueryInterruptTimePrecise(&time);
LARGE_INTEGER freq; // ticks/second
LARGE_INTEGER time; // tick count
QueryPerformanceFrequency(&freq);
QueryPerformanceCounter(&time);
// convert ticks to microseconds
time.QuadPart *= 1000000;
time.QuadPart /= freq.QuadPart;
return al_nsec(time.QuadPart);
}
al_sec al_system_time(){ return system_time_100ns() * 1e-7; }
al_nsec al_system_time_nsec(){ return system_time_100ns() * al_nsec(100); }
al_sec al_steady_time(){ return steady_time_us() * 1e-6; }
al_nsec al_steady_time_nsec(){ return steady_time_us() * al_nsec(1e3); }
void al_sleep(al_sec v){ sleep_ms(v * 1e3); }
void al_sleep_nsec(al_nsec v){ sleep_ms(v / 1e6); }
//void al_sleep(al_sec v){ sleep_us(v * 1e6); }
//void al_sleep_nsec(al_nsec v){ sleep_us(v / 1e3); }
//*/
/* Posix (Mac, Linux) */
#else
#include <time.h> // nanosleep, clock_gettime
#include <sys/time.h> // gettimeofday
#include <unistd.h> // _POSIX_TIMERS
al_sec al_system_time(){
timeval t;
gettimeofday(&t, NULL);
return al_sec(t.tv_sec) + al_sec(t.tv_usec) * 1e-6;
}
al_nsec al_system_time_nsec(){
timeval t;
gettimeofday(&t, NULL);
return al_nsec(t.tv_sec) * al_nsec(1e9) + al_nsec(t.tv_usec) * al_nsec(1e3);
}
#ifdef AL_OSX
#include <mach/mach_time.h>
// Code from:
// http://stackoverflow.com/questions/23378063/how-can-i-use-mach-absolute-time-without-overflowing
al_sec al_steady_time(){
return al_steady_time_nsec() * 1e-9;
}
al_nsec al_steady_time_nsec(){
uint64_t now = mach_absolute_time();
static struct Data {
Data(uint64_t bias_) : bias(bias_) {
mach_timebase_info(&tb);
if (tb.denom > 1024) {
double frac = (double)tb.numer/tb.denom;
tb.denom = 1024;
tb.numer = tb.denom * frac + 0.5;
}
}
mach_timebase_info_data_t tb;
uint64_t bias;
} data(now);
return (now - data.bias) * data.tb.numer / data.tb.denom;
}
// Posix timers available?
#elif _POSIX_TIMERS > 0 && defined(_POSIX_MONOTONIC_CLOCK)
al_sec al_steady_time(){
struct timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
return al_sec(t.tv_sec) + al_sec(t.tv_nsec) * 1e-9;
}
al_nsec al_steady_time_nsec(){
struct timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
return al_nsec(t.tv_sec) * al_nsec(1e9) + al_nsec(t.tv_nsec);
}
// Otherwise fallback to system time
#else
al_sec al_steady_time(){
return al_system_time();
}
al_nsec al_steady_time_nsec(){
return al_system_time_nsec();
}
#endif
void al_sleep(al_sec v) {
time_t sec = time_t(v);
al_nsec nsec = al_time_s2ns * (v - al_sec(sec));
timespec tspec = { sec, long(nsec) };
while (nanosleep(&tspec, &tspec) == -1)
continue;
}
void al_sleep_nsec(al_nsec v) {
al_sleep(al_sec(v) * al_time_ns2s);
}
#endif
/* end platform specific */
void al_sleep_until(al_sec target) {
al_sec dt = target - al_time();
if (dt > 0) al_sleep(dt);
}
al_sec al_time(){ return al_system_time(); }
al_nsec al_time_nsec(){ return al_system_time_nsec(); }
namespace al {
std::string toTimecode(al_nsec t, const std::string& format){
unsigned day = t/(al_nsec(1000000000) * 60 * 60 * 24); // basically for overflow
unsigned hrs = t/(al_nsec(1000000000) * 60 * 60) % 24;
unsigned min = t/(al_nsec(1000000000) * 60) % 60;
unsigned sec = t/(al_nsec(1000000000)) % 60;
unsigned msc = t/(al_nsec(1000000)) % 1000;
unsigned usc = t/(al_nsec(1000)) % 1000;
std::ostringstream s;
s.fill('0');
for(unsigned i=0; i<format.size(); ++i){
const auto c = format[i];
switch(c){
case 'D': s << day; break;
case 'H': s << std::setw(2) << hrs; break;
case 'M': s << std::setw(2) << min; break;
case 'S': s << std::setw(2) << sec; break;
case 'm': s << std::setw(3) << msc; break;
case 'u': s << std::setw(3) << usc; break;
default: s << c;
}
}
return s.str();
}
std::string timecodeNow(const std::string& format){
return toTimecode(al_system_time_nsec(), format);
}
void Timer::print() const {
auto t = getTime();
auto dt = t-mStart;
double dtSec = al_time_ns2s * dt;
printf("%g sec (%g ms) elapsed\n", dtSec, dtSec*1000.);
}
void DelayLockedLoop :: setBandwidth(double bandwidth) {
double F = 1./tperiod; // step rate
double omega = M_PI * 2.8 * bandwidth/F;
mB = omega * sqrt(2.); // 1st-order weight
mC = omega * omega; // 2nd-order weight
}
void DelayLockedLoop :: step(al_sec realtime) {
if (mReset) {
// The first iteration sets initial conditions.
// init loop
t2 = tperiod;
t0 = realtime;
t1 = t0 + t2; // t1 is ideally the timestamp of the next block start
// subsequent iterations use the other branch:
mReset = false;
} else {
// read timer and calculate loop error
// e.g. if t1 underestimated, terr will be
al_sec terr = realtime - t1;
// update loop
t0 = t1; // 0th-order (distance)
t1 += mB * terr + t2; // integration of 1st-order (velocity)
t2 += mC * terr; // integration of 2nd-order (acceleration)
}
// // now t0 is the current system time, and t1 is the estimated system time at the next step
// //
// al_sec tper_estimate = t1-t0; // estimated real duration between this step & the next one
// double factor = tperiod/tper_estimate; // <1 if we are too slow, >1 if we are too fast
// double real_rate = 1./tper_estimate;
// al_sec tper_estimate2 = t2; // estimated real duration between this step & the next one
// double factor2 = 1./t2; // <1 if we are too slow, >1 if we are too fast
// printf("factor %f %f rate %f\n", factor, factor2, real_rate);
}
} // al::
<|endoftext|> |
<commit_before>/**
* \file
* \brief ConditionVariableOperationsTestCase class implementation
*
* \author Copyright (C) 2014-2015 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/.
*
* \date 2015-11-11
*/
#include "ConditionVariableOperationsTestCase.hpp"
#include "waitForNextTick.hpp"
#include "Mutex/mutexTestTryLockWhenLocked.hpp"
#include "distortos/ConditionVariable.hpp"
#include "distortos/Mutex.hpp"
#include "distortos/ThisThread.hpp"
#include "distortos/StaticSoftwareTimer.hpp"
#include "distortos/StaticThread.hpp"
#include "distortos/statistics.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 testMutexAndUnlock(): main -> idle -> main
constexpr decltype(statistics::getContextSwitchCount()) testMutexAndUnlockContextSwitchCount
{
waitForNextTickContextSwitchCount + 2
};
/// expected number of context switches in phase1 block involving waitFor() or waitUntil() (excluding
/// waitForNextTick() and testMutexAndUnlock()): 1 - main thread blocks on condition variable (main -> idle), 2 - main
/// thread wakes up (idle -> main)
constexpr decltype(statistics::getContextSwitchCount()) phase1WaitForUntilContextSwitchCount {2};
/// expected number of context switches in phase2 block involving test thread (excluding waitForNextTick() and
/// testMutexAndUnlock()): 1 - test thread starts (main -> test), 2 - test thread goes to sleep (test -> main), 3 - main
/// thread blocks on condition variable (main -> idle), 4 - test thread wakes (idle -> test), 5 - test thread terminates
/// (test -> main)
constexpr decltype(statistics::getContextSwitchCount()) phase2ThreadContextSwitchCount {5};
/// expected number of context switches in phase3 block involving software timer (excluding waitForNextTick() and
/// testMutexAndUnlock()): 1 - main thread blocks on condition variable (main -> idle), 2 - main thread is unblocked by
/// interrupt (idle -> main)
constexpr decltype(statistics::getContextSwitchCount()) phase3SoftwareTimerContextSwitchCount {2};
/*---------------------------------------------------------------------------------------------------------------------+
| local functions
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief Tests whether supplied mutex is properly locked and unlocks it.
*
* \param [in] mutex is a reference to mutex that will be tested and unlocked
*
* \return true if test succeeded and mutex was sucessfully unlocked, false otherwise
*/
bool testMutexAndUnlock(Mutex& mutex)
{
const auto testRet = mutexTestTryLockWhenLocked(mutex, UINT8_MAX);
const auto unlockRet = mutex.unlock();
return testRet == true && unlockRet == 0;
}
/**
* \brief Phase 1 of test case.
*
* Tests whether both waitFor() and waitUntil() functions properly return some error and properly handle mutex when
* timing out without notification.
*
* \param [in] mutex is a reference to mutex used with condition variable, must be unlocked
*
* \return true if test succeeded, false otherwise
*/
bool phase1(Mutex& mutex)
{
ConditionVariable conditionVariable;
{
const auto ret = mutex.lock();
if (ret != 0)
return false;
}
{
waitForNextTick();
// there will be no notification, so waitFor() should time-out at expected time
const auto contextSwitchCount = statistics::getContextSwitchCount();
const auto start = TickClock::now();
const auto ret = conditionVariable.waitFor(mutex, singleDuration);
const auto realDuration = TickClock::now() - start;
const auto contextSwitches = statistics::getContextSwitchCount() - contextSwitchCount;
const auto mutexTest = testMutexAndUnlock(mutex);
if (ret != ETIMEDOUT || realDuration != singleDuration + decltype(singleDuration){1} || mutexTest != true ||
contextSwitches != phase1WaitForUntilContextSwitchCount)
return false;
}
{
const auto ret = mutex.lock();
if (ret != 0)
return false;
}
{
waitForNextTick();
// there will be no notification, so waitUntil() should time-out at exact expected time
const auto contextSwitchCount = statistics::getContextSwitchCount();
const auto wakeUpTimePoint = TickClock::now() + singleDuration;
const auto ret = conditionVariable.waitUntil(mutex, wakeUpTimePoint);
const auto wokenUpTimePoint = TickClock::now();
const auto contextSwitches = statistics::getContextSwitchCount() - contextSwitchCount;
const auto mutexTest = testMutexAndUnlock(mutex);
if (ret != ETIMEDOUT || wakeUpTimePoint != wokenUpTimePoint || mutexTest != true ||
contextSwitches != phase1WaitForUntilContextSwitchCount)
return false;
}
return true;
}
/**
* \brief Phase 2 of test case.
*
* Tests thread-thread signaling scenario. Main (current) thread waits for condition variable notification (using
* wait(), waitFor() and waitUntil()). Test thread notifies one waiter at specified time point, main thread is expected
* to wake up and acquire ownership of the mutex in the same moment.
*
* \param [in] mutex is a reference to mutex used with condition variable, must be unlocked
*
* \return true if test succeeded, false otherwise
*/
bool phase2(Mutex& mutex)
{
constexpr size_t testThreadStackSize {384};
ConditionVariable conditionVariable;
const auto sleepUntilFunctor = [&conditionVariable](const TickClock::time_point timePoint)
{
ThisThread::sleepUntil(timePoint);
conditionVariable.notifyOne();
};
{
const auto ret = mutex.lock();
if (ret != 0)
return false;
}
{
waitForNextTick();
const auto contextSwitchCount = statistics::getContextSwitchCount();
const auto wakeUpTimePoint = TickClock::now() + longDuration;
auto thread = makeStaticThread<testThreadStackSize>(UINT8_MAX, sleepUntilFunctor, wakeUpTimePoint);
thread.start();
ThisThread::yield();
// wait() should succeed at expected time
const auto ret = conditionVariable.wait(mutex);
const auto wokenUpTimePoint = TickClock::now();
const auto contextSwitches = statistics::getContextSwitchCount() - contextSwitchCount;
thread.join();
const auto mutexTest = testMutexAndUnlock(mutex);
if (ret != 0 || wakeUpTimePoint != wokenUpTimePoint || mutexTest != true ||
contextSwitches != phase2ThreadContextSwitchCount)
return false;
}
{
const auto ret = mutex.lock();
if (ret != 0)
return false;
}
{
waitForNextTick();
const auto contextSwitchCount = statistics::getContextSwitchCount();
const auto wakeUpTimePoint = TickClock::now() + longDuration;
auto thread = makeStaticThread<testThreadStackSize>(UINT8_MAX, sleepUntilFunctor, wakeUpTimePoint);
thread.start();
ThisThread::yield();
// waitFor() should succeed at expected time
const auto ret = conditionVariable.waitFor(mutex, wakeUpTimePoint - TickClock::now() + longDuration);
const auto wokenUpTimePoint = TickClock::now();
const auto contextSwitches = statistics::getContextSwitchCount() - contextSwitchCount;
thread.join();
const auto mutexTest = testMutexAndUnlock(mutex);
if (ret != 0 || wakeUpTimePoint != wokenUpTimePoint || mutexTest != true ||
contextSwitches != phase2ThreadContextSwitchCount)
return false;
}
{
const auto ret = mutex.lock();
if (ret != 0)
return false;
}
{
waitForNextTick();
const auto contextSwitchCount = statistics::getContextSwitchCount();
const auto wakeUpTimePoint = TickClock::now() + longDuration;
auto thread = makeStaticThread<testThreadStackSize>(UINT8_MAX, sleepUntilFunctor, wakeUpTimePoint);
thread.start();
ThisThread::yield();
// waitUntil() should succeed at expected time
const auto ret = conditionVariable.waitUntil(mutex, wakeUpTimePoint + longDuration);
const auto wokenUpTimePoint = TickClock::now();
const auto contextSwitches = statistics::getContextSwitchCount() - contextSwitchCount;
thread.join();
const auto mutexTest = testMutexAndUnlock(mutex);
if (ret != 0 || wakeUpTimePoint != wokenUpTimePoint || mutexTest != true ||
contextSwitches != phase2ThreadContextSwitchCount)
return false;
}
return true;
}
/**
* \brief Phase 3 of test case.
*
* Tests interrupt-thread signaling scenario. Main (current) thread waits for condition variable notification (using
* wait(), waitFor() and waitUntil()). Software timer is used to notify one waiter at specified time point from
* interrupt context, main thread is expected to wake up and acquire ownership of the mutex in the same moment.
*
* \param [in] mutex is a reference to mutex used with condition variable, must be unlocked
*
* \return true if test succeeded, false otherwise
*/
bool phase3(Mutex& mutex)
{
ConditionVariable conditionVariable;
auto softwareTimer = makeStaticSoftwareTimer(&ConditionVariable::notifyOne, std::ref(conditionVariable));
{
const auto ret = mutex.lock();
if (ret != 0)
return false;
}
{
waitForNextTick();
const auto contextSwitchCount = statistics::getContextSwitchCount();
const auto wakeUpTimePoint = TickClock::now() + longDuration;
softwareTimer.start(wakeUpTimePoint);
// wait() should succeed at expected time
const auto ret = conditionVariable.wait(mutex);
const auto wokenUpTimePoint = TickClock::now();
const auto contextSwitches = statistics::getContextSwitchCount() - contextSwitchCount;
const auto mutexTest = testMutexAndUnlock(mutex);
if (ret != 0 || wakeUpTimePoint != wokenUpTimePoint || mutexTest != true ||
contextSwitches != phase3SoftwareTimerContextSwitchCount)
return false;
}
{
const auto ret = mutex.lock();
if (ret != 0)
return false;
}
{
waitForNextTick();
const auto contextSwitchCount = statistics::getContextSwitchCount();
const auto wakeUpTimePoint = TickClock::now() + longDuration;
softwareTimer.start(wakeUpTimePoint);
// waitFor() should succeed at expected time
const auto ret = conditionVariable.waitFor(mutex, wakeUpTimePoint - TickClock::now() + longDuration);
const auto wokenUpTimePoint = TickClock::now();
const auto contextSwitches = statistics::getContextSwitchCount() - contextSwitchCount;
const auto mutexTest = testMutexAndUnlock(mutex);
if (ret != 0 || wakeUpTimePoint != wokenUpTimePoint || mutexTest != true ||
contextSwitches != phase3SoftwareTimerContextSwitchCount)
return false;
}
{
const auto ret = mutex.lock();
if (ret != 0)
return false;
}
{
waitForNextTick();
const auto contextSwitchCount = statistics::getContextSwitchCount();
const auto wakeUpTimePoint = TickClock::now() + longDuration;
softwareTimer.start(wakeUpTimePoint);
// waitUntil() should succeed at expected time
const auto ret = conditionVariable.waitUntil(mutex, wakeUpTimePoint + longDuration);
const auto wokenUpTimePoint = TickClock::now();
const auto contextSwitches = statistics::getContextSwitchCount() - contextSwitchCount;
const auto mutexTest = testMutexAndUnlock(mutex);
if (ret != 0 || wakeUpTimePoint != wokenUpTimePoint || mutexTest != true ||
contextSwitches != phase3SoftwareTimerContextSwitchCount)
return false;
}
return true;
}
} // namespace
/*---------------------------------------------------------------------------------------------------------------------+
| private functions
+---------------------------------------------------------------------------------------------------------------------*/
bool ConditionVariableOperationsTestCase::run_() const
{
using Parameters = std::tuple<Mutex::Type, Mutex::Protocol, uint8_t>;
static const std::array<Parameters, 9> parametersArray
{{
Parameters{Mutex::Type::Normal, Mutex::Protocol::None, {}},
Parameters{Mutex::Type::Normal, Mutex::Protocol::PriorityProtect, UINT8_MAX},
Parameters{Mutex::Type::Normal, Mutex::Protocol::PriorityInheritance, {}},
Parameters{Mutex::Type::ErrorChecking, Mutex::Protocol::None, {}},
Parameters{Mutex::Type::ErrorChecking, Mutex::Protocol::PriorityProtect, UINT8_MAX},
Parameters{Mutex::Type::ErrorChecking, Mutex::Protocol::PriorityInheritance, {}},
Parameters{Mutex::Type::Recursive, Mutex::Protocol::None, {}},
Parameters{Mutex::Type::Recursive, Mutex::Protocol::PriorityProtect, UINT8_MAX},
Parameters{Mutex::Type::Recursive, Mutex::Protocol::PriorityInheritance, {}},
}};
constexpr auto phase1ExpectedContextSwitchCount = 2 * (waitForNextTickContextSwitchCount +
phase1WaitForUntilContextSwitchCount + testMutexAndUnlockContextSwitchCount);
constexpr auto phase2ExpectedContextSwitchCount = 3 * (waitForNextTickContextSwitchCount +
phase2ThreadContextSwitchCount + testMutexAndUnlockContextSwitchCount);
constexpr auto phase3ExpectedContextSwitchCount = 3 * (waitForNextTickContextSwitchCount +
phase3SoftwareTimerContextSwitchCount + testMutexAndUnlockContextSwitchCount);
constexpr auto expectedContextSwitchCount = parametersArray.size() * (phase1ExpectedContextSwitchCount +
phase2ExpectedContextSwitchCount + phase3ExpectedContextSwitchCount);
const auto contextSwitchCount = statistics::getContextSwitchCount();
for (const auto& parameters : parametersArray)
for (const auto& function : {phase1, phase2, phase3})
{
Mutex mutex {std::get<0>(parameters), std::get<1>(parameters), std::get<2>(parameters)};
const auto ret = function(mutex);
if (ret != true)
return ret;
}
if (statistics::getContextSwitchCount() - contextSwitchCount != expectedContextSwitchCount)
return false;
return true;
}
} // namespace test
} // namespace distortos
<commit_msg>test: convert ConditionVariableOperationsTestCase to use dynamic threads<commit_after>/**
* \file
* \brief ConditionVariableOperationsTestCase 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/.
*
* \date 2016-01-04
*/
#include "ConditionVariableOperationsTestCase.hpp"
#include "waitForNextTick.hpp"
#include "Mutex/mutexTestTryLockWhenLocked.hpp"
#include "distortos/ConditionVariable.hpp"
#include "distortos/DynamicThread.hpp"
#include "distortos/Mutex.hpp"
#include "distortos/ThisThread.hpp"
#include "distortos/StaticSoftwareTimer.hpp"
#include "distortos/statistics.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 testMutexAndUnlock(): main -> idle -> main
constexpr decltype(statistics::getContextSwitchCount()) testMutexAndUnlockContextSwitchCount
{
waitForNextTickContextSwitchCount + 2
};
/// expected number of context switches in phase1 block involving waitFor() or waitUntil() (excluding
/// waitForNextTick() and testMutexAndUnlock()): 1 - main thread blocks on condition variable (main -> idle), 2 - main
/// thread wakes up (idle -> main)
constexpr decltype(statistics::getContextSwitchCount()) phase1WaitForUntilContextSwitchCount {2};
/// expected number of context switches in phase2 block involving test thread (excluding waitForNextTick() and
/// testMutexAndUnlock()): 1 - test thread starts (main -> test), 2 - test thread goes to sleep (test -> main), 3 - main
/// thread blocks on condition variable (main -> idle), 4 - test thread wakes (idle -> test), 5 - test thread terminates
/// (test -> main)
constexpr decltype(statistics::getContextSwitchCount()) phase2ThreadContextSwitchCount {5};
/// expected number of context switches in phase3 block involving software timer (excluding waitForNextTick() and
/// testMutexAndUnlock()): 1 - main thread blocks on condition variable (main -> idle), 2 - main thread is unblocked by
/// interrupt (idle -> main)
constexpr decltype(statistics::getContextSwitchCount()) phase3SoftwareTimerContextSwitchCount {2};
/*---------------------------------------------------------------------------------------------------------------------+
| local functions
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief Tests whether supplied mutex is properly locked and unlocks it.
*
* \param [in] mutex is a reference to mutex that will be tested and unlocked
*
* \return true if test succeeded and mutex was sucessfully unlocked, false otherwise
*/
bool testMutexAndUnlock(Mutex& mutex)
{
const auto testRet = mutexTestTryLockWhenLocked(mutex, UINT8_MAX);
const auto unlockRet = mutex.unlock();
return testRet == true && unlockRet == 0;
}
/**
* \brief Phase 1 of test case.
*
* Tests whether both waitFor() and waitUntil() functions properly return some error and properly handle mutex when
* timing out without notification.
*
* \param [in] mutex is a reference to mutex used with condition variable, must be unlocked
*
* \return true if test succeeded, false otherwise
*/
bool phase1(Mutex& mutex)
{
ConditionVariable conditionVariable;
{
const auto ret = mutex.lock();
if (ret != 0)
return false;
}
{
waitForNextTick();
// there will be no notification, so waitFor() should time-out at expected time
const auto contextSwitchCount = statistics::getContextSwitchCount();
const auto start = TickClock::now();
const auto ret = conditionVariable.waitFor(mutex, singleDuration);
const auto realDuration = TickClock::now() - start;
const auto contextSwitches = statistics::getContextSwitchCount() - contextSwitchCount;
const auto mutexTest = testMutexAndUnlock(mutex);
if (ret != ETIMEDOUT || realDuration != singleDuration + decltype(singleDuration){1} || mutexTest != true ||
contextSwitches != phase1WaitForUntilContextSwitchCount)
return false;
}
{
const auto ret = mutex.lock();
if (ret != 0)
return false;
}
{
waitForNextTick();
// there will be no notification, so waitUntil() should time-out at exact expected time
const auto contextSwitchCount = statistics::getContextSwitchCount();
const auto wakeUpTimePoint = TickClock::now() + singleDuration;
const auto ret = conditionVariable.waitUntil(mutex, wakeUpTimePoint);
const auto wokenUpTimePoint = TickClock::now();
const auto contextSwitches = statistics::getContextSwitchCount() - contextSwitchCount;
const auto mutexTest = testMutexAndUnlock(mutex);
if (ret != ETIMEDOUT || wakeUpTimePoint != wokenUpTimePoint || mutexTest != true ||
contextSwitches != phase1WaitForUntilContextSwitchCount)
return false;
}
return true;
}
/**
* \brief Phase 2 of test case.
*
* Tests thread-thread signaling scenario. Main (current) thread waits for condition variable notification (using
* wait(), waitFor() and waitUntil()). Test thread notifies one waiter at specified time point, main thread is expected
* to wake up and acquire ownership of the mutex in the same moment.
*
* \param [in] mutex is a reference to mutex used with condition variable, must be unlocked
*
* \return true if test succeeded, false otherwise
*/
bool phase2(Mutex& mutex)
{
constexpr size_t testThreadStackSize {384};
ConditionVariable conditionVariable;
const auto sleepUntilFunctor = [&conditionVariable](const TickClock::time_point timePoint)
{
ThisThread::sleepUntil(timePoint);
conditionVariable.notifyOne();
};
{
const auto ret = mutex.lock();
if (ret != 0)
return false;
}
{
waitForNextTick();
const auto contextSwitchCount = statistics::getContextSwitchCount();
const auto wakeUpTimePoint = TickClock::now() + longDuration;
auto thread = makeDynamicThread({testThreadStackSize, UINT8_MAX}, sleepUntilFunctor, wakeUpTimePoint);
thread.start();
ThisThread::yield();
// wait() should succeed at expected time
const auto ret = conditionVariable.wait(mutex);
const auto wokenUpTimePoint = TickClock::now();
const auto contextSwitches = statistics::getContextSwitchCount() - contextSwitchCount;
thread.join();
const auto mutexTest = testMutexAndUnlock(mutex);
if (ret != 0 || wakeUpTimePoint != wokenUpTimePoint || mutexTest != true ||
contextSwitches != phase2ThreadContextSwitchCount)
return false;
}
{
const auto ret = mutex.lock();
if (ret != 0)
return false;
}
{
waitForNextTick();
const auto contextSwitchCount = statistics::getContextSwitchCount();
const auto wakeUpTimePoint = TickClock::now() + longDuration;
auto thread = makeDynamicThread({testThreadStackSize, UINT8_MAX}, sleepUntilFunctor, wakeUpTimePoint);
thread.start();
ThisThread::yield();
// waitFor() should succeed at expected time
const auto ret = conditionVariable.waitFor(mutex, wakeUpTimePoint - TickClock::now() + longDuration);
const auto wokenUpTimePoint = TickClock::now();
const auto contextSwitches = statistics::getContextSwitchCount() - contextSwitchCount;
thread.join();
const auto mutexTest = testMutexAndUnlock(mutex);
if (ret != 0 || wakeUpTimePoint != wokenUpTimePoint || mutexTest != true ||
contextSwitches != phase2ThreadContextSwitchCount)
return false;
}
{
const auto ret = mutex.lock();
if (ret != 0)
return false;
}
{
waitForNextTick();
const auto contextSwitchCount = statistics::getContextSwitchCount();
const auto wakeUpTimePoint = TickClock::now() + longDuration;
auto thread = makeDynamicThread({testThreadStackSize, UINT8_MAX}, sleepUntilFunctor, wakeUpTimePoint);
thread.start();
ThisThread::yield();
// waitUntil() should succeed at expected time
const auto ret = conditionVariable.waitUntil(mutex, wakeUpTimePoint + longDuration);
const auto wokenUpTimePoint = TickClock::now();
const auto contextSwitches = statistics::getContextSwitchCount() - contextSwitchCount;
thread.join();
const auto mutexTest = testMutexAndUnlock(mutex);
if (ret != 0 || wakeUpTimePoint != wokenUpTimePoint || mutexTest != true ||
contextSwitches != phase2ThreadContextSwitchCount)
return false;
}
return true;
}
/**
* \brief Phase 3 of test case.
*
* Tests interrupt-thread signaling scenario. Main (current) thread waits for condition variable notification (using
* wait(), waitFor() and waitUntil()). Software timer is used to notify one waiter at specified time point from
* interrupt context, main thread is expected to wake up and acquire ownership of the mutex in the same moment.
*
* \param [in] mutex is a reference to mutex used with condition variable, must be unlocked
*
* \return true if test succeeded, false otherwise
*/
bool phase3(Mutex& mutex)
{
ConditionVariable conditionVariable;
auto softwareTimer = makeStaticSoftwareTimer(&ConditionVariable::notifyOne, std::ref(conditionVariable));
{
const auto ret = mutex.lock();
if (ret != 0)
return false;
}
{
waitForNextTick();
const auto contextSwitchCount = statistics::getContextSwitchCount();
const auto wakeUpTimePoint = TickClock::now() + longDuration;
softwareTimer.start(wakeUpTimePoint);
// wait() should succeed at expected time
const auto ret = conditionVariable.wait(mutex);
const auto wokenUpTimePoint = TickClock::now();
const auto contextSwitches = statistics::getContextSwitchCount() - contextSwitchCount;
const auto mutexTest = testMutexAndUnlock(mutex);
if (ret != 0 || wakeUpTimePoint != wokenUpTimePoint || mutexTest != true ||
contextSwitches != phase3SoftwareTimerContextSwitchCount)
return false;
}
{
const auto ret = mutex.lock();
if (ret != 0)
return false;
}
{
waitForNextTick();
const auto contextSwitchCount = statistics::getContextSwitchCount();
const auto wakeUpTimePoint = TickClock::now() + longDuration;
softwareTimer.start(wakeUpTimePoint);
// waitFor() should succeed at expected time
const auto ret = conditionVariable.waitFor(mutex, wakeUpTimePoint - TickClock::now() + longDuration);
const auto wokenUpTimePoint = TickClock::now();
const auto contextSwitches = statistics::getContextSwitchCount() - contextSwitchCount;
const auto mutexTest = testMutexAndUnlock(mutex);
if (ret != 0 || wakeUpTimePoint != wokenUpTimePoint || mutexTest != true ||
contextSwitches != phase3SoftwareTimerContextSwitchCount)
return false;
}
{
const auto ret = mutex.lock();
if (ret != 0)
return false;
}
{
waitForNextTick();
const auto contextSwitchCount = statistics::getContextSwitchCount();
const auto wakeUpTimePoint = TickClock::now() + longDuration;
softwareTimer.start(wakeUpTimePoint);
// waitUntil() should succeed at expected time
const auto ret = conditionVariable.waitUntil(mutex, wakeUpTimePoint + longDuration);
const auto wokenUpTimePoint = TickClock::now();
const auto contextSwitches = statistics::getContextSwitchCount() - contextSwitchCount;
const auto mutexTest = testMutexAndUnlock(mutex);
if (ret != 0 || wakeUpTimePoint != wokenUpTimePoint || mutexTest != true ||
contextSwitches != phase3SoftwareTimerContextSwitchCount)
return false;
}
return true;
}
} // namespace
/*---------------------------------------------------------------------------------------------------------------------+
| private functions
+---------------------------------------------------------------------------------------------------------------------*/
bool ConditionVariableOperationsTestCase::run_() const
{
using Parameters = std::tuple<Mutex::Type, Mutex::Protocol, uint8_t>;
static const std::array<Parameters, 9> parametersArray
{{
Parameters{Mutex::Type::Normal, Mutex::Protocol::None, {}},
Parameters{Mutex::Type::Normal, Mutex::Protocol::PriorityProtect, UINT8_MAX},
Parameters{Mutex::Type::Normal, Mutex::Protocol::PriorityInheritance, {}},
Parameters{Mutex::Type::ErrorChecking, Mutex::Protocol::None, {}},
Parameters{Mutex::Type::ErrorChecking, Mutex::Protocol::PriorityProtect, UINT8_MAX},
Parameters{Mutex::Type::ErrorChecking, Mutex::Protocol::PriorityInheritance, {}},
Parameters{Mutex::Type::Recursive, Mutex::Protocol::None, {}},
Parameters{Mutex::Type::Recursive, Mutex::Protocol::PriorityProtect, UINT8_MAX},
Parameters{Mutex::Type::Recursive, Mutex::Protocol::PriorityInheritance, {}},
}};
constexpr auto phase1ExpectedContextSwitchCount = 2 * (waitForNextTickContextSwitchCount +
phase1WaitForUntilContextSwitchCount + testMutexAndUnlockContextSwitchCount);
constexpr auto phase2ExpectedContextSwitchCount = 3 * (waitForNextTickContextSwitchCount +
phase2ThreadContextSwitchCount + testMutexAndUnlockContextSwitchCount);
constexpr auto phase3ExpectedContextSwitchCount = 3 * (waitForNextTickContextSwitchCount +
phase3SoftwareTimerContextSwitchCount + testMutexAndUnlockContextSwitchCount);
constexpr auto expectedContextSwitchCount = parametersArray.size() * (phase1ExpectedContextSwitchCount +
phase2ExpectedContextSwitchCount + phase3ExpectedContextSwitchCount);
const auto contextSwitchCount = statistics::getContextSwitchCount();
for (const auto& parameters : parametersArray)
for (const auto& function : {phase1, phase2, phase3})
{
Mutex mutex {std::get<0>(parameters), std::get<1>(parameters), std::get<2>(parameters)};
const auto ret = function(mutex);
if (ret != true)
return ret;
}
if (statistics::getContextSwitchCount() - contextSwitchCount != expectedContextSwitchCount)
return false;
return true;
}
} // namespace test
} // namespace distortos
<|endoftext|> |
<commit_before>#include "gc_mark_queue.h"
#include "logging.h"
namespace precisegc { namespace details {
gc_mark_queue::gc_mark_queue()
: m_queue(MAX_SIZE)
{}
//gc_mark_queue& gc_mark_queue::instance()
//{
// static gc_mark_queue queue;
// return queue;
//}
bool gc_mark_queue::empty()
{
return m_queue.empty();
}
bool gc_mark_queue::push(void* ptr)
{
return m_queue.push(ptr);
}
bool gc_mark_queue::pop(void*& p)
{
return m_queue.pop(p);
}
void gc_mark_queue::clear()
{
void* ret;
while (m_queue.pop(ret)) {}
}
}}<commit_msg>dijcstra write-barrier<commit_after>#include "gc_mark_queue.h"
#include "managed_ptr.h"
#include "logging.h"
namespace precisegc { namespace details {
gc_mark_queue::gc_mark_queue()
: m_queue(MAX_SIZE)
{}
//gc_mark_queue& gc_mark_queue::instance()
//{
// static gc_mark_queue queue;
// return queue;
//}
bool gc_mark_queue::empty()
{
return m_queue.empty();
}
bool gc_mark_queue::push(void* ptr)
{
return m_queue.push(ptr);
}
bool gc_mark_queue::pop(void*& p)
{
p = nullptr;
void* ptr = nullptr;
if (m_queue.pop(ptr)) {
managed_cell_ptr cell_ptr(managed_ptr(reinterpret_cast<byte*>(ptr)), 0);
if (!cell_ptr.get_mark()) {
p = ptr;
}
return true;
}
return false;
// // this check will be failed only when ptr is pointed to non gc_heap memory,
// // that is not possible in correct program (i.e. when gc_new is used to create managed objects),
// // but could occur during testing.
// try {
// cell_ptr.lock_descriptor();
// if (!cell_ptr.get_mark()) {
//// static gc_mark_queue& queue = gc_mark_queue::instance();
// queue->push(ptr);
// }
// } catch (managed_cell_ptr::unindexed_memory_exception& exc) {
// return;
// }
return m_queue.pop(p);
}
void gc_mark_queue::clear()
{
void* ret;
while (m_queue.pop(ret)) {}
}
}}<|endoftext|> |
<commit_before>#include <stdio.h> // for printf()
#include <stdlib.h> // for malloc()
#include <algorithm>
#include <fstream> // for std::ifstream
#include <iostream> // for std::cout
#include <map> // for std::map
std::vector<char> bases = {'A', 'T', 'C', 'G'};
std::map<char, char> complement_map = {{'A', 'T'}, {'T', 'A'}, {'C', 'G'}, {'G', 'C'}};
std::string ReverseComplement(const std::string &src) {
int len = src.size();
std::string ret_str = src;
for (int i = 0; i < len; ++i) {
ret_str[len - 1 - i] = complement_map[src[i]];
}
return ret_str;
}
bool ValidSequence(std::string str) {
for (char c : str) {
if (c != 'A' && c != 'T' && c != 'C' && c != 'G') {
return false;
}
}
return true;
}
int DpAlignment(const std::string &seq1, const std::string &seq2) {
std::vector<std::vector<std::pair<unsigned, char>>> table;
// char is the direction you follow back to the (0, 0).
// L is left, U is down, D is diagonal.
unsigned cols = seq1.size() + 1;
unsigned rows = seq2.size() + 1;
std::vector<std::pair<unsigned, char>> zero_row(cols, {0, '\0'});
for (unsigned i = 0; i < rows; ++i) table.push_back(zero_row);
for (unsigned i = 0; i < cols; ++i) table.at(0).at(i) = {i, 'L'};
for (unsigned i = 0; i < rows; ++i) table.at(i).at(0) = {i, 'U'};
// write table
unsigned min;
for (unsigned i = 1; i < cols; ++i) {
for (unsigned j = 1; j < rows; ++j) {
if (seq1.at(i - 1) == seq2.at(j - 1)) {
table.at(j).at(i) = {table.at(j - 1).at(i - 1).first, 'D'};
min = table.at(j).at(i).first;
} else {
table.at(j).at(i) = {table.at(j - 1).at(i - 1).first + 1, 'D'};;
min = table.at(j).at(i).first;
}
if (table.at(j - 1).at(i).first + 1 < min) {
table.at(j).at(i) = {table.at(j - 1).at(i).first + 1, 'U'};
min = table.at(j).at(i).first;
}
if (table.at(j).at(i - 1).first + 1 < min) {
table.at(j).at(i) = {table.at(j).at(i - 1).first + 1, 'L'};
min = table.at(j).at(i).first;
}
}
}
// print table
/*
for (unsigned i = 0; i < cols; ++i) {
for (unsigned j = 0; j < rows; ++j) {
printf("%2d ", table.at(j).at(i).first);
}
std::cout << '\n';
}
*/
// trace path back to origin and visualise
std::string out_top, out_mid, out_bot;
for (unsigned col = cols - 1, row = rows - 1; col + row != 0; ) {
if (row == 0 || table.at(row).at(col).second == 'L') {
out_top.append(1, seq1.at(col - 1));
out_bot.append(1, ' ');
out_mid.append(1, '-');
--col;
} else if (col == 0 || table.at(row).at(col).second == 'L') {
out_top.append(1, ' ');
out_bot.append(1, seq2.at(row - 1));
out_mid.append(1, '-');
--row;
} else if (table.at(row).at(col).second == 'D') {
out_top.append(1, seq1.at(col - 1));
out_bot.append(1, seq2.at(row - 1));
if (seq1.at(col - 1) == seq2.at(row - 1)) {
out_mid.append(1, '|');
} else {
out_mid.append(1, ' ');
}
--row;
--col;
} else {
std::cout << "error\n";
exit(EXIT_FAILURE);
}
}
std::reverse(std::begin(out_top), std::end(out_top));
std::reverse(std::begin(out_mid), std::end(out_mid));
std::reverse(std::begin(out_bot), std::end(out_bot));
std::cout << out_top << "\n";
std::cout << out_mid << "\n";
std::cout << out_bot << "\n";
return table.at(rows - 1).at(cols - 1).first;
}
int main(int argc, char* argv[]) {
if (argc < 2) std::cout << "please supply one input argument, the input file path\n";
std::string input_file_name;
input_file_name = argv[1];
std::cout << "input_file_name = " << input_file_name << '\n';
// check file exists
std::ifstream instream(input_file_name);
if (!instream.is_open()) {
std::cout << "Could not open input file.\n";
std::exit(EXIT_FAILURE);
}
// read file
std::string seq1, seq2;
std::getline(instream, seq1, '\n');
std::getline(instream, seq2, '\n');
std::transform(seq1.begin(), seq1.end(), seq1.begin(), ::toupper);
std::transform(seq2.begin(), seq2.end(), seq2.begin(), ::toupper);
instream.close();
// check valid sequence
if (!ValidSequence(seq1)) {
std::cout << "seq1 = " << seq1 << " is invalid\n";
}
if (!ValidSequence(seq2)) {
std::cout << "seq2 = " << seq2 << " is invalid\n";
}
// print input strings
std::cout << '\n';
std::cout << "input sequences:\n";
std::cout << "seq1 = " << seq1 << '\n';
std::cout << "seq2 = " << seq2 << '\n';
std::cout << '\n';
// align using dynamic programming
DpAlignment(ReverseComplement(seq1), seq2);
return 0;
}
<commit_msg>fixed dp_alignment bug<commit_after>#include <stdio.h> // for printf()
#include <stdlib.h> // for malloc()
#include <algorithm>
#include <fstream> // for std::ifstream
#include <iostream> // for std::cout
#include <map> // for std::map
std::vector<char> bases = {'A', 'T', 'C', 'G'};
std::map<char, char> complement_map = {{'A', 'T'}, {'T', 'A'}, {'C', 'G'}, {'G', 'C'}};
std::string ReverseComplement(const std::string &src) {
int len = src.size();
std::string ret_str = src;
for (int i = 0; i < len; ++i) {
ret_str[len - 1 - i] = complement_map[src[i]];
}
return ret_str;
}
bool ValidSequence(std::string str) {
for (char c : str) {
if (c != 'A' && c != 'T' && c != 'C' && c != 'G') {
return false;
}
}
return true;
}
int DpAlignment(const std::string &seq1, const std::string &seq2) {
std::vector<std::vector<std::pair<unsigned, char>>> table;
// char is the direction you follow back to the (0, 0).
// L is left, U is down, D is diagonal.
std::cout << "aligning the following sequences:\n";
std::cout << seq1 << '\n' << seq2 << "\n\n";
unsigned cols = seq1.size() + 1;
unsigned rows = seq2.size() + 1;
std::vector<std::pair<unsigned, char>> zero_row(cols, {0, '\0'});
for (unsigned i = 0; i < rows; ++i) table.push_back(zero_row);
for (unsigned i = 0; i < cols; ++i) table.at(0).at(i) = {i, 'U'};
for (unsigned i = 0; i < rows; ++i) table.at(i).at(0) = {i, 'L'};
// write table
unsigned min;
for (unsigned row = 1; row < rows; ++row) {
for (unsigned col = 1; col < cols; ++col) {
std::cout << "new\n";
if (seq1.at(col - 1) == seq2.at(row - 1)) {
std::cout << "1\n";
table.at(row).at(col) = {table.at(row - 1).at(col - 1).first, 'D'};
min = table.at(row).at(col).first;
} else {
std::cout << "2\n";
table.at(row).at(col) = {table.at(row - 1).at(col - 1).first + 1, 'D'};;
min = table.at(row).at(col).first;
}
if (table.at(row - 1).at(col).first + 1 < min) {
std::cout << "val = " << table.at(row - 1).at(col).first + 1 << '\n';
std::cout << "3\n";
table.at(row).at(col) = {table.at(row - 1).at(col).first + 1, 'U'};
min = table.at(row).at(col).first;
}
if (table.at(row).at(col - 1).first + 1 < min) {
std::cout << "val = " << table.at(row).at(col - 1).first + 1 << '\n';
std::cout << "4\n";
table.at(row).at(col) = {table.at(row).at(col - 1).first + 1, 'L'};
min = table.at(row).at(col).first;
}
}
}
// print table
/*
for (unsigned j = 0; j < rows; ++j) {
for (unsigned i = 0; i < cols; ++i) {
printf("%2d ", table.at(j).at(i).first);
printf("%c ", table.at(j).at(i).second);
}
std::cout << '\n';
}
*/
// trace path back to origin and visualise
std::string out_top, out_mid, out_bot;
for (unsigned col = cols - 1, row = rows - 1; col + row != 0; ) {
//std::cout << row << ',' << col << ',' << table.at(row).at(col).second << '\n';
if (row == 0 || table.at(row).at(col).second == 'L') {
out_top.append(1, seq1.at(col - 1));
out_bot.append(1, ' ');
out_mid.append(1, '-');
--col;
} else if (col == 0 || table.at(row).at(col).second == 'U') {
out_top.append(1, ' ');
out_bot.append(1, seq2.at(row - 1));
out_mid.append(1, '-');
--row;
} else if (table.at(row).at(col).second == 'D') {
out_top.append(1, seq1.at(col - 1));
out_bot.append(1, seq2.at(row - 1));
if (seq1.at(col - 1) == seq2.at(row - 1)) {
out_mid.append(1, '|');
} else {
out_mid.append(1, ' ');
}
--row;
--col;
} else {
std::cout << "error\n";
exit(EXIT_FAILURE);
}
}
std::reverse(std::begin(out_top), std::end(out_top));
std::reverse(std::begin(out_mid), std::end(out_mid));
std::reverse(std::begin(out_bot), std::end(out_bot));
std::cout << out_top << "\n";
std::cout << out_mid << "\n";
std::cout << out_bot << "\n";
return table.at(rows - 1).at(cols - 1).first;
}
int main(int argc, char* argv[]) {
if (argc < 2) std::cout << "please supply one input argument, the input file path\n";
std::string input_file_name;
input_file_name = argv[1];
std::cout << "input_file_name = " << input_file_name << '\n';
// check file exists
std::ifstream instream(input_file_name);
if (!instream.is_open()) {
std::cout << "Could not open input file.\n";
std::exit(EXIT_FAILURE);
}
// read file
std::string seq1, seq2;
std::getline(instream, seq1, '\n');
std::getline(instream, seq2, '\n');
std::transform(seq1.begin(), seq1.end(), seq1.begin(), ::toupper);
std::transform(seq2.begin(), seq2.end(), seq2.begin(), ::toupper);
instream.close();
// check valid sequence
if (!ValidSequence(seq1)) {
std::cout << "seq1 = " << seq1 << " is invalid\n";
}
if (!ValidSequence(seq2)) {
std::cout << "seq2 = " << seq2 << " is invalid\n";
}
// print input strings
std::cout << '\n';
std::cout << "input sequences:\n";
std::cout << "seq1 = " << seq1 << '\n';
std::cout << "seq2 = " << seq2 << '\n';
std::cout << '\n';
// align using dynamic programming
DpAlignment(ReverseComplement(seq1), seq2);
return 0;
}
<|endoftext|> |
<commit_before>/***********************************************************************
filename: NavigationStrategies.cpp
created: 25/08/2013
author: Timotei Dolean
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team
*
* 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 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 "NavigationStrategies.h"
using namespace CEGUI;
using namespace NavigationStrategiesPayloads;
Window* LinearNavigationStrategy::getWindow(Window* neighbour, const String& payload)
{
std::vector<Window*>::const_iterator itor;
// start at the beginning
if (neighbour == 0)
return *d_windows.begin();
else
itor = std::find(d_windows.begin(), d_windows.end(), neighbour);
// no such neighbour window in here
if (itor == d_windows.end())
return 0;
if (payload == NAVIGATE_PREVIOUS)
{
// first item. wrap to end
if (itor == d_windows.begin())
return *(d_windows.end() - 1);
return *(itor - 1);
}
else if (payload == NAVIGATE_NEXT)
{
// last item. wrap to beginning
if (itor == d_windows.end() - 1)
return *d_windows.begin();
return *(itor + 1);
}
// no payload handling, just return the same window
return neighbour;
}
Window* MatrixNavigationStrategy::getWindow(Window* neighbour, const String& payload)
{
size_t rows = d_windows.size();
for (size_t row = 0; row < rows; ++row)
{
std::vector<Window*> column = d_windows.at(row);
size_t cols = column.size();
for (size_t col = 0; col < cols; ++col)
{
if (neighbour == column.at(col))
{
// compute the new window (wrapping)
if (payload == NAVIGATE_RIGHT)
col = (col + 1) % cols;
else if (payload == NAVIGATE_DOWN)
row = (row + 1) % rows;
else if (payload == NAVIGATE_LEFT)
{
if (col == 0)
col = cols - 1;
else
col --;
}
else if (payload == NAVIGATE_UP)
{
if (row == 0)
row = rows - 1;
else
row --;
}
return d_windows.at(row).at(col);
}
}
}
// first button
return d_windows.at(0).at(0);
}
<commit_msg>Fix compilation error on non-MSVC compilers (missed including the algorithm header)<commit_after>/***********************************************************************
filename: NavigationStrategies.cpp
created: 25/08/2013
author: Timotei Dolean
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team
*
* 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 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 "NavigationStrategies.h"
#include <algorithm>
using namespace CEGUI;
using namespace NavigationStrategiesPayloads;
Window* LinearNavigationStrategy::getWindow(Window* neighbour, const String& payload)
{
std::vector<Window*>::const_iterator itor;
// start at the beginning
if (neighbour == 0)
return *d_windows.begin();
else
itor = std::find(d_windows.begin(), d_windows.end(), neighbour);
// no such neighbour window in here
if (itor == d_windows.end())
return 0;
if (payload == NAVIGATE_PREVIOUS)
{
// first item. wrap to end
if (itor == d_windows.begin())
return *(d_windows.end() - 1);
return *(itor - 1);
}
else if (payload == NAVIGATE_NEXT)
{
// last item. wrap to beginning
if (itor == d_windows.end() - 1)
return *d_windows.begin();
return *(itor + 1);
}
// no payload handling, just return the same window
return neighbour;
}
Window* MatrixNavigationStrategy::getWindow(Window* neighbour, const String& payload)
{
size_t rows = d_windows.size();
for (size_t row = 0; row < rows; ++row)
{
std::vector<Window*> column = d_windows.at(row);
size_t cols = column.size();
for (size_t col = 0; col < cols; ++col)
{
if (neighbour == column.at(col))
{
// compute the new window (wrapping)
if (payload == NAVIGATE_RIGHT)
col = (col + 1) % cols;
else if (payload == NAVIGATE_DOWN)
row = (row + 1) % rows;
else if (payload == NAVIGATE_LEFT)
{
if (col == 0)
col = cols - 1;
else
col --;
}
else if (payload == NAVIGATE_UP)
{
if (row == 0)
row = rows - 1;
else
row --;
}
return d_windows.at(row).at(col);
}
}
}
// first button
return d_windows.at(0).at(0);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: AccessibleDocument.hxx,v $
*
* $Revision: 1.23 $
*
* last change: $Author: vg $ $Date: 2003-05-22 13:46:50 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SC_ACCESSIBLEDOCUMENT_HXX
#define _SC_ACCESSIBLEDOCUMENT_HXX
#ifndef _SC_ACCESSIBLEDOCUMENTBASE_HXX
#include "AccessibleDocumentBase.hxx"
#endif
#ifndef SC_VIEWDATA_HXX
#include "viewdata.hxx"
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLESELECTION_HPP_
#include <com/sun/star/accessibility/XAccessibleSelection.hpp>
#endif
#ifndef _COM_SUN_STAR_VIEW_XSELECTIONCHANGELISTENER_HPP_
#include <com/sun/star/view/XSelectionChangeListener.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif
#ifndef _SVX_ACCESSIBILITY_IACCESSIBLE_VIEW_FORWARDER_HXX
#include <svx/IAccessibleViewForwarder.hxx>
#endif
class ScTabViewShell;
class ScAccessibleSpreadsheet;
class ScChildrenShapes;
class ScAccessibleEditObject;
namespace accessibility
{
class AccessibleShape;
}
namespace utl
{
class AccessibleRelationSetHelper;
}
/** @descr
This base class provides an implementation of the
<code>AccessibleContext</code> service.
*/
typedef cppu::ImplHelper2< ::com::sun::star::accessibility::XAccessibleSelection,
::com::sun::star::view::XSelectionChangeListener >
ScAccessibleDocumentImpl;
class ScAccessibleDocument
: public ScAccessibleDocumentBase,
public ScAccessibleDocumentImpl,
public accessibility::IAccessibleViewForwarder
{
public:
//===== internal ========================================================
ScAccessibleDocument(
const ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessible>& rxParent,
ScTabViewShell* pViewShell,
ScSplitPos eSplitPos);
virtual void Init();
DECL_LINK( WindowChildEventListener, VclSimpleEvent* );
protected:
virtual ~ScAccessibleDocument(void);
public:
virtual void SAL_CALL disposing();
///===== SfxListener =====================================================
virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );
///===== XInterface =====================================================
virtual ::com::sun::star::uno::Any SAL_CALL queryInterface(
::com::sun::star::uno::Type const & rType )
throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL acquire() throw ();
virtual void SAL_CALL release() throw ();
///===== XAccessibleComponent ============================================
virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >
SAL_CALL getAccessibleAtPoint(
const ::com::sun::star::awt::Point& rPoint )
throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL grabFocus( )
throw (::com::sun::star::uno::RuntimeException);
///===== XAccessibleContext ==============================================
/// Return the number of currently visible children.
virtual long SAL_CALL
getAccessibleChildCount(void)
throw (::com::sun::star::uno::RuntimeException);
/// Return the specified child or NULL if index is invalid.
virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> SAL_CALL
getAccessibleChild(long nIndex)
throw (::com::sun::star::uno::RuntimeException,
::com::sun::star::lang::IndexOutOfBoundsException);
/// Return the set of current states.
virtual ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessibleStateSet> SAL_CALL
getAccessibleStateSet(void)
throw (::com::sun::star::uno::RuntimeException);
///===== XAccessibleSelection ===========================================
virtual void SAL_CALL
selectAccessibleChild( sal_Int32 nChildIndex )
throw (::com::sun::star::lang::IndexOutOfBoundsException,
::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL
isAccessibleChildSelected( sal_Int32 nChildIndex )
throw (::com::sun::star::lang::IndexOutOfBoundsException,
::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL
clearAccessibleSelection( )
throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL
selectAllAccessibleChildren( )
throw (::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL
getSelectedAccessibleChildCount( )
throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessible > SAL_CALL
getSelectedAccessibleChild( sal_Int32 nSelectedChildIndex )
throw (::com::sun::star::lang::IndexOutOfBoundsException,
::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL
deselectAccessibleChild( sal_Int32 nChildIndex )
throw (::com::sun::star::lang::IndexOutOfBoundsException,
::com::sun::star::uno::RuntimeException);
///===== XSelectionListener =============================================
virtual void SAL_CALL selectionChanged( const ::com::sun::star::lang::EventObject& aEvent )
throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source )
throw (::com::sun::star::uno::RuntimeException);
///===== XServiceInfo ===================================================
/** Returns an identifier for the implementation of this object.
*/
virtual ::rtl::OUString SAL_CALL
getImplementationName(void)
throw (::com::sun::star::uno::RuntimeException);
/** Returns a list of all supported services.
*/
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL
getSupportedServiceNames(void)
throw (::com::sun::star::uno::RuntimeException);
///===== XTypeProvider ===================================================
/// returns the possible types
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL
getTypes()
throw (::com::sun::star::uno::RuntimeException);
/** Returns a implementation id.
*/
virtual ::com::sun::star::uno::Sequence<sal_Int8> SAL_CALL
getImplementationId(void)
throw (::com::sun::star::uno::RuntimeException);
///===== IAccessibleViewForwarder ========================================
/** This method informs you about the state of the forwarder. Do not
use it when the returned value is <false/>.
@return
Return <true/> if the view forwarder is valid and <false/> else.
*/
virtual sal_Bool IsValid (void) const;
/** Returns the area of the underlying document that is visible in the
* corresponding window.
@return
The rectangle of the visible part of the document. The values
are, contrary to the base class, in internal coordinates.
*/
virtual Rectangle GetVisibleArea() const;
/** Transform the specified point from internal coordinates to an
absolute screen position.
@param rPoint
Point in internal coordinates.
@return
The same point but in screen coordinates relative to the upper
left corner of the (current) screen.
*/
virtual Point LogicToPixel (const Point& rPoint) const;
/** Transform the specified size from internal coordinates to a screen
* oriented pixel size.
@param rSize
Size in internal coordinates.
@return
The same size but in screen coordinates.
*/
virtual Size LogicToPixel (const Size& rSize) const;
/** Transform the specified point from absolute screen coordinates to
internal coordinates.
@param rPoint
Point in screen coordinates relative to the upper left corner of
the (current) screen.
@return
The same point but in internal coordinates.
*/
virtual Point PixelToLogic (const Point& rPoint) const;
/** Transform the specified size from screen coordinates to internal
coordinates.
@param rSize
Size in screen coordinates.
@return
The same size but in internal coordinates.
*/
virtual Size PixelToLogic (const Size& rSize) const;
///======== internal =====================================================
utl::AccessibleRelationSetHelper* GetRelationSet(const ScAddress* pAddress) const;
::com::sun::star::uno::Reference
< ::com::sun::star::accessibility::XAccessible >
GetAccessibleSpreadsheet();
protected:
/// Return this object's description.
virtual ::rtl::OUString SAL_CALL
createAccessibleDescription(void)
throw (::com::sun::star::uno::RuntimeException);
/// Return the object's current name.
virtual ::rtl::OUString SAL_CALL
createAccessibleName(void)
throw (::com::sun::star::uno::RuntimeException);
/// Return the object's current bounding box relative to the desktop.
virtual Rectangle GetBoundingBoxOnScreen(void) const
throw (::com::sun::star::uno::RuntimeException);
/// Return the object's current bounding box relative to the parent object.
virtual Rectangle GetBoundingBox(void) const
throw (::com::sun::star::uno::RuntimeException);
private:
ScTabViewShell* mpViewShell;
ScSplitPos meSplitPos;
ScAccessibleSpreadsheet* mpAccessibleSpreadsheet;
ScChildrenShapes* mpChildrenShapes;
ScAccessibleEditObject* mpTempAccEdit;
com::sun::star::uno::Reference<com::sun::star::accessibility::XAccessible> mxTempAcc;
Rectangle maVisArea;
sal_Bool mbCompleteSheetSelected;
public:
sal_uInt16 getVisibleTable() const; // use it in ScChildrenShapes
private:
void FreeAccessibleSpreadsheet();
sal_Bool IsTableSelected() const;
sal_Bool IsDefunc(
const com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessibleStateSet>& rxParentStates);
sal_Bool IsEditable(
const com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessibleStateSet>& rxParentStates);
void AddChild(const com::sun::star::uno::Reference<com::sun::star::accessibility::XAccessible>& xAcc, sal_Bool bFireEvent);
void RemoveChild(const com::sun::star::uno::Reference<com::sun::star::accessibility::XAccessible>& xAcc, sal_Bool bFireEvent);
rtl::OUString GetCurrentCellName() const;
rtl::OUString GetCurrentCellDescription() const;
Rectangle GetVisibleArea_Impl() const;
};
#endif
<commit_msg>INTEGRATION: CWS rowlimit (1.23.160); FILE MERGED 2004/01/16 17:42:48 er 1.23.160.1: #i1967# SCCOL,SCROW,SCTAB replace USHORT; SCsCOL,SCsROW,SCsTAB replace short<commit_after>/*************************************************************************
*
* $RCSfile: AccessibleDocument.hxx,v $
*
* $Revision: 1.24 $
*
* last change: $Author: obo $ $Date: 2004-06-04 11:28:26 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SC_ACCESSIBLEDOCUMENT_HXX
#define _SC_ACCESSIBLEDOCUMENT_HXX
#ifndef _SC_ACCESSIBLEDOCUMENTBASE_HXX
#include "AccessibleDocumentBase.hxx"
#endif
#ifndef SC_VIEWDATA_HXX
#include "viewdata.hxx"
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLESELECTION_HPP_
#include <com/sun/star/accessibility/XAccessibleSelection.hpp>
#endif
#ifndef _COM_SUN_STAR_VIEW_XSELECTIONCHANGELISTENER_HPP_
#include <com/sun/star/view/XSelectionChangeListener.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif
#ifndef _SVX_ACCESSIBILITY_IACCESSIBLE_VIEW_FORWARDER_HXX
#include <svx/IAccessibleViewForwarder.hxx>
#endif
class ScTabViewShell;
class ScAccessibleSpreadsheet;
class ScChildrenShapes;
class ScAccessibleEditObject;
namespace accessibility
{
class AccessibleShape;
}
namespace utl
{
class AccessibleRelationSetHelper;
}
/** @descr
This base class provides an implementation of the
<code>AccessibleContext</code> service.
*/
typedef cppu::ImplHelper2< ::com::sun::star::accessibility::XAccessibleSelection,
::com::sun::star::view::XSelectionChangeListener >
ScAccessibleDocumentImpl;
class ScAccessibleDocument
: public ScAccessibleDocumentBase,
public ScAccessibleDocumentImpl,
public accessibility::IAccessibleViewForwarder
{
public:
//===== internal ========================================================
ScAccessibleDocument(
const ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessible>& rxParent,
ScTabViewShell* pViewShell,
ScSplitPos eSplitPos);
virtual void Init();
DECL_LINK( WindowChildEventListener, VclSimpleEvent* );
protected:
virtual ~ScAccessibleDocument(void);
public:
virtual void SAL_CALL disposing();
///===== SfxListener =====================================================
virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );
///===== XInterface =====================================================
virtual ::com::sun::star::uno::Any SAL_CALL queryInterface(
::com::sun::star::uno::Type const & rType )
throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL acquire() throw ();
virtual void SAL_CALL release() throw ();
///===== XAccessibleComponent ============================================
virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >
SAL_CALL getAccessibleAtPoint(
const ::com::sun::star::awt::Point& rPoint )
throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL grabFocus( )
throw (::com::sun::star::uno::RuntimeException);
///===== XAccessibleContext ==============================================
/// Return the number of currently visible children.
virtual long SAL_CALL
getAccessibleChildCount(void)
throw (::com::sun::star::uno::RuntimeException);
/// Return the specified child or NULL if index is invalid.
virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> SAL_CALL
getAccessibleChild(long nIndex)
throw (::com::sun::star::uno::RuntimeException,
::com::sun::star::lang::IndexOutOfBoundsException);
/// Return the set of current states.
virtual ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessibleStateSet> SAL_CALL
getAccessibleStateSet(void)
throw (::com::sun::star::uno::RuntimeException);
///===== XAccessibleSelection ===========================================
virtual void SAL_CALL
selectAccessibleChild( sal_Int32 nChildIndex )
throw (::com::sun::star::lang::IndexOutOfBoundsException,
::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL
isAccessibleChildSelected( sal_Int32 nChildIndex )
throw (::com::sun::star::lang::IndexOutOfBoundsException,
::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL
clearAccessibleSelection( )
throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL
selectAllAccessibleChildren( )
throw (::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL
getSelectedAccessibleChildCount( )
throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessible > SAL_CALL
getSelectedAccessibleChild( sal_Int32 nSelectedChildIndex )
throw (::com::sun::star::lang::IndexOutOfBoundsException,
::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL
deselectAccessibleChild( sal_Int32 nChildIndex )
throw (::com::sun::star::lang::IndexOutOfBoundsException,
::com::sun::star::uno::RuntimeException);
///===== XSelectionListener =============================================
virtual void SAL_CALL selectionChanged( const ::com::sun::star::lang::EventObject& aEvent )
throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source )
throw (::com::sun::star::uno::RuntimeException);
///===== XServiceInfo ===================================================
/** Returns an identifier for the implementation of this object.
*/
virtual ::rtl::OUString SAL_CALL
getImplementationName(void)
throw (::com::sun::star::uno::RuntimeException);
/** Returns a list of all supported services.
*/
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL
getSupportedServiceNames(void)
throw (::com::sun::star::uno::RuntimeException);
///===== XTypeProvider ===================================================
/// returns the possible types
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL
getTypes()
throw (::com::sun::star::uno::RuntimeException);
/** Returns a implementation id.
*/
virtual ::com::sun::star::uno::Sequence<sal_Int8> SAL_CALL
getImplementationId(void)
throw (::com::sun::star::uno::RuntimeException);
///===== IAccessibleViewForwarder ========================================
/** This method informs you about the state of the forwarder. Do not
use it when the returned value is <false/>.
@return
Return <true/> if the view forwarder is valid and <false/> else.
*/
virtual sal_Bool IsValid (void) const;
/** Returns the area of the underlying document that is visible in the
* corresponding window.
@return
The rectangle of the visible part of the document. The values
are, contrary to the base class, in internal coordinates.
*/
virtual Rectangle GetVisibleArea() const;
/** Transform the specified point from internal coordinates to an
absolute screen position.
@param rPoint
Point in internal coordinates.
@return
The same point but in screen coordinates relative to the upper
left corner of the (current) screen.
*/
virtual Point LogicToPixel (const Point& rPoint) const;
/** Transform the specified size from internal coordinates to a screen
* oriented pixel size.
@param rSize
Size in internal coordinates.
@return
The same size but in screen coordinates.
*/
virtual Size LogicToPixel (const Size& rSize) const;
/** Transform the specified point from absolute screen coordinates to
internal coordinates.
@param rPoint
Point in screen coordinates relative to the upper left corner of
the (current) screen.
@return
The same point but in internal coordinates.
*/
virtual Point PixelToLogic (const Point& rPoint) const;
/** Transform the specified size from screen coordinates to internal
coordinates.
@param rSize
Size in screen coordinates.
@return
The same size but in internal coordinates.
*/
virtual Size PixelToLogic (const Size& rSize) const;
///======== internal =====================================================
utl::AccessibleRelationSetHelper* GetRelationSet(const ScAddress* pAddress) const;
::com::sun::star::uno::Reference
< ::com::sun::star::accessibility::XAccessible >
GetAccessibleSpreadsheet();
protected:
/// Return this object's description.
virtual ::rtl::OUString SAL_CALL
createAccessibleDescription(void)
throw (::com::sun::star::uno::RuntimeException);
/// Return the object's current name.
virtual ::rtl::OUString SAL_CALL
createAccessibleName(void)
throw (::com::sun::star::uno::RuntimeException);
/// Return the object's current bounding box relative to the desktop.
virtual Rectangle GetBoundingBoxOnScreen(void) const
throw (::com::sun::star::uno::RuntimeException);
/// Return the object's current bounding box relative to the parent object.
virtual Rectangle GetBoundingBox(void) const
throw (::com::sun::star::uno::RuntimeException);
private:
ScTabViewShell* mpViewShell;
ScSplitPos meSplitPos;
ScAccessibleSpreadsheet* mpAccessibleSpreadsheet;
ScChildrenShapes* mpChildrenShapes;
ScAccessibleEditObject* mpTempAccEdit;
com::sun::star::uno::Reference<com::sun::star::accessibility::XAccessible> mxTempAcc;
Rectangle maVisArea;
sal_Bool mbCompleteSheetSelected;
public:
SCTAB getVisibleTable() const; // use it in ScChildrenShapes
private:
void FreeAccessibleSpreadsheet();
sal_Bool IsTableSelected() const;
sal_Bool IsDefunc(
const com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessibleStateSet>& rxParentStates);
sal_Bool IsEditable(
const com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessibleStateSet>& rxParentStates);
void AddChild(const com::sun::star::uno::Reference<com::sun::star::accessibility::XAccessible>& xAcc, sal_Bool bFireEvent);
void RemoveChild(const com::sun::star::uno::Reference<com::sun::star::accessibility::XAccessible>& xAcc, sal_Bool bFireEvent);
rtl::OUString GetCurrentCellName() const;
rtl::OUString GetCurrentCellDescription() const;
Rectangle GetVisibleArea_Impl() const;
};
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: ScriptData.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: dfoster $ $Date: 2002-10-30 16:12:39 $
*
* 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 _SCRIPTING_STORAGE_SCRIPTDATA_HXX_
#define _SCRIPTING_STORAGE_SCRIPTDATA_HXX_
#include <vector>
#include <hash_map>
#include <cppu/macros.hxx>
#include <rtl/ustring.hxx>
namespace scripting_impl
{
typedef ::std::pair< ::rtl::OUString, ::rtl::OUString > str_pair;
typedef ::std::vector< str_pair > props_vec;
typedef ::std::hash_map< ::rtl::OUString, props_vec, ::rtl::OUStringHash,
::std::equal_to< ::rtl::OUString > > strpairvec_map;
typedef ::std::hash_map< ::rtl::OUString, ::std::pair< ::rtl::OUString,
::rtl::OUString >, ::rtl::OUStringHash, ::std::equal_to< ::rtl::OUString > > strpair_map;
typedef ::std::hash_map< ::rtl::OUString, ::std::pair< props_vec, strpairvec_map >, ::rtl::OUStringHash, ::std::equal_to< ::rtl::OUString > > filesets_map;
struct ScriptData
{
inline ScriptData::ScriptData() SAL_THROW( () )
: parcelURI()
, language()
, locales()
, functionname()
, logicalname()
, languagedepprops()
, filesets()
{
}
inline ScriptData::ScriptData( const ::rtl::OUString __parcelURI,
const ::rtl::OUString& __language,
const strpair_map& __locales,
const ::rtl::OUString& __functionname,
const ::rtl::OUString& __logicalname,
const props_vec& __languagedepprops,
const filesets_map& __filesets ) SAL_THROW( () )
: parcelURI( __parcelURI )
, language( __language )
, locales( __locales )
, functionname( __functionname )
, logicalname( __logicalname )
, languagedepprops( __languagedepprops )
, filesets( __filesets )
{
}
::rtl::OUString parcelURI;
::rtl::OUString language;
strpair_map locales;
::rtl::OUString functionname;
::rtl::OUString logicalname;
props_vec languagedepprops;
filesets_map filesets;
};
} // namespace scripting_impl
#endif // _SCRIPTING_STORAGE_ScriptData_HXX_
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.90); FILE MERGED 2005/09/05 12:05:26 rt 1.4.90.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ScriptData.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-09 02:35:25 $
*
* 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 _SCRIPTING_STORAGE_SCRIPTDATA_HXX_
#define _SCRIPTING_STORAGE_SCRIPTDATA_HXX_
#include <vector>
#include <hash_map>
#include <cppu/macros.hxx>
#include <rtl/ustring.hxx>
namespace scripting_impl
{
typedef ::std::pair< ::rtl::OUString, ::rtl::OUString > str_pair;
typedef ::std::vector< str_pair > props_vec;
typedef ::std::hash_map< ::rtl::OUString, props_vec, ::rtl::OUStringHash,
::std::equal_to< ::rtl::OUString > > strpairvec_map;
typedef ::std::hash_map< ::rtl::OUString, ::std::pair< ::rtl::OUString,
::rtl::OUString >, ::rtl::OUStringHash, ::std::equal_to< ::rtl::OUString > > strpair_map;
typedef ::std::hash_map< ::rtl::OUString, ::std::pair< props_vec, strpairvec_map >, ::rtl::OUStringHash, ::std::equal_to< ::rtl::OUString > > filesets_map;
struct ScriptData
{
inline ScriptData::ScriptData() SAL_THROW( () )
: parcelURI()
, language()
, locales()
, functionname()
, logicalname()
, languagedepprops()
, filesets()
{
}
inline ScriptData::ScriptData( const ::rtl::OUString __parcelURI,
const ::rtl::OUString& __language,
const strpair_map& __locales,
const ::rtl::OUString& __functionname,
const ::rtl::OUString& __logicalname,
const props_vec& __languagedepprops,
const filesets_map& __filesets ) SAL_THROW( () )
: parcelURI( __parcelURI )
, language( __language )
, locales( __locales )
, functionname( __functionname )
, logicalname( __logicalname )
, languagedepprops( __languagedepprops )
, filesets( __filesets )
{
}
::rtl::OUString parcelURI;
::rtl::OUString language;
strpair_map locales;
::rtl::OUString functionname;
::rtl::OUString logicalname;
props_vec languagedepprops;
filesets_map filesets;
};
} // namespace scripting_impl
#endif // _SCRIPTING_STORAGE_ScriptData_HXX_
<|endoftext|> |
<commit_before>/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Foobar 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 Foobar. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file peer.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
* Peer Network test functions.
*/
#include <PeerNetwork.h>
using namespace std;
using namespace eth;
using boost::asio::ip::tcp;
int peerTest(int argc, char** argv)
{
short listenPort = 30303;
string remoteHost;
short remotePort = 30303;
for (int i = 1; i < argc; ++i)
{
string arg = argv[i];
if (arg == "-l" && i + 1 < argc)
listenPort = atoi(argv[++i]);
else if (arg == "-r" && i + 1 < argc)
remoteHost = argv[++i];
else if (arg == "-p" && i + 1 < argc)
remotePort = atoi(argv[++i]);
else
remoteHost = argv[i];
}
PeerServer pn(0, listenPort);
if (!remoteHost.empty())
pn.connect(remoteHost, remotePort);
for (int i = 0; ; ++i)
{
usleep(100000);
pn.process();
if (!(i % 10))
pn.pingAll();
}
return 0;
}
<commit_msg>Added client API & prototypal GUI.<commit_after>/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Foobar 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 Foobar. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file peer.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
* Peer Network test functions.
*/
#include <BlockChain.h>
#include <PeerNetwork.h>
using namespace std;
using namespace eth;
using boost::asio::ip::tcp;
int peerTest(int argc, char** argv)
{
short listenPort = 30303;
string remoteHost;
short remotePort = 30303;
for (int i = 1; i < argc; ++i)
{
string arg = argv[i];
if (arg == "-l" && i + 1 < argc)
listenPort = atoi(argv[++i]);
else if (arg == "-r" && i + 1 < argc)
remoteHost = argv[++i];
else if (arg == "-p" && i + 1 < argc)
remotePort = atoi(argv[++i]);
else
remoteHost = argv[i];
}
BlockChain ch("/tmp");
PeerServer pn(ch, 0, listenPort);
if (!remoteHost.empty())
pn.connect(remoteHost, remotePort);
for (int i = 0; ; ++i)
{
usleep(100000);
pn.process();
if (!(i % 10))
pn.pingAll();
}
return 0;
}
<|endoftext|> |
<commit_before>//
// Copyright © 2021 Arm Ltd and Contributors. All rights reserved.
// SPDX-License-Identifier: MIT
//
#include <armnn/backends/ICustomAllocator.hpp>
#include <armnn/Descriptors.hpp>
#include <armnn/Exceptions.hpp>
#include <armnn/INetwork.hpp>
#include <armnn/IRuntime.hpp>
#include <armnn/Utils.hpp>
#include <armnn/BackendRegistry.hpp>
#include <cl/ClBackend.hpp>
#include <doctest/doctest.h>
// Contains the OpenCl interfaces for mapping memory in the Gpu Page Tables
// Requires the OpenCl backend to be included (GpuAcc)
#include <arm_compute/core/CL/CLKernelLibrary.h>
#include <CL/cl_ext.h>
#include <arm_compute/runtime/CL/CLScheduler.h>
/** Sample implementation of ICustomAllocator for use with the ClBackend.
* Note: any memory allocated must be host accessible with write access to allow for weights and biases
* to be passed in. Read access is not required.. */
class SampleClBackendCustomAllocator : public armnn::ICustomAllocator
{
public:
SampleClBackendCustomAllocator() = default;
void* allocate(size_t size, size_t alignment)
{
// If alignment is 0 just use the CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE for alignment
if (alignment == 0)
{
alignment = arm_compute::CLKernelLibrary::get().get_device().getInfo<CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE>();
}
size_t space = size + alignment + alignment;
auto allocatedMemPtr = std::malloc(space * sizeof(size_t));
if (std::align(alignment, size, allocatedMemPtr, space) == nullptr)
{
throw armnn::Exception("SampleClBackendCustomAllocator::Alignment failed");
}
return allocatedMemPtr;
}
/** Interface to be implemented by the child class to free the allocated tensor */
void free(void* ptr)
{
std::free(ptr);
}
armnn::MemorySource GetMemorySourceType()
{
return armnn::MemorySource::Malloc;
}
};
armnn::INetworkPtr CreateTestNetwork(armnn::TensorInfo& inputTensorInfo)
{
using namespace armnn;
INetworkPtr myNetwork = INetwork::Create();
armnn::FullyConnectedDescriptor fullyConnectedDesc;
float weightsData[] = {1.0f}; // Identity
TensorInfo weightsInfo(TensorShape({1, 1}), DataType::Float32);
weightsInfo.SetConstant(true);
armnn::ConstTensor weights(weightsInfo, weightsData);
ARMNN_NO_DEPRECATE_WARN_BEGIN
IConnectableLayer* fullyConnected = myNetwork->AddFullyConnectedLayer(fullyConnectedDesc,
weights,
EmptyOptional(),
"fully connected");
ARMNN_NO_DEPRECATE_WARN_END
IConnectableLayer* InputLayer = myNetwork->AddInputLayer(0);
IConnectableLayer* OutputLayer = myNetwork->AddOutputLayer(0);
InputLayer->GetOutputSlot(0).Connect(fullyConnected->GetInputSlot(0));
fullyConnected->GetOutputSlot(0).Connect(OutputLayer->GetInputSlot(0));
//Set the tensors in the network.
InputLayer->GetOutputSlot(0).SetTensorInfo(inputTensorInfo);
TensorInfo outputTensorInfo(TensorShape({1, 1}), DataType::Float32);
fullyConnected->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
return myNetwork;
}
TEST_SUITE("ClCustomAllocatorTests")
{
// This is a copy of the SimpleSample app modified to use a custom
// allocator for the clbackend. It creates a FullyConnected network with a single layer
// taking a single number as an input
TEST_CASE("ClCustomAllocatorTest")
{
using namespace armnn;
float number = 3;
// Construct ArmNN network
armnn::NetworkId networkIdentifier;
TensorInfo inputTensorInfo(TensorShape({1, 1}), DataType::Float32);
INetworkPtr myNetwork = CreateTestNetwork(inputTensorInfo);
// Create ArmNN runtime
IRuntime::CreationOptions options; // default options
auto customAllocator = std::make_shared<SampleClBackendCustomAllocator>();
options.m_CustomAllocatorMap = {{"GpuAcc", std::move(customAllocator)}};
IRuntimePtr run = IRuntime::Create(options);
// Optimise ArmNN network
OptimizerOptions optOptions;
optOptions.m_ImportEnabled = true;
armnn::IOptimizedNetworkPtr optNet = Optimize(*myNetwork, {"GpuAcc"}, run->GetDeviceSpec(), optOptions);
CHECK(optNet);
// Load graph into runtime
std::string ignoredErrorMessage;
INetworkProperties networkProperties(false, MemorySource::Malloc, MemorySource::Malloc);
run->LoadNetwork(networkIdentifier, std::move(optNet), ignoredErrorMessage, networkProperties);
// Creates structures for input & output
unsigned int numElements = inputTensorInfo.GetNumElements();
size_t totalBytes = numElements * sizeof(float);
const size_t alignment =
arm_compute::CLKernelLibrary::get().get_device().getInfo<CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE>();
void* alignedInputPtr = options.m_CustomAllocatorMap["GpuAcc"]->allocate(totalBytes, alignment);
// Input with negative values
auto* inputPtr = reinterpret_cast<float*>(alignedInputPtr);
std::fill_n(inputPtr, numElements, number);
void* alignedOutputPtr = options.m_CustomAllocatorMap["GpuAcc"]->allocate(totalBytes, alignment);
auto* outputPtr = reinterpret_cast<float*>(alignedOutputPtr);
std::fill_n(outputPtr, numElements, -10.0f);
armnn::InputTensors inputTensors
{
{0, armnn::ConstTensor(run->GetInputTensorInfo(networkIdentifier, 0), alignedInputPtr)},
};
armnn::OutputTensors outputTensors
{
{0, armnn::Tensor(run->GetOutputTensorInfo(networkIdentifier, 0), alignedOutputPtr)}
};
// Execute network
run->EnqueueWorkload(networkIdentifier, inputTensors, outputTensors);
run->UnloadNetwork(networkIdentifier);
// Tell the CLBackend to sync memory so we can read the output.
arm_compute::CLScheduler::get().sync();
auto* outputResult = reinterpret_cast<float*>(alignedOutputPtr);
run->UnloadNetwork(networkIdentifier);
CHECK(outputResult[0] == number);
auto& backendRegistry = armnn::BackendRegistryInstance();
backendRegistry.DeregisterAllocator(ClBackend::GetIdStatic());
}
TEST_CASE("ClCustomAllocatorCpuAccNegativeTest")
{
using namespace armnn;
// Create ArmNN runtime
IRuntime::CreationOptions options; // default options
auto customAllocator = std::make_shared<SampleClBackendCustomAllocator>();
options.m_CustomAllocatorMap = {{"CpuAcc", std::move(customAllocator)}};
IRuntimePtr run = IRuntime::Create(options);
TensorInfo inputTensorInfo(TensorShape({1, 1}), DataType::Float32);
INetworkPtr myNetwork = CreateTestNetwork(inputTensorInfo);
// Optimise ArmNN network
OptimizerOptions optOptions;
optOptions.m_ImportEnabled = true;
IOptimizedNetworkPtr optNet(nullptr, nullptr);
std::vector<std::string> errMessages;
try
{
optNet = Optimize(*myNetwork, {"CpuAcc"}, run->GetDeviceSpec(), optOptions, errMessages);
FAIL("Should have thrown an exception as GetAvailablePreferredBackends() should be empty in Optimize().");
}
catch (const armnn::InvalidArgumentException& e)
{
// Different exceptions are thrown on different backends
}
CHECK(errMessages.size() > 0);
auto& backendRegistry = armnn::BackendRegistryInstance();
backendRegistry.DeregisterAllocator(ClBackend::GetIdStatic());
}
TEST_CASE("ClCustomAllocatorGpuAccNullptrTest")
{
using namespace armnn;
// Create ArmNN runtime
IRuntime::CreationOptions options; // default options
auto customAllocator = std::make_shared<SampleClBackendCustomAllocator>();
options.m_CustomAllocatorMap = {{"GpuAcc", nullptr}};
try
{
IRuntimePtr run = IRuntime::Create(options);
FAIL("Should have thrown an exception in RuntimeImpl::RuntimeImpl().");
}
catch (const armnn::Exception& e)
{
// Caught successfully
}
auto& backendRegistry = armnn::BackendRegistryInstance();
backendRegistry.DeregisterAllocator(ClBackend::GetIdStatic());
}
} // test suite ClCustomAllocatorTests<commit_msg>Bugfix: Only run ClCustomAllocatorCpuAccNegativeTest if Neon Enabled<commit_after>//
// Copyright © 2021 Arm Ltd and Contributors. All rights reserved.
// SPDX-License-Identifier: MIT
//
#include <armnn/backends/ICustomAllocator.hpp>
#include <armnn/Descriptors.hpp>
#include <armnn/Exceptions.hpp>
#include <armnn/INetwork.hpp>
#include <armnn/IRuntime.hpp>
#include <armnn/Utils.hpp>
#include <armnn/BackendRegistry.hpp>
#include <cl/ClBackend.hpp>
#if defined(ARMCOMPUTENEON_ENABLED)
#include <neon/NeonBackend.hpp>
#endif
#include <doctest/doctest.h>
// Contains the OpenCl interfaces for mapping memory in the Gpu Page Tables
// Requires the OpenCl backend to be included (GpuAcc)
#include <arm_compute/core/CL/CLKernelLibrary.h>
#include <CL/cl_ext.h>
#include <arm_compute/runtime/CL/CLScheduler.h>
/** Sample implementation of ICustomAllocator for use with the ClBackend.
* Note: any memory allocated must be host accessible with write access to allow for weights and biases
* to be passed in. Read access is not required.. */
class SampleClBackendCustomAllocator : public armnn::ICustomAllocator
{
public:
SampleClBackendCustomAllocator() = default;
void* allocate(size_t size, size_t alignment)
{
// If alignment is 0 just use the CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE for alignment
if (alignment == 0)
{
alignment = arm_compute::CLKernelLibrary::get().get_device().getInfo<CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE>();
}
size_t space = size + alignment + alignment;
auto allocatedMemPtr = std::malloc(space * sizeof(size_t));
if (std::align(alignment, size, allocatedMemPtr, space) == nullptr)
{
throw armnn::Exception("SampleClBackendCustomAllocator::Alignment failed");
}
return allocatedMemPtr;
}
/** Interface to be implemented by the child class to free the allocated tensor */
void free(void* ptr)
{
std::free(ptr);
}
armnn::MemorySource GetMemorySourceType()
{
return armnn::MemorySource::Malloc;
}
};
armnn::INetworkPtr CreateTestNetwork(armnn::TensorInfo& inputTensorInfo)
{
using namespace armnn;
INetworkPtr myNetwork = INetwork::Create();
armnn::FullyConnectedDescriptor fullyConnectedDesc;
float weightsData[] = {1.0f}; // Identity
TensorInfo weightsInfo(TensorShape({1, 1}), DataType::Float32);
weightsInfo.SetConstant(true);
armnn::ConstTensor weights(weightsInfo, weightsData);
ARMNN_NO_DEPRECATE_WARN_BEGIN
IConnectableLayer* fullyConnected = myNetwork->AddFullyConnectedLayer(fullyConnectedDesc,
weights,
EmptyOptional(),
"fully connected");
ARMNN_NO_DEPRECATE_WARN_END
IConnectableLayer* InputLayer = myNetwork->AddInputLayer(0);
IConnectableLayer* OutputLayer = myNetwork->AddOutputLayer(0);
InputLayer->GetOutputSlot(0).Connect(fullyConnected->GetInputSlot(0));
fullyConnected->GetOutputSlot(0).Connect(OutputLayer->GetInputSlot(0));
//Set the tensors in the network.
InputLayer->GetOutputSlot(0).SetTensorInfo(inputTensorInfo);
TensorInfo outputTensorInfo(TensorShape({1, 1}), DataType::Float32);
fullyConnected->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
return myNetwork;
}
TEST_SUITE("ClCustomAllocatorTests")
{
// This is a copy of the SimpleSample app modified to use a custom
// allocator for the clbackend. It creates a FullyConnected network with a single layer
// taking a single number as an input
TEST_CASE("ClCustomAllocatorTest")
{
using namespace armnn;
float number = 3;
// Construct ArmNN network
armnn::NetworkId networkIdentifier;
TensorInfo inputTensorInfo(TensorShape({1, 1}), DataType::Float32);
INetworkPtr myNetwork = CreateTestNetwork(inputTensorInfo);
// Create ArmNN runtime
IRuntime::CreationOptions options; // default options
auto customAllocator = std::make_shared<SampleClBackendCustomAllocator>();
options.m_CustomAllocatorMap = {{"GpuAcc", std::move(customAllocator)}};
IRuntimePtr run = IRuntime::Create(options);
// Optimise ArmNN network
OptimizerOptions optOptions;
optOptions.m_ImportEnabled = true;
armnn::IOptimizedNetworkPtr optNet = Optimize(*myNetwork, {"GpuAcc"}, run->GetDeviceSpec(), optOptions);
CHECK(optNet);
// Load graph into runtime
std::string ignoredErrorMessage;
INetworkProperties networkProperties(false, MemorySource::Malloc, MemorySource::Malloc);
run->LoadNetwork(networkIdentifier, std::move(optNet), ignoredErrorMessage, networkProperties);
// Creates structures for input & output
unsigned int numElements = inputTensorInfo.GetNumElements();
size_t totalBytes = numElements * sizeof(float);
const size_t alignment =
arm_compute::CLKernelLibrary::get().get_device().getInfo<CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE>();
void* alignedInputPtr = options.m_CustomAllocatorMap["GpuAcc"]->allocate(totalBytes, alignment);
// Input with negative values
auto* inputPtr = reinterpret_cast<float*>(alignedInputPtr);
std::fill_n(inputPtr, numElements, number);
void* alignedOutputPtr = options.m_CustomAllocatorMap["GpuAcc"]->allocate(totalBytes, alignment);
auto* outputPtr = reinterpret_cast<float*>(alignedOutputPtr);
std::fill_n(outputPtr, numElements, -10.0f);
armnn::InputTensors inputTensors
{
{0, armnn::ConstTensor(run->GetInputTensorInfo(networkIdentifier, 0), alignedInputPtr)},
};
armnn::OutputTensors outputTensors
{
{0, armnn::Tensor(run->GetOutputTensorInfo(networkIdentifier, 0), alignedOutputPtr)}
};
// Execute network
run->EnqueueWorkload(networkIdentifier, inputTensors, outputTensors);
run->UnloadNetwork(networkIdentifier);
// Tell the CLBackend to sync memory so we can read the output.
arm_compute::CLScheduler::get().sync();
auto* outputResult = reinterpret_cast<float*>(alignedOutputPtr);
run->UnloadNetwork(networkIdentifier);
CHECK(outputResult[0] == number);
auto& backendRegistry = armnn::BackendRegistryInstance();
backendRegistry.DeregisterAllocator(ClBackend::GetIdStatic());
}
// Only run this test if NEON is enabled
#if defined(ARMCOMPUTENEON_ENABLED)
TEST_CASE("ClCustomAllocatorCpuAccNegativeTest")
{
using namespace armnn;
// Create ArmNN runtime
IRuntime::CreationOptions options; // default options
auto customAllocator = std::make_shared<SampleClBackendCustomAllocator>();
options.m_CustomAllocatorMap = {{"CpuAcc", std::move(customAllocator)}};
IRuntimePtr run = IRuntime::Create(options);
TensorInfo inputTensorInfo(TensorShape({1, 1}), DataType::Float32);
INetworkPtr myNetwork = CreateTestNetwork(inputTensorInfo);
// Optimise ArmNN network
OptimizerOptions optOptions;
optOptions.m_ImportEnabled = true;
IOptimizedNetworkPtr optNet(nullptr, nullptr);
std::vector<std::string> errMessages;
try
{
optNet = Optimize(*myNetwork, {"CpuAcc"}, run->GetDeviceSpec(), optOptions, errMessages);
FAIL("Should have thrown an exception as GetAvailablePreferredBackends() should be empty in Optimize().");
}
catch (const armnn::InvalidArgumentException& e)
{
// Different exceptions are thrown on different backends
}
CHECK(errMessages.size() > 0);
auto& backendRegistry = armnn::BackendRegistryInstance();
backendRegistry.DeregisterAllocator(NeonBackend::GetIdStatic());
}
#endif
} // test suite ClCustomAllocatorTests<|endoftext|> |
<commit_before>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/micro/examples/magic_wand/accelerometer_handler.h"
#include <stdio.h>
#include <zephyr.h>
#include <device.h>
#include <string.h>
#include <drivers/sensor.h>
#define BUFLEN 300
int begin_index = 0;
struct device *sensor = NULL;
int current_index = 0;
float bufx[BUFLEN] = {0.0f};
float bufy[BUFLEN] = {0.0f};
float bufz[BUFLEN] = {0.0f};
bool initial = true;
TfLiteStatus SetupAccelerometer(tflite::ErrorReporter* error_reporter) {
sensor = device_get_binding(DT_INST_0_ADI_ADXL345_LABEL);
if(sensor == NULL) {
error_reporter->Report("Failed to get accelerometer, label: %s\n", DT_INST_0_ADI_ADXL345_LABEL);
} else {
error_reporter->Report("Got accelerometer, label: %s\n", DT_INST_0_ADI_ADXL345_LABEL);
}
return kTfLiteOk;
}
bool ReadAccelerometer(tflite::ErrorReporter* error_reporter, float* input,
int length) {
int rc;
struct sensor_value accel[3];
int samples_count;
rc = sensor_sample_fetch(sensor);
if(rc < 0) {
error_reporter -> Report("Fetch failed\n");
return false;
}
//skip if there is no data
if(!rc) {
return false;
}
samples_count = rc;
for(int i = 0; i < samples_count; i++) {
rc = sensor_channel_get(sensor,
SENSOR_CHAN_ACCEL_XYZ,
accel);
if (rc < 0) {
error_reporter->Report("ERROR: Update failed: %d\n", rc);
return false;
}
bufx[begin_index] = (float)sensor_value_to_double(&accel[0]);
bufy[begin_index] = (float)sensor_value_to_double(&accel[1]);
bufz[begin_index] = (float)sensor_value_to_double(&accel[2]);
begin_index++;
if (begin_index >= BUFLEN) begin_index = 0;
}
if(initial && begin_index >= 100) {
initial = false;
}
if (initial) {
return false;
}
int sample = 0;
for (int i = 0; i < (length - 3); i+=3) {
int ring_index = begin_index + sample - length/3;
if(ring_index < 0) {
ring_index += BUFLEN;
}
input[i] = bufx[ring_index];
input[i+1] = bufy[ring_index];
input[i+2] = bufz[ring_index];
sample++;
}
return true;
}
<commit_msg>lite: magic_wand: zephyr: report errors with macro<commit_after>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/micro/examples/magic_wand/accelerometer_handler.h"
#include <stdio.h>
#include <zephyr.h>
#include <device.h>
#include <string.h>
#include <drivers/sensor.h>
#define BUFLEN 300
int begin_index = 0;
struct device *sensor = NULL;
int current_index = 0;
float bufx[BUFLEN] = {0.0f};
float bufy[BUFLEN] = {0.0f};
float bufz[BUFLEN] = {0.0f};
bool initial = true;
TfLiteStatus SetupAccelerometer(tflite::ErrorReporter* error_reporter) {
sensor = device_get_binding(DT_INST_0_ADI_ADXL345_LABEL);
if(sensor == NULL) {
TF_LITE_REPORT_ERROR(error_reporter, "Failed to get accelerometer, label: %s\n", DT_INST_0_ADI_ADXL345_LABEL);
} else {
TF_LITE_REPORT_ERROR(error_reporter, "Got accelerometer, label: %s\n", DT_INST_0_ADI_ADXL345_LABEL);
}
return kTfLiteOk;
}
bool ReadAccelerometer(tflite::ErrorReporter* error_reporter, float* input,
int length) {
int rc;
struct sensor_value accel[3];
int samples_count;
rc = sensor_sample_fetch(sensor);
if(rc < 0) {
TF_LITE_REPORT_ERROR(error_reporter, "Fetch failed\n");
return false;
}
//skip if there is no data
if(!rc) {
return false;
}
samples_count = rc;
for(int i = 0; i < samples_count; i++) {
rc = sensor_channel_get(sensor,
SENSOR_CHAN_ACCEL_XYZ,
accel);
if (rc < 0) {
TF_LITE_REPORT_ERROR(error_reporter, "ERROR: Update failed: %d\n", rc);
return false;
}
bufx[begin_index] = (float)sensor_value_to_double(&accel[0]);
bufy[begin_index] = (float)sensor_value_to_double(&accel[1]);
bufz[begin_index] = (float)sensor_value_to_double(&accel[2]);
begin_index++;
if (begin_index >= BUFLEN) begin_index = 0;
}
if(initial && begin_index >= 100) {
initial = false;
}
if (initial) {
return false;
}
int sample = 0;
for (int i = 0; i < (length - 3); i+=3) {
int ring_index = begin_index + sample - length/3;
if(ring_index < 0) {
ring_index += BUFLEN;
}
input[i] = bufx[ring_index];
input[i+1] = bufy[ring_index];
input[i+2] = bufz[ring_index];
sample++;
}
return true;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: sbxcore.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: obo $ $Date: 2008-01-07 08:44:34 $
*
* 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 _SBXCORE_HXX
#define _SBXCORE_HXX
#ifndef _RTTI_HXX //autogen
#include <tools/rtti.hxx>
#endif
#ifndef _REF_HXX
#include <tools/ref.hxx>
#endif
#ifndef _DEBUG_HXX
#include <tools/debug.hxx>
#endif
#include <basic/sbxdef.hxx>
class SvStream;
class String;
class UniString;
// Das nachfolgende Makro definiert die vier (fuenf) notwendigen Methoden
// innerhalb eines SBX-Objekts. LoadPrivateData() und StorePrivateData()
// muessen selbst implementiert werden. Sie sind fuer das Laden/Speichern
// der Daten der abgeleiteten Klasse notwendig. Load() und Store() duerfen
// nicht ueberlagert werden.
// Diese Version des Makros definiert keine Load/StorePrivateData()-Methoden
#define SBX_DECL_PERSIST_NODATA( nCre, nSbxId, nVer ) \
virtual UINT32 GetCreator() const { return nCre; } \
virtual UINT16 GetVersion() const { return nVer; } \
virtual UINT16 GetSbxId() const { return nSbxId; }
#define SBX_DECL_PERSIST_NODATA_() \
virtual UINT32 GetCreator() const; \
virtual UINT16 GetVersion() const; \
virtual UINT16 GetSbxId() const;
// Diese Version des Makros definiert Load/StorePrivateData()-Methoden
#define SBX_DECL_PERSIST( nCre, nSbxId, nVer ) \
virtual BOOL LoadPrivateData( SvStream&, USHORT ); \
virtual BOOL StorePrivateData( SvStream& ) const; \
SBX_DECL_PERSIST_NODATA( nCre, nSbxId, nVer )
#define SBX_DECL_PERSIST_() \
virtual BOOL LoadPrivateData( SvStream&, USHORT ); \
virtual BOOL StorePrivateData( SvStream& ) const; \
SBX_DECL_PERSIST_NODATA_()
#define SBX_IMPL_PERSIST( C, nCre, nSbxId, nVer ) \
UINT32 C::GetCreator() const { return nCre; } \
UINT16 C::GetVersion() const { return nVer; } \
UINT16 C::GetSbxId() const { return nSbxId; }
class SbxBase;
class SbxFactory;
class SbxObject;
DBG_NAMEEX(SbxBase)
class SbxBaseImpl;
class SbxBase : virtual public SvRefBase
{
SbxBaseImpl* mpSbxBaseImpl; // Impl data
virtual BOOL LoadData( SvStream&, USHORT );
virtual BOOL StoreData( SvStream& ) const;
protected:
USHORT nFlags; // Flag-Bits
SbxBase();
SbxBase( const SbxBase& );
SbxBase& operator=( const SbxBase& );
virtual ~SbxBase();
SBX_DECL_PERSIST(0,0,0);
public:
TYPEINFO();
inline void SetFlags( USHORT n );
inline USHORT GetFlags() const;
inline void SetFlag( USHORT n );
inline void ResetFlag( USHORT n );
inline BOOL IsSet( USHORT n ) const;
inline BOOL IsReset( USHORT n ) const;
inline BOOL CanRead() const;
inline BOOL CanWrite() const;
inline BOOL IsModified() const;
inline BOOL IsConst() const;
inline BOOL IsHidden() const;
inline BOOL IsVisible() const;
virtual BOOL IsFixed() const;
virtual void SetModified( BOOL );
virtual SbxDataType GetType() const;
virtual SbxClassType GetClass() const;
virtual void Clear();
static SbxBase* Load( SvStream& );
static void Skip( SvStream& );
BOOL Store( SvStream& );
virtual BOOL LoadCompleted();
virtual BOOL StoreCompleted();
static SbxError GetError();
static void SetError( SbxError );
static BOOL IsError();
static void ResetError();
// Setzen der Factory fuer Load/Store/Create
static void AddFactory( SbxFactory* );
static void RemoveFactory( SbxFactory* );
static SbxBase* Create( UINT16, UINT32=SBXCR_SBX );
static SbxObject* CreateObject( const String& );
// Sbx-Loesung als Ersatz fuer SfxBroadcaster::Enable()
static void StaticEnableBroadcasting( BOOL bEnable );
static BOOL StaticIsEnabledBroadcasting( void );
};
#ifndef SBX_BASE_DECL_DEFINED
#define SBX_BASE_DECL_DEFINED
SV_DECL_REF(SbxBase)
#endif
inline void SbxBase::SetFlags( USHORT n )
{ DBG_CHKTHIS( SbxBase, 0 ); nFlags = n; }
inline USHORT SbxBase::GetFlags() const
{ DBG_CHKTHIS( SbxBase, 0 ); return nFlags; }
inline void SbxBase::SetFlag( USHORT n )
{ DBG_CHKTHIS( SbxBase, 0 ); nFlags |= n; }
inline void SbxBase::ResetFlag( USHORT n )
{ DBG_CHKTHIS( SbxBase, 0 ); nFlags &= ~n; }
inline BOOL SbxBase::IsSet( USHORT n ) const
{ DBG_CHKTHIS( SbxBase, 0 ); return BOOL( ( nFlags & n ) != 0 ); }
inline BOOL SbxBase::IsReset( USHORT n ) const
{ DBG_CHKTHIS( SbxBase, 0 ); return BOOL( ( nFlags & n ) == 0 ); }
inline BOOL SbxBase::CanRead() const
{ DBG_CHKTHIS( SbxBase, 0 ); return IsSet( SBX_READ ); }
inline BOOL SbxBase::CanWrite() const
{ DBG_CHKTHIS( SbxBase, 0 ); return IsSet( SBX_WRITE ); }
inline BOOL SbxBase::IsModified() const
{ DBG_CHKTHIS( SbxBase, 0 ); return IsSet( SBX_MODIFIED ); }
inline BOOL SbxBase::IsConst() const
{ DBG_CHKTHIS( SbxBase, 0 ); return IsSet( SBX_CONST ); }
inline BOOL SbxBase::IsHidden() const
{ DBG_CHKTHIS( SbxBase, 0 ); return IsSet( SBX_HIDDEN ); }
inline BOOL SbxBase::IsVisible() const
{ DBG_CHKTHIS( SbxBase, 0 ); return IsReset( SBX_INVISIBLE ); }
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.3.28); FILE MERGED 2008/04/01 15:01:45 thb 1.3.28.2: #i85898# Stripping all external header guards 2008/03/28 16:06:57 rt 1.3.28.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: sbxcore.hxx,v $
* $Revision: 1.4 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _SBXCORE_HXX
#define _SBXCORE_HXX
#include <tools/rtti.hxx>
#include <tools/ref.hxx>
#include <tools/debug.hxx>
#include <basic/sbxdef.hxx>
class SvStream;
class String;
class UniString;
// Das nachfolgende Makro definiert die vier (fuenf) notwendigen Methoden
// innerhalb eines SBX-Objekts. LoadPrivateData() und StorePrivateData()
// muessen selbst implementiert werden. Sie sind fuer das Laden/Speichern
// der Daten der abgeleiteten Klasse notwendig. Load() und Store() duerfen
// nicht ueberlagert werden.
// Diese Version des Makros definiert keine Load/StorePrivateData()-Methoden
#define SBX_DECL_PERSIST_NODATA( nCre, nSbxId, nVer ) \
virtual UINT32 GetCreator() const { return nCre; } \
virtual UINT16 GetVersion() const { return nVer; } \
virtual UINT16 GetSbxId() const { return nSbxId; }
#define SBX_DECL_PERSIST_NODATA_() \
virtual UINT32 GetCreator() const; \
virtual UINT16 GetVersion() const; \
virtual UINT16 GetSbxId() const;
// Diese Version des Makros definiert Load/StorePrivateData()-Methoden
#define SBX_DECL_PERSIST( nCre, nSbxId, nVer ) \
virtual BOOL LoadPrivateData( SvStream&, USHORT ); \
virtual BOOL StorePrivateData( SvStream& ) const; \
SBX_DECL_PERSIST_NODATA( nCre, nSbxId, nVer )
#define SBX_DECL_PERSIST_() \
virtual BOOL LoadPrivateData( SvStream&, USHORT ); \
virtual BOOL StorePrivateData( SvStream& ) const; \
SBX_DECL_PERSIST_NODATA_()
#define SBX_IMPL_PERSIST( C, nCre, nSbxId, nVer ) \
UINT32 C::GetCreator() const { return nCre; } \
UINT16 C::GetVersion() const { return nVer; } \
UINT16 C::GetSbxId() const { return nSbxId; }
class SbxBase;
class SbxFactory;
class SbxObject;
DBG_NAMEEX(SbxBase)
class SbxBaseImpl;
class SbxBase : virtual public SvRefBase
{
SbxBaseImpl* mpSbxBaseImpl; // Impl data
virtual BOOL LoadData( SvStream&, USHORT );
virtual BOOL StoreData( SvStream& ) const;
protected:
USHORT nFlags; // Flag-Bits
SbxBase();
SbxBase( const SbxBase& );
SbxBase& operator=( const SbxBase& );
virtual ~SbxBase();
SBX_DECL_PERSIST(0,0,0);
public:
TYPEINFO();
inline void SetFlags( USHORT n );
inline USHORT GetFlags() const;
inline void SetFlag( USHORT n );
inline void ResetFlag( USHORT n );
inline BOOL IsSet( USHORT n ) const;
inline BOOL IsReset( USHORT n ) const;
inline BOOL CanRead() const;
inline BOOL CanWrite() const;
inline BOOL IsModified() const;
inline BOOL IsConst() const;
inline BOOL IsHidden() const;
inline BOOL IsVisible() const;
virtual BOOL IsFixed() const;
virtual void SetModified( BOOL );
virtual SbxDataType GetType() const;
virtual SbxClassType GetClass() const;
virtual void Clear();
static SbxBase* Load( SvStream& );
static void Skip( SvStream& );
BOOL Store( SvStream& );
virtual BOOL LoadCompleted();
virtual BOOL StoreCompleted();
static SbxError GetError();
static void SetError( SbxError );
static BOOL IsError();
static void ResetError();
// Setzen der Factory fuer Load/Store/Create
static void AddFactory( SbxFactory* );
static void RemoveFactory( SbxFactory* );
static SbxBase* Create( UINT16, UINT32=SBXCR_SBX );
static SbxObject* CreateObject( const String& );
// Sbx-Loesung als Ersatz fuer SfxBroadcaster::Enable()
static void StaticEnableBroadcasting( BOOL bEnable );
static BOOL StaticIsEnabledBroadcasting( void );
};
#ifndef SBX_BASE_DECL_DEFINED
#define SBX_BASE_DECL_DEFINED
SV_DECL_REF(SbxBase)
#endif
inline void SbxBase::SetFlags( USHORT n )
{ DBG_CHKTHIS( SbxBase, 0 ); nFlags = n; }
inline USHORT SbxBase::GetFlags() const
{ DBG_CHKTHIS( SbxBase, 0 ); return nFlags; }
inline void SbxBase::SetFlag( USHORT n )
{ DBG_CHKTHIS( SbxBase, 0 ); nFlags |= n; }
inline void SbxBase::ResetFlag( USHORT n )
{ DBG_CHKTHIS( SbxBase, 0 ); nFlags &= ~n; }
inline BOOL SbxBase::IsSet( USHORT n ) const
{ DBG_CHKTHIS( SbxBase, 0 ); return BOOL( ( nFlags & n ) != 0 ); }
inline BOOL SbxBase::IsReset( USHORT n ) const
{ DBG_CHKTHIS( SbxBase, 0 ); return BOOL( ( nFlags & n ) == 0 ); }
inline BOOL SbxBase::CanRead() const
{ DBG_CHKTHIS( SbxBase, 0 ); return IsSet( SBX_READ ); }
inline BOOL SbxBase::CanWrite() const
{ DBG_CHKTHIS( SbxBase, 0 ); return IsSet( SBX_WRITE ); }
inline BOOL SbxBase::IsModified() const
{ DBG_CHKTHIS( SbxBase, 0 ); return IsSet( SBX_MODIFIED ); }
inline BOOL SbxBase::IsConst() const
{ DBG_CHKTHIS( SbxBase, 0 ); return IsSet( SBX_CONST ); }
inline BOOL SbxBase::IsHidden() const
{ DBG_CHKTHIS( SbxBase, 0 ); return IsSet( SBX_HIDDEN ); }
inline BOOL SbxBase::IsVisible() const
{ DBG_CHKTHIS( SbxBase, 0 ); return IsReset( SBX_INVISIBLE ); }
#endif
<|endoftext|> |
<commit_before>#include <iostream>
#include <unistd.h>
#include <getopt.h>
#include "gen.h"
#include "interface.h"
#include "parser.h"
int main(int argc, char *argv[])
{
Generate Gen;
Parser Prs;
char *ybf;
while (1) {
static struct option long_options[] = {
{ "new", optional_argument, 0, 'n' },
{ "help", no_argument, 0, 'h' },
{ "debug", no_argument, 0, 'd' },
{ 0, 0, 0, 0 }
};
int option_index = 0;
int c = getopt_long(argc, argv, "dhnm", long_options, &option_index);
if (c == -1)
break;
switch (c) {
case 'd':
Gen.CheckMake();
Gen.WriteMake();
Gen.GenMakeFromTemplate();
Gen.WalkDir(Gen.current_dir, ".\\.cpp$", FS_DEFAULT | FS_MATCHDIRS);
Gen.WalkDir(Gen.current_dir, ".\\.h$", FS_DEFAULT | FS_MATCHDIRS);
Prs.OpenConfig(argv[2]);
break;
case 'h':
printHelp();
break;
case 'n':
Gen.GenBlankConfig(0);
break;
}
}
return 0;
}
<commit_msg>yabs: fix debug optional argument<commit_after>#include <iostream>
#include <unistd.h>
#include <getopt.h>
#include "gen.h"
#include "interface.h"
#include "parser.h"
int main(int argc, char *argv[])
{
Generate Gen;
Parser Prs;
char *ybf;
while (1) {
static struct option long_options[] = {
{ "new", optional_argument, 0, 'n' },
{ "help", no_argument, 0, 'h' },
{ "debug", no_argument, 0, 'd' },
{ 0, 0, 0, 0 }
};
int option_index = 0;
int c = getopt_long(argc, argv, "dhnm", long_options, &option_index);
if (c == -1)
break;
switch (c) {
case 'd':
Gen.CheckMake();
Gen.WriteMake();
Gen.GenMakeFromTemplate();
Gen.WalkDir(Gen.current_dir, ".\\.cpp$", FS_DEFAULT | FS_MATCHDIRS);
Gen.WalkDir(Gen.current_dir, ".\\.h$", FS_DEFAULT | FS_MATCHDIRS);
if (argv[2] != NULL)
Prs.OpenConfig(argv[2]);
break;
case 'h':
printHelp();
break;
case 'n':
Gen.GenBlankConfig(0);
break;
}
}
return 0;
}
<|endoftext|> |
<commit_before>#include "update.hpp"
#include <cstdio>
#include "storage.hpp"
static std::map<uint16_t, LiveUpdate::resume_func> resume_funcs;
bool resume_begin(storage_header& storage, LiveUpdate::resume_func func)
{
/// verify checksum
/// restore each entry one by one, calling registered handlers
printf("* Resuming %d stored entries\n", storage.entries);
for (auto* ptr = storage.begin(); ptr->type != TYPE_END; ptr = storage.next(ptr))
{
// use registered functions when we can, otherwise, use normal
auto it = resume_funcs.find(ptr->id);
if (it != resume_funcs.end())
{
it->second(*ptr);
} else {
func(*ptr);
}
}
return true;
}
void LiveUpdate::on_resume(uint16_t id, resume_func func)
{
resume_funcs[id] = func;
}
/// struct Restore
std::string Restore::as_string() const
{
if (ent.type == TYPE_STRING)
return std::string(ent.vla, ent.len);
throw std::runtime_error("Incorrect type: " + std::to_string(ent.type));
}
buffer_len Restore::as_buffer() const
{
if (ent.type == TYPE_BUFFER)
return {ent.vla, ent.len};
throw std::runtime_error("Incorrect type: " + std::to_string(ent.type));
}
#include "serialize_tcp.hpp"
Restore::Connection Restore::as_tcp_connection(net::TCP& tcp) const
{
return deserialize_connection(ent.vla, tcp);
}
int16_t Restore::get_type() const noexcept
{
return ent.type;
}
uint16_t Restore::get_id() const noexcept
{
return ent.id;
}
int32_t Restore::length() const noexcept
{
return ent.len;
}
void* Restore::data() const noexcept
{
return ent.vla;
}
<commit_msg>Zero storage after resuming for security<commit_after>#include "update.hpp"
#include <cstdio>
#include "storage.hpp"
static std::map<uint16_t, LiveUpdate::resume_func> resume_funcs;
bool resume_begin(storage_header& storage, LiveUpdate::resume_func func)
{
/// verify checksum
/// restore each entry one by one, calling registered handlers
printf("* Resuming %d stored entries\n", storage.entries);
for (auto* ptr = storage.begin(); ptr->type != TYPE_END; ptr = storage.next(ptr))
{
// use registered functions when we can, otherwise, use normal
auto it = resume_funcs.find(ptr->id);
if (it != resume_funcs.end())
{
it->second(*ptr);
} else {
func(*ptr);
}
}
/// zero out all the values for security reasons
memset(&storage, 0, sizeof(storage_header) + storage.length);
return true;
}
void LiveUpdate::on_resume(uint16_t id, resume_func func)
{
resume_funcs[id] = func;
}
/// struct Restore
std::string Restore::as_string() const
{
if (ent.type == TYPE_STRING)
return std::string(ent.vla, ent.len);
throw std::runtime_error("Incorrect type: " + std::to_string(ent.type));
}
buffer_len Restore::as_buffer() const
{
if (ent.type == TYPE_BUFFER)
return {ent.vla, ent.len};
throw std::runtime_error("Incorrect type: " + std::to_string(ent.type));
}
#include "serialize_tcp.hpp"
Restore::Connection Restore::as_tcp_connection(net::TCP& tcp) const
{
return deserialize_connection(ent.vla, tcp);
}
int16_t Restore::get_type() const noexcept
{
return ent.type;
}
uint16_t Restore::get_id() const noexcept
{
return ent.id;
}
int32_t Restore::length() const noexcept
{
return ent.len;
}
void* Restore::data() const noexcept
{
return ent.vla;
}
<|endoftext|> |
<commit_before>#include <hx/CFFI.h>
#include <ui/GamepadEvent.h>
namespace lime {
AutoGCRoot* GamepadEvent::callback = 0;
AutoGCRoot* GamepadEvent::eventObject = 0;
static double id_axis;
static int id_button;
static int id_id;
static int id_type;
static int id_value;
static bool init = false;
GamepadEvent::GamepadEvent () {
axis = 0;
axisValue = 0;
button = 0;
id = 0;
type = AXIS_MOVE;
}
void GamepadEvent::Dispatch (GamepadEvent* event) {
if (GamepadEvent::callback) {
if (!init) {
id_axis = val_id ("axis");
id_button = val_id ("button");
id_id = val_id ("id");
id_type = val_id ("type");
id_value = val_id ("value");
init = true;
}
value object = (GamepadEvent::eventObject ? GamepadEvent::eventObject->get () : alloc_empty_object ());
alloc_field (object, id_axis, alloc_float (event->axis));
alloc_field (object, id_button, alloc_int (event->button));
alloc_field (object, id_id, alloc_int (event->id));
alloc_field (object, id_type, alloc_int (event->type));
alloc_field (object, id_value, alloc_float (event->axisValue));
val_call0 (GamepadEvent::callback->get ());
}
}
}<commit_msg>Should be alloc_int<commit_after>#include <hx/CFFI.h>
#include <ui/GamepadEvent.h>
namespace lime {
AutoGCRoot* GamepadEvent::callback = 0;
AutoGCRoot* GamepadEvent::eventObject = 0;
static double id_axis;
static int id_button;
static int id_id;
static int id_type;
static int id_value;
static bool init = false;
GamepadEvent::GamepadEvent () {
axis = 0;
axisValue = 0;
button = 0;
id = 0;
type = AXIS_MOVE;
}
void GamepadEvent::Dispatch (GamepadEvent* event) {
if (GamepadEvent::callback) {
if (!init) {
id_axis = val_id ("axis");
id_button = val_id ("button");
id_id = val_id ("id");
id_type = val_id ("type");
id_value = val_id ("value");
init = true;
}
value object = (GamepadEvent::eventObject ? GamepadEvent::eventObject->get () : alloc_empty_object ());
alloc_field (object, id_axis, alloc_int (event->axis));
alloc_field (object, id_button, alloc_int (event->button));
alloc_field (object, id_id, alloc_int (event->id));
alloc_field (object, id_type, alloc_int (event->type));
alloc_field (object, id_value, alloc_float (event->axisValue));
val_call0 (GamepadEvent::callback->get ());
}
}
}<|endoftext|> |
<commit_before>/**
Copyright (c) 2013, Philip Deegan.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Philip Deegan nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _KUL_TCP_BASE_HPP_
#define _KUL_TCP_BASE_HPP_
namespace kul{ namespace tcp {
class Exception : public kul::Exception{
public:
Exception(const char*f, const uint16_t& l, const std::string& s) : kul::Exception(f, l, s){}
};
template <class T = uint8_t>
class ASocket{
protected:
bool open = 0;
public:
virtual ~ASocket(){}
virtual bool connect(const std::string& host, const int16_t& port) = 0;
virtual bool close() = 0;
virtual uint16_t read(T* data, const size_t& len) throw(kul::tcp::Exception) = 0;
virtual bool write(const T* data, const size_t& len) = 0;
};
template <class T = uint8_t>
class ASocketServer{
protected:
uint16_t p;
uint64_t s;
ASocketServer(const uint16_t& p) : p(p){}
public:
virtual ~ASocketServer(){}
virtual void start() throw (kul::tcp::Exception) = 0;
virtual void onConnect(const char* ip, const uint16_t& port){}
virtual void onDisconnect(const char* ip, const uint16_t& port){}
const uint64_t up() const { return s - kul::Now::MILLIS(); }
const uint16_t& port() const { return p; }
bool started() const { return s; }
};
}// END NAMESPACE tcp
}// END NAMESPACE kul
#endif /* _KUL_HTTP_BASE_HPP_ */<commit_msg>Update tcp.base.hpp<commit_after>/**
Copyright (c) 2013, Philip Deegan.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Philip Deegan nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _KUL_TCP_BASE_HPP_
#define _KUL_TCP_BASE_HPP_
namespace kul{ namespace tcp {
class Exception : public kul::Exception{
public:
Exception(const char*f, const uint16_t& l, const std::string& s) : kul::Exception(f, l, s){}
};
template <class T = uint8_t>
class ASocket{
protected:
bool open = 0;
public:
virtual ~ASocket(){}
virtual bool connect(const std::string& host, const int16_t& port) = 0;
virtual bool close() = 0;
virtual uint16_t read(T* data, const uint16_t& len) throw(kul::tcp::Exception) = 0;
virtual bool write(const T* data, const uint16_t& len) = 0;
};
template <class T = uint8_t>
class ASocketServer{
protected:
uint16_t p;
uint64_t s;
ASocketServer(const uint16_t& p) : p(p){}
public:
virtual ~ASocketServer(){}
virtual void start() throw (kul::tcp::Exception) = 0;
virtual void onConnect(const char* ip, const uint16_t& port){}
virtual void onDisconnect(const char* ip, const uint16_t& port){}
const uint64_t up() const { return s - kul::Now::MILLIS(); }
const uint16_t& port() const { return p; }
bool started() const { return s; }
};
}// END NAMESPACE tcp
}// END NAMESPACE kul
#endif /* _KUL_HTTP_BASE_HPP_ */
<|endoftext|> |
<commit_before>/**
@file Log.hpp
@brief Logging utilities.
@author Timothy Howard
@copyright 2013-2014 Timothy Howard under the MIT license;
see @ref index or the accompanying LICENSE file for full text.
*/
#ifndef HORD_LOG_HPP_
#define HORD_LOG_HPP_
#include <Hord/config.hpp>
#include <Hord/String.hpp>
#include <duct/StateStore.hpp>
#include <duct/IO/multistream.hpp>
#include <fstream>
#include <ostream>
namespace Hord {
namespace Log {
// TODO: Common output sentinels (e.g., current time in ISO-8601)
// TODO: Logging interface like exception throwing
// TODO: Datastores need to logify by roots.. somehow.
// Driver should probably manage that. Actually, Driver will
// probably be doing most of the Datastore logging anyways.
// TODO: Need to handle multi-threaded output to file stream properly
// FIXME: thread_local requires g++ 4.8!? (In Clang!)
// Forward declarations
class Controller;
class OutputStream;
/**
@addtogroup etc
@{
*/
/**
@addtogroup log
@{
*/
/**
Stream type.
*/
enum StreamType : unsigned {
general = 0u,
debug,
error,
/** @cond INTERNAL */
LAST
/** @endcond */ // INTERNAL
};
/** Stream prefixes. */
enum class Pre : unsigned {
general = 0u,
debug,
error,
none,
current,
/** @cond INTERNAL */
LAST,
LAST_TYPE = error
/** @endcond */ // INTERNAL
};
/** @cond INTERNAL */
enum : std::size_t {
STREAMBUF_BUFFER_SIZE = 2048u
};
extern /*thread_local*/ Controller
s_controller;
/** @endcond */ // INTERNAL
/**
Get the log controller.
*/
inline Controller&
get_controller() noexcept {
return s_controller;
}
/**
Log controller.
*/
class Controller final {
private:
friend class OutputStream;
/**
State flags.
*/
enum class Flag : unsigned {
write_stdout = 1 << 0,
write_file = 1 << 1,
write_datastore = 1 << 2
};
duct::StateStore<Flag> m_flags;
String m_file_path;
std::ofstream m_file_stream;
char m_mc_buffer[STREAMBUF_BUFFER_SIZE];
duct::IO::multicast_vector_type m_mc_vectors[
static_cast<unsigned>(StreamType::LAST)
];
duct::IO::multistreambuf m_mc_streambufs[
static_cast<unsigned>(StreamType::LAST)
];
/** Disable multicast to log file stream. */
void
disable_file_stream() noexcept;
/** Enable multicast to log file stream. */
void
enable_file_stream() noexcept;
/**
Open the log file stream.
@returns Whether the operation succeeded.
*/
bool
open_file();
/**
Close the log file stream.
@returns Whether the operation succeeded.
*/
bool
close_file();
Controller(Controller&&) = delete;
Controller(Controller const&) = delete;
Controller& operator=(Controller const&) = delete;
Controller& operator=(Controller&&) = delete;
public:
/** @name Constructors and destructor */ /// @{
/**
Constructor with flags and log file path.
@param enable_stdout Enable or disable standard output.
@param enable_file Enable or disable log file output.
@param enable_datastore Enable or disable datastore-local
file output.
@param path Log file path.
*/
Controller(
bool const enable_stdout,
bool const enable_file,
bool const enable_datastore,
String path
) noexcept;
/** Destructor. */
~Controller() noexcept;
/// @}
/** @name Configuration */ /// @{
/**
Enable or disable standard output.
@param enable Whether to enable or disable output.
*/
void
stdout(
bool const enable
) noexcept;
/**
Check whether standard output is enabled.
*/
bool
stdout_enabled() const noexcept {
return m_flags.test(Flag::write_stdout);
}
/**
Enable or disable file output.
@returns
- @c true if the operation succeeded (i.e., opening or closing
the log file stream);
- @c false if the operation failed.
@param enable Whether to enable or disable output.
*/
bool
file(
bool const enable
) noexcept;
/**
Check whether file output is enabled.
*/
bool
file_enabled() const noexcept {
return m_flags.test(Flag::write_file);
}
/**
Check whether the file stream is open.
@remarks If this returns @c true, it implies
<code>file_enabled() == true</code>.
*/
bool
file_active() const noexcept {
return m_file_stream.is_open();
}
/**
Enable or disable datastore-local file output.
@param enable Whether to enable or disable output.
*/
void
datastore(
bool const enable
) noexcept;
/**
Check whether datastore-local file output is enabled.
*/
bool
datastore_enabled() const noexcept {
return m_flags.test(Flag::write_datastore);
}
/**
Set the log file path.
@remarks If the file stream is currently open, it is closed.
If opening on @a path fails, @c false is returned, but file
output is still enabled. If log file output is disabled,
this only assigns the log file path.
@returns
- @c true if the file stream was successfully opened;
- @c false if the file path could not be opened for writing.
@param path Log file path.
*/
bool
set_file_path(
String path
) noexcept;
/**
Get log file path.
*/
String const&
get_file_path() const noexcept {
return m_file_path;
}
/// @}
};
/**
Log output stream.
*/
class OutputStream final
: public std::ostream
{
private:
using base = std::ostream;
StreamType const m_type;
OutputStream() = delete;
OutputStream(OutputStream const&) = delete;
OutputStream& operator=(OutputStream const&) = delete;
OutputStream& operator=(OutputStream&&) = delete;
public:
/** @name Constructors and destructor */ /// @{
/**
Constructor with type and streambuf.
@param type Stream type.
@param put_prefix Whether to write Pre::current.
*/
OutputStream(
StreamType const type,
bool const put_prefix
) noexcept;
// FIXME: Defect in libstdc++ 4.7.3: basic_ostream
// move ctor is deleted and swap() is not defined
/**
Move constructor.
@param other Stream to take ownership of.
*/
OutputStream(
OutputStream&& other
) noexcept
//: base(std::move(other))
: base(other.rdbuf())
, m_type(other.m_type)
{}
/** Destructor. */
~OutputStream() noexcept override {
// Force-write streambuf to multicast streams
static_cast<duct::IO::multistreambuf*>(
this->rdbuf()
)->multicast();
}
/// @}
/** @name Properties */ /// @{
/**
Get stream type.
*/
StreamType
get_type() const noexcept {
return m_type;
}
/// @}
};
/**
Acquire log output stream for type.
@param type Stream type.
*/
inline OutputStream
acquire(
StreamType const type = Log::StreamType::general,
bool const put_prefix = true
) noexcept {
return OutputStream(type, put_prefix);
}
/** @cond INTERNAL */
OutputStream&
operator<<(
OutputStream& stream,
Pre prefix
);
/** @endcond */ // INTERNAL
/** @} */ // end of doc-group log
/** @} */ // end of doc-group etc
} // namespace Log
} // namespace Hord
#endif // HORD_LOG_HPP_
<commit_msg>doc: added missing description for put_prefix in Log::acquire().<commit_after>/**
@file Log.hpp
@brief Logging utilities.
@author Timothy Howard
@copyright 2013-2014 Timothy Howard under the MIT license;
see @ref index or the accompanying LICENSE file for full text.
*/
#ifndef HORD_LOG_HPP_
#define HORD_LOG_HPP_
#include <Hord/config.hpp>
#include <Hord/String.hpp>
#include <duct/StateStore.hpp>
#include <duct/IO/multistream.hpp>
#include <fstream>
#include <ostream>
namespace Hord {
namespace Log {
// TODO: Common output sentinels (e.g., current time in ISO-8601)
// TODO: Logging interface like exception throwing
// TODO: Datastores need to logify by roots.. somehow.
// Driver should probably manage that. Actually, Driver will
// probably be doing most of the Datastore logging anyways.
// TODO: Need to handle multi-threaded output to file stream properly
// FIXME: thread_local requires g++ 4.8!? (In Clang!)
// Forward declarations
class Controller;
class OutputStream;
/**
@addtogroup etc
@{
*/
/**
@addtogroup log
@{
*/
/**
Stream type.
*/
enum StreamType : unsigned {
general = 0u,
debug,
error,
/** @cond INTERNAL */
LAST
/** @endcond */ // INTERNAL
};
/** Stream prefixes. */
enum class Pre : unsigned {
general = 0u,
debug,
error,
none,
current,
/** @cond INTERNAL */
LAST,
LAST_TYPE = error
/** @endcond */ // INTERNAL
};
/** @cond INTERNAL */
enum : std::size_t {
STREAMBUF_BUFFER_SIZE = 2048u
};
extern /*thread_local*/ Controller
s_controller;
/** @endcond */ // INTERNAL
/**
Get the log controller.
*/
inline Controller&
get_controller() noexcept {
return s_controller;
}
/**
Log controller.
*/
class Controller final {
private:
friend class OutputStream;
/**
State flags.
*/
enum class Flag : unsigned {
write_stdout = 1 << 0,
write_file = 1 << 1,
write_datastore = 1 << 2
};
duct::StateStore<Flag> m_flags;
String m_file_path;
std::ofstream m_file_stream;
char m_mc_buffer[STREAMBUF_BUFFER_SIZE];
duct::IO::multicast_vector_type m_mc_vectors[
static_cast<unsigned>(StreamType::LAST)
];
duct::IO::multistreambuf m_mc_streambufs[
static_cast<unsigned>(StreamType::LAST)
];
/** Disable multicast to log file stream. */
void
disable_file_stream() noexcept;
/** Enable multicast to log file stream. */
void
enable_file_stream() noexcept;
/**
Open the log file stream.
@returns Whether the operation succeeded.
*/
bool
open_file();
/**
Close the log file stream.
@returns Whether the operation succeeded.
*/
bool
close_file();
Controller(Controller&&) = delete;
Controller(Controller const&) = delete;
Controller& operator=(Controller const&) = delete;
Controller& operator=(Controller&&) = delete;
public:
/** @name Constructors and destructor */ /// @{
/**
Constructor with flags and log file path.
@param enable_stdout Enable or disable standard output.
@param enable_file Enable or disable log file output.
@param enable_datastore Enable or disable datastore-local
file output.
@param path Log file path.
*/
Controller(
bool const enable_stdout,
bool const enable_file,
bool const enable_datastore,
String path
) noexcept;
/** Destructor. */
~Controller() noexcept;
/// @}
/** @name Configuration */ /// @{
/**
Enable or disable standard output.
@param enable Whether to enable or disable output.
*/
void
stdout(
bool const enable
) noexcept;
/**
Check whether standard output is enabled.
*/
bool
stdout_enabled() const noexcept {
return m_flags.test(Flag::write_stdout);
}
/**
Enable or disable file output.
@returns
- @c true if the operation succeeded (i.e., opening or closing
the log file stream);
- @c false if the operation failed.
@param enable Whether to enable or disable output.
*/
bool
file(
bool const enable
) noexcept;
/**
Check whether file output is enabled.
*/
bool
file_enabled() const noexcept {
return m_flags.test(Flag::write_file);
}
/**
Check whether the file stream is open.
@remarks If this returns @c true, it implies
<code>file_enabled() == true</code>.
*/
bool
file_active() const noexcept {
return m_file_stream.is_open();
}
/**
Enable or disable datastore-local file output.
@param enable Whether to enable or disable output.
*/
void
datastore(
bool const enable
) noexcept;
/**
Check whether datastore-local file output is enabled.
*/
bool
datastore_enabled() const noexcept {
return m_flags.test(Flag::write_datastore);
}
/**
Set the log file path.
@remarks If the file stream is currently open, it is closed.
If opening on @a path fails, @c false is returned, but file
output is still enabled. If log file output is disabled,
this only assigns the log file path.
@returns
- @c true if the file stream was successfully opened;
- @c false if the file path could not be opened for writing.
@param path Log file path.
*/
bool
set_file_path(
String path
) noexcept;
/**
Get log file path.
*/
String const&
get_file_path() const noexcept {
return m_file_path;
}
/// @}
};
/**
Log output stream.
*/
class OutputStream final
: public std::ostream
{
private:
using base = std::ostream;
StreamType const m_type;
OutputStream() = delete;
OutputStream(OutputStream const&) = delete;
OutputStream& operator=(OutputStream const&) = delete;
OutputStream& operator=(OutputStream&&) = delete;
public:
/** @name Constructors and destructor */ /// @{
/**
Constructor with type and streambuf.
@param type Stream type.
@param put_prefix Whether to write Pre::current.
*/
OutputStream(
StreamType const type,
bool const put_prefix
) noexcept;
// FIXME: Defect in libstdc++ 4.7.3: basic_ostream
// move ctor is deleted and swap() is not defined
/**
Move constructor.
@param other Stream to take ownership of.
*/
OutputStream(
OutputStream&& other
) noexcept
//: base(std::move(other))
: base(other.rdbuf())
, m_type(other.m_type)
{}
/** Destructor. */
~OutputStream() noexcept override {
// Force-write streambuf to multicast streams
static_cast<duct::IO::multistreambuf*>(
this->rdbuf()
)->multicast();
}
/// @}
/** @name Properties */ /// @{
/**
Get stream type.
*/
StreamType
get_type() const noexcept {
return m_type;
}
/// @}
};
/**
Acquire log output stream for type.
@param type Stream type.
@param put_prefix Whether to put the current prefix before
returning.
*/
inline OutputStream
acquire(
StreamType const type = Log::StreamType::general,
bool const put_prefix = true
) noexcept {
return OutputStream(type, put_prefix);
}
/** @cond INTERNAL */
OutputStream&
operator<<(
OutputStream& stream,
Pre prefix
);
/** @endcond */ // INTERNAL
/** @} */ // end of doc-group log
/** @} */ // end of doc-group etc
} // namespace Log
} // namespace Hord
#endif // HORD_LOG_HPP_
<|endoftext|> |
<commit_before><commit_msg>CWS-TOOLING: integrate CWS ab61 2009-01-29 09:39:19 +0100 jsk r267096 : #i97038 2009-01-20 12:35:31 +0100 ab r266568 : #i94994# Applied patch 2009-01-19 17:50:55 +0100 ab r266514 : #i97038# Applied patch 2009-01-13 14:47:20 +0100 ab r266226 : #i96087# Applied patch 2009-01-13 12:24:30 +0100 ab r266207 : #i95200# Applied patch 2008-12-19 16:37:32 +0100 ab r265735 : #i93214# Applied patch 2008-12-19 16:21:38 +0100 ab r265730 : #i57749# Applied patch<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-443271.
//
// This file is part of the GLVis visualization tool and library. For more
// information and source code availability see https://glvis.org.
//
// GLVis is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#include "shader.hpp"
#include <regex>
namespace gl3
{
bool ShaderProgram::create(std::string vertexShader,
std::string fragmentShader,
std::unordered_map<int, std::string> inAttributes,
int numOutputs)
{
attrib_idx = inAttributes;
num_outputs = numOutputs;
is_compiled = false;
GetGLSLVersion();
std::string fmtVS = formatShader(vertexShader, GL_VERTEX_SHADER);
vertex_shader = compileShader(fmtVS, GL_VERTEX_SHADER);
if (vertex_shader == 0)
{
return false;
}
std::string fmtFS = formatShader(fragmentShader, GL_FRAGMENT_SHADER);
fragment_shader = compileShader(fmtFS, GL_FRAGMENT_SHADER);
if (fragment_shader == 0)
{
return false;
}
if (!linkShaders({vertex_shader, fragment_shader}))
{
std::cerr << "Failed to link shaders for program." << std::endl;
return false;
}
mapShaderUniforms();
is_compiled = true;
return is_compiled;
}
int ShaderProgram::glsl_version = -1;
#ifndef __EMSCRIPTEN__
const bool ShaderProgram::glsl_is_es = false;
#else
const bool ShaderProgram::glsl_is_es = true;
#endif
void ShaderProgram::GetGLSLVersion()
{
if (glsl_version == -1)
{
std::string verStr = (char*)glGetString(GL_VERSION);
int ver_major, ver_minor;
int vs_idx = verStr.find_first_of(".");
ver_major = std::stoi(verStr.substr(vs_idx - 1, vs_idx));
ver_minor = std::stoi(verStr.substr(vs_idx + 1, 1));
int opengl_ver = ver_major * 100 + ver_minor * 10;
#ifndef __EMSCRIPTEN__
// The GLSL version is the same as the OpenGL version when the OpenGL
// version is >= 3.30, otherwise it is:
//
// GL Version | GLSL Version
// -------------------------
// 2.0 | 1.10
// 2.1 | 1.20
// 3.0 | 1.30
// 3.1 | 1.40
// 3.2 | 1.50
if (opengl_ver < 330)
{
if (ver_major == 2)
{
glsl_version = opengl_ver - 90;
}
else if (ver_major == 3)
{
glsl_version = opengl_ver - 170;
}
else
{
std::cerr << "fatal: unsupported OpenGL version " << opengl_ver << std::endl;
glsl_version = 100;
}
}
else
{
glsl_version = opengl_ver;
}
#else
// GL Version | WebGL Version | GLSL Version
// 2.0 | 1.0 | 1.00 ES
// 3.0 | 2.0 | 3.00 ES
// 3.1 | | 3.10 ES
if (opengl_ver < 300)
{
glsl_version = 100;
}
else
{
glsl_version = 300;
}
#endif
std::cerr << "Using GLSL " << glsl_version;
if (glsl_is_es) { std::cerr << " ES"; }
std::cerr << std::endl;
}
}
std::string ShaderProgram::formatShader(const std::string& inShader,
GLenum shaderType)
{
std::string formatted = inShader;
// replace some identifiers depending on the version of glsl we're using
if (glsl_version >= 130)
{
if (shaderType == GL_VERTEX_SHADER)
{
formatted = std::regex_replace(formatted, std::regex("attribute"), "in");
formatted = std::regex_replace(formatted, std::regex("varying"), "out");
}
else if (shaderType == GL_FRAGMENT_SHADER)
{
formatted = std::regex_replace(formatted, std::regex("varying"), "in");
for (int i = 0; i < num_outputs; i++)
{
std::string indexString = "gl_FragData[";
indexString += std::to_string(i) + "]";
std::string outputString = "out vec4 fragColor_";
outputString += std::to_string(i) + ";\n";
if (glsl_version >= 300)
{
// GLSL/OpenGL 3.30+ or WebGL 2 (GLSL 3.00 ES):
// Prefer in-shader output index setting.
std::string layoutString = "layout(location = ";
layoutString += std::to_string(i) + ") ";
formatted = layoutString + outputString + formatted;
}
else
{
// GLSL 1.30-1.50 (OpenGL 3.0-3.2):
// No in-shader output indexing.
// Output locations will be set using glBindFragDataLocation.
formatted = outputString + formatted;
formatted = std::regex_replace(formatted, std::regex(indexString),
"fragColor");
}
if (i == 0)
{
formatted = std::regex_replace(formatted, std::regex("gl_FragColor"),
"fragColor_0");
}
}
}
else
{
std::cerr << "buildShaderString: unknown shader type" << std::endl;
return {};
}
formatted = std::regex_replace(formatted, std::regex("texture2D"), "texture");
}
if (GLDevice::useLegacyTextureFmts())
{
formatted = "#define USE_ALPHA\n" + formatted;
}
if (glsl_is_es)
{
// Add precision specifier - required for WebGL
formatted = "precision mediump float;\n" + formatted;
if (num_outputs > 1 && glsl_version == 100)
{
// Enable WEBGL_draw_buffers in the shader
formatted = "#extension GL_EXT_draw_buffers : require\n" + formatted;
}
if (glsl_version == 300)
{
// WebGL 2 shaders require explicit version setting
formatted = "#version 300 es\n" + formatted;
}
}
else
{
// Append version setting for all desktop shaders
formatted = std::regex_replace("#version GLSL_VER\n", std::regex("GLSL_VER"),
std::to_string(glsl_version)) + formatted;
}
return formatted;
}
GLuint ShaderProgram::compileShader(const std::string& inShader,
GLenum shaderType)
{
int shader_len = inShader.length();
const char *shader_cstr = inShader.c_str();
GLuint shader = glCreateShader(shaderType);
glShaderSource(shader, 1, &shader_cstr, &shader_len);
glCompileShader(shader);
GLint stat;
glGetShaderiv(shader, GL_COMPILE_STATUS, &stat);
// glGetObjectParameteriv
if (stat == GL_FALSE)
{
std::cerr << "failed to compile shader" << std::endl;
int err_len;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &err_len);
char *error_text = new char[err_len];
glGetShaderInfoLog(shader, err_len, &err_len, error_text);
std::cerr << error_text << std::endl;
delete[] error_text;
return 0;
}
return shader;
}
bool ShaderProgram::linkShaders(const std::vector<GLuint>& shaders)
{
// Bind all incoming attributes to their VAO indices.
for (auto attrib_pair : attrib_idx)
{
glBindAttribLocation(program_id, attrib_pair.first,
attrib_pair.second.c_str());
}
#ifndef __EMSCRIPTEN__
if (glsl_version >= 130 && glsl_version < 300)
{
// Bind fragment output variables to MRT indices.
for (int i = 0; i < num_outputs; i++)
{
std::string fragOutVar = "fragColor_" + std::to_string(i);
glBindFragDataLocation(program_id, i, fragOutVar.c_str());
}
}
#endif
for (GLuint i : shaders)
{
glAttachShader(program_id, i);
}
glLinkProgram(program_id);
GLint stat;
glGetProgramiv(program_id, GL_LINK_STATUS, &stat);
if (stat == GL_FALSE)
{
cerr << "fatal: Shader linking failed" << endl;
}
return (stat == GL_TRUE);
}
void ShaderProgram::mapShaderUniforms()
{
int num_unifs;
glGetProgramiv(program_id, GL_ACTIVE_UNIFORMS, &num_unifs);
int max_unif_len;
glGetProgramiv(program_id, GL_ACTIVE_UNIFORM_MAX_LENGTH, &max_unif_len);
for (int i = 0; i < num_unifs; i++)
{
vector<char> unif_buf(max_unif_len+1);
GLsizei name_length;
GLint gl_size;
GLenum gl_type;
glGetActiveUniform(program_id, i, max_unif_len, &name_length, &gl_size,
&gl_type,
unif_buf.data());
std::string unif_name(unif_buf.data(), name_length);
GLuint location = glGetUniformLocation(program_id, unif_name.c_str());
uniform_idx[unif_name] = location;
}
}
}
<commit_msg>Fix MRT variable string replacements<commit_after>// Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-443271.
//
// This file is part of the GLVis visualization tool and library. For more
// information and source code availability see https://glvis.org.
//
// GLVis is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#include "shader.hpp"
#include <regex>
namespace gl3
{
bool ShaderProgram::create(std::string vertexShader,
std::string fragmentShader,
std::unordered_map<int, std::string> inAttributes,
int numOutputs)
{
attrib_idx = inAttributes;
num_outputs = numOutputs;
is_compiled = false;
GetGLSLVersion();
std::string fmtVS = formatShader(vertexShader, GL_VERTEX_SHADER);
vertex_shader = compileShader(fmtVS, GL_VERTEX_SHADER);
if (vertex_shader == 0)
{
return false;
}
std::string fmtFS = formatShader(fragmentShader, GL_FRAGMENT_SHADER);
fragment_shader = compileShader(fmtFS, GL_FRAGMENT_SHADER);
if (fragment_shader == 0)
{
return false;
}
if (!linkShaders({vertex_shader, fragment_shader}))
{
std::cerr << "Failed to link shaders for program." << std::endl;
return false;
}
mapShaderUniforms();
is_compiled = true;
return is_compiled;
}
int ShaderProgram::glsl_version = -1;
#ifndef __EMSCRIPTEN__
const bool ShaderProgram::glsl_is_es = false;
#else
const bool ShaderProgram::glsl_is_es = true;
#endif
void ShaderProgram::GetGLSLVersion()
{
if (glsl_version == -1)
{
std::string verStr = (char*)glGetString(GL_VERSION);
int ver_major, ver_minor;
int vs_idx = verStr.find_first_of(".");
ver_major = std::stoi(verStr.substr(vs_idx - 1, vs_idx));
ver_minor = std::stoi(verStr.substr(vs_idx + 1, 1));
int opengl_ver = ver_major * 100 + ver_minor * 10;
#ifndef __EMSCRIPTEN__
// The GLSL version is the same as the OpenGL version when the OpenGL
// version is >= 3.30, otherwise it is:
//
// GL Version | GLSL Version
// -------------------------
// 2.0 | 1.10
// 2.1 | 1.20
// 3.0 | 1.30
// 3.1 | 1.40
// 3.2 | 1.50
if (opengl_ver < 330)
{
if (ver_major == 2)
{
glsl_version = opengl_ver - 90;
}
else if (ver_major == 3)
{
glsl_version = opengl_ver - 170;
}
else
{
std::cerr << "fatal: unsupported OpenGL version " << opengl_ver << std::endl;
glsl_version = 100;
}
}
else
{
glsl_version = opengl_ver;
}
#else
// GL Version | WebGL Version | GLSL Version
// 2.0 | 1.0 | 1.00 ES
// 3.0 | 2.0 | 3.00 ES
// 3.1 | | 3.10 ES
if (opengl_ver < 300)
{
glsl_version = 100;
}
else
{
glsl_version = 300;
}
#endif
std::cerr << "Using GLSL " << glsl_version;
if (glsl_is_es) { std::cerr << " ES"; }
std::cerr << std::endl;
}
}
std::string ShaderProgram::formatShader(const std::string& inShader,
GLenum shaderType)
{
std::string formatted = inShader;
// replace some identifiers depending on the version of glsl we're using
if (glsl_version >= 130)
{
if (shaderType == GL_VERTEX_SHADER)
{
formatted = std::regex_replace(formatted, std::regex("attribute"), "in");
formatted = std::regex_replace(formatted, std::regex("varying"), "out");
}
else if (shaderType == GL_FRAGMENT_SHADER)
{
formatted = std::regex_replace(formatted, std::regex("varying"), "in");
for (int i = 0; i < num_outputs; i++)
{
std::string indexString = "gl_FragData[";
indexString += std::to_string(i) + "]";
std::string outputString = "out vec4 fragColor_";
outputString += std::to_string(i) + ";\n";
if (glsl_version >= 300)
{
// GLSL/OpenGL 3.30+ or WebGL 2 (GLSL 3.00 ES):
// Prefer in-shader output index setting.
std::string layoutString = "layout(location = ";
layoutString += std::to_string(i) + ") ";
formatted = layoutString + outputString + formatted;
}
else
{
// GLSL 1.30-1.50 (OpenGL 3.0-3.2):
// No in-shader output indexing.
// Output locations will be set using glBindFragDataLocation.
formatted = outputString + formatted;
}
std::string indexStringRgx = "gl_FragData\\[";
indexStringRgx += std::to_string(i) + "\\]";
formatted = std::regex_replace(formatted, std::regex(indexStringRgx),
"fragColor_" + std::to_string(i));
if (i == 0)
{
formatted = std::regex_replace(formatted, std::regex("gl_FragColor"),
"fragColor_0");
}
}
}
else
{
std::cerr << "buildShaderString: unknown shader type" << std::endl;
return {};
}
formatted = std::regex_replace(formatted, std::regex("texture2D"), "texture");
}
if (GLDevice::useLegacyTextureFmts())
{
formatted = "#define USE_ALPHA\n" + formatted;
}
if (glsl_is_es)
{
// Add precision specifier - required for WebGL
formatted = "precision mediump float;\n" + formatted;
if (num_outputs > 1 && glsl_version == 100)
{
// Enable WEBGL_draw_buffers in the shader
formatted = "#extension GL_EXT_draw_buffers : require\n" + formatted;
}
if (glsl_version == 300)
{
// WebGL 2 shaders require explicit version setting
formatted = "#version 300 es\n" + formatted;
}
}
else
{
// Append version setting for all desktop shaders
formatted = std::regex_replace("#version GLSL_VER\n", std::regex("GLSL_VER"),
std::to_string(glsl_version)) + formatted;
}
return formatted;
}
GLuint ShaderProgram::compileShader(const std::string& inShader,
GLenum shaderType)
{
int shader_len = inShader.length();
const char *shader_cstr = inShader.c_str();
GLuint shader = glCreateShader(shaderType);
glShaderSource(shader, 1, &shader_cstr, &shader_len);
glCompileShader(shader);
GLint stat;
glGetShaderiv(shader, GL_COMPILE_STATUS, &stat);
// glGetObjectParameteriv
if (stat == GL_FALSE)
{
std::cerr << "failed to compile shader" << std::endl;
int err_len;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &err_len);
char *error_text = new char[err_len];
glGetShaderInfoLog(shader, err_len, &err_len, error_text);
std::cerr << error_text << std::endl;
delete[] error_text;
return 0;
}
return shader;
}
bool ShaderProgram::linkShaders(const std::vector<GLuint>& shaders)
{
// Bind all incoming attributes to their VAO indices.
for (auto attrib_pair : attrib_idx)
{
glBindAttribLocation(program_id, attrib_pair.first,
attrib_pair.second.c_str());
}
#ifndef __EMSCRIPTEN__
if (glsl_version >= 130 && glsl_version < 300)
{
// Bind fragment output variables to MRT indices.
for (int i = 0; i < num_outputs; i++)
{
std::string fragOutVar = "fragColor_" + std::to_string(i);
glBindFragDataLocation(program_id, i, fragOutVar.c_str());
}
}
#endif
for (GLuint i : shaders)
{
glAttachShader(program_id, i);
}
glLinkProgram(program_id);
GLint stat;
glGetProgramiv(program_id, GL_LINK_STATUS, &stat);
if (stat == GL_FALSE)
{
cerr << "fatal: Shader linking failed" << endl;
}
return (stat == GL_TRUE);
}
void ShaderProgram::mapShaderUniforms()
{
int num_unifs;
glGetProgramiv(program_id, GL_ACTIVE_UNIFORMS, &num_unifs);
int max_unif_len;
glGetProgramiv(program_id, GL_ACTIVE_UNIFORM_MAX_LENGTH, &max_unif_len);
for (int i = 0; i < num_unifs; i++)
{
vector<char> unif_buf(max_unif_len+1);
GLsizei name_length;
GLint gl_size;
GLenum gl_type;
glGetActiveUniform(program_id, i, max_unif_len, &name_length, &gl_size,
&gl_type,
unif_buf.data());
std::string unif_name(unif_buf.data(), name_length);
GLuint location = glGetUniformLocation(program_id, unif_name.c_str());
uniform_idx[unif_name] = location;
}
}
}
<|endoftext|> |
<commit_before>/**
* @file
* @copyright defined in eos/LICENSE
*/
#include <appbase/application.hpp>
#include <eosio/http_plugin/http_plugin.hpp>
#include <eosio/wallet_plugin/wallet_plugin.hpp>
#include <eosio/wallet_api_plugin/wallet_api_plugin.hpp>
#include <fc/log/logger_config.hpp>
#include <fc/exception/exception.hpp>
#include <boost/exception/diagnostic_information.hpp>
#include <pwd.h>
#include "config.hpp"
using namespace appbase;
using namespace eosio;
bfs::path determine_home_directory()
{
bfs::path home;
struct passwd* pwd = getpwuid(getuid());
if(pwd) {
home = pwd->pw_dir;
}
else {
home = getenv("HOME");
}
if(home.empty())
home = "./";
return home;
}
int main(int argc, char** argv)
{
try {
bfs::path home = determine_home_directory();
app().set_default_data_dir(home / "eosio-wallet");
app().set_default_config_dir(home / "eosio-wallet");
http_plugin::set_defaults({
.default_unix_socket_path = keosd::config::key_store_executable_name + ".sock",
.default_http_port = 0
});
app().register_plugin<wallet_api_plugin>();
if(!app().initialize<wallet_plugin, wallet_api_plugin, http_plugin>(argc, argv))
return -1;
auto& http = app().get_plugin<http_plugin>();
http.add_handler("/v1/" + keosd::config::key_store_executable_name + "/stop", [](string, string, url_response_callback cb) { cb(200, fc::variant(fc::variant_object())); std::raise(SIGTERM); } );
app().startup();
app().exec();
} catch (const fc::exception& e) {
elog("${e}", ("e",e.to_detail_string()));
} catch (const boost::exception& e) {
elog("${e}", ("e",boost::diagnostic_information(e)));
} catch (const std::exception& e) {
elog("${e}", ("e",e.what()));
} catch (...) {
elog("unknown exception");
}
return 0;
}
<commit_msg>remove raise() in keosd in favor of simple appbase quit (de-posix it)<commit_after>/**
* @file
* @copyright defined in eos/LICENSE
*/
#include <appbase/application.hpp>
#include <eosio/http_plugin/http_plugin.hpp>
#include <eosio/wallet_plugin/wallet_plugin.hpp>
#include <eosio/wallet_api_plugin/wallet_api_plugin.hpp>
#include <fc/log/logger_config.hpp>
#include <fc/exception/exception.hpp>
#include <boost/exception/diagnostic_information.hpp>
#include <pwd.h>
#include "config.hpp"
using namespace appbase;
using namespace eosio;
bfs::path determine_home_directory()
{
bfs::path home;
struct passwd* pwd = getpwuid(getuid());
if(pwd) {
home = pwd->pw_dir;
}
else {
home = getenv("HOME");
}
if(home.empty())
home = "./";
return home;
}
int main(int argc, char** argv)
{
try {
bfs::path home = determine_home_directory();
app().set_default_data_dir(home / "eosio-wallet");
app().set_default_config_dir(home / "eosio-wallet");
http_plugin::set_defaults({
.default_unix_socket_path = keosd::config::key_store_executable_name + ".sock",
.default_http_port = 0
});
app().register_plugin<wallet_api_plugin>();
if(!app().initialize<wallet_plugin, wallet_api_plugin, http_plugin>(argc, argv))
return -1;
auto& http = app().get_plugin<http_plugin>();
http.add_handler("/v1/" + keosd::config::key_store_executable_name + "/stop", [&a=app()](string, string, url_response_callback cb) { cb(200, fc::variant(fc::variant_object())); a.quit(); } );
app().startup();
app().exec();
} catch (const fc::exception& e) {
elog("${e}", ("e",e.to_detail_string()));
} catch (const boost::exception& e) {
elog("${e}", ("e",boost::diagnostic_information(e)));
} catch (const std::exception& e) {
elog("${e}", ("e",e.what()));
} catch (...) {
elog("unknown exception");
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* file.cpp
*
* Created on: Feb 5, 2014
* Author: nbingham
*/
#include <std/file.h>
#include <unistd.h>
#include <fcntl.h>
namespace core
{
file::file()
{
desc = -1;
}
file::file(int desc)
{
this->desc = desc;
index = -1;
}
file::file(const file ©)
{
desc = ::dup(copy.desc);
index = copy.index;
}
file::file(const char *filename, unsigned char mode, unsigned char owner, unsigned char group, unsigned char user)
{
desc = -1;
open(filename, mode, owner, group, user);
}
file::file(array<char> filename, unsigned char mode, unsigned char owner, unsigned char group, unsigned char user)
{
desc = -1;
open(filename, mode, owner, group, user);
}
file::~file()
{
close();
}
file::operator bool() const
{
return desc >= 0;
}
bool file::open(const char *filename, unsigned char mode, unsigned char owner, unsigned char group, unsigned char user)
{
if (desc >= 0)
return false;
int oflags = O_CREAT;
int rights = 0;
index = 0;
if ((mode & rw) == rw)
oflags |= O_RDWR;
else if (mode & r)
oflags |= O_RDONLY;
else if (mode & w)
oflags |= O_WRONLY;
if (mode & replace)
oflags |= O_TRUNC;
if (mode & exists)
oflags &= ~O_CREAT;
else if (mode & not_exists)
oflags |= O_EXCL;
if (owner & r)
rights |= S_IRUSR;
if (owner & w)
rights |= S_IWUSR;
if (owner & x)
rights |= S_IXUSR;
if (group & r)
rights |= S_IRGRP;
if (group & w)
rights |= S_IWGRP;
if (group & x)
rights |= S_IXGRP;
if (user & r)
rights |= S_IROTH;
if (user & w)
rights |= S_IWOTH;
if (user & x)
rights |= S_IXOTH;
desc = ::open(filename, oflags, rights);
return desc >= 0;
}
bool file::open(array<char> filename, unsigned char mode, unsigned char owner, unsigned char group, unsigned char user)
{
if (filename[-1] != '\0')
filename.push_back('\0');
return open(filename.data, mode, owner, group, user);
}
bool file::close()
{
if (desc >= 0)
return ::close(desc) == 0;
else
return true;
}
intptr_t file::size()
{
intptr_t result = ::lseek(desc, 0, SEEK_END);
::lseek(desc, index, SEEK_SET);
return result;
}
intptr_t file::set(intptr_t offset)
{
if (offset >= 0)
index = ::lseek(desc, offset, SEEK_SET);
else
index = ::lseek(desc, offset, SEEK_END);
return index;
}
intptr_t file::mov(intptr_t offset)
{
index = ::lseek(desc, offset, SEEK_CUR);
return index;
}
intptr_t file::read(intptr_t length, char *str)
{
intptr_t result = ::read(desc, str, length);
index += result;
return result;
}
intptr_t file::read(intptr_t length, array<char> &str)
{
str.reserve(length);
str.count = ::read(desc, str.data, length);
index += str.count;
return str.count;
}
array<char> file::read(intptr_t length)
{
array<char> result;
result.reserve(length);
result.count = ::read(desc, result.data, length);
index += result.count;
return result;
}
intptr_t file::write(intptr_t length, const char *str)
{
intptr_t result = ::write(desc, str, length);
index += result;
return result;
}
intptr_t file::write(const array<char> &str)
{
intptr_t result = ::write(desc, str.data, str.count);
index += result;
return result;
}
}
<commit_msg>don't close the standard file descriptors (stdout, stderr, stdin)<commit_after>/*
* file.cpp
*
* Created on: Feb 5, 2014
* Author: nbingham
*/
#include <std/file.h>
#include <unistd.h>
#include <fcntl.h>
namespace core
{
file::file()
{
desc = -1;
}
file::file(int desc)
{
this->desc = desc;
index = -1;
}
file::file(const file ©)
{
desc = ::dup(copy.desc);
index = copy.index;
}
file::file(const char *filename, unsigned char mode, unsigned char owner, unsigned char group, unsigned char user)
{
desc = -1;
open(filename, mode, owner, group, user);
}
file::file(array<char> filename, unsigned char mode, unsigned char owner, unsigned char group, unsigned char user)
{
desc = -1;
open(filename, mode, owner, group, user);
}
file::~file()
{
close();
}
file::operator bool() const
{
return desc >= 0;
}
bool file::open(const char *filename, unsigned char mode, unsigned char owner, unsigned char group, unsigned char user)
{
if (desc >= 0)
return false;
int oflags = O_CREAT;
int rights = 0;
index = 0;
if ((mode & rw) == rw)
oflags |= O_RDWR;
else if (mode & r)
oflags |= O_RDONLY;
else if (mode & w)
oflags |= O_WRONLY;
if (mode & replace)
oflags |= O_TRUNC;
if (mode & exists)
oflags &= ~O_CREAT;
else if (mode & not_exists)
oflags |= O_EXCL;
if (owner & r)
rights |= S_IRUSR;
if (owner & w)
rights |= S_IWUSR;
if (owner & x)
rights |= S_IXUSR;
if (group & r)
rights |= S_IRGRP;
if (group & w)
rights |= S_IWGRP;
if (group & x)
rights |= S_IXGRP;
if (user & r)
rights |= S_IROTH;
if (user & w)
rights |= S_IWOTH;
if (user & x)
rights |= S_IXOTH;
desc = ::open(filename, oflags, rights);
return desc >= 0;
}
bool file::open(array<char> filename, unsigned char mode, unsigned char owner, unsigned char group, unsigned char user)
{
if (filename[-1] != '\0')
filename.push_back('\0');
return open(filename.data, mode, owner, group, user);
}
bool file::close()
{
if (desc >= 3)
return ::close(desc) == 0;
else
return true;
}
intptr_t file::size()
{
intptr_t result = ::lseek(desc, 0, SEEK_END);
::lseek(desc, index, SEEK_SET);
return result;
}
intptr_t file::set(intptr_t offset)
{
if (offset >= 0)
index = ::lseek(desc, offset, SEEK_SET);
else
index = ::lseek(desc, offset, SEEK_END);
return index;
}
intptr_t file::mov(intptr_t offset)
{
index = ::lseek(desc, offset, SEEK_CUR);
return index;
}
intptr_t file::read(intptr_t length, char *str)
{
intptr_t result = ::read(desc, str, length);
index += result;
return result;
}
intptr_t file::read(intptr_t length, array<char> &str)
{
str.reserve(length);
str.count = ::read(desc, str.data, length);
index += str.count;
return str.count;
}
array<char> file::read(intptr_t length)
{
array<char> result;
result.reserve(length);
result.count = ::read(desc, result.data, length);
index += result.count;
return result;
}
intptr_t file::write(intptr_t length, const char *str)
{
intptr_t result = ::write(desc, str, length);
index += result;
return result;
}
intptr_t file::write(const array<char> &str)
{
intptr_t result = ::write(desc, str.data, str.count);
index += result;
return result;
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: propread.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-09 03:16:31 $
*
* 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 _PROPREAD_HXX_
#define _PROPREAD_HXX_
#ifndef _SOLAR_H
#include <tools/solar.h>
#endif
#include <sot/storage.hxx>
#ifndef _SV_GEN_HXX
#include <tools/gen.hxx>
#endif
#ifndef _LIST_HXX
#include <tools/list.hxx>
#endif
#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif
#ifndef _DATETIME_HXX
#include <tools/datetime.hxx>
#endif
#include <tools/string.hxx>
// SummaryInformation
#define PID_TITLE 0x02
#define PID_SUBJECT 0x03
#define PID_AUTHOR 0x04
#define PID_KEYWORDS 0x05
#define PID_COMMENTS 0x06
#define PID_TEMPLATE 0x07
#define PID_LASTAUTHOR 0x08
#define PID_REVNUMBER 0x09
#define PID_EDITTIME 0x0a
#define PID_LASTPRINTED_DTM 0x0b
#define PID_CREATE_DTM 0x0c
#define PID_LASTSAVED_DTM 0x0d
// DocumentSummaryInformation
#define PID_CATEGORY 0x02
#define PID_PRESFORMAT 0x03
#define PID_BYTECOUNT 0x04
#define PID_LINECOUNT 0x05
#define PID_PARACOUNT 0x06
#define PID_SLIDECOUNT 0x07
#define PID_NOTECOUNT 0x08
#define PID_HIDDENCOUNT 0x09
#define PID_MMCLIPCOUNT 0x0a
#define PID_SCALE 0x0b
#define PID_HEADINGPAIR 0x0c
#define PID_DOCPARTS 0x0d
#define PID_MANAGER 0x0e
#define PID_COMPANY 0x0f
#define PID_LINKSDIRTY 0x10
#define VT_EMPTY 0
#define VT_NULL 1
#define VT_I2 2
#define VT_I4 3
#define VT_R4 4
#define VT_R8 5
#define VT_CY 6
#define VT_DATE 7
#define VT_BSTR 8
#define VT_UI4 9
#define VT_ERROR 10
#define VT_BOOL 11
#define VT_VARIANT 12
#define VT_DECIMAL 14
#define VT_I1 16
#define VT_UI1 17
#define VT_UI2 18
#define VT_I8 20
#define VT_UI8 21
#define VT_INT 22
#define VT_UINT 23
#define VT_LPSTR 30
#define VT_LPWSTR 31
#define VT_FILETIME 64
#define VT_BLOB 65
#define VT_STREAM 66
#define VT_STORAGE 67
#define VT_STREAMED_OBJECT 68
#define VT_STORED_OBJECT 69
#define VT_BLOB_OBJECT 70
#define VT_CF 71
#define VT_CLSID 72
#define VT_VECTOR 0x1000
#define VT_ARRAY 0x2000
#define VT_BYREF 0x4000
#define VT_TYPEMASK 0xFFF
// ------------------------------------------------------------------------
class PropItem : public SvMemoryStream
{
sal_uInt16 mnTextEnc;
public :
PropItem(){};
void Clear();
void SetTextEncoding( sal_uInt16 nTextEnc ){ mnTextEnc = nTextEnc; };
sal_Bool Read( String& rString, sal_uInt32 nType = VT_EMPTY, sal_Bool bDwordAlign = sal_True );
PropItem& operator=( PropItem& rPropItem );
};
// ------------------------------------------------------------------------
class Dictionary : protected List
{
friend class Section;
void AddProperty( UINT32 nId, const String& rString );
public :
Dictionary(){};
~Dictionary();
Dictionary& operator=( Dictionary& rDictionary );
UINT32 GetProperty( const String& rPropName );
};
// ------------------------------------------------------------------------
class Section : private List
{
sal_uInt16 mnTextEnc;
protected:
BYTE aFMTID[ 16 ];
void AddProperty( sal_uInt32 nId, const sal_uInt8* pBuf, sal_uInt32 nBufSize );
public:
Section( const sal_uInt8* pFMTID );
Section( Section& rSection );
~Section();
Section& operator=( Section& rSection );
sal_Bool GetProperty( sal_uInt32 nId, PropItem& rPropItem );
sal_Bool GetDictionary( Dictionary& rDict );
const sal_uInt8* GetFMTID() const { return aFMTID; };
void Read( SvStorageStream* pStrm );
};
// ------------------------------------------------------------------------
class PropRead : private List
{
sal_Bool mbStatus;
SvStorageStream* mpSvStream;
sal_uInt16 mnByteOrder;
sal_uInt16 mnFormat;
sal_uInt16 mnVersionLo;
sal_uInt16 mnVersionHi;
sal_uInt8 mApplicationCLSID[ 16 ];
void AddSection( Section& rSection );
public:
PropRead( SvStorage& rSvStorage, const String& rName );
~PropRead();
PropRead& operator=( PropRead& rPropRead );
const Section* GetSection( const BYTE* pFMTID );
sal_Bool IsValid() const { return mbStatus; };
void Read();
};
#endif
<commit_msg>INTEGRATION: CWS sdwarningsbegone (1.5.316); FILE MERGED 2006/11/22 12:41:34 cl 1.5.316.1: #i69285# warning free code changes for unxlngi6.pro<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: propread.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: kz $ $Date: 2006-12-12 16:36:45 $
*
* 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 _PROPREAD_HXX_
#define _PROPREAD_HXX_
#ifndef _SOLAR_H
#include <tools/solar.h>
#endif
#include <sot/storage.hxx>
#ifndef _SV_GEN_HXX
#include <tools/gen.hxx>
#endif
#ifndef _LIST_HXX
#include <tools/list.hxx>
#endif
#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif
#ifndef _DATETIME_HXX
#include <tools/datetime.hxx>
#endif
#include <tools/string.hxx>
// SummaryInformation
#define PID_TITLE 0x02
#define PID_SUBJECT 0x03
#define PID_AUTHOR 0x04
#define PID_KEYWORDS 0x05
#define PID_COMMENTS 0x06
#define PID_TEMPLATE 0x07
#define PID_LASTAUTHOR 0x08
#define PID_REVNUMBER 0x09
#define PID_EDITTIME 0x0a
#define PID_LASTPRINTED_DTM 0x0b
#define PID_CREATE_DTM 0x0c
#define PID_LASTSAVED_DTM 0x0d
// DocumentSummaryInformation
#define PID_CATEGORY 0x02
#define PID_PRESFORMAT 0x03
#define PID_BYTECOUNT 0x04
#define PID_LINECOUNT 0x05
#define PID_PARACOUNT 0x06
#define PID_SLIDECOUNT 0x07
#define PID_NOTECOUNT 0x08
#define PID_HIDDENCOUNT 0x09
#define PID_MMCLIPCOUNT 0x0a
#define PID_SCALE 0x0b
#define PID_HEADINGPAIR 0x0c
#define PID_DOCPARTS 0x0d
#define PID_MANAGER 0x0e
#define PID_COMPANY 0x0f
#define PID_LINKSDIRTY 0x10
#define VT_EMPTY 0
#define VT_NULL 1
#define VT_I2 2
#define VT_I4 3
#define VT_R4 4
#define VT_R8 5
#define VT_CY 6
#define VT_DATE 7
#define VT_BSTR 8
#define VT_UI4 9
#define VT_ERROR 10
#define VT_BOOL 11
#define VT_VARIANT 12
#define VT_DECIMAL 14
#define VT_I1 16
#define VT_UI1 17
#define VT_UI2 18
#define VT_I8 20
#define VT_UI8 21
#define VT_INT 22
#define VT_UINT 23
#define VT_LPSTR 30
#define VT_LPWSTR 31
#define VT_FILETIME 64
#define VT_BLOB 65
#define VT_STREAM 66
#define VT_STORAGE 67
#define VT_STREAMED_OBJECT 68
#define VT_STORED_OBJECT 69
#define VT_BLOB_OBJECT 70
#define VT_CF 71
#define VT_CLSID 72
#define VT_VECTOR 0x1000
#define VT_ARRAY 0x2000
#define VT_BYREF 0x4000
#define VT_TYPEMASK 0xFFF
// ------------------------------------------------------------------------
class PropItem : public SvMemoryStream
{
sal_uInt16 mnTextEnc;
public :
PropItem(){};
void Clear();
void SetTextEncoding( sal_uInt16 nTextEnc ){ mnTextEnc = nTextEnc; };
sal_Bool Read( String& rString, sal_uInt32 nType = VT_EMPTY, sal_Bool bDwordAlign = sal_True );
PropItem& operator=( PropItem& rPropItem );
using SvStream::Read;
};
// ------------------------------------------------------------------------
class Dictionary : protected List
{
friend class Section;
void AddProperty( UINT32 nId, const String& rString );
public :
Dictionary(){};
~Dictionary();
Dictionary& operator=( Dictionary& rDictionary );
UINT32 GetProperty( const String& rPropName );
};
// ------------------------------------------------------------------------
class Section : private List
{
sal_uInt16 mnTextEnc;
protected:
BYTE aFMTID[ 16 ];
void AddProperty( sal_uInt32 nId, const sal_uInt8* pBuf, sal_uInt32 nBufSize );
public:
Section( const sal_uInt8* pFMTID );
Section( Section& rSection );
~Section();
Section& operator=( Section& rSection );
sal_Bool GetProperty( sal_uInt32 nId, PropItem& rPropItem );
sal_Bool GetDictionary( Dictionary& rDict );
const sal_uInt8* GetFMTID() const { return aFMTID; };
void Read( SvStorageStream* pStrm );
};
// ------------------------------------------------------------------------
class PropRead : private List
{
sal_Bool mbStatus;
SvStorageStream* mpSvStream;
sal_uInt16 mnByteOrder;
sal_uInt16 mnFormat;
sal_uInt16 mnVersionLo;
sal_uInt16 mnVersionHi;
sal_uInt8 mApplicationCLSID[ 16 ];
void AddSection( Section& rSection );
public:
PropRead( SvStorage& rSvStorage, const String& rName );
~PropRead();
PropRead& operator=( PropRead& rPropRead );
const Section* GetSection( const BYTE* pFMTID );
sal_Bool IsValid() const { return mbStatus; };
void Read();
};
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: dlgolbul.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hr $ $Date: 2004-05-10 15:43:33 $
*
* 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): _______________________________________
*
*
************************************************************************/
#include "OutlineBulletDlg.hxx"
#ifndef _SVX_SVXIDS_HRC
#include <svx/svxids.hrc>
#endif
#ifndef _SFX_OBJSH_HXX //autogen
#include <sfx2/objsh.hxx>
#endif
#define ITEMID_COLOR_TABLE SID_COLOR_TABLE
#ifndef _SVX_DRAWITEM_HXX //autogen
#include <svx/drawitem.hxx>
#endif
#ifndef _SVX_BULITEM_HXX
#include <svx/bulitem.hxx>
#endif
#ifndef _EEITEM_HXX
#include <svx/eeitem.hxx>
#endif
//CHINA001 #include <svx/numpages.hxx>
#include <svx/numitem.hxx>
#include <svx/dialogs.hrc>
#ifndef _SFXINTITEM_HXX //autogen
#include <svtools/intitem.hxx>
#endif
#ifndef _SVDMARK_HXX //autogen
#include <svx/svdmark.hxx>
#endif
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#ifndef _SVDOBJ_HXX //autogen
#include <svx/svdobj.hxx>
#endif
#ifndef _SFXSTYLE_HXX //autogen
#include <svtools/style.hxx>
#endif
#ifndef _DRAWDOC_HXX
#include <drawdoc.hxx>
#endif
#ifndef _SD_SDRESID_HXX
#include "sdresid.hxx"
#endif
#include "glob.hrc"
#include "dlgolbul.hrc"
//#include "enumdlg.hxx"
#include "bulmaper.hxx"
#include "DrawDocShell.hxx"
#include <svx/svxids.hrc> //add CHINA001
#include <svtools/aeitem.hxx> //add CHINA001
namespace sd {
/*************************************************************************
|*
|* Konstruktor des Tab-Dialogs: Fuegt die Seiten zum Dialog hinzu
|*
\************************************************************************/
OutlineBulletDlg::OutlineBulletDlg(
::Window* pParent,
const SfxItemSet* pAttr,
::sd::View* pView )
: SfxTabDialog ( pParent, SdResId(TAB_OUTLINEBULLET) ),
aInputSet ( *pAttr ),
bTitle ( FALSE ),
pSdView ( pView )
{
FreeResource();
aInputSet.MergeRange( SID_PARAM_NUM_PRESET, SID_PARAM_CUR_NUM_LEVEL );
aInputSet.Put( *pAttr );
pOutputSet = new SfxItemSet( *pAttr );
pOutputSet->ClearItem();
BOOL bOutliner = FALSE;
// Sonderbehandlung wenn eine Title Objekt selektiert wurde
if( pView )
{
const SdrMarkList& rMarkList = pView->GetMarkList();
const ULONG nCount = rMarkList.GetMarkCount();
for(ULONG nNum = 0; nNum < nCount; nNum++)
{
SdrObject* pObj = rMarkList.GetMark(nNum)->GetObj();
if( pObj->GetObjInventor() == SdrInventor )
{
switch(pObj->GetObjIdentifier())
{
case OBJ_TITLETEXT:
bTitle = TRUE;
break;
case OBJ_OUTLINETEXT:
bOutliner = TRUE;
break;
}
}
}
}
if( SFX_ITEM_SET != aInputSet.GetItemState(EE_PARA_NUMBULLET))
{
const SvxNumBulletItem *pItem = NULL;
if(bOutliner)
{
SfxStyleSheetBasePool* pSSPool = pView->GetDocSh()->GetStyleSheetPool();
String aStyleName((SdResId(STR_LAYOUT_OUTLINE)));
aStyleName.AppendAscii( RTL_CONSTASCII_STRINGPARAM( " 1" ) );
SfxStyleSheetBase* pFirstStyleSheet = pSSPool->Find( aStyleName, SFX_STYLE_FAMILY_PSEUDO);
if( pFirstStyleSheet )
pFirstStyleSheet->GetItemSet().GetItemState(EE_PARA_NUMBULLET, FALSE, (const SfxPoolItem**)&pItem);
}
if( pItem == NULL )
pItem = (SvxNumBulletItem*) aInputSet.GetPool()->GetSecondaryPool()->GetPoolDefaultItem(EE_PARA_NUMBULLET);
DBG_ASSERT( pItem, "Kein EE_PARA_NUMBULLET im Pool! [CL]" );
aInputSet.Put(*pItem, EE_PARA_NUMBULLET);
}
/* debug
if( SFX_ITEM_SET == aInputSet.GetItemState(EE_PARA_NUMBULLET, FALSE, &pItem ))
{
SvxNumRule& rItem = *((SvxNumBulletItem*)pItem)->GetNumRule();
for( int i = 0; i < 9; i++ )
{
SvxNumberFormat aNumberFormat = rItem.GetLevel(i);
}
}
*/
if(bTitle && aInputSet.GetItemState(EE_PARA_NUMBULLET,TRUE) == SFX_ITEM_ON )
{
SvxNumBulletItem* pItem = (SvxNumBulletItem*)aInputSet.GetItem(EE_PARA_NUMBULLET,TRUE);
SvxNumRule* pRule = pItem->GetNumRule();
if(pRule)
{
SvxNumRule aNewRule( *pRule );
aNewRule.SetFeatureFlag( NUM_NO_NUMBERS, TRUE );
SvxNumBulletItem aNewItem( aNewRule, EE_PARA_NUMBULLET );
aInputSet.Put(aNewItem);
}
}
SdBulletMapper::PreMapNumBulletForDialog( aInputSet );
SetInputSet( &aInputSet );
if(!bTitle)
AddTabPage(RID_SVXPAGE_PICK_SINGLE_NUM);//CHINA001 AddTabPage(RID_SVXPAGE_PICK_SINGLE_NUM, &SvxSingleNumPickTabPage::Create, 0);
else
RemoveTabPage( RID_SVXPAGE_PICK_SINGLE_NUM );
AddTabPage( RID_SVXPAGE_PICK_BULLET ); //CHINA001 AddTabPage(RID_SVXPAGE_PICK_BULLET , &SvxBulletPickTabPage::Create, 0);
AddTabPage( RID_SVXPAGE_PICK_BMP ); //CHINA001 AddTabPage(RID_SVXPAGE_PICK_BMP , &SvxBitmapPickTabPage::Create, 0);
AddTabPage(RID_SVXPAGE_NUM_OPTIONS ); //CHINA001 AddTabPage(RID_SVXPAGE_NUM_OPTIONS , &SvxNumOptionsTabPage::Create, 0);
AddTabPage(RID_SVXPAGE_NUM_POSITION ); //CHINA001 AddTabPage(RID_SVXPAGE_NUM_POSITION , &SvxNumPositionTabPage::Create, 0);
}
OutlineBulletDlg::~OutlineBulletDlg()
{
delete pOutputSet;
}
void OutlineBulletDlg::PageCreated( USHORT nId, SfxTabPage &rPage )
{
switch ( nId )
{
case RID_SVXPAGE_NUM_OPTIONS:
{
if( pSdView )
{
FieldUnit eMetric = pSdView->GetDoc()->GetUIUnit();
//CHINA001 ((SvxNumOptionsTabPage&)rPage).SetMetric(eMetric);
SfxAllItemSet aSet(*(GetInputSetImpl()->GetPool()));//add CHINA001
aSet.Put ( SfxAllEnumItem(SID_METRIC_ITEM,eMetric));//add CHINA001
rPage.PageCreated(aSet);//add CHINA001
}
}
break;
case RID_SVXPAGE_NUM_POSITION:
{
if( pSdView )
{
FieldUnit eMetric = pSdView->GetDoc()->GetUIUnit();
//CHINA001 ((SvxNumPositionTabPage&)rPage).SetMetric(eMetric);
SfxAllItemSet aSet(*(GetInputSetImpl()->GetPool()));//add CHINA001
aSet.Put ( SfxAllEnumItem(SID_METRIC_ITEM,eMetric));//add CHINA001
rPage.PageCreated(aSet);//add CHINA001
}
}
break;
}
}
const SfxItemSet* OutlineBulletDlg::GetOutputItemSet()
{
SfxItemSet aSet( *SfxTabDialog::GetOutputItemSet() );
pOutputSet->Put( aSet );
const SfxPoolItem *pItem = NULL;
if( SFX_ITEM_SET == pOutputSet->GetItemState(pOutputSet->GetPool()->GetWhich(SID_ATTR_NUMBERING_RULE), FALSE, &pItem ))
{
SdBulletMapper::MapFontsInNumRule( *((SvxNumBulletItem*)pItem)->GetNumRule(), *pOutputSet );
SfxUInt16Item aBulletState( EE_PARA_BULLETSTATE, 1 );
pOutputSet->Put(aBulletState);
}
SdBulletMapper::PostMapNumBulletForDialog( *pOutputSet );
if(bTitle && pOutputSet->GetItemState(EE_PARA_NUMBULLET,TRUE) == SFX_ITEM_ON )
{
SvxNumBulletItem* pItem = (SvxNumBulletItem*)pOutputSet->GetItem(EE_PARA_NUMBULLET,TRUE);
SvxNumRule* pRule = pItem->GetNumRule();
if(pRule)
pRule->SetFeatureFlag( NUM_NO_NUMBERS, FALSE );
}
return pOutputSet;
}
} // end of namespace sd
<commit_msg>INTEGRATION: CWS aw013 (1.4.36); FILE MERGED 2004/06/24 09:33:07 aw 1.4.36.1: #i29181#<commit_after>/*************************************************************************
*
* $RCSfile: dlgolbul.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2004-07-12 14:58:46 $
*
* 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): _______________________________________
*
*
************************************************************************/
#include "OutlineBulletDlg.hxx"
#ifndef _SVX_SVXIDS_HRC
#include <svx/svxids.hrc>
#endif
#ifndef _SFX_OBJSH_HXX //autogen
#include <sfx2/objsh.hxx>
#endif
#define ITEMID_COLOR_TABLE SID_COLOR_TABLE
#ifndef _SVX_DRAWITEM_HXX //autogen
#include <svx/drawitem.hxx>
#endif
#ifndef _SVX_BULITEM_HXX
#include <svx/bulitem.hxx>
#endif
#ifndef _EEITEM_HXX
#include <svx/eeitem.hxx>
#endif
//CHINA001 #include <svx/numpages.hxx>
#include <svx/numitem.hxx>
#include <svx/dialogs.hrc>
#ifndef _SFXINTITEM_HXX //autogen
#include <svtools/intitem.hxx>
#endif
#ifndef _SVDMARK_HXX //autogen
#include <svx/svdmark.hxx>
#endif
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#ifndef _SVDOBJ_HXX //autogen
#include <svx/svdobj.hxx>
#endif
#ifndef _SFXSTYLE_HXX //autogen
#include <svtools/style.hxx>
#endif
#ifndef _DRAWDOC_HXX
#include <drawdoc.hxx>
#endif
#ifndef _SD_SDRESID_HXX
#include "sdresid.hxx"
#endif
#include "glob.hrc"
#include "dlgolbul.hrc"
//#include "enumdlg.hxx"
#include "bulmaper.hxx"
#include "DrawDocShell.hxx"
#include <svx/svxids.hrc> //add CHINA001
#include <svtools/aeitem.hxx> //add CHINA001
namespace sd {
/*************************************************************************
|*
|* Konstruktor des Tab-Dialogs: Fuegt die Seiten zum Dialog hinzu
|*
\************************************************************************/
OutlineBulletDlg::OutlineBulletDlg(
::Window* pParent,
const SfxItemSet* pAttr,
::sd::View* pView )
: SfxTabDialog ( pParent, SdResId(TAB_OUTLINEBULLET) ),
aInputSet ( *pAttr ),
bTitle ( FALSE ),
pSdView ( pView )
{
FreeResource();
aInputSet.MergeRange( SID_PARAM_NUM_PRESET, SID_PARAM_CUR_NUM_LEVEL );
aInputSet.Put( *pAttr );
pOutputSet = new SfxItemSet( *pAttr );
pOutputSet->ClearItem();
BOOL bOutliner = FALSE;
// Sonderbehandlung wenn eine Title Objekt selektiert wurde
if( pView )
{
const SdrMarkList& rMarkList = pView->GetMarkedObjectList();
const ULONG nCount = rMarkList.GetMarkCount();
for(ULONG nNum = 0; nNum < nCount; nNum++)
{
SdrObject* pObj = rMarkList.GetMark(nNum)->GetObj();
if( pObj->GetObjInventor() == SdrInventor )
{
switch(pObj->GetObjIdentifier())
{
case OBJ_TITLETEXT:
bTitle = TRUE;
break;
case OBJ_OUTLINETEXT:
bOutliner = TRUE;
break;
}
}
}
}
if( SFX_ITEM_SET != aInputSet.GetItemState(EE_PARA_NUMBULLET))
{
const SvxNumBulletItem *pItem = NULL;
if(bOutliner)
{
SfxStyleSheetBasePool* pSSPool = pView->GetDocSh()->GetStyleSheetPool();
String aStyleName((SdResId(STR_LAYOUT_OUTLINE)));
aStyleName.AppendAscii( RTL_CONSTASCII_STRINGPARAM( " 1" ) );
SfxStyleSheetBase* pFirstStyleSheet = pSSPool->Find( aStyleName, SFX_STYLE_FAMILY_PSEUDO);
if( pFirstStyleSheet )
pFirstStyleSheet->GetItemSet().GetItemState(EE_PARA_NUMBULLET, FALSE, (const SfxPoolItem**)&pItem);
}
if( pItem == NULL )
pItem = (SvxNumBulletItem*) aInputSet.GetPool()->GetSecondaryPool()->GetPoolDefaultItem(EE_PARA_NUMBULLET);
DBG_ASSERT( pItem, "Kein EE_PARA_NUMBULLET im Pool! [CL]" );
aInputSet.Put(*pItem, EE_PARA_NUMBULLET);
}
/* debug
if( SFX_ITEM_SET == aInputSet.GetItemState(EE_PARA_NUMBULLET, FALSE, &pItem ))
{
SvxNumRule& rItem = *((SvxNumBulletItem*)pItem)->GetNumRule();
for( int i = 0; i < 9; i++ )
{
SvxNumberFormat aNumberFormat = rItem.GetLevel(i);
}
}
*/
if(bTitle && aInputSet.GetItemState(EE_PARA_NUMBULLET,TRUE) == SFX_ITEM_ON )
{
SvxNumBulletItem* pItem = (SvxNumBulletItem*)aInputSet.GetItem(EE_PARA_NUMBULLET,TRUE);
SvxNumRule* pRule = pItem->GetNumRule();
if(pRule)
{
SvxNumRule aNewRule( *pRule );
aNewRule.SetFeatureFlag( NUM_NO_NUMBERS, TRUE );
SvxNumBulletItem aNewItem( aNewRule, EE_PARA_NUMBULLET );
aInputSet.Put(aNewItem);
}
}
SdBulletMapper::PreMapNumBulletForDialog( aInputSet );
SetInputSet( &aInputSet );
if(!bTitle)
AddTabPage(RID_SVXPAGE_PICK_SINGLE_NUM);//CHINA001 AddTabPage(RID_SVXPAGE_PICK_SINGLE_NUM, &SvxSingleNumPickTabPage::Create, 0);
else
RemoveTabPage( RID_SVXPAGE_PICK_SINGLE_NUM );
AddTabPage( RID_SVXPAGE_PICK_BULLET ); //CHINA001 AddTabPage(RID_SVXPAGE_PICK_BULLET , &SvxBulletPickTabPage::Create, 0);
AddTabPage( RID_SVXPAGE_PICK_BMP ); //CHINA001 AddTabPage(RID_SVXPAGE_PICK_BMP , &SvxBitmapPickTabPage::Create, 0);
AddTabPage(RID_SVXPAGE_NUM_OPTIONS ); //CHINA001 AddTabPage(RID_SVXPAGE_NUM_OPTIONS , &SvxNumOptionsTabPage::Create, 0);
AddTabPage(RID_SVXPAGE_NUM_POSITION ); //CHINA001 AddTabPage(RID_SVXPAGE_NUM_POSITION , &SvxNumPositionTabPage::Create, 0);
}
OutlineBulletDlg::~OutlineBulletDlg()
{
delete pOutputSet;
}
void OutlineBulletDlg::PageCreated( USHORT nId, SfxTabPage &rPage )
{
switch ( nId )
{
case RID_SVXPAGE_NUM_OPTIONS:
{
if( pSdView )
{
FieldUnit eMetric = pSdView->GetDoc()->GetUIUnit();
//CHINA001 ((SvxNumOptionsTabPage&)rPage).SetMetric(eMetric);
SfxAllItemSet aSet(*(GetInputSetImpl()->GetPool()));//add CHINA001
aSet.Put ( SfxAllEnumItem(SID_METRIC_ITEM,eMetric));//add CHINA001
rPage.PageCreated(aSet);//add CHINA001
}
}
break;
case RID_SVXPAGE_NUM_POSITION:
{
if( pSdView )
{
FieldUnit eMetric = pSdView->GetDoc()->GetUIUnit();
//CHINA001 ((SvxNumPositionTabPage&)rPage).SetMetric(eMetric);
SfxAllItemSet aSet(*(GetInputSetImpl()->GetPool()));//add CHINA001
aSet.Put ( SfxAllEnumItem(SID_METRIC_ITEM,eMetric));//add CHINA001
rPage.PageCreated(aSet);//add CHINA001
}
}
break;
}
}
const SfxItemSet* OutlineBulletDlg::GetOutputItemSet()
{
SfxItemSet aSet( *SfxTabDialog::GetOutputItemSet() );
pOutputSet->Put( aSet );
const SfxPoolItem *pItem = NULL;
if( SFX_ITEM_SET == pOutputSet->GetItemState(pOutputSet->GetPool()->GetWhich(SID_ATTR_NUMBERING_RULE), FALSE, &pItem ))
{
SdBulletMapper::MapFontsInNumRule( *((SvxNumBulletItem*)pItem)->GetNumRule(), *pOutputSet );
SfxUInt16Item aBulletState( EE_PARA_BULLETSTATE, 1 );
pOutputSet->Put(aBulletState);
}
SdBulletMapper::PostMapNumBulletForDialog( *pOutputSet );
if(bTitle && pOutputSet->GetItemState(EE_PARA_NUMBULLET,TRUE) == SFX_ITEM_ON )
{
SvxNumBulletItem* pItem = (SvxNumBulletItem*)pOutputSet->GetItem(EE_PARA_NUMBULLET,TRUE);
SvxNumRule* pRule = pItem->GetNumRule();
if(pRule)
pRule->SetFeatureFlag( NUM_NO_NUMBERS, FALSE );
}
return pOutputSet;
}
} // end of namespace sd
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: fudspord.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: obo $ $Date: 2004-01-20 12:00:22 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef SD_FU_DISPLAY_ORDER_HXX
#define SD_FU_DISPLAY_ORDER_HXX
#ifndef SD_FU_POOR_HXX
#include "fupoor.hxx"
#endif
#ifndef _VCL_POINTR_HXX
#include <vcl/pointr.hxx>
#endif
class SdrObject;
class SdrViewUserMarker;
namespace sd {
/*************************************************************************
|*
|* Funktion DisplayOrder
|*
\************************************************************************/
class FuDisplayOrder
: public FuPoor
{
public:
TYPEINFO();
FuDisplayOrder (
ViewShell* pViewSh,
::sd::Window* pWin,
::sd::View* pView,
SdDrawDocument* pDoc,
SfxRequest& rReq);
virtual ~FuDisplayOrder (void);
// Mouse- & Key-Events
virtual BOOL MouseMove(const MouseEvent& rMEvt);
virtual BOOL MouseButtonUp(const MouseEvent& rMEvt);
virtual BOOL MouseButtonDown(const MouseEvent& rMEvt);
virtual void Activate(); // Function aktivieren
virtual void Deactivate(); // Function deaktivieren
protected:
Pointer aPtr;
SdrObject* pRefObj;
SdrViewUserMarker* pUserMarker;
};
} // end of namespace sd
#endif // _SD_FUDSPORD_HXX
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.560); FILE MERGED 2005/09/05 13:23:05 rt 1.2.560.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fudspord.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-09 05:32:55 $
*
* 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_FU_DISPLAY_ORDER_HXX
#define SD_FU_DISPLAY_ORDER_HXX
#ifndef SD_FU_POOR_HXX
#include "fupoor.hxx"
#endif
#ifndef _VCL_POINTR_HXX
#include <vcl/pointr.hxx>
#endif
class SdrObject;
class SdrViewUserMarker;
namespace sd {
/*************************************************************************
|*
|* Funktion DisplayOrder
|*
\************************************************************************/
class FuDisplayOrder
: public FuPoor
{
public:
TYPEINFO();
FuDisplayOrder (
ViewShell* pViewSh,
::sd::Window* pWin,
::sd::View* pView,
SdDrawDocument* pDoc,
SfxRequest& rReq);
virtual ~FuDisplayOrder (void);
// Mouse- & Key-Events
virtual BOOL MouseMove(const MouseEvent& rMEvt);
virtual BOOL MouseButtonUp(const MouseEvent& rMEvt);
virtual BOOL MouseButtonDown(const MouseEvent& rMEvt);
virtual void Activate(); // Function aktivieren
virtual void Deactivate(); // Function deaktivieren
protected:
Pointer aPtr;
SdrObject* pRefObj;
SdrViewUserMarker* pUserMarker;
};
} // end of namespace sd
#endif // _SD_FUDSPORD_HXX
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: fuoaprms.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: obo $ $Date: 2004-01-20 12:04:54 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef SD_FU_OBJECT_ANIMATION_PARAMETERS
#define SD_FU_OBJECT_ANIMATION_PARAMETERS
#ifndef SD_FU_POOR_HXX
#include "fupoor.hxx"
#endif
namespace sd {
class FuObjectAnimationParameters
: public FuPoor
{
public:
TYPEINFO();
FuObjectAnimationParameters (
ViewShell* pViewSh,
::sd::Window* pWin,
::sd::View* pView,
SdDrawDocument* pDoc,
SfxRequest& rReq);
virtual ~FuObjectAnimationParameters (void);
virtual void Activate(); // Function aktivieren
virtual void Deactivate(); // Function deaktivieren
};
} // end of namespace sd
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.562); FILE MERGED 2005/09/05 13:23:09 rt 1.3.562.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fuoaprms.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-09 05:36:09 $
*
* 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_FU_OBJECT_ANIMATION_PARAMETERS
#define SD_FU_OBJECT_ANIMATION_PARAMETERS
#ifndef SD_FU_POOR_HXX
#include "fupoor.hxx"
#endif
namespace sd {
class FuObjectAnimationParameters
: public FuPoor
{
public:
TYPEINFO();
FuObjectAnimationParameters (
ViewShell* pViewSh,
::sd::Window* pWin,
::sd::View* pView,
SdDrawDocument* pDoc,
SfxRequest& rReq);
virtual ~FuObjectAnimationParameters (void);
virtual void Activate(); // Function aktivieren
virtual void Deactivate(); // Function deaktivieren
};
} // end of namespace sd
#endif
<|endoftext|> |
<commit_before>/* TimeManager.cpp
*
* Kubo Ryosuke
*/
#include "TimeManager.h"
#include "core/def.h"
#include "logger/Logger.h"
#include <cassert>
#define ENABLE_EASY_LOG 1
namespace sunfish {
void TimeManager::init() {
_depth = 0;
}
void TimeManager::nextDepth() {
_depth++;
assert(_depth < Tree::StackSize);
}
void TimeManager::startDepth() {
_stack[_depth].firstMove = Move::empty();
_stack[_depth].firstValue = -Value::Inf;
}
void TimeManager::addMove(Move move, Value value) {
if (value > _stack[_depth].firstValue) {
_stack[_depth].firstMove = move;
_stack[_depth].firstValue = value;
}
}
bool TimeManager::isEasy(double limit, double elapsed) {
CONSTEXPR int easyDepth = 5;
if (_depth <= easyDepth) {
return false;
}
const auto& easy = _stack[_depth-easyDepth];
const auto& prev = _stack[_depth-1];
const auto& curr = _stack[_depth];
limit = std::min(limit, 3600.0);
if (elapsed < std::max(limit * 0.02, 3.0)) {
return false;
}
double r = elapsed / std::max(limit * 0.25, 3.0);
#if ENABLE_EASY_LOG
{
int easyDiff = curr.firstValue.int32() - easy.firstValue.int32();
int prevDiff = curr.firstValue.int32() - prev.firstValue.int32();
int isSame = curr.firstMove == easy.firstMove ? 1 : 0;
Loggers::message << "time_manager," << r << ',' << easyDiff << ',' << prevDiff << ',' << isSame << ',';
}
#endif
if (curr.firstValue >= easy.firstValue - (256 * r) && curr.firstValue <= easy.firstValue + (512 * r) &&
curr.firstValue >= prev.firstValue - (64 * r) && curr.firstValue <= prev.firstValue + (256 * r)) {
#if ENABLE_EASY_LOG
Loggers::message << __FILE_LINE__;
#endif
return true;
}
if (curr.firstMove == easy.firstMove && curr.firstMove == prev.firstMove &&
curr.firstValue >= easy.firstValue - (256 * r) && curr.firstValue <= easy.firstValue + (512 * r) &&
curr.firstValue >= prev.firstValue - (128 * r) && curr.firstValue <= prev.firstValue + (256 * r)) {
#if ENABLE_EASY_LOG
Loggers::message << __FILE_LINE__;
#endif
return true;
}
if (curr.firstMove == prev.firstMove &&
curr.firstValue >= prev.firstValue && curr.firstValue <= prev.firstValue + (256 * r)) {
#if ENABLE_EASY_LOG
Loggers::message << __FILE_LINE__;
#endif
return true;
}
if (curr.firstMove == easy.firstMove &&
curr.firstValue >= easy.firstValue && curr.firstValue <= easy.firstValue + (128 * r)) {
#if ENABLE_EASY_LOG
Loggers::message << __FILE_LINE__;
#endif
return true;
}
return false;
}
}
<commit_msg>Update TimeManager<commit_after>/* TimeManager.cpp
*
* Kubo Ryosuke
*/
#include "TimeManager.h"
#include "core/def.h"
#include "logger/Logger.h"
#include <cassert>
#define ENABLE_EASY_LOG 1
namespace sunfish {
void TimeManager::init() {
_depth = 0;
}
void TimeManager::nextDepth() {
_depth++;
assert(_depth < Tree::StackSize);
}
void TimeManager::startDepth() {
_stack[_depth].firstMove = Move::empty();
_stack[_depth].firstValue = -Value::Inf;
}
void TimeManager::addMove(Move move, Value value) {
if (value > _stack[_depth].firstValue) {
_stack[_depth].firstMove = move;
_stack[_depth].firstValue = value;
}
}
bool TimeManager::isEasy(double limit, double elapsed) {
CONSTEXPR int easyDepth = 5;
if (_depth <= easyDepth) {
return false;
}
const auto& easy = _stack[_depth-easyDepth];
const auto& prev = _stack[_depth-1];
const auto& curr = _stack[_depth];
limit = std::min(limit, 3600.0);
if (elapsed < std::max(limit * 0.02, 3.0)) {
return false;
}
double r = elapsed / std::max(limit * 0.25, 3.0);
#if ENABLE_EASY_LOG
{
int easyDiff = curr.firstValue.int32() - easy.firstValue.int32();
int prevDiff = curr.firstValue.int32() - prev.firstValue.int32();
int isSame = curr.firstMove == easy.firstMove ? 1 : 0;
Loggers::message << "time_manager," << r << ',' << easyDiff << ',' << prevDiff << ',' << isSame << ',';
}
#endif
if (curr.firstValue >= easy.firstValue - (256 * r) && curr.firstValue <= easy.firstValue + (512 * r) &&
curr.firstValue >= prev.firstValue - (64 * r) && curr.firstValue <= prev.firstValue + (256 * r)) {
#if ENABLE_EASY_LOG
Loggers::message << __FILE_LINE__;
#endif
return true;
}
if (curr.firstMove == easy.firstMove && curr.firstMove == prev.firstMove &&
curr.firstValue >= prev.firstValue - (128 * r) && curr.firstValue <= prev.firstValue + (512 * r)) {
#if ENABLE_EASY_LOG
Loggers::message << __FILE_LINE__;
#endif
return true;
}
if (curr.firstMove == prev.firstMove &&
curr.firstValue >= prev.firstValue - (64 * r) && curr.firstValue <= prev.firstValue + (256 * r)) {
#if ENABLE_EASY_LOG
Loggers::message << __FILE_LINE__;
#endif
return true;
}
if (curr.firstMove == easy.firstMove &&
curr.firstValue >= easy.firstValue - (128 * r) && curr.firstValue <= easy.firstValue + (512 * r)) {
#if ENABLE_EASY_LOG
Loggers::message << __FILE_LINE__;
#endif
return true;
}
return false;
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <stdexcept>
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include <Eigen/Core>
#include <QApplication>
#include <QMainWindow>
#include <QMenu>
#include <QAction>
#include <QKeyEvent>
#include <QHBoxLayout>
#include <dependency_graph/graph.h>
#include <dependency_graph/node_base.inl>
#include <dependency_graph/datablock.inl>
#include <dependency_graph/metadata.inl>
#include <dependency_graph/attr.inl>
#include <qt_node_editor/node.h>
#include <qt_node_editor/connected_edge.h>
#include <qt_node_editor/graph_widget.h>
#include <possumwood_sdk/app.h>
#include <possumwood_sdk/gl.h>
#include "adaptor.h"
#include "main_window.h"
#include "gl_init.h"
#include "common.h"
#include "error_dialog.h"
namespace po = boost::program_options;
using std::cout;
using std::endl;
using std::flush;
int main(int argc, char* argv[]) {
// // Declare the supported options.
po::options_description desc("Allowed options");
desc.add_options()
("help", "produce help message")
("scene", po::value<std::string>(), "open a scene file")
;
// process the options
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if(vm.count("help")) {
cout << desc << "\n";
return 1;
}
///////////////////////////////
// create the possumwood application
std::unique_ptr<possumwood::App> papp(new possumwood::App());
// load all plugins into an RAII container - loading of plugins requires path expansion from the main app instance
std::unique_ptr<PluginsRAII> plugins(new PluginsRAII());
{
GL_CHECK_ERR;
{
QSurfaceFormat format = QSurfaceFormat::defaultFormat();
// way higher than currently supported - will fall back to highest
format.setVersion(6, 0);
format.setProfile(QSurfaceFormat::CoreProfile);
#ifndef NDEBUG
format.setOption(QSurfaceFormat::DebugContext);
#endif
format.setSwapBehavior(QSurfaceFormat::DoubleBuffer);
QSurfaceFormat::setDefaultFormat(format);
}
// initialise eigen
Eigen::initParallel();
// create the application object
QApplication app(argc, argv);
// nice scaling on High DPI displays is support in Qt 5.6+
#if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
#endif
GL_CHECK_ERR;
// make a main window
MainWindow win;
win.setWindowIcon(QIcon(":icons/app.png"));
win.showMaximized();
GL_CHECK_ERR;
std::cout << "OpenGL version supported by this platform is "
<< glGetString(GL_VERSION) << std::endl;
GL_CHECK_ERR;
// open the scene file, if specified on the command line
if(vm.count("scene"))
win.loadFile(vm["scene"].as<std::string>());
GL_CHECK_ERR;
// and start the main application loop
app.exec();
GL_CHECK_ERR;
}
// delete the application before unloading plugins - app will need metadata from plugins to close cleanly
papp.reset();
plugins.reset();
return 0;
}
<commit_msg>Fixed QApplication creation warning for Qt 5.12<commit_after>#include <iostream>
#include <string>
#include <stdexcept>
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include <Eigen/Core>
#include <QApplication>
#include <QMainWindow>
#include <QMenu>
#include <QAction>
#include <QKeyEvent>
#include <QHBoxLayout>
#include <dependency_graph/graph.h>
#include <dependency_graph/node_base.inl>
#include <dependency_graph/datablock.inl>
#include <dependency_graph/metadata.inl>
#include <dependency_graph/attr.inl>
#include <qt_node_editor/node.h>
#include <qt_node_editor/connected_edge.h>
#include <qt_node_editor/graph_widget.h>
#include <possumwood_sdk/app.h>
#include <possumwood_sdk/gl.h>
#include "adaptor.h"
#include "main_window.h"
#include "gl_init.h"
#include "common.h"
#include "error_dialog.h"
namespace po = boost::program_options;
using std::cout;
using std::endl;
using std::flush;
int main(int argc, char* argv[]) {
// // Declare the supported options.
po::options_description desc("Allowed options");
desc.add_options()
("help", "produce help message")
("scene", po::value<std::string>(), "open a scene file")
;
// process the options
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if(vm.count("help")) {
cout << desc << "\n";
return 1;
}
///////////////////////////////
// create the possumwood application
std::unique_ptr<possumwood::App> papp(new possumwood::App());
// load all plugins into an RAII container - loading of plugins requires path expansion from the main app instance
std::unique_ptr<PluginsRAII> plugins(new PluginsRAII());
{
GL_CHECK_ERR;
{
QSurfaceFormat format = QSurfaceFormat::defaultFormat();
// way higher than currently supported - will fall back to highest
format.setVersion(6, 0);
format.setProfile(QSurfaceFormat::CoreProfile);
#ifndef NDEBUG
format.setOption(QSurfaceFormat::DebugContext);
#endif
format.setSwapBehavior(QSurfaceFormat::DoubleBuffer);
QSurfaceFormat::setDefaultFormat(format);
}
// initialise eigen
Eigen::initParallel();
GL_CHECK_ERR;
// nice scaling on High DPI displays is support in Qt 5.6+
#if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
#endif
GL_CHECK_ERR;
// create the application object
QApplication app(argc, argv);
GL_CHECK_ERR;
// make a main window
MainWindow win;
win.setWindowIcon(QIcon(":icons/app.png"));
win.showMaximized();
GL_CHECK_ERR;
std::cout << "OpenGL version supported by this platform is "
<< glGetString(GL_VERSION) << std::endl;
GL_CHECK_ERR;
// open the scene file, if specified on the command line
if(vm.count("scene"))
win.loadFile(vm["scene"].as<std::string>());
GL_CHECK_ERR;
// and start the main application loop
app.exec();
GL_CHECK_ERR;
}
// delete the application before unloading plugins - app will need metadata from plugins to close cleanly
papp.reset();
plugins.reset();
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>const correctness<commit_after><|endoftext|> |
<commit_before>/*
* Sponge: hash sha-3 (keccak)
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "keccak.H"
#include "action_sponge.H"
#define HASH_SIZE 64
#define RESULT_SIZE 8
#define TEST /* get faster turn-around time */
#ifdef TEST /* NO_SYNTH */ /* TEST */
# define NB_SLICES 4
# define NB_ROUND 1<<10
#else
# ifndef NB_SLICES
# define NB_SLICES 65536 /* 4 */ //65536--for first synthesis
# endif
# ifndef NB_ROUND
# define NB_ROUND 1<<24 /* 10 */ //24--for first synthesis
# endif
#endif
uint64_t sponge (const uint64_t rank)
{
uint64_t magic[8] = {0x0123456789abcdeful,0x13579bdf02468aceul,
0xfdecba9876543210ul,0xeca86420fdb97531ul,
0x571e30cf4b29a86dul,0xd48f0c376e1b29a5ul,
0xc5301e9f6b2ad748ul,0x3894d02e5ba71c6ful};
uint64_t odd[8],even[8],result;
int i,j;
even_init:
for(i=0;i<RESULT_SIZE;i++) {
even[i] = magic[i] + rank;
}
//keccak((uint8_t*)even,HASH_SIZE,(uint8_t*)odd,HASH_SIZE);
keccak((uint64_t*)even,HASH_SIZE,(uint64_t*)odd,HASH_SIZE);
nb_round_process:
for(i=0;i<NB_ROUND;i++) {
process_odd:
for(j=0;j<4;j++) {
odd[2*j] ^= ROTL64( even[2*j] , 4*j+1);
odd[2*j+1] = ROTL64( even[2*j+1] + odd[2*j+1], 4*j+3);
}
//keccak((uint8_t*)odd,HASH_SIZE,(uint8_t*)even,HASH_SIZE);
keccak((uint64_t*)odd,HASH_SIZE,(uint64_t*)even,HASH_SIZE);
process_even:
for(j=0;j<4;j++) {
even[2*j] += ROTL64( odd[2*j] , 4*j+5);
even[2*j+1] = ROTL64( even[2*j+1] ^ odd[2*j+1], 4*j+7);
}
//keccak((uint8_t*)even,HASH_SIZE,(uint8_t*)odd,HASH_SIZE);
keccak((uint64_t*)even,HASH_SIZE,(uint64_t*)odd,HASH_SIZE);
}
result=0;
process_result:
for(i=0;i<RESULT_SIZE;i++) {
result += (even[i] ^ odd[i]);
}
return result;
}
/*
* WRITE RESULTS IN MMIO REGS
*
* Always check that ALL Outputs are tied to a value or HLS will generate a
* Action_Output_i and a Action_Output_o registers and address to read results
* will be shifted ...and wrong
* => easy checking in generated files:
* grep 0x184 action_wrapper_ctrl_reg_s_axi.vhd
* this grep should return nothing if no duplication of registers
* (which is expected)
*/
static void write_results(action_output_reg *Action_Output,
action_input_reg *Action_Input,
snapu32_t ReturnCode,
snapu64_t field1,
snapu64_t field2)
{
Action_Output->Retc = (snapu32_t)ReturnCode;
Action_Output->Data.chk_out = field1;
Action_Output->Data.timer_ticks = field2;
Action_Output->Data.action_version = RELEASE_VERSION;
Action_Output->Reserved = 0;
Action_Output->Data.in = Action_Input->Data.in;
Action_Output->Data.chk_type = Action_Input->Data.chk_type;
Action_Output->Data.chk_in = Action_Input->Data.chk_in;
Action_Output->Data.pe = Action_Input->Data.pe;
Action_Output->Data.nb_pe = Action_Input->Data.nb_pe;
Action_Output->Data.nb_slices = NB_SLICES;
Action_Output->Data.nb_round = NB_ROUND;
}
//-----------------------------------------------------------------------------
//--- MAIN PROGRAM ------------------------------------------------------------
//-----------------------------------------------------------------------------
/**
* Remarks: Using pointers for the din_gmem, ... parameters is requiring to
* to set the depth=... parameter via the pragma below. If missing to do this
* the cosimulation will not work, since the width of the interface cannot
* be determined. Using an array din_gmem[...] works too to fix that.
*/
void action_wrapper(snap_membus_t *din_gmem,
snap_membus_t *dout_gmem,
snap_membus_t *d_ddrmem,
action_input_reg *Action_Input,
action_output_reg *Action_Output)
{
// Host Memory AXI Interface
#pragma HLS INTERFACE m_axi depth=256 port=din_gmem bundle=host_mem
#pragma HLS INTERFACE m_axi depth=256 port=dout_gmem bundle=host_mem
#pragma HLS INTERFACE s_axilite depth=256 port=din_gmem bundle=ctrl_reg
#pragma HLS INTERFACE s_axilite depth=256 port=dout_gmem bundle=ctrl_reg
//DDR memory Interface
#pragma HLS INTERFACE m_axi depth=256 port=d_ddrmem offset=slave bundle=card_mem0
#pragma HLS INTERFACE s_axilite depth=256 port=d_ddrmem bundle=ctrl_reg
// Host Memory AXI Lite Master Interface
#pragma HLS DATA_PACK variable=Action_Input
#pragma HLS INTERFACE s_axilite port=Action_Input offset=0x080 bundle=ctrl_reg
#pragma HLS DATA_PACK variable=Action_Output
#pragma HLS INTERFACE s_axilite port=Action_Output offset=0x104 bundle=ctrl_reg
#pragma HLS INTERFACE s_axilite port=return bundle=ctrl_reg
snapu32_t ReturnCode = 0;
uint64_t checksum = 0;
uint32_t slice = 0;
uint32_t pe, nb_pe;
uint64_t timer_ticks = 0;
pe = Action_Input->Data.pe;
nb_pe = Action_Input->Data.nb_pe;
do {
/* FIXME Please check if the data alignment matches
the expectations */
if (Action_Input->Control.action != SPONGE_ACTION_TYPE) {
ReturnCode = RET_CODE_FAILURE;
break;
}
for (slice = 0; slice < NB_SLICES; slice++) {
if (pe == (slice % nb_pe))
checksum ^= sponge(slice);
}
timer_ticks += 42;
} while (0);
write_results(Action_Output, Action_Input, ReturnCode,
checksum, timer_ticks);
}
#ifdef NO_SYNTH
/**
* FIXME We need to use action_wrapper from here to get the real thing
* simulated. For now let's take the short path and try without it.
*/
int main(void)
{
uint64_t slice;
//uint32_t pe,nb_pe;
uint64_t checksum=0;
short i, rc=0;
typedef struct {
uint32_t pe;
uint32_t nb_pe;
uint64_t checksum;
} arguments_t;
static arguments_t sequence[] = {
{ 0, /*nb_pe =*/ 1, /*expected checksum =*/ 0x948dd5b0109342d4 },
{ 0, /*nb_pe =*/ 2, /*expected checksum =*/ 0x0bca19b17df64085 },
{ 1, /*nb_pe =*/ 2, /*expected checksum =*/ 0x9f47cc016d650251 },
{ 0, /*nb_pe =*/ 4, /*expected checksum =*/ 0x7f13a4a377a2c4fe },
{ 1, /*nb_pe =*/ 4, /*expected checksum =*/ 0xee0710b96b0748fb },
{ 2, /*nb_pe =*/ 4, /*expected checksum =*/ 0x74d9bd120a54847b },
{ 3, /*nb_pe =*/ 4, /*expected checksum =*/ 0x7140dcb806624aaa }
};
for(i=0; i < 7; i++) {
checksum = 0;
for(slice=0;slice<NB_SLICES;slice++) {
if(sequence[i].pe == (slice % sequence[i].nb_pe))
checksum ^= sponge(slice);
}
printf("pe=%d - nb_pe=%d - processed checksum=%016llx ",
sequence[i].pe,
sequence[i].nb_pe,
(unsigned long long) checksum);
if (sequence[i].checksum == checksum) {
printf(" ==> CORRECT \n");
rc |= 0;
}
else {
printf(" ==> ERROR : expected checksum=%016llx \n",
(unsigned long long) sequence[i].checksum);
rc |= 1;
}
}
if (rc != 0)
printf("\n\t Checksums are given with use of -DTEST "
"flag. Please check you have set it!\n\n");
return rc;
}
#endif // end of NO_SYNTH flag
<commit_msg>HSL Sponge: Use the real stuff<commit_after>/*
* Sponge: hash sha-3 (keccak)
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "keccak.H"
#include "action_sponge.H"
#define HASH_SIZE 64
#define RESULT_SIZE 8
#undef TEST /* get faster turn-around time */
#ifdef TEST /* NO_SYNTH */ /* TEST */
# define NB_SLICES 4
# define NB_ROUND 1<<10
#else
# ifndef NB_SLICES
# define NB_SLICES 65536 /* 4 */ //65536--for first synthesis
# endif
# ifndef NB_ROUND
# define NB_ROUND 1<<24 /* 10 */ //24--for first synthesis
# endif
#endif
uint64_t sponge (const uint64_t rank)
{
uint64_t magic[8] = {0x0123456789abcdeful,0x13579bdf02468aceul,
0xfdecba9876543210ul,0xeca86420fdb97531ul,
0x571e30cf4b29a86dul,0xd48f0c376e1b29a5ul,
0xc5301e9f6b2ad748ul,0x3894d02e5ba71c6ful};
uint64_t odd[8],even[8],result;
int i,j;
even_init:
for(i=0;i<RESULT_SIZE;i++) {
even[i] = magic[i] + rank;
}
//keccak((uint8_t*)even,HASH_SIZE,(uint8_t*)odd,HASH_SIZE);
keccak((uint64_t*)even,HASH_SIZE,(uint64_t*)odd,HASH_SIZE);
nb_round_process:
for(i=0;i<NB_ROUND;i++) {
process_odd:
for(j=0;j<4;j++) {
odd[2*j] ^= ROTL64( even[2*j] , 4*j+1);
odd[2*j+1] = ROTL64( even[2*j+1] + odd[2*j+1], 4*j+3);
}
//keccak((uint8_t*)odd,HASH_SIZE,(uint8_t*)even,HASH_SIZE);
keccak((uint64_t*)odd,HASH_SIZE,(uint64_t*)even,HASH_SIZE);
process_even:
for(j=0;j<4;j++) {
even[2*j] += ROTL64( odd[2*j] , 4*j+5);
even[2*j+1] = ROTL64( even[2*j+1] ^ odd[2*j+1], 4*j+7);
}
//keccak((uint8_t*)even,HASH_SIZE,(uint8_t*)odd,HASH_SIZE);
keccak((uint64_t*)even,HASH_SIZE,(uint64_t*)odd,HASH_SIZE);
}
result=0;
process_result:
for(i=0;i<RESULT_SIZE;i++) {
result += (even[i] ^ odd[i]);
}
return result;
}
/*
* WRITE RESULTS IN MMIO REGS
*
* Always check that ALL Outputs are tied to a value or HLS will generate a
* Action_Output_i and a Action_Output_o registers and address to read results
* will be shifted ...and wrong
* => easy checking in generated files:
* grep 0x184 action_wrapper_ctrl_reg_s_axi.vhd
* this grep should return nothing if no duplication of registers
* (which is expected)
*/
static void write_results(action_output_reg *Action_Output,
action_input_reg *Action_Input,
snapu32_t ReturnCode,
snapu64_t field1,
snapu64_t field2)
{
Action_Output->Retc = (snapu32_t)ReturnCode;
Action_Output->Data.chk_out = field1;
Action_Output->Data.timer_ticks = field2;
Action_Output->Data.action_version = RELEASE_VERSION;
Action_Output->Reserved = 0;
Action_Output->Data.in = Action_Input->Data.in;
Action_Output->Data.chk_type = Action_Input->Data.chk_type;
Action_Output->Data.chk_in = Action_Input->Data.chk_in;
Action_Output->Data.pe = Action_Input->Data.pe;
Action_Output->Data.nb_pe = Action_Input->Data.nb_pe;
Action_Output->Data.nb_slices = NB_SLICES;
Action_Output->Data.nb_round = NB_ROUND;
}
//-----------------------------------------------------------------------------
//--- MAIN PROGRAM ------------------------------------------------------------
//-----------------------------------------------------------------------------
/**
* Remarks: Using pointers for the din_gmem, ... parameters is requiring to
* to set the depth=... parameter via the pragma below. If missing to do this
* the cosimulation will not work, since the width of the interface cannot
* be determined. Using an array din_gmem[...] works too to fix that.
*/
void action_wrapper(snap_membus_t *din_gmem,
snap_membus_t *dout_gmem,
snap_membus_t *d_ddrmem,
action_input_reg *Action_Input,
action_output_reg *Action_Output)
{
// Host Memory AXI Interface
#pragma HLS INTERFACE m_axi depth=256 port=din_gmem bundle=host_mem
#pragma HLS INTERFACE m_axi depth=256 port=dout_gmem bundle=host_mem
#pragma HLS INTERFACE s_axilite depth=256 port=din_gmem bundle=ctrl_reg
#pragma HLS INTERFACE s_axilite depth=256 port=dout_gmem bundle=ctrl_reg
//DDR memory Interface
#pragma HLS INTERFACE m_axi depth=256 port=d_ddrmem offset=slave bundle=card_mem0
#pragma HLS INTERFACE s_axilite depth=256 port=d_ddrmem bundle=ctrl_reg
// Host Memory AXI Lite Master Interface
#pragma HLS DATA_PACK variable=Action_Input
#pragma HLS INTERFACE s_axilite port=Action_Input offset=0x080 bundle=ctrl_reg
#pragma HLS DATA_PACK variable=Action_Output
#pragma HLS INTERFACE s_axilite port=Action_Output offset=0x104 bundle=ctrl_reg
#pragma HLS INTERFACE s_axilite port=return bundle=ctrl_reg
snapu32_t ReturnCode = 0;
uint64_t checksum = 0;
uint32_t slice = 0;
uint32_t pe, nb_pe;
uint64_t timer_ticks = 0;
pe = Action_Input->Data.pe;
nb_pe = Action_Input->Data.nb_pe;
do {
/* FIXME Please check if the data alignment matches
the expectations */
if (Action_Input->Control.action != SPONGE_ACTION_TYPE) {
ReturnCode = RET_CODE_FAILURE;
break;
}
for (slice = 0; slice < NB_SLICES; slice++) {
if (pe == (slice % nb_pe))
checksum ^= sponge(slice);
}
timer_ticks += 42;
} while (0);
write_results(Action_Output, Action_Input, ReturnCode,
checksum, timer_ticks);
}
#ifdef NO_SYNTH
/**
* FIXME We need to use action_wrapper from here to get the real thing
* simulated. For now let's take the short path and try without it.
*/
int main(void)
{
uint64_t slice;
//uint32_t pe,nb_pe;
uint64_t checksum=0;
short i, rc=0;
typedef struct {
uint32_t pe;
uint32_t nb_pe;
uint64_t checksum;
} arguments_t;
static arguments_t sequence[] = {
{ 0, /*nb_pe =*/ 1, /*expected checksum =*/ 0x948dd5b0109342d4 },
{ 0, /*nb_pe =*/ 2, /*expected checksum =*/ 0x0bca19b17df64085 },
{ 1, /*nb_pe =*/ 2, /*expected checksum =*/ 0x9f47cc016d650251 },
{ 0, /*nb_pe =*/ 4, /*expected checksum =*/ 0x7f13a4a377a2c4fe },
{ 1, /*nb_pe =*/ 4, /*expected checksum =*/ 0xee0710b96b0748fb },
{ 2, /*nb_pe =*/ 4, /*expected checksum =*/ 0x74d9bd120a54847b },
{ 3, /*nb_pe =*/ 4, /*expected checksum =*/ 0x7140dcb806624aaa }
};
for(i=0; i < 7; i++) {
checksum = 0;
for(slice=0;slice<NB_SLICES;slice++) {
if(sequence[i].pe == (slice % sequence[i].nb_pe))
checksum ^= sponge(slice);
}
printf("pe=%d - nb_pe=%d - processed checksum=%016llx ",
sequence[i].pe,
sequence[i].nb_pe,
(unsigned long long) checksum);
if (sequence[i].checksum == checksum) {
printf(" ==> CORRECT \n");
rc |= 0;
}
else {
printf(" ==> ERROR : expected checksum=%016llx \n",
(unsigned long long) sequence[i].checksum);
rc |= 1;
}
}
if (rc != 0)
printf("\n\t Checksums are given with use of -DTEST "
"flag. Please check you have set it!\n\n");
return rc;
}
#endif // end of NO_SYNTH flag
<|endoftext|> |
<commit_before>#include <QSettings>
#include <QDebug>
#include <QCoreApplication>
#include <QFile>
#include <QRegularExpression>
#include "QGC.h"
#include "QGCAudioWorker.h"
#include "GAudioOutput.h"
#if defined Q_OS_MAC && defined QGC_SPEECH_ENABLED
#include <ApplicationServices/ApplicationServices.h>
#endif
// Speech synthesis is only supported with MSVC compiler
#if defined _MSC_VER && defined QGC_SPEECH_ENABLED
// Documentation: http://msdn.microsoft.com/en-us/library/ee125082%28v=VS.85%29.aspx
#include <sapi.h>
#endif
#if defined Q_OS_LINUX && defined QGC_SPEECH_ENABLED
// Using eSpeak for speech synthesis: following https://github.com/mondhs/espeak-sample/blob/master/sampleSpeak.cpp
#include <espeak/speak_lib.h>
#endif
#define QGC_GAUDIOOUTPUT_KEY QString("QGC_AUDIOOUTPUT_")
QGCAudioWorker::QGCAudioWorker(QObject *parent) :
QObject(parent),
voiceIndex(0),
#if defined _MSC_VER && defined QGC_SPEECH_ENABLED
pVoice(NULL),
#endif
#ifdef QGC_NOTIFY_TUNES_ENABLED
sound(NULL),
#endif
emergency(false),
muted(false)
{
// Load settings
QSettings settings;
muted = settings.value(QGC_GAUDIOOUTPUT_KEY + "muted", muted).toBool();
}
void QGCAudioWorker::init()
{
#ifdef QGC_NOTIFY_TUNES_ENABLED
sound = new QSound(":/files/audio/alert.wav");
#endif
#if defined Q_OS_LINUX && defined QGC_SPEECH_ENABLED
espeak_Initialize(AUDIO_OUTPUT_SYNCH_PLAYBACK, 500, NULL, 0); // initialize for playback with 500ms buffer and no options (see speak_lib.h)
espeak_VOICE *espeak_voice = espeak_GetCurrentVoice();
espeak_voice->languages = "en-uk"; // Default to British English
espeak_voice->identifier = NULL; // no specific voice file specified
espeak_voice->name = "klatt"; // espeak voice name
espeak_voice->gender = 2; // Female
espeak_voice->age = 0; // age not specified
espeak_SetVoiceByProperties(espeak_voice);
#endif
#if defined _MSC_VER && defined QGC_SPEECH_ENABLED
if (FAILED(::CoInitialize(NULL)))
{
qDebug() << "ERROR: Creating COM object for audio output failed!";
}
else
{
HRESULT hr = CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL, IID_ISpVoice, (void **)&pVoice);
if (FAILED(hr))
{
qDebug() << "ERROR: Initializing voice for audio output failed!";
}
}
#endif
}
QGCAudioWorker::~QGCAudioWorker()
{
#if defined _MSC_VER && defined QGC_SPEECH_ENABLED
if (pVoice) {
pVoice->Release();
pVoice = NULL;
}
::CoUninitialize();
#endif
}
void QGCAudioWorker::say(QString inText, int severity)
{
static bool threadInit = false;
if (!threadInit) {
threadInit = true;
init();
}
if (!muted)
{
QString text = _fixMillisecondString(inText);
// Prepend high priority text with alert beep
if (severity < GAudioOutput::AUDIO_SEVERITY_CRITICAL) {
beep();
}
#ifdef QGC_NOTIFY_TUNES_ENABLED
// Wait for the last sound to finish
while (!sound->isFinished()) {
QGC::SLEEP::msleep(100);
}
#endif
#if defined _MSC_VER && defined QGC_SPEECH_ENABLED
HRESULT hr = pVoice->Speak(text.toStdWString().c_str(), SPF_DEFAULT, NULL);
if (FAILED(hr)) {
qDebug() << "Speak failed, HR:" << QString("%1").arg(hr, 0, 16);
}
#elif defined Q_OS_LINUX && defined QGC_SPEECH_ENABLED
// Set size of string for espeak: +1 for the null-character
unsigned int espeak_size = strlen(text.toStdString().c_str()) + 1;
espeak_Synth(text.toStdString().c_str(), espeak_size, 0, POS_CHARACTER, 0, espeakCHARS_AUTO, NULL, NULL);
#elif defined Q_OS_MAC && defined QGC_SPEECH_ENABLED
// Slashes necessary to have the right start to the sentence
// copying data prevents SpeakString from reading additional chars
text = "\\" + text;
std::wstring str = text.toStdWString();
unsigned char str2[1024] = {};
memcpy(str2, text.toLatin1().data(), str.length());
SpeakString(str2);
// Block the thread while busy
// because we run in our own thread, this doesn't
// halt the main application
while (SpeechBusy()) {
QGC::SLEEP::msleep(100);
}
#else
// Make sure there isn't an unused variable warning when speech output is disabled
Q_UNUSED(inText);
#endif
}
}
void QGCAudioWorker::mute(bool mute)
{
if (mute != muted)
{
this->muted = mute;
QSettings settings;
settings.setValue(QGC_GAUDIOOUTPUT_KEY + "muted", this->muted);
// emit mutedChanged(muted);
}
}
void QGCAudioWorker::beep()
{
if (!muted)
{
#ifdef QGC_NOTIFY_TUNES_ENABLED
sound->play(":/files/audio/alert.wav");
#endif
}
}
bool QGCAudioWorker::isMuted()
{
return this->muted;
}
bool QGCAudioWorker::_getMillisecondString(const QString& string, QString& match, int& number) {
QRegularExpression re("([0-9]*ms)");
QRegularExpressionMatchIterator i = re.globalMatch(string);
while (i.hasNext()) {
QRegularExpressionMatch qmatch = i.next();
if (qmatch.hasMatch()) {
match = qmatch.captured(0);
number = qmatch.captured(0).replace("ms", "").toInt();
return true;
}
}
return false;
}
QString QGCAudioWorker::_fixMillisecondString(const QString& string) {
QString match;
QString newNumber;
QString result = string;
int number;
if(_getMillisecondString(string, match, number) && number > 1000) {
if(number < 60000) {
int seconds = number / 1000;
newNumber = QString("%1 second%2").arg(seconds).arg(seconds > 1 ? "s" : "");
} else {
int minutes = number / 60000;
int seconds = (number - (minutes * 60000)) / 1000;
if (!seconds) {
newNumber = QString("%1 minute%2").arg(minutes).arg(minutes > 1 ? "s" : "");
} else {
newNumber = QString("%1 minute%2 and %3 second%4").arg(minutes).arg(minutes > 1 ? "s" : "").arg(seconds).arg(seconds > 1 ? "s" : "");
}
}
result.replace(match, newNumber);
}
return result;
}
<commit_msg>Text to speech tweak.<commit_after>#include <QSettings>
#include <QDebug>
#include <QCoreApplication>
#include <QFile>
#include <QRegularExpression>
#include "QGC.h"
#include "QGCAudioWorker.h"
#include "GAudioOutput.h"
#if defined Q_OS_MAC && defined QGC_SPEECH_ENABLED
#include <ApplicationServices/ApplicationServices.h>
#endif
// Speech synthesis is only supported with MSVC compiler
#if defined _MSC_VER && defined QGC_SPEECH_ENABLED
// Documentation: http://msdn.microsoft.com/en-us/library/ee125082%28v=VS.85%29.aspx
#include <sapi.h>
#endif
#if defined Q_OS_LINUX && defined QGC_SPEECH_ENABLED
// Using eSpeak for speech synthesis: following https://github.com/mondhs/espeak-sample/blob/master/sampleSpeak.cpp
#include <espeak/speak_lib.h>
#endif
#define QGC_GAUDIOOUTPUT_KEY QString("QGC_AUDIOOUTPUT_")
QGCAudioWorker::QGCAudioWorker(QObject *parent) :
QObject(parent),
voiceIndex(0),
#if defined _MSC_VER && defined QGC_SPEECH_ENABLED
pVoice(NULL),
#endif
#ifdef QGC_NOTIFY_TUNES_ENABLED
sound(NULL),
#endif
emergency(false),
muted(false)
{
// Load settings
QSettings settings;
muted = settings.value(QGC_GAUDIOOUTPUT_KEY + "muted", muted).toBool();
}
void QGCAudioWorker::init()
{
#ifdef QGC_NOTIFY_TUNES_ENABLED
sound = new QSound(":/files/audio/alert.wav");
#endif
#if defined Q_OS_LINUX && defined QGC_SPEECH_ENABLED
espeak_Initialize(AUDIO_OUTPUT_SYNCH_PLAYBACK, 500, NULL, 0); // initialize for playback with 500ms buffer and no options (see speak_lib.h)
espeak_VOICE *espeak_voice = espeak_GetCurrentVoice();
espeak_voice->languages = "en-uk"; // Default to British English
espeak_voice->identifier = NULL; // no specific voice file specified
espeak_voice->name = "klatt"; // espeak voice name
espeak_voice->gender = 2; // Female
espeak_voice->age = 0; // age not specified
espeak_SetVoiceByProperties(espeak_voice);
#endif
#if defined _MSC_VER && defined QGC_SPEECH_ENABLED
if (FAILED(::CoInitialize(NULL)))
{
qDebug() << "ERROR: Creating COM object for audio output failed!";
}
else
{
HRESULT hr = CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL, IID_ISpVoice, (void **)&pVoice);
if (FAILED(hr))
{
qDebug() << "ERROR: Initializing voice for audio output failed!";
}
}
#endif
}
QGCAudioWorker::~QGCAudioWorker()
{
#if defined _MSC_VER && defined QGC_SPEECH_ENABLED
if (pVoice) {
pVoice->Release();
pVoice = NULL;
}
::CoUninitialize();
#endif
}
void QGCAudioWorker::say(QString inText, int severity)
{
static bool threadInit = false;
if (!threadInit) {
threadInit = true;
init();
}
if (!muted)
{
QString text = _fixMillisecondString(inText);
// Prepend high priority text with alert beep
if (severity < GAudioOutput::AUDIO_SEVERITY_CRITICAL) {
beep();
}
#ifdef QGC_NOTIFY_TUNES_ENABLED
// Wait for the last sound to finish
while (!sound->isFinished()) {
QGC::SLEEP::msleep(100);
}
#endif
#if defined _MSC_VER && defined QGC_SPEECH_ENABLED
HRESULT hr = pVoice->Speak(text.toStdWString().c_str(), SPF_DEFAULT, NULL);
if (FAILED(hr)) {
qDebug() << "Speak failed, HR:" << QString("%1").arg(hr, 0, 16);
}
#elif defined Q_OS_LINUX && defined QGC_SPEECH_ENABLED
// Set size of string for espeak: +1 for the null-character
unsigned int espeak_size = strlen(text.toStdString().c_str()) + 1;
espeak_Synth(text.toStdString().c_str(), espeak_size, 0, POS_CHARACTER, 0, espeakCHARS_AUTO, NULL, NULL);
#elif defined Q_OS_MAC && defined QGC_SPEECH_ENABLED
// Slashes necessary to have the right start to the sentence
// copying data prevents SpeakString from reading additional chars
text = "\\" + text;
std::wstring str = text.toStdWString();
unsigned char str2[1024] = {};
memcpy(str2, text.toLatin1().data(), str.length());
SpeakString(str2);
// Block the thread while busy
// because we run in our own thread, this doesn't
// halt the main application
while (SpeechBusy()) {
QGC::SLEEP::msleep(100);
}
#else
// Make sure there isn't an unused variable warning when speech output is disabled
Q_UNUSED(inText);
#endif
}
}
void QGCAudioWorker::mute(bool mute)
{
if (mute != muted)
{
this->muted = mute;
QSettings settings;
settings.setValue(QGC_GAUDIOOUTPUT_KEY + "muted", this->muted);
// emit mutedChanged(muted);
}
}
void QGCAudioWorker::beep()
{
if (!muted)
{
#ifdef QGC_NOTIFY_TUNES_ENABLED
sound->play(":/files/audio/alert.wav");
#endif
}
}
bool QGCAudioWorker::isMuted()
{
return this->muted;
}
bool QGCAudioWorker::_getMillisecondString(const QString& string, QString& match, int& number) {
static QRegularExpression re("([0-9]+ms)");
QRegularExpressionMatchIterator i = re.globalMatch(string);
while (i.hasNext()) {
QRegularExpressionMatch qmatch = i.next();
if (qmatch.hasMatch()) {
match = qmatch.captured(0);
number = qmatch.captured(0).replace("ms", "").toInt();
return true;
}
}
return false;
}
QString QGCAudioWorker::_fixMillisecondString(const QString& string) {
QString match;
QString newNumber;
QString result = string;
int number;
if(_getMillisecondString(string, match, number) && number > 1000) {
if(number < 60000) {
int seconds = number / 1000;
newNumber = QString("%1 second%2").arg(seconds).arg(seconds > 1 ? "s" : "");
} else {
int minutes = number / 60000;
int seconds = (number - (minutes * 60000)) / 1000;
if (!seconds) {
newNumber = QString("%1 minute%2").arg(minutes).arg(minutes > 1 ? "s" : "");
} else {
newNumber = QString("%1 minute%2 and %3 second%4").arg(minutes).arg(minutes > 1 ? "s" : "").arg(seconds).arg(seconds > 1 ? "s" : "");
}
}
result.replace(match, newNumber);
}
return result;
}
<|endoftext|> |
<commit_before>/* -*- mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
// vim:sts=4:sw=4:ts=4:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
/* Copyright (c) FFLAS-FFPACK
* Written by Philippe LEDENT <philippe.ledent@etu.univ-grenoble-alpes.fr>
* ========LICENCE========
* This file is part of the library FFLAS-FFPACK.
*
* FFLAS-FFPACK 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
* ========LICENCE========
*/
#include "fflas-ffpack/fflas-ffpack-config.h"
#include <iostream>
#include <givaro/modular.h>
#include <givaro/givrational.h>
#include "fflas-ffpack/fflas-ffpack.h"
#include "fflas-ffpack/utils/timer.h"
#include "fflas-ffpack/utils/fflas_io.h"
#include "fflas-ffpack/paladin/parallel.h"
#include "fflas-ffpack/paladin/fflas_plevel1.h"
#include "fflas-ffpack/utils/args-parser.h"
using namespace std;
using namespace FFLAS;
using namespace FFPACK;
template<class Field>
typename Field::Element run_with_field(int q, size_t iter, size_t N, const size_t BS, const size_t p, const size_t threads){
Field F(q);
typename Field::RandIter G(F, BS);
typename Field::Element_ptr A, B;
typename Field::Element d; F.init(d);
#ifdef __GIVARO_USE_OPENMP
Givaro::OMPTimer chrono, time;
#else
Givaro::Timer chrono, time;
#endif
time.clear();
for (size_t i=0;i<iter;++i){
A = fflas_new(F, N);
B = fflas_new(F, N);
PAR_BLOCK { pfrand(F, G, N, 1, A); pfrand(F, G, N, 1, B); }
// FFLAS::WriteMatrix(std::cerr, F, 1, N, A, 1);
// FFLAS::WriteMatrix(std::cerr, F, 1, N, B, 1);
F.assign(d, F.zero);
FFLAS::ParSeqHelper::Parallel<
FFLAS::CuttingStrategy::Block,
FFLAS::StrategyParameter::Threads> ParHelper(threads);
chrono.clear();
if (p){
chrono.start();
F.assign(d, fdot(F, N, A, 1U, B, 1U, ParHelper));
chrono.stop();
} else {
chrono.start();
F.assign(d, fdot(F, N, A, 1U, B, 1U, FFLAS::ParSeqHelper::Sequential()));
chrono.stop();
}
// std::cerr << chrono
// << " Gfops: " << ((double(2*N)/1000.)/1000.)/(1000.*chrono.realtime())
// << std::endl;
time+=chrono;
FFLAS::fflas_delete(A);
FFLAS::fflas_delete(B);
}
// -----------
// Standard output for benchmark
std::cout << "Time: " << time
<< " Gfops: " << ((double(2*N)/1000.)/1000.)/(1000.*time.realtime())* double(iter);
// F.write(std::cerr, d) << std::endl;
return d;
}
int main(int argc, char** argv) {
size_t iter = 3;
size_t N = 5000;
size_t BS = 5000;
int q = 131071101;
size_t p =0;
size_t maxallowed_threads; PAR_BLOCK { maxallowed_threads=NUM_THREADS; }
size_t threads=maxallowed_threads;
Argument as[] = {
{ 'n', "-n N", "Set the dimension of the matrix C.",TYPE_INT , &N },
{ 'q', "-q Q", "Set the field characteristic (0 for the integers).", TYPE_INT , &q },
{ 'i', "-i R", "Set number of repetitions.", TYPE_INT , &iter },
{ 'b', "-b B", "Set the bitsize of the random elements.", TYPE_INT , &BS},
{ 'p', "-p P", "0 for sequential, 1 for parallel.", TYPE_INT , &p },
{ 't', "-t T", "number of virtual threads to drive the partition.", TYPE_INT , &threads },
END_OF_ARGUMENTS
};
FFLAS::parseArguments(argc,argv,as);
if (q > 0){
BS = Givaro::Integer(q).bitsize();
double d = run_with_field<Givaro::ModularBalanced<double> >(q, iter, N, BS, p, threads);
std::cout << ", d: " << d;
} else {
auto d = run_with_field<Givaro::ZRing<Givaro::Integer> > (q, iter, N, BS, p, threads);
std::cout << ", size: " << logtwo(d>0?d:-d);
}
FFLAS::writeCommandString(std::cerr, as) << std::endl;
return 0;
}
<commit_msg>fix output<commit_after>/* -*- mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
// vim:sts=4:sw=4:ts=4:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
/* Copyright (c) FFLAS-FFPACK
* Written by Philippe LEDENT <philippe.ledent@etu.univ-grenoble-alpes.fr>
* ========LICENCE========
* This file is part of the library FFLAS-FFPACK.
*
* FFLAS-FFPACK 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
* ========LICENCE========
*/
#include "fflas-ffpack/fflas-ffpack-config.h"
#include <iostream>
#include <givaro/modular.h>
#include <givaro/givrational.h>
#include "fflas-ffpack/fflas-ffpack.h"
#include "fflas-ffpack/utils/timer.h"
#include "fflas-ffpack/utils/fflas_io.h"
#include "fflas-ffpack/paladin/parallel.h"
#include "fflas-ffpack/paladin/fflas_plevel1.h"
#include "fflas-ffpack/utils/args-parser.h"
using namespace std;
using namespace FFLAS;
using namespace FFPACK;
template<class Field>
typename Field::Element run_with_field(int q, size_t iter, size_t N, const size_t BS, const size_t p, const size_t threads){
Field F(q);
typename Field::RandIter G(F, BS);
typename Field::Element_ptr A, B;
typename Field::Element d; F.init(d);
#ifdef __GIVARO_USE_OPENMP
Givaro::OMPTimer chrono, time;
#else
Givaro::Timer chrono, time;
#endif
time.clear();
for (size_t i=0;i<iter;++i){
A = fflas_new(F, N);
B = fflas_new(F, N);
PAR_BLOCK { pfrand(F, G, N, 1, A); pfrand(F, G, N, 1, B); }
// FFLAS::WriteMatrix(std::cerr, F, 1, N, A, 1);
// FFLAS::WriteMatrix(std::cerr, F, 1, N, B, 1);
F.assign(d, F.zero);
FFLAS::ParSeqHelper::Parallel<
FFLAS::CuttingStrategy::Block,
FFLAS::StrategyParameter::Threads> ParHelper(threads);
chrono.clear();
if (p){
chrono.start();
F.assign(d, fdot(F, N, A, 1U, B, 1U, ParHelper));
chrono.stop();
} else {
chrono.start();
F.assign(d, fdot(F, N, A, 1U, B, 1U, FFLAS::ParSeqHelper::Sequential()));
chrono.stop();
}
// std::cerr << chrono
// << " Gfops: " << ((double(2*N)/1000.)/1000.)/(1000.*chrono.realtime())
// << std::endl;
time+=chrono;
FFLAS::fflas_delete(A);
FFLAS::fflas_delete(B);
}
// -----------
// Standard output for benchmark
std::cout << "Time: " << time.realtime()
<< " Gfops: " << ((double(2*N)/1000.)/1000.)/(1000.*time.realtime())* double(iter);
// F.write(std::cerr, d) << std::endl;
return d;
}
int main(int argc, char** argv) {
size_t iter = 3;
size_t N = 5000;
size_t BS = 5000;
int q = 131071101;
size_t p =0;
size_t maxallowed_threads; PAR_BLOCK { maxallowed_threads=NUM_THREADS; }
size_t threads=maxallowed_threads;
Argument as[] = {
{ 'n', "-n N", "Set the dimension of the matrix C.",TYPE_INT , &N },
{ 'q', "-q Q", "Set the field characteristic (0 for the integers).", TYPE_INT , &q },
{ 'i', "-i R", "Set number of repetitions.", TYPE_INT , &iter },
{ 'b', "-b B", "Set the bitsize of the random elements.", TYPE_INT , &BS},
{ 'p', "-p P", "0 for sequential, 1 for parallel.", TYPE_INT , &p },
{ 't', "-t T", "number of virtual threads to drive the partition.", TYPE_INT , &threads },
END_OF_ARGUMENTS
};
FFLAS::parseArguments(argc,argv,as);
if (q > 0){
BS = Givaro::Integer(q).bitsize();
double d = run_with_field<Givaro::ModularBalanced<double> >(q, iter, N, BS, p, threads);
std::cout << ", d: " << d;
} else {
auto d = run_with_field<Givaro::ZRing<Givaro::Integer> > (q, iter, N, BS, p, threads);
std::cout << ", size: " << logtwo(d>0?d:-d);
}
FFLAS::writeCommandString(std::cerr, as) << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>
// .\Release\x64\benchmarks.exe --benchmark_repetitions=10 --benchmark_min_time=2 --benchmark_filter=Geopotential // NOLINT(whitespace/line_length)
#include "physics/geopotential_body.hpp"
#include <random>
#include <vector>
#include "astronomy/fortran_astrodynamics_toolkit.hpp"
#include "astronomy/frames.hpp"
#include "base/not_null.hpp"
#include "benchmark/benchmark.h"
#include "geometry/grassmann.hpp"
#include "geometry/named_quantities.hpp"
#include "geometry/r3_element.hpp"
#include "numerics/fixed_arrays.hpp"
#include "numerics/legendre.hpp"
#include "physics/solar_system.hpp"
#include "quantities/named_quantities.hpp"
#include "quantities/parser.hpp"
#include "quantities/quantities.hpp"
#include "quantities/si.hpp"
namespace principia {
namespace physics {
using astronomy::ICRS;
using astronomy::ITRS;
using base::not_null;
using geometry::Displacement;
using geometry::Instant;
using geometry::R3Element;
using geometry::Vector;
using numerics::FixedMatrix;
using numerics::LegendreNormalizationFactor;
using physics::SolarSystem;
using quantities::Acceleration;
using quantities::Angle;
using quantities::Exponentiation;
using quantities::GravitationalParameter;
using quantities::Length;
using quantities::ParseQuantity;
using quantities::Pow;
using quantities::Quotient;
using quantities::SIUnit;
using quantities::Sqrt;
using quantities::si::Degree;
using quantities::si::Kilo;
using quantities::si::Metre;
using quantities::si::Radian;
using quantities::si::Second;
template<typename Frame>
Vector<Quotient<Acceleration, GravitationalParameter>, Frame>
GeneralSphericalHarmonicsAccelerationCpp(
Geopotential<Frame> const& geopotential,
Instant const& t,
Displacement<Frame> const& r) {
auto const r² = r.Norm²();
auto const r_norm = Sqrt(r²);
auto const one_over_r³ = r_norm / (r² * r²);
return geopotential.GeneralSphericalHarmonicsAcceleration(
t, r, r_norm, r², one_over_r³);
}
// For fairness, the Fortran implementation is wrapped to have the same API as
// the C++ one.
template<typename Frame, int degree, int order>
Vector<Quotient<Acceleration, GravitationalParameter>, Frame>
GeneralSphericalHarmonicsAccelerationF90(
not_null<OblateBody<Frame> const*> const body,
double const mu,
double const rbar,
FixedMatrix<double, degree + 1, order + 1> const& cnm,
FixedMatrix<double, degree + 1, order + 1> const& snm,
Instant const& t,
Displacement<Frame> const& r) {
struct SurfaceFrame;
auto const from_surface_frame =
body->template FromSurfaceFrame<SurfaceFrame>(t);
auto const to_surface_frame = from_surface_frame.Inverse();
Displacement<SurfaceFrame> const r_surface = to_surface_frame(r);
auto const acceleration_surface =
Vector<Quotient<Acceleration, GravitationalParameter>, SurfaceFrame>(
SIUnit<Quotient<Acceleration, GravitationalParameter>>() *
astronomy::fortran_astrodynamics_toolkit::
ComputeGravityAccelerationLear<degree, order>(
r_surface.coordinates() / Metre, mu, rbar, cnm, snm));
return from_surface_frame(acceleration_surface);
}
OblateBody<ICRS> MakeEarthBody(SolarSystem<ICRS>& solar_system,
int const max_degree) {
solar_system.LimitOblatenessToDegree("Earth", max_degree);
auto earth_message = solar_system.gravity_model_message("Earth");
Angle const earth_right_ascension_of_pole = 0 * Degree;
Angle const earth_declination_of_pole = 90 * Degree;
auto const earth_μ = solar_system.gravitational_parameter("Earth");
auto const earth_reference_radius =
ParseQuantity<Length>(earth_message.reference_radius());
MassiveBody::Parameters const massive_body_parameters(earth_μ);
RotatingBody<ICRS>::Parameters rotating_body_parameters(
/*mean_radius=*/solar_system.mean_radius("Earth"),
/*reference_angle=*/0 * Radian,
/*reference_instant=*/Instant(),
/*angular_frequency=*/1 * Radian / Second,
earth_right_ascension_of_pole,
earth_declination_of_pole);
return OblateBody<ICRS>(
massive_body_parameters,
rotating_body_parameters,
OblateBody<ICRS>::Parameters::ReadFromMessage(
earth_message.geopotential(), earth_reference_radius));
}
void BM_ComputeGeopotentialCpp(benchmark::State& state) {
int const max_degree = state.range(0);
SolarSystem<ICRS> solar_system_2000(
SOLUTION_DIR / "astronomy" / "sol_gravity_model.proto.txt",
SOLUTION_DIR / "astronomy" /
"sol_initial_state_jd_2451545_000000000.proto.txt");
auto const earth = MakeEarthBody(solar_system_2000, max_degree);
Geopotential<ICRS> const geopotential(&earth, /*tolerance=*/0);
std::mt19937_64 random(42);
std::uniform_real_distribution<> distribution(-1e7, 1e7);
std::vector<Displacement<ICRS>> displacements;
for (int i = 0; i < 1e3; ++i) {
displacements.push_back(earth.FromSurfaceFrame<ITRS>(Instant())(
Displacement<ITRS>({distribution(random) * Metre,
distribution(random) * Metre,
distribution(random) * Metre})));
}
while (state.KeepRunning()) {
Vector<Exponentiation<Length, -2>, ICRS> acceleration;
for (auto const& displacement : displacements) {
acceleration = GeneralSphericalHarmonicsAccelerationCpp(
geopotential, Instant(), displacement);
}
benchmark::DoNotOptimize(acceleration);
}
}
void BM_ComputeGeopotentialDistance(benchmark::State& state) {
// Check the performance around this distance. May be used to tell apart the
// various contributions.
double const distance_in_kilometres = state.range(0);
SolarSystem<ICRS> solar_system_2000(
SOLUTION_DIR / "astronomy" / "sol_gravity_model.proto.txt",
SOLUTION_DIR / "astronomy" /
"sol_initial_state_jd_2451545_000000000.proto.txt");
auto const earth = MakeEarthBody(solar_system_2000, /*max_degree=*/10);
Geopotential<ICRS> const geopotential(&earth, /*tolerance=*/0x1.0p-24);
std::mt19937_64 random(42);
std::uniform_real_distribution<> distribution(0.9 * distance_in_kilometres,
1.1 * distance_in_kilometres);
std::vector<Displacement<ICRS>> displacements;
for (int i = 0; i < 1e3; ++i) {
displacements.push_back(earth.FromSurfaceFrame<ITRS>(Instant())(
Displacement<ITRS>({distribution(random) * Kilo(Metre),
distribution(random) * Kilo(Metre),
distribution(random) * Kilo(Metre)})));
}
while (state.KeepRunning()) {
Vector<Exponentiation<Length, -2>, ICRS> acceleration;
for (auto const& displacement : displacements) {
acceleration = GeneralSphericalHarmonicsAccelerationCpp(
geopotential, Instant(), displacement);
}
benchmark::DoNotOptimize(acceleration);
}
}
#define PRINCIPIA_CASE_COMPUTE_GEOPOTENTIAL_F90(d) \
case (d): { \
numerics::FixedMatrix<double, (d) + 1, (d) + 1> cnm; \
numerics::FixedMatrix<double, (d) + 1, (d) + 1> snm; \
for (int n = 0; n <= (d); ++n) { \
for (int m = 0; m <= n; ++m) { \
cnm[n][m] = earth.cos()[n][m] * LegendreNormalizationFactor(n, m); \
snm[n][m] = earth.sin()[n][m] * LegendreNormalizationFactor(n, m); \
} \
} \
while (state.KeepRunning()) { \
Vector<Exponentiation<Length, -2>, ICRS> acceleration; \
for (auto const& displacement : displacements) { \
acceleration = \
GeneralSphericalHarmonicsAccelerationF90<ICRS, (d), (d)>( \
&earth, mu, rbar, cnm, snm, Instant(), displacement); \
} \
benchmark::DoNotOptimize(acceleration); \
} \
break; \
}
void BM_ComputeGeopotentialF90(benchmark::State& state) {
int const max_degree = state.range(0);
SolarSystem<ICRS> solar_system_2000(
SOLUTION_DIR / "astronomy" / "sol_gravity_model.proto.txt",
SOLUTION_DIR / "astronomy" /
"sol_initial_state_jd_2451545_000000000.proto.txt");
auto const earth = MakeEarthBody(solar_system_2000, max_degree);
double mu =
earth.gravitational_parameter() / SIUnit<GravitationalParameter>();
double rbar = earth.reference_radius() / Metre;
std::mt19937_64 random(42);
std::uniform_real_distribution<> distribution(-1e7, 1e7);
std::vector<Displacement<ICRS>> displacements;
for (int i = 0; i < 1e3; ++i) {
displacements.push_back(earth.FromSurfaceFrame<ITRS>(Instant())(
Displacement<ITRS>({distribution(random) * Metre,
distribution(random) * Metre,
distribution(random) * Metre})));
}
switch (max_degree) {
PRINCIPIA_CASE_COMPUTE_GEOPOTENTIAL_F90(2);
PRINCIPIA_CASE_COMPUTE_GEOPOTENTIAL_F90(3);
PRINCIPIA_CASE_COMPUTE_GEOPOTENTIAL_F90(4);
PRINCIPIA_CASE_COMPUTE_GEOPOTENTIAL_F90(5);
PRINCIPIA_CASE_COMPUTE_GEOPOTENTIAL_F90(6);
PRINCIPIA_CASE_COMPUTE_GEOPOTENTIAL_F90(7);
PRINCIPIA_CASE_COMPUTE_GEOPOTENTIAL_F90(8);
PRINCIPIA_CASE_COMPUTE_GEOPOTENTIAL_F90(9);
PRINCIPIA_CASE_COMPUTE_GEOPOTENTIAL_F90(10);
}
}
#undef PRINCIPIA_CASE_COMPUTE_GEOPOTENTIAL_F90
BENCHMARK(BM_ComputeGeopotentialCpp)->Arg(2)->Arg(3)->Arg(5)->Arg(10);
BENCHMARK(BM_ComputeGeopotentialF90)->Arg(2)->Arg(3)->Arg(5)->Arg(10);
BENCHMARK(BM_ComputeGeopotentialDistance)
->Arg(80'000) // C₂₂, S₂₂, J₂.
->Arg(500'000) // J₂.
->Arg(5'000'000); // Central
} // namespace physics
} // namespace principia
<commit_msg>After egg's review.<commit_after>
// .\Release\x64\benchmarks.exe --benchmark_repetitions=10 --benchmark_min_time=2 --benchmark_filter=Geopotential // NOLINT(whitespace/line_length)
#include "physics/geopotential_body.hpp"
#include <random>
#include <vector>
#include "astronomy/fortran_astrodynamics_toolkit.hpp"
#include "astronomy/frames.hpp"
#include "base/not_null.hpp"
#include "benchmark/benchmark.h"
#include "geometry/grassmann.hpp"
#include "geometry/named_quantities.hpp"
#include "geometry/r3_element.hpp"
#include "numerics/fixed_arrays.hpp"
#include "numerics/legendre.hpp"
#include "physics/solar_system.hpp"
#include "quantities/named_quantities.hpp"
#include "quantities/parser.hpp"
#include "quantities/quantities.hpp"
#include "quantities/si.hpp"
namespace principia {
namespace physics {
using astronomy::ICRS;
using astronomy::ITRS;
using base::not_null;
using geometry::Displacement;
using geometry::Instant;
using geometry::R3Element;
using geometry::Vector;
using numerics::FixedMatrix;
using numerics::LegendreNormalizationFactor;
using physics::SolarSystem;
using quantities::Acceleration;
using quantities::Angle;
using quantities::Exponentiation;
using quantities::GravitationalParameter;
using quantities::Length;
using quantities::ParseQuantity;
using quantities::Pow;
using quantities::Quotient;
using quantities::SIUnit;
using quantities::Sqrt;
using quantities::si::Degree;
using quantities::si::Kilo;
using quantities::si::Metre;
using quantities::si::Radian;
using quantities::si::Second;
template<typename Frame>
Vector<Quotient<Acceleration, GravitationalParameter>, Frame>
GeneralSphericalHarmonicsAccelerationCpp(
Geopotential<Frame> const& geopotential,
Instant const& t,
Displacement<Frame> const& r) {
auto const r² = r.Norm²();
auto const r_norm = Sqrt(r²);
auto const one_over_r³ = r_norm / (r² * r²);
return geopotential.GeneralSphericalHarmonicsAcceleration(
t, r, r_norm, r², one_over_r³);
}
// For fairness, the Fortran implementation is wrapped to have the same API as
// the C++ one.
template<typename Frame, int degree, int order>
Vector<Quotient<Acceleration, GravitationalParameter>, Frame>
GeneralSphericalHarmonicsAccelerationF90(
not_null<OblateBody<Frame> const*> const body,
double const mu,
double const rbar,
FixedMatrix<double, degree + 1, order + 1> const& cnm,
FixedMatrix<double, degree + 1, order + 1> const& snm,
Instant const& t,
Displacement<Frame> const& r) {
struct SurfaceFrame;
auto const from_surface_frame =
body->template FromSurfaceFrame<SurfaceFrame>(t);
auto const to_surface_frame = from_surface_frame.Inverse();
Displacement<SurfaceFrame> const r_surface = to_surface_frame(r);
auto const acceleration_surface =
Vector<Quotient<Acceleration, GravitationalParameter>, SurfaceFrame>(
SIUnit<Quotient<Acceleration, GravitationalParameter>>() *
astronomy::fortran_astrodynamics_toolkit::
ComputeGravityAccelerationLear<degree, order>(
r_surface.coordinates() / Metre, mu, rbar, cnm, snm));
return from_surface_frame(acceleration_surface);
}
OblateBody<ICRS> MakeEarthBody(SolarSystem<ICRS>& solar_system,
int const max_degree) {
solar_system.LimitOblatenessToDegree("Earth", max_degree);
auto earth_message = solar_system.gravity_model_message("Earth");
Angle const earth_right_ascension_of_pole = 0 * Degree;
Angle const earth_declination_of_pole = 90 * Degree;
auto const earth_μ = solar_system.gravitational_parameter("Earth");
auto const earth_reference_radius =
ParseQuantity<Length>(earth_message.reference_radius());
MassiveBody::Parameters const massive_body_parameters(earth_μ);
RotatingBody<ICRS>::Parameters rotating_body_parameters(
/*mean_radius=*/solar_system.mean_radius("Earth"),
/*reference_angle=*/0 * Radian,
/*reference_instant=*/Instant(),
/*angular_frequency=*/1 * Radian / Second,
earth_right_ascension_of_pole,
earth_declination_of_pole);
return OblateBody<ICRS>(
massive_body_parameters,
rotating_body_parameters,
OblateBody<ICRS>::Parameters::ReadFromMessage(
earth_message.geopotential(), earth_reference_radius));
}
void BM_ComputeGeopotentialCpp(benchmark::State& state) {
int const max_degree = state.range(0);
SolarSystem<ICRS> solar_system_2000(
SOLUTION_DIR / "astronomy" / "sol_gravity_model.proto.txt",
SOLUTION_DIR / "astronomy" /
"sol_initial_state_jd_2451545_000000000.proto.txt");
auto const earth = MakeEarthBody(solar_system_2000, max_degree);
Geopotential<ICRS> const geopotential(&earth, /*tolerance=*/0);
std::mt19937_64 random(42);
std::uniform_real_distribution<> distribution(-1e7, 1e7);
std::vector<Displacement<ICRS>> displacements;
for (int i = 0; i < 1e3; ++i) {
displacements.push_back(earth.FromSurfaceFrame<ITRS>(Instant())(
Displacement<ITRS>({distribution(random) * Metre,
distribution(random) * Metre,
distribution(random) * Metre})));
}
while (state.KeepRunning()) {
Vector<Exponentiation<Length, -2>, ICRS> acceleration;
for (auto const& displacement : displacements) {
acceleration = GeneralSphericalHarmonicsAccelerationCpp(
geopotential, Instant(), displacement);
}
benchmark::DoNotOptimize(acceleration);
}
}
void BM_ComputeGeopotentialDistance(benchmark::State& state) {
// Check the performance around this distance. May be used to tell apart the
// various contributions.
double const distance_in_kilometres = state.range(0);
SolarSystem<ICRS> solar_system_2000(
SOLUTION_DIR / "astronomy" / "sol_gravity_model.proto.txt",
SOLUTION_DIR / "astronomy" /
"sol_initial_state_jd_2451545_000000000.proto.txt");
auto const earth = MakeEarthBody(solar_system_2000, /*max_degree=*/10);
Geopotential<ICRS> const geopotential(&earth, /*tolerance=*/0x1.0p-24);
// Generate points in a spherical shell.
std::mt19937_64 random(42);
std::uniform_real_distribution<> distribution(0 * distance_in_kilometres,
1.1 * distance_in_kilometres);
std::vector<Displacement<ICRS>> displacements;
for (int i = 0; i < 1e3;) {
Displacement<ITRS> const displacement({distribution(random) * Kilo(Metre),
distribution(random) * Kilo(Metre),
distribution(random) * Kilo(Metre)});
if (displacement.Norm() > 0.9 * distance_in_kilometres * Kilo(Metre) &&
displacement.Norm() < 1.1 * distance_in_kilometres * Kilo(Metre)) {
displacements.push_back(
earth.FromSurfaceFrame<ITRS>(Instant())(displacement));
++i;
}
}
while (state.KeepRunning()) {
Vector<Exponentiation<Length, -2>, ICRS> acceleration;
for (auto const& displacement : displacements) {
acceleration = GeneralSphericalHarmonicsAccelerationCpp(
geopotential, Instant(), displacement);
}
benchmark::DoNotOptimize(acceleration);
}
}
#define PRINCIPIA_CASE_COMPUTE_GEOPOTENTIAL_F90(d) \
case (d): { \
numerics::FixedMatrix<double, (d) + 1, (d) + 1> cnm; \
numerics::FixedMatrix<double, (d) + 1, (d) + 1> snm; \
for (int n = 0; n <= (d); ++n) { \
for (int m = 0; m <= n; ++m) { \
cnm[n][m] = earth.cos()[n][m] * LegendreNormalizationFactor(n, m); \
snm[n][m] = earth.sin()[n][m] * LegendreNormalizationFactor(n, m); \
} \
} \
while (state.KeepRunning()) { \
Vector<Exponentiation<Length, -2>, ICRS> acceleration; \
for (auto const& displacement : displacements) { \
acceleration = \
GeneralSphericalHarmonicsAccelerationF90<ICRS, (d), (d)>( \
&earth, mu, rbar, cnm, snm, Instant(), displacement); \
} \
benchmark::DoNotOptimize(acceleration); \
} \
break; \
}
void BM_ComputeGeopotentialF90(benchmark::State& state) {
int const max_degree = state.range(0);
SolarSystem<ICRS> solar_system_2000(
SOLUTION_DIR / "astronomy" / "sol_gravity_model.proto.txt",
SOLUTION_DIR / "astronomy" /
"sol_initial_state_jd_2451545_000000000.proto.txt");
auto const earth = MakeEarthBody(solar_system_2000, max_degree);
double mu =
earth.gravitational_parameter() / SIUnit<GravitationalParameter>();
double rbar = earth.reference_radius() / Metre;
std::mt19937_64 random(42);
std::uniform_real_distribution<> distribution(-1e7, 1e7);
std::vector<Displacement<ICRS>> displacements;
for (int i = 0; i < 1e3; ++i) {
displacements.push_back(earth.FromSurfaceFrame<ITRS>(Instant())(
Displacement<ITRS>({distribution(random) * Metre,
distribution(random) * Metre,
distribution(random) * Metre})));
}
switch (max_degree) {
PRINCIPIA_CASE_COMPUTE_GEOPOTENTIAL_F90(2);
PRINCIPIA_CASE_COMPUTE_GEOPOTENTIAL_F90(3);
PRINCIPIA_CASE_COMPUTE_GEOPOTENTIAL_F90(4);
PRINCIPIA_CASE_COMPUTE_GEOPOTENTIAL_F90(5);
PRINCIPIA_CASE_COMPUTE_GEOPOTENTIAL_F90(6);
PRINCIPIA_CASE_COMPUTE_GEOPOTENTIAL_F90(7);
PRINCIPIA_CASE_COMPUTE_GEOPOTENTIAL_F90(8);
PRINCIPIA_CASE_COMPUTE_GEOPOTENTIAL_F90(9);
PRINCIPIA_CASE_COMPUTE_GEOPOTENTIAL_F90(10);
}
}
#undef PRINCIPIA_CASE_COMPUTE_GEOPOTENTIAL_F90
BENCHMARK(BM_ComputeGeopotentialCpp)->Arg(2)->Arg(3)->Arg(5)->Arg(10);
BENCHMARK(BM_ComputeGeopotentialF90)->Arg(2)->Arg(3)->Arg(5)->Arg(10);
BENCHMARK(BM_ComputeGeopotentialDistance)
->Arg(80'000) // C₂₂, S₂₂, J₂.
->Arg(500'000) // J₂.
->Arg(5'000'000); // Central
} // namespace physics
} // namespace principia
<|endoftext|> |
<commit_before>#include "manip.h"
using namespace std;
// Manipulator stuff is _always_ in namespace mysqlpp.
namespace mysqlpp {
extern bool dont_quote_auto;
// quote manipulator
bool dont_quote_auto = false;
SQLQueryParms& operator <<(quote_type2 p, SQLString& in)
{
if (in.is_string) {
if (in.dont_escape) {
SQLString in2 = "'" + in + "'";
in2.processed = true;
return *p.qparms << in2;
}
else {
char *s = new char[in.size() * 2 + 1];
mysql_escape_string(s, in.c_str(), (unsigned long)in.size());
SQLString in2 = SQLString("'") + s + "'";
in2.processed = true;
*p.qparms << in2;
delete[]s;
return *p.qparms;
}
}
else {
in.processed = true;
return *p.qparms << in;
}
}
template<>
ostream& operator<<(quote_type1 o, const string& in)
{
char *s = new char[in.size() * 2 + 1];
mysql_escape_string(s, in.c_str(), (unsigned long)in.size());
*o.ostr << "'" << s << "'";
delete[] s;
return *o.ostr;
}
template<>
ostream& operator<<(quote_type1 o, const char* const& in)
{
unsigned int size;
for (size = 0; in[size]; size++) ;
char *s = new char[size * 2 + 1];
mysql_escape_string(s, const_cast < char *>(in), size);
*o.ostr << "'" << s << "'";
delete[] s;
return *o.ostr;
}
template<class Str>
inline ostream& _manip(quote_type1 o, const ColData_Tmpl<Str>& in)
{
if (in.escape_q()) {
char *s = new char[in.size() * 2 + 1];
mysql_escape_string(s, in.c_str(), (unsigned long)in.size());
if (in.quote_q())
*o.ostr << "'" << s << "'";
else
*o.ostr << s;
delete[] s;
}
else if (in.quote_q()) {
*o.ostr << "'" << in << "'";
}
else {
*o.ostr << in;
}
return *o.ostr;
}
template<>
ostream& operator<<(quote_type1 o, const ColData_Tmpl<string>& in)
{
return _manip(o, in);
}
template<>
ostream& operator<<(quote_type1 o, const ColData_Tmpl<const_string>& in)
{
return _manip(o, in);
}
ostream& operator<<(ostream& o, const ColData_Tmpl<string>& in)
{
if (dont_quote_auto || (o.rdbuf() == cout.rdbuf()) ||
(o.rdbuf() == cerr.rdbuf())) {
return o << in.get_string();
}
if (in.escape_q()) {
char *s = new char[in.size() * 2 + 1];
mysql_escape_string(s, in.c_str(), (unsigned long)in.size());
if (in.quote_q())
o << "'" << s << "'";
else
o << s;
delete[] s;
}
else if (in.quote_q()) {
o << "'" << in.get_string() << "'";
}
else {
o << in.get_string();
}
return o;
}
ostream& operator<<(ostream& o, const ColData_Tmpl<const_string>& in)
{
if (dont_quote_auto || (o.rdbuf() == cout.rdbuf()) ||
(o.rdbuf() == cerr.rdbuf())) {
return o << in.get_string();
}
if (in.escape_q()) {
char *s = new char[in.size() * 2 + 1];
mysql_escape_string(s, const_cast < char *>(in.c_str()),
in.size());
if (in.quote_q())
o << "'" << s << "'";
else
o << s;
delete[] s;
}
else if (in.quote_q()) {
o << "'" << in.get_string() << "'";
}
else {
o << in.get_string();
}
return o;
}
SQLQuery& operator<<(SQLQuery& o, const ColData_Tmpl<string>& in)
{
if (dont_quote_auto) {
o << in.get_string();
return o;
}
if (in.escape_q()) {
char *s = new char[in.size() * 2 + 1];
mysql_escape_string(s, in.c_str(), (unsigned long)in.size());
if (in.quote_q())
static_cast<ostream &>(o) << "'" << s << "'";
else
static_cast<ostream &>(o) << s;
delete[] s;
}
else if (in.quote_q()) {
static_cast<ostream &>(o) << "'" << in.get_string() << "'";
}
else {
static_cast<ostream &>(o) << in.get_string();
}
return o;
}
SQLQuery& operator<<(SQLQuery& o, const ColData_Tmpl<const_string>& in)
{
if (dont_quote_auto) {
o << in.get_string();
return o;
}
if (in.escape_q()) {
char *s = new char[in.size() * 2 + 1];
mysql_escape_string(s, const_cast < char *>(in.c_str()),
in.size());
if (in.quote_q())
static_cast<ostream &>(o) << "'" << s << "'";
else
static_cast<ostream &>(o) << s;
delete[] s;
}
else if (in.quote_q()) {
static_cast<ostream &>(o) << "'" << in.get_string() << "'";
}
else {
static_cast<ostream &>(o) << in.get_string();
}
return o;
}
// quote only manipulator
SQLQueryParms& operator<<(quote_only_type2 p, SQLString& in)
{
if (in.is_string) {
SQLString in2 = "'" + in + "'";
in2.processed = true;
return *p.qparms << in2;
}
else {
in.processed = true;
return *p.qparms << in;
}
}
template<>
ostream& operator<<(quote_only_type1 o, const ColData_Tmpl<string>& in)
{
if (in.quote_q()) {
*o.ostr << "'" << in << "'";
}
else {
*o.ostr << in;
}
return *o.ostr;
}
template<>
ostream& operator<<(quote_only_type1 o,
const ColData_Tmpl<const_string>& in)
{
if (in.quote_q()) {
*o.ostr << "'" << in << "'";
}
else {
*o.ostr << in;
}
return *o.ostr;
}
// quote double only manipulator
SQLQueryParms& operator<<(quote_double_only_type2 p, SQLString& in)
{
if (in.is_string) {
SQLString in2 = "\"" + in + "\"";
in2.processed = true;
return *p.qparms << in2;
}
else {
in.processed = true;
return *p.qparms << in;
}
}
template<>
ostream& operator<<(quote_double_only_type1 o,
const ColData_Tmpl<string>& in)
{
if (in.quote_q()) {
*o.ostr << "'" << in << "'";
}
else {
*o.ostr << in;
}
return *o.ostr;
}
template<>
ostream& operator<<(quote_double_only_type1 o,
const ColData_Tmpl<const_string>& in)
{
if (in.quote_q()) {
*o.ostr << "'" << in << "'";
}
else {
*o.ostr << in;
}
return *o.ostr;
}
// escape manipulator
SQLQueryParms& operator<<(escape_type2 p, SQLString& in)
{
if (in.is_string) {
if (in.dont_escape) {
in.processed = true;
return *p.qparms << in;
}
else {
char *s = new char[in.size() * 2 + 1];
mysql_escape_string(s, in.c_str(), (unsigned long)in.size());
SQLString in2 = s;
in2.processed = true;
*p.qparms << in2;
delete[] s;
return *p.qparms;
}
}
else {
in.processed = true;
return *p.qparms << in;
}
}
template<>
ostream& operator<<(escape_type1 o, const string& in)
{
char *s = new char[in.size() * 2 + 1];
mysql_escape_string(s, in.c_str(), (unsigned long)in.size());
*o.ostr << s;
delete[] s;
return *o.ostr;
}
template<>
ostream& operator<<(escape_type1 o, const char* const& in)
{
unsigned int size;
for (size = 0; in[size]; size++) ;
char *s = new char[size * 2 + 1];
mysql_escape_string(s, const_cast < char *>(in), size);
*o.ostr << s;
delete[] s;
return *o.ostr;
}
template<class Str>
inline ostream& _manip(escape_type1 o, const ColData_Tmpl<Str>& in)
{
if (in.escape_q()) {
char *s = new char[in.size() * 2 + 1];
mysql_escape_string(s, in.c_str(), (unsigned long)in.size());
delete[] s;
}
else {
*o.ostr << in;
}
return *o.ostr;
}
template<>
ostream& operator<<(escape_type1 o, const ColData_Tmpl<string>& in)
{
return _manip(o, in);
}
template<>
ostream& operator<<(escape_type1 o, const ColData_Tmpl<const_string>& in)
{
return _manip(o, in);
}
} // end namespace mysqlpp
<commit_msg>Removed an unnecessary 'extern'. (The variable we so declared is defined in this same file!)<commit_after>#include "manip.h"
using namespace std;
// Manipulator stuff is _always_ in namespace mysqlpp.
namespace mysqlpp {
bool dont_quote_auto = false;
// quote manipulator
SQLQueryParms& operator <<(quote_type2 p, SQLString& in)
{
if (in.is_string) {
if (in.dont_escape) {
SQLString in2 = "'" + in + "'";
in2.processed = true;
return *p.qparms << in2;
}
else {
char *s = new char[in.size() * 2 + 1];
mysql_escape_string(s, in.c_str(), (unsigned long)in.size());
SQLString in2 = SQLString("'") + s + "'";
in2.processed = true;
*p.qparms << in2;
delete[]s;
return *p.qparms;
}
}
else {
in.processed = true;
return *p.qparms << in;
}
}
template<>
ostream& operator<<(quote_type1 o, const string& in)
{
char *s = new char[in.size() * 2 + 1];
mysql_escape_string(s, in.c_str(), (unsigned long)in.size());
*o.ostr << "'" << s << "'";
delete[] s;
return *o.ostr;
}
template<>
ostream& operator<<(quote_type1 o, const char* const& in)
{
unsigned int size;
for (size = 0; in[size]; size++) ;
char *s = new char[size * 2 + 1];
mysql_escape_string(s, const_cast < char *>(in), size);
*o.ostr << "'" << s << "'";
delete[] s;
return *o.ostr;
}
template<class Str>
inline ostream& _manip(quote_type1 o, const ColData_Tmpl<Str>& in)
{
if (in.escape_q()) {
char *s = new char[in.size() * 2 + 1];
mysql_escape_string(s, in.c_str(), (unsigned long)in.size());
if (in.quote_q())
*o.ostr << "'" << s << "'";
else
*o.ostr << s;
delete[] s;
}
else if (in.quote_q()) {
*o.ostr << "'" << in << "'";
}
else {
*o.ostr << in;
}
return *o.ostr;
}
template<>
ostream& operator<<(quote_type1 o, const ColData_Tmpl<string>& in)
{
return _manip(o, in);
}
template<>
ostream& operator<<(quote_type1 o, const ColData_Tmpl<const_string>& in)
{
return _manip(o, in);
}
ostream& operator<<(ostream& o, const ColData_Tmpl<string>& in)
{
if (dont_quote_auto || (o.rdbuf() == cout.rdbuf()) ||
(o.rdbuf() == cerr.rdbuf())) {
return o << in.get_string();
}
if (in.escape_q()) {
char *s = new char[in.size() * 2 + 1];
mysql_escape_string(s, in.c_str(), (unsigned long)in.size());
if (in.quote_q())
o << "'" << s << "'";
else
o << s;
delete[] s;
}
else if (in.quote_q()) {
o << "'" << in.get_string() << "'";
}
else {
o << in.get_string();
}
return o;
}
ostream& operator<<(ostream& o, const ColData_Tmpl<const_string>& in)
{
if (dont_quote_auto || (o.rdbuf() == cout.rdbuf()) ||
(o.rdbuf() == cerr.rdbuf())) {
return o << in.get_string();
}
if (in.escape_q()) {
char *s = new char[in.size() * 2 + 1];
mysql_escape_string(s, const_cast < char *>(in.c_str()),
in.size());
if (in.quote_q())
o << "'" << s << "'";
else
o << s;
delete[] s;
}
else if (in.quote_q()) {
o << "'" << in.get_string() << "'";
}
else {
o << in.get_string();
}
return o;
}
SQLQuery& operator<<(SQLQuery& o, const ColData_Tmpl<string>& in)
{
if (dont_quote_auto) {
o << in.get_string();
return o;
}
if (in.escape_q()) {
char *s = new char[in.size() * 2 + 1];
mysql_escape_string(s, in.c_str(), (unsigned long)in.size());
if (in.quote_q())
static_cast<ostream &>(o) << "'" << s << "'";
else
static_cast<ostream &>(o) << s;
delete[] s;
}
else if (in.quote_q()) {
static_cast<ostream &>(o) << "'" << in.get_string() << "'";
}
else {
static_cast<ostream &>(o) << in.get_string();
}
return o;
}
SQLQuery& operator<<(SQLQuery& o, const ColData_Tmpl<const_string>& in)
{
if (dont_quote_auto) {
o << in.get_string();
return o;
}
if (in.escape_q()) {
char *s = new char[in.size() * 2 + 1];
mysql_escape_string(s, const_cast < char *>(in.c_str()),
in.size());
if (in.quote_q())
static_cast<ostream &>(o) << "'" << s << "'";
else
static_cast<ostream &>(o) << s;
delete[] s;
}
else if (in.quote_q()) {
static_cast<ostream &>(o) << "'" << in.get_string() << "'";
}
else {
static_cast<ostream &>(o) << in.get_string();
}
return o;
}
// quote only manipulator
SQLQueryParms& operator<<(quote_only_type2 p, SQLString& in)
{
if (in.is_string) {
SQLString in2 = "'" + in + "'";
in2.processed = true;
return *p.qparms << in2;
}
else {
in.processed = true;
return *p.qparms << in;
}
}
template<>
ostream& operator<<(quote_only_type1 o, const ColData_Tmpl<string>& in)
{
if (in.quote_q()) {
*o.ostr << "'" << in << "'";
}
else {
*o.ostr << in;
}
return *o.ostr;
}
template<>
ostream& operator<<(quote_only_type1 o,
const ColData_Tmpl<const_string>& in)
{
if (in.quote_q()) {
*o.ostr << "'" << in << "'";
}
else {
*o.ostr << in;
}
return *o.ostr;
}
// quote double only manipulator
SQLQueryParms& operator<<(quote_double_only_type2 p, SQLString& in)
{
if (in.is_string) {
SQLString in2 = "\"" + in + "\"";
in2.processed = true;
return *p.qparms << in2;
}
else {
in.processed = true;
return *p.qparms << in;
}
}
template<>
ostream& operator<<(quote_double_only_type1 o,
const ColData_Tmpl<string>& in)
{
if (in.quote_q()) {
*o.ostr << "'" << in << "'";
}
else {
*o.ostr << in;
}
return *o.ostr;
}
template<>
ostream& operator<<(quote_double_only_type1 o,
const ColData_Tmpl<const_string>& in)
{
if (in.quote_q()) {
*o.ostr << "'" << in << "'";
}
else {
*o.ostr << in;
}
return *o.ostr;
}
// escape manipulator
SQLQueryParms& operator<<(escape_type2 p, SQLString& in)
{
if (in.is_string) {
if (in.dont_escape) {
in.processed = true;
return *p.qparms << in;
}
else {
char *s = new char[in.size() * 2 + 1];
mysql_escape_string(s, in.c_str(), (unsigned long)in.size());
SQLString in2 = s;
in2.processed = true;
*p.qparms << in2;
delete[] s;
return *p.qparms;
}
}
else {
in.processed = true;
return *p.qparms << in;
}
}
template<>
ostream& operator<<(escape_type1 o, const string& in)
{
char *s = new char[in.size() * 2 + 1];
mysql_escape_string(s, in.c_str(), (unsigned long)in.size());
*o.ostr << s;
delete[] s;
return *o.ostr;
}
template<>
ostream& operator<<(escape_type1 o, const char* const& in)
{
unsigned int size;
for (size = 0; in[size]; size++) ;
char *s = new char[size * 2 + 1];
mysql_escape_string(s, const_cast < char *>(in), size);
*o.ostr << s;
delete[] s;
return *o.ostr;
}
template<class Str>
inline ostream& _manip(escape_type1 o, const ColData_Tmpl<Str>& in)
{
if (in.escape_q()) {
char *s = new char[in.size() * 2 + 1];
mysql_escape_string(s, in.c_str(), (unsigned long)in.size());
delete[] s;
}
else {
*o.ostr << in;
}
return *o.ostr;
}
template<>
ostream& operator<<(escape_type1 o, const ColData_Tmpl<string>& in)
{
return _manip(o, in);
}
template<>
ostream& operator<<(escape_type1 o, const ColData_Tmpl<const_string>& in)
{
return _manip(o, in);
}
} // end namespace mysqlpp
<|endoftext|> |
<commit_before><commit_msg>Removed an excessively brittle test.<commit_after><|endoftext|> |
<commit_before><commit_msg>Added some comments to better explain the test.<commit_after><|endoftext|> |
<commit_before>/**
* @file instance.hpp
* @brief COSSB Instance
* @author Byunghun Hwang<bhhwang@nsynapse.com>
* @date 2015. 7. 27
* @details COSSB Instance
*/
#ifndef _COSSB_INSTANCE_HPP_
#define _COSSB_INSTANCE_HPP_
#include "config.hpp"
namespace cossb {
namespace core {
#ifndef _cplusplus
extern "C" {
#endif
/**
* @brief create COSSB core instances
*/
extern bool cossb_init(base::config* config);
/**
* @brief destroy COSSB core instances
*/
extern void cossb_destroy();
/**
* @brief service components synchronization
*/
extern bool cossb_sync();
#ifndef _cplusplus
}
#endif
} /* namespace core */
} /* namespace cossb */
#endif /* _COSSB_INSTANCE_HPP_ */
<commit_msg>change the argument cossb_init function<commit_after>/**
* @file instance.hpp
* @brief COSSB Instance
* @author Byunghun Hwang<bhhwang@nsynapse.com>
* @date 2015. 7. 27
* @details COSSB Instance
*/
#ifndef _COSSB_INSTANCE_HPP_
#define _COSSB_INSTANCE_HPP_
#include "config.hpp"
namespace cossb {
namespace core {
#ifndef _cplusplus
extern "C" {
#endif
/**
* @brief create COSSB core instances
*/
extern bool cossb_init(const char* manifest);
/**
* @brief destroy COSSB core instances
*/
extern void cossb_destroy();
/**
* @brief service components synchronization
*/
extern bool cossb_sync();
/**
* @brief start COSSB engine
*/
extern bool cossb_start();
/**
* @brief stop COSSB Engine
*/
extern bool cossb_stop();
#ifndef _cplusplus
}
#endif
} /* namespace core */
} /* namespace cossb */
#endif /* _COSSB_INSTANCE_HPP_ */
<|endoftext|> |
<commit_before>#ifndef US_WORLD_HPP
#define US_WORLD_HPP
/*
Copyright (c) 2013, J.D. Koftinoff Software, Ltd.
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 J.D. Koftinoff Software, Ltd. 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 J.D. KOFTINOFF SOFTWARE, LTD.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 <cstdint>
#include "us_world.h"
#include <string>
#include <iostream>
#include <stdexcept>
#include <vector>
#endif
<commit_msg>use stdint.h instead of cstdint<commit_after>#ifndef US_WORLD_HPP
#define US_WORLD_HPP
/*
Copyright (c) 2013, J.D. Koftinoff Software, Ltd.
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 J.D. Koftinoff Software, Ltd. 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 J.D. KOFTINOFF SOFTWARE, LTD.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 <stdint.h>
#include "us_world.h"
#include <string>
#include <iostream>
#include <stdexcept>
#include <vector>
#endif
<|endoftext|> |
<commit_before>// Copyright 2017 The NXT Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "backend/d3d12/ShaderModuleD3D12.h"
#include <spirv-cross/spirv_hlsl.hpp>
namespace backend { namespace d3d12 {
ShaderModule::ShaderModule(Device* device, ShaderModuleBuilder* builder)
: ShaderModuleBase(builder), mDevice(device) {
spirv_cross::CompilerHLSL compiler(builder->AcquireSpirv());
spirv_cross::CompilerGLSL::Options options_glsl;
options_glsl.vertex.fixup_clipspace = true;
compiler.spirv_cross::CompilerGLSL::set_options(options_glsl);
spirv_cross::CompilerHLSL::Options options_hlsl;
options_hlsl.shader_model = 51;
compiler.spirv_cross::CompilerHLSL::set_options(options_hlsl);
ExtractSpirvInfo(compiler);
// rename bindings so that each register type b/u/t/s starts at 0 and then offset by
// kMaxBindingsPerGroup * bindGroupIndex
auto RenumberBindings = [&](std::vector<spirv_cross::Resource> resources) {
std::array<uint32_t, kMaxBindGroups> baseRegisters = {};
for (const auto& resource : resources) {
auto bindGroupIndex =
compiler.get_decoration(resource.id, spv::DecorationDescriptorSet);
auto& baseRegister = baseRegisters[bindGroupIndex];
auto bindGroupOffset = bindGroupIndex * kMaxBindingsPerGroup;
compiler.set_decoration(resource.id, spv::DecorationBinding,
bindGroupOffset + baseRegister++);
}
};
const auto& resources = compiler.get_shader_resources();
RenumberBindings(resources.uniform_buffers); // c
RenumberBindings(resources.storage_buffers); // u
RenumberBindings(resources.separate_images); // t
RenumberBindings(resources.separate_samplers); // s
mHlslSource = compiler.compile();
}
const std::string& ShaderModule::GetHLSLSource() const {
return mHlslSource;
}
}} // namespace backend::d3d12
<commit_msg>D3D12: Add back flip_vert_y.<commit_after>// Copyright 2017 The NXT Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "backend/d3d12/ShaderModuleD3D12.h"
#include <spirv-cross/spirv_hlsl.hpp>
namespace backend { namespace d3d12 {
ShaderModule::ShaderModule(Device* device, ShaderModuleBuilder* builder)
: ShaderModuleBase(builder), mDevice(device) {
spirv_cross::CompilerHLSL compiler(builder->AcquireSpirv());
spirv_cross::CompilerGLSL::Options options_glsl;
options_glsl.vertex.fixup_clipspace = true;
options_glsl.vertex.flip_vert_y = true;
compiler.spirv_cross::CompilerGLSL::set_options(options_glsl);
spirv_cross::CompilerHLSL::Options options_hlsl;
options_hlsl.shader_model = 51;
compiler.spirv_cross::CompilerHLSL::set_options(options_hlsl);
ExtractSpirvInfo(compiler);
// rename bindings so that each register type b/u/t/s starts at 0 and then offset by
// kMaxBindingsPerGroup * bindGroupIndex
auto RenumberBindings = [&](std::vector<spirv_cross::Resource> resources) {
std::array<uint32_t, kMaxBindGroups> baseRegisters = {};
for (const auto& resource : resources) {
auto bindGroupIndex =
compiler.get_decoration(resource.id, spv::DecorationDescriptorSet);
auto& baseRegister = baseRegisters[bindGroupIndex];
auto bindGroupOffset = bindGroupIndex * kMaxBindingsPerGroup;
compiler.set_decoration(resource.id, spv::DecorationBinding,
bindGroupOffset + baseRegister++);
}
};
const auto& resources = compiler.get_shader_resources();
RenumberBindings(resources.uniform_buffers); // c
RenumberBindings(resources.storage_buffers); // u
RenumberBindings(resources.separate_images); // t
RenumberBindings(resources.separate_samplers); // s
mHlslSource = compiler.compile();
}
const std::string& ShaderModule::GetHLSLSource() const {
return mHlslSource;
}
}} // namespace backend::d3d12
<|endoftext|> |
<commit_before><commit_msg>Reorganized smoke tests, removed videoplayer from windows.<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2011-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <bench/bench.h>
#include <policy/policy.h>
#include <test/util/setup_common.h>
#include <txmempool.h>
#include <vector>
static void AddTx(const CTransactionRef& tx, CTxMemPool& pool) EXCLUSIVE_LOCKS_REQUIRED(cs_main, pool.cs)
{
int64_t nTime = 0;
unsigned int nHeight = 1;
bool spendsCoinbase = false;
unsigned int sigOpCost = 4;
LockPoints lp;
pool.addUnchecked(CTxMemPoolEntry(tx, 1000, nTime, nHeight, spendsCoinbase, sigOpCost, lp));
}
struct Available {
CTransactionRef ref;
size_t vin_left{0};
size_t tx_count;
Available(CTransactionRef& ref, size_t tx_count) : ref(ref), tx_count(tx_count){}
};
static void ComplexMemPool(benchmark::Bench& bench)
{
int childTxs = 800;
if (bench.complexityN() > 1) {
childTxs = static_cast<int>(bench.complexityN());
}
FastRandomContext det_rand{true};
std::vector<Available> available_coins;
std::vector<CTransactionRef> ordered_coins;
// Create some base transactions
size_t tx_counter = 1;
for (auto x = 0; x < 100; ++x) {
CMutableTransaction tx = CMutableTransaction();
tx.vin.resize(1);
tx.vin[0].scriptSig = CScript() << CScriptNum(tx_counter);
tx.vin[0].scriptWitness.stack.push_back(CScriptNum(x).getvch());
tx.vout.resize(det_rand.randrange(10)+2);
for (auto& out : tx.vout) {
out.scriptPubKey = CScript() << CScriptNum(tx_counter) << OP_EQUAL;
out.nValue = 10 * COIN;
}
ordered_coins.emplace_back(MakeTransactionRef(tx));
available_coins.emplace_back(ordered_coins.back(), tx_counter++);
}
for (auto x = 0; x < childTxs && !available_coins.empty(); ++x) {
CMutableTransaction tx = CMutableTransaction();
size_t n_ancestors = det_rand.randrange(10)+1;
for (size_t ancestor = 0; ancestor < n_ancestors && !available_coins.empty(); ++ancestor){
size_t idx = det_rand.randrange(available_coins.size());
Available coin = available_coins[idx];
uint256 hash = coin.ref->GetHash();
// biased towards taking just one ancestor, but maybe more
size_t n_to_take = det_rand.randrange(2) == 0 ? 1 : 1+det_rand.randrange(coin.ref->vout.size() - coin.vin_left);
for (size_t i = 0; i < n_to_take; ++i) {
tx.vin.emplace_back();
tx.vin.back().prevout = COutPoint(hash, coin.vin_left++);
tx.vin.back().scriptSig = CScript() << coin.tx_count;
tx.vin.back().scriptWitness.stack.push_back(CScriptNum(coin.tx_count).getvch());
}
if (coin.vin_left == coin.ref->vin.size()) {
coin = available_coins.back();
available_coins.pop_back();
}
tx.vout.resize(det_rand.randrange(10)+2);
for (auto& out : tx.vout) {
out.scriptPubKey = CScript() << CScriptNum(tx_counter) << OP_EQUAL;
out.nValue = 10 * COIN;
}
}
ordered_coins.emplace_back(MakeTransactionRef(tx));
available_coins.emplace_back(ordered_coins.back(), tx_counter++);
}
const auto testing_setup = MakeNoLogFileContext<const TestingSetup>(CBaseChainParams::MAIN);
CTxMemPool pool;
LOCK2(cs_main, pool.cs);
bench.run([&]() NO_THREAD_SAFETY_ANALYSIS {
for (auto& tx : ordered_coins) {
AddTx(tx, pool);
}
pool.TrimToSize(pool.DynamicMemoryUsage() * 3 / 4);
pool.TrimToSize(GetVirtualTransactionSize(*ordered_coins.front()));
});
}
BENCHMARK(ComplexMemPool);
<commit_msg>[refactor/bench] make mempool_stress bench reusable and parameterizable<commit_after>// Copyright (c) 2011-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <bench/bench.h>
#include <policy/policy.h>
#include <test/util/setup_common.h>
#include <txmempool.h>
#include <vector>
static void AddTx(const CTransactionRef& tx, CTxMemPool& pool) EXCLUSIVE_LOCKS_REQUIRED(cs_main, pool.cs)
{
int64_t nTime = 0;
unsigned int nHeight = 1;
bool spendsCoinbase = false;
unsigned int sigOpCost = 4;
LockPoints lp;
pool.addUnchecked(CTxMemPoolEntry(tx, 1000, nTime, nHeight, spendsCoinbase, sigOpCost, lp));
}
struct Available {
CTransactionRef ref;
size_t vin_left{0};
size_t tx_count;
Available(CTransactionRef& ref, size_t tx_count) : ref(ref), tx_count(tx_count){}
};
static std::vector<CTransactionRef> CreateOrderedCoins(FastRandomContext& det_rand, int childTxs, int min_ancestors)
{
std::vector<Available> available_coins;
std::vector<CTransactionRef> ordered_coins;
// Create some base transactions
size_t tx_counter = 1;
for (auto x = 0; x < 100; ++x) {
CMutableTransaction tx = CMutableTransaction();
tx.vin.resize(1);
tx.vin[0].scriptSig = CScript() << CScriptNum(tx_counter);
tx.vin[0].scriptWitness.stack.push_back(CScriptNum(x).getvch());
tx.vout.resize(det_rand.randrange(10)+2);
for (auto& out : tx.vout) {
out.scriptPubKey = CScript() << CScriptNum(tx_counter) << OP_EQUAL;
out.nValue = 10 * COIN;
}
ordered_coins.emplace_back(MakeTransactionRef(tx));
available_coins.emplace_back(ordered_coins.back(), tx_counter++);
}
for (auto x = 0; x < childTxs && !available_coins.empty(); ++x) {
CMutableTransaction tx = CMutableTransaction();
size_t n_ancestors = det_rand.randrange(10)+1;
for (size_t ancestor = 0; ancestor < n_ancestors && !available_coins.empty(); ++ancestor){
size_t idx = det_rand.randrange(available_coins.size());
Available coin = available_coins[idx];
uint256 hash = coin.ref->GetHash();
// biased towards taking min_ancestors parents, but maybe more
size_t n_to_take = det_rand.randrange(2) == 0 ?
min_ancestors :
min_ancestors + det_rand.randrange(coin.ref->vout.size() - coin.vin_left);
for (size_t i = 0; i < n_to_take; ++i) {
tx.vin.emplace_back();
tx.vin.back().prevout = COutPoint(hash, coin.vin_left++);
tx.vin.back().scriptSig = CScript() << coin.tx_count;
tx.vin.back().scriptWitness.stack.push_back(CScriptNum(coin.tx_count).getvch());
}
if (coin.vin_left == coin.ref->vin.size()) {
coin = available_coins.back();
available_coins.pop_back();
}
tx.vout.resize(det_rand.randrange(10)+2);
for (auto& out : tx.vout) {
out.scriptPubKey = CScript() << CScriptNum(tx_counter) << OP_EQUAL;
out.nValue = 10 * COIN;
}
}
ordered_coins.emplace_back(MakeTransactionRef(tx));
available_coins.emplace_back(ordered_coins.back(), tx_counter++);
}
return ordered_coins;
}
static void ComplexMemPool(benchmark::Bench& bench)
{
FastRandomContext det_rand{true};
int childTxs = 800;
if (bench.complexityN() > 1) {
childTxs = static_cast<int>(bench.complexityN());
}
std::vector<CTransactionRef> ordered_coins = CreateOrderedCoins(det_rand, childTxs, /* min_ancestors */ 1);
const auto testing_setup = MakeNoLogFileContext<const TestingSetup>(CBaseChainParams::MAIN);
CTxMemPool pool;
LOCK2(cs_main, pool.cs);
bench.run([&]() NO_THREAD_SAFETY_ANALYSIS {
for (auto& tx : ordered_coins) {
AddTx(tx, pool);
}
pool.TrimToSize(pool.DynamicMemoryUsage() * 3 / 4);
pool.TrimToSize(GetVirtualTransactionSize(*ordered_coins.front()));
});
}
BENCHMARK(ComplexMemPool);
<|endoftext|> |
<commit_before>#pragma once
#include "blackhole/attribute.hpp"
#include "blackhole/repository/factory/traits.hpp"
#include "blackhole/sink/files/backend.hpp"
#include "blackhole/sink/files/config.hpp"
#include "blackhole/sink/files/flusher.hpp"
#include "blackhole/sink/files/rotation.hpp"
#include "blackhole/sink/files/writer.hpp"
#include "blackhole/utils/unique.hpp"
namespace blackhole {
namespace sink {
template<class Backend, class Rotator, class = void>
class file_hander_t;
template<class Backend>
class file_hander_t<Backend, NoRotation, void> {
Backend m_backend;
files::writer_t<Backend> writer;
files::flusher_t<Backend> flusher;
public:
file_hander_t(const std::string& path, const files::config_t<NoRotation>& config) :
m_backend(path),
writer(m_backend),
flusher(config.autoflush, m_backend)
{}
void handle(const std::string& message) {
writer.write(message);
flusher.flush();
}
const Backend& backend() {
return m_backend;
}
};
template<class Backend, class Rotator>
class file_hander_t<
Backend,
Rotator,
typename std::enable_if<
!std::is_same<Rotator, NoRotation>::value
>::type>
{
Backend m_backend;
files::writer_t<Backend> writer;
files::flusher_t<Backend> flusher;
Rotator rotator;
public:
file_hander_t(const std::string& path, const files::config_t<Rotator>& config) :
m_backend(path),
writer(m_backend),
flusher(config.autoflush, m_backend),
rotator(config.rotation, m_backend)
{}
void handle(const std::string& message) {
writer.write(message);
flusher.flush();
if (BOOST_UNLIKELY(rotator.necessary(message))) {
rotator.rotate();
}
}
const Backend& backend() {
return m_backend;
}
};
template<class Backend = files::boost_backend_t, class Rotator = NoRotation>
class files_t {
typedef file_hander_t<Backend, Rotator> file_handler_type;
typedef std::map<std::string, std::shared_ptr<file_handler_type>> file_handlers_type;
files::config_t<Rotator> config;
file_handlers_type m_handlers;
public:
typedef files::config_t<Rotator> config_type;
static const char* name() {
return "files";
}
files_t(const config_type& config) :
config(config)
{}
//!@todo: second arg is temporary
void consume(const std::string& message, const log::attributes_t& attributes = log::attributes_t()) {
auto filename = make_filename(attributes);
auto it = m_handlers.find(filename);
if (it == m_handlers.end()) {
it = m_handlers.insert(it, std::make_pair(filename, std::make_shared<file_handler_type>(filename, config)));
}
it->second->handle(message);
}
const file_handlers_type& handlers() {
return m_handlers;
}
std::string make_filename(const log::attributes_t& attributes) const {
auto it = config.path.begin();
auto end = config.path.end();
std::string filename;
while (it != end) {
if (*it == '%' && it + 1 != end && *(it + 1) == '(') {
it += 2;
std::string key;
bool found = false;
while (it != end) {
if (*it == ')' && it + 1 != end && *(it + 1) == 's') {
found = true;
it += 2;
break;
}
key.push_back(*it);
it++;
}
if (found) {
auto ait = attributes.find(key);
if (ait != attributes.end()) {
std::ostringstream stream;
stream << ait->second.value;
filename.append(stream.str());
} else {
filename.append(key);
}
} else {
filename.append(key);
}
}
if (it == end) {
break;
}
filename.push_back(*it);
it++;
}
// std::cout << "filename=" << filename << std::endl;
return filename;
}
};
} // namespace sink
template<class Backend, class Watcher>
struct unique_id_traits<sink::files_t<Backend, sink::rotator_t<Backend, Watcher>>> {
typedef sink::rotator_t<Backend, Watcher> rotator_type;
typedef sink::files_t<Backend, rotator_type> sink_type;
typedef std::map<std::string, boost::any> variant_map_t;
static std::string generate(const boost::any& config) {
const variant_map_t& cfg = boost::any_cast<variant_map_t>(config);
auto rotation_it = cfg.find("rotation");
if (rotation_it != cfg.end()) {
const variant_map_t& rotation = boost::any_cast<variant_map_t>(rotation_it->second);
const bool has_size_watcher = rotation.find("size") != rotation.end();
const bool has_datetime_watcher = rotation.find("period") != rotation.end();
if (has_size_watcher && has_datetime_watcher) {
throw blackhole::error_t("set watcher is not implemented yet");
} else if (has_size_watcher) {
return utils::format("%s/%s/%s", sink_type::name(), rotator_type::name(), "size");
} else if (has_datetime_watcher) {
return utils::format("%s/%s/%s", sink_type::name(), rotator_type::name(), "datetime");
}
throw blackhole::error_t("rotation section not properly configures: no watcher settings found");
}
return sink_type::name();
}
};
template<class Backend>
struct config_traits<sink::files_t<Backend, sink::NoRotation>> {
static std::string name() {
return sink::files_t<Backend, sink::NoRotation>::name();
}
};
template<class Backend, class Watcher>
struct config_traits<sink::files_t<Backend, sink::rotator_t<Backend, Watcher>>> {
typedef sink::rotator_t<Backend, Watcher> rotator_type;
typedef sink::files_t<Backend, rotator_type> sink_type;
static std::string name() {
return utils::format("%s/%s/%s", sink_type::name(), rotator_type::name(), Watcher::name());
}
};
namespace aux {
template<class Backend, class Rotator>
struct filler<sink::files_t<Backend, Rotator>> {
template<class Extractor, class Config>
static void extract_to(const Extractor& ex, Config& config) {
ex["path"].to(config.path);
ex["autoflush"].to(config.autoflush);
}
};
template<class Backend, class Watcher>
struct filler<sink::rotator_t<Backend, Watcher>> {
template<class Extractor, class Config>
static void extract_to(const Extractor& ex, Config& config) {
ex["rotation"]["pattern"].to(config.rotation.pattern);
ex["rotation"]["backups"].to(config.rotation.backups);
}
};
} // namespace aux
template<class Backend>
struct factory_traits<sink::files_t<Backend>> {
typedef sink::files_t<Backend> sink_type;
typedef typename sink_type::config_type config_type;
static void map_config(const aux::extractor<sink_type>& ex, config_type& config) {
aux::filler<sink_type>::extract_to(ex, config);
}
};
template<class Backend>
struct factory_traits<sink::files_t<Backend, sink::rotator_t<Backend, sink::rotation::watcher::size_t>>> {
typedef sink::rotation::watcher::size_t watcher_type;
typedef sink::rotator_t<Backend, watcher_type> rotator_type;
typedef sink::files_t<Backend, rotator_type> sink_type;
typedef typename sink_type::config_type config_type;
static void map_config(const aux::extractor<sink_type>& ex, config_type& config) {
aux::filler<sink_type>::extract_to(ex, config);
aux::filler<rotator_type>::extract_to(ex, config);
ex["rotation"]["size"].to(config.rotation.watcher.size);
}
};
template<class Backend>
struct factory_traits<sink::files_t<Backend, sink::rotator_t<Backend, sink::rotation::watcher::datetime_t<>>>> {
typedef sink::rotation::watcher::datetime_t<> watcher_type;
typedef sink::rotator_t<Backend, watcher_type> rotator_type;
typedef sink::files_t<Backend, rotator_type> sink_type;
typedef typename sink_type::config_type config_type;
static void map_config(const aux::extractor<sink_type>& ex, config_type& config) {
aux::filler<sink_type>::extract_to(ex, config);
aux::filler<rotator_type>::extract_to(ex, config);
ex["rotation"]["period"].to(config.rotation.watcher.period);
}
};
} // namespace blackhole
<commit_msg>[Aux] Using hash table instead of RBT. [Code style] Renaming done.<commit_after>#pragma once
#include "blackhole/attribute.hpp"
#include "blackhole/repository/factory/traits.hpp"
#include "blackhole/sink/files/backend.hpp"
#include "blackhole/sink/files/config.hpp"
#include "blackhole/sink/files/flusher.hpp"
#include "blackhole/sink/files/rotation.hpp"
#include "blackhole/sink/files/writer.hpp"
#include "blackhole/utils/unique.hpp"
namespace blackhole {
namespace sink {
template<class Backend, class Rotator, class = void>
class file_hander_t;
template<class Backend>
class file_hander_t<Backend, NoRotation, void> {
Backend m_backend;
files::writer_t<Backend> writer;
files::flusher_t<Backend> flusher;
public:
file_hander_t(const std::string& path, const files::config_t<NoRotation>& config) :
m_backend(path),
writer(m_backend),
flusher(config.autoflush, m_backend)
{}
void handle(const std::string& message) {
writer.write(message);
flusher.flush();
}
const Backend& backend() {
return m_backend;
}
};
template<class Backend, class Rotator>
class file_hander_t<
Backend,
Rotator,
typename std::enable_if<
!std::is_same<Rotator, NoRotation>::value
>::type>
{
Backend m_backend;
files::writer_t<Backend> writer;
files::flusher_t<Backend> flusher;
Rotator rotator;
public:
file_hander_t(const std::string& path, const files::config_t<Rotator>& config) :
m_backend(path),
writer(m_backend),
flusher(config.autoflush, m_backend),
rotator(config.rotation, m_backend)
{}
void handle(const std::string& message) {
writer.write(message);
flusher.flush();
if (BOOST_UNLIKELY(rotator.necessary(message))) {
rotator.rotate();
}
}
const Backend& backend() {
return m_backend;
}
};
template<class Backend = files::boost_backend_t, class Rotator = NoRotation>
class files_t {
typedef file_hander_t<Backend, Rotator> handler_type;
typedef std::unordered_map<std::string, std::shared_ptr<handler_type>> handlers_type;
files::config_t<Rotator> config;
handlers_type m_handlers;
public:
typedef files::config_t<Rotator> config_type;
static const char* name() {
return "files";
}
files_t(const config_type& config) :
config(config)
{}
void consume(const std::string& message, const log::attributes_t& attributes = log::attributes_t()) {
auto filename = make_filename(attributes);
auto it = m_handlers.find(filename);
if (it == m_handlers.end()) {
it = m_handlers.insert(it, std::make_pair(filename, std::make_shared<handler_type>(filename, config)));
}
it->second->handle(message);
}
const handlers_type& handlers() {
return m_handlers;
}
std::string make_filename(const log::attributes_t& attributes) const {
auto it = config.path.begin();
auto end = config.path.end();
std::string filename;
while (it != end) {
if (*it == '%' && it + 1 != end && *(it + 1) == '(') {
it += 2;
std::string key;
bool found = false;
while (it != end) {
if (*it == ')' && it + 1 != end && *(it + 1) == 's') {
found = true;
it += 2;
break;
}
key.push_back(*it);
it++;
}
if (found) {
auto ait = attributes.find(key);
if (ait != attributes.end()) {
std::ostringstream stream;
stream << ait->second.value;
filename.append(stream.str());
} else {
filename.append(key);
}
} else {
filename.append(key);
}
}
if (it == end) {
break;
}
filename.push_back(*it);
it++;
}
// std::cout << "filename=" << filename << std::endl;
return filename;
}
};
} // namespace sink
template<class Backend, class Watcher>
struct unique_id_traits<sink::files_t<Backend, sink::rotator_t<Backend, Watcher>>> {
typedef sink::rotator_t<Backend, Watcher> rotator_type;
typedef sink::files_t<Backend, rotator_type> sink_type;
typedef std::map<std::string, boost::any> variant_map_t;
static std::string generate(const boost::any& config) {
const variant_map_t& cfg = boost::any_cast<variant_map_t>(config);
auto rotation_it = cfg.find("rotation");
if (rotation_it != cfg.end()) {
const variant_map_t& rotation = boost::any_cast<variant_map_t>(rotation_it->second);
const bool has_size_watcher = rotation.find("size") != rotation.end();
const bool has_datetime_watcher = rotation.find("period") != rotation.end();
if (has_size_watcher && has_datetime_watcher) {
throw blackhole::error_t("set watcher is not implemented yet");
} else if (has_size_watcher) {
return utils::format("%s/%s/%s", sink_type::name(), rotator_type::name(), "size");
} else if (has_datetime_watcher) {
return utils::format("%s/%s/%s", sink_type::name(), rotator_type::name(), "datetime");
}
throw blackhole::error_t("rotation section not properly configures: no watcher settings found");
}
return sink_type::name();
}
};
template<class Backend>
struct config_traits<sink::files_t<Backend, sink::NoRotation>> {
static std::string name() {
return sink::files_t<Backend, sink::NoRotation>::name();
}
};
template<class Backend, class Watcher>
struct config_traits<sink::files_t<Backend, sink::rotator_t<Backend, Watcher>>> {
typedef sink::rotator_t<Backend, Watcher> rotator_type;
typedef sink::files_t<Backend, rotator_type> sink_type;
static std::string name() {
return utils::format("%s/%s/%s", sink_type::name(), rotator_type::name(), Watcher::name());
}
};
namespace aux {
template<class Backend, class Rotator>
struct filler<sink::files_t<Backend, Rotator>> {
template<class Extractor, class Config>
static void extract_to(const Extractor& ex, Config& config) {
ex["path"].to(config.path);
ex["autoflush"].to(config.autoflush);
}
};
template<class Backend, class Watcher>
struct filler<sink::rotator_t<Backend, Watcher>> {
template<class Extractor, class Config>
static void extract_to(const Extractor& ex, Config& config) {
ex["rotation"]["pattern"].to(config.rotation.pattern);
ex["rotation"]["backups"].to(config.rotation.backups);
}
};
} // namespace aux
template<class Backend>
struct factory_traits<sink::files_t<Backend>> {
typedef sink::files_t<Backend> sink_type;
typedef typename sink_type::config_type config_type;
static void map_config(const aux::extractor<sink_type>& ex, config_type& config) {
aux::filler<sink_type>::extract_to(ex, config);
}
};
template<class Backend>
struct factory_traits<sink::files_t<Backend, sink::rotator_t<Backend, sink::rotation::watcher::size_t>>> {
typedef sink::rotation::watcher::size_t watcher_type;
typedef sink::rotator_t<Backend, watcher_type> rotator_type;
typedef sink::files_t<Backend, rotator_type> sink_type;
typedef typename sink_type::config_type config_type;
static void map_config(const aux::extractor<sink_type>& ex, config_type& config) {
aux::filler<sink_type>::extract_to(ex, config);
aux::filler<rotator_type>::extract_to(ex, config);
ex["rotation"]["size"].to(config.rotation.watcher.size);
}
};
template<class Backend>
struct factory_traits<sink::files_t<Backend, sink::rotator_t<Backend, sink::rotation::watcher::datetime_t<>>>> {
typedef sink::rotation::watcher::datetime_t<> watcher_type;
typedef sink::rotator_t<Backend, watcher_type> rotator_type;
typedef sink::files_t<Backend, rotator_type> sink_type;
typedef typename sink_type::config_type config_type;
static void map_config(const aux::extractor<sink_type>& ex, config_type& config) {
aux::filler<sink_type>::extract_to(ex, config);
aux::filler<rotator_type>::extract_to(ex, config);
ex["rotation"]["period"].to(config.rotation.watcher.period);
}
};
} // namespace blackhole
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: pe_class.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-07 18:23:07 $
*
* 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 ADC_CPP_PE_CLASS_HXX
#define ADC_CPP_PE_CLASS_HXX
// USED SERVICES
// BASE CLASSES
#include "cpp_pe.hxx"
// COMPONENTS
#include <semantic/callf.hxx>
#include <semantic/sub_peu.hxx>
#include <ary/cpp/c_etypes.hxx>
#include <ary/cpp/c_idlist.hxx>
// PARAMETERS
#include "all_toks.hxx"
namespace ary
{
namespace cpp
{
class Class;
}
}
namespace cpp
{
using ary::cpp::E_Protection;
using ary::cpp::E_Virtuality;
class PE_Base;
class PE_Enum;
class PE_Typedef;
class PE_VarFunc;
class PE_Ignore;
class PE_Class : public cpp::Cpp_PE
{
public:
enum E_State
{
start, /// before class, struct or union
expectName, /// after class, struct or union
gotName, /// after name, before : or {
bodyStd, /// after {
inProtection, /// after public, protected or private and before ":"
afterDecl, /// after ending }
size_of_states
};
enum E_KindOfResult
{
is_declaration, // normal
is_implicit_declaration, // like in: class Abc { public int n; } aAbc;
is_predeclaration, // like: class Abc;
is_qualified_typename // like in: class Abc * fx();
};
PE_Class(
Cpp_PE * i_pParent );
~PE_Class();
virtual void Call_Handler(
const cpp::Token & i_rTok );
virtual Cpp_PE * Handle_ChildFailure();
E_KindOfResult Result_KindOf() const;
const udmstri & Result_LocalName() const;
const udmstri & Result_FirstNameSegment() const;
private:
typedef SubPe< PE_Class, PE_Base > SP_Base;
// typedef SubPe< PE_Class, PE_Enum> SP_Enum;
typedef SubPe< PE_Class, PE_Typedef> SP_Typedef;
typedef SubPe< PE_Class, PE_VarFunc> SP_VarFunc;
typedef SubPe< PE_Class, PE_Ignore > SP_Ignore;
typedef SubPeUse< PE_Class, PE_Base> SPU_Base;
// typedef SubPeUse< PE_Class, PE_Enum> SPU_Enum;
typedef SubPeUse< PE_Class, PE_Typedef> SPU_Typedef;
typedef SubPeUse< PE_Class, PE_VarFunc> SPU_VarFunc;
typedef SubPeUse< PE_Class, PE_Ignore> SPU_Ignore;
typedef ary::cpp::List_Bases BaseList;
typedef ary::cpp::S_Classes_Base Base;
typedef ary::cpp::E_Protection E_Protection;
void Setup_StatusFunctions();
virtual void InitData();
virtual void TransferData();
void Hdl_SyntaxError( const char *);
void Init_CurObject();
void SpReturn_Base();
void On_start_class( const char * );
void On_start_struct( const char * );
void On_start_union( const char * );
void On_expectName_Identifier( const char * );
void On_expectName_SwBracket_Left( const char * );
void On_expectName_Colon( const char * );
void On_gotName_SwBracket_Left( const char * );
void On_gotName_Semicolon( const char * );
void On_gotName_Colon( const char * );
void On_gotName_Return2Type( const char * );
void On_bodyStd_VarFunc( const char * );
void On_bodyStd_ClassKey( const char * );
void On_bodyStd_enum( const char * );
void On_bodyStd_typedef( const char * );
void On_bodyStd_public( const char * );
void On_bodyStd_protected( const char * );
void On_bodyStd_private( const char * );
void On_bodyStd_template( const char * );
void On_bodyStd_friend( const char * );
void On_bodyStd_using( const char * );
void On_bodyStd_SwBracket_Right( const char * );
void On_inProtection_Colon( const char * );
void On_afterDecl_Semicolon( const char * );
void On_afterDecl_Return2Type( const char * );
// DATA
Dyn< PeStatusArray<PE_Class> >
pStati;
Dyn<SP_Base> pSpBase;
// Dyn<SP_Enum> pSpEnum;
Dyn<SP_Typedef> pSpTypedef;
Dyn<SP_VarFunc> pSpVarFunc;
Dyn<SP_Ignore> pSpIgnore;
Dyn<SPU_Base> pSpuBase;
// Dyn<SPU_Enum> pSpuEnum;
Dyn<SPU_Typedef> pSpuTypedef;
Dyn<SPU_VarFunc> pSpuVarFunc;
Dyn<SPU_Ignore> pSpuTemplate;
Dyn<SPU_Ignore> pSpuUsing;
Dyn<SPU_Ignore> pSpuIgnoreFailure;
udmstri sLocalName;
ary::cpp::E_ClassKey
eClassKey;
ary::cpp::Class * pCurObject;
BaseList aBases;
E_KindOfResult eResult_KindOf;
};
// IMPLEMENTATION
inline PE_Class::E_KindOfResult
PE_Class::Result_KindOf() const
{
return eResult_KindOf;
}
inline const udmstri &
PE_Class::Result_LocalName() const
{
return sLocalName;
}
inline const udmstri &
PE_Class::Result_FirstNameSegment() const
{
return sLocalName;
}
} // namespace cpp
#if 0 // Branches
class struct union
-> Class
-> Predeclaration
typedef
-> Typedef
enum
-> Enum
TypeDeclaration
-> Function In Class
-> Variable
public, protected, private
-> Protection declaration
friend
-> Friend Class
-> Friend Function
virtual
-> Function In Class
using
-> Using Declaration
#endif // 0
#endif
<commit_msg>INTEGRATION: CWS adc18 (1.2.56); FILE MERGED 2007/10/19 10:37:30 np 1.2.56.2: #i81775# 2007/10/17 09:30:49 np 1.2.56.1: #i54779#<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: pe_class.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hr $ $Date: 2007-11-02 16:53:05 $
*
* 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 ADC_CPP_PE_CLASS_HXX
#define ADC_CPP_PE_CLASS_HXX
// USED SERVICES
// BASE CLASSES
#include "cpp_pe.hxx"
// OTHER
#include <semantic/callf.hxx>
#include <semantic/sub_peu.hxx>
#include <ary/cpp/c_types4cpp.hxx>
#include <ary/cpp/c_slntry.hxx>
#include "all_toks.hxx"
namespace ary
{
namespace cpp
{
class Class;
}
}
namespace cpp
{
using ary::cpp::E_Protection;
using ary::cpp::E_Virtuality;
class PE_Base;
class PE_Enum;
class PE_Typedef;
class PE_VarFunc;
class PE_Ignore;
class PE_Defines;
class PE_Class : public cpp::Cpp_PE
{
public:
enum E_State
{
start, /// before class, struct or union
expectName, /// after class, struct or union
gotName, /// after name, before : or {
bodyStd, /// after {
inProtection, /// after public, protected or private and before ":"
afterDecl, /// after ending }
size_of_states
};
enum E_KindOfResult
{
is_declaration, // normal
is_implicit_declaration, // like in: class Abc { public int n; } aAbc;
is_predeclaration, // like: class Abc;
is_qualified_typename // like in: class Abc * fx();
};
PE_Class(
Cpp_PE * i_pParent );
~PE_Class();
virtual void Call_Handler(
const cpp::Token & i_rTok );
virtual Cpp_PE * Handle_ChildFailure();
E_KindOfResult Result_KindOf() const;
const String & Result_LocalName() const;
const String & Result_FirstNameSegment() const;
private:
typedef SubPe< PE_Class, PE_Base > SP_Base;
// typedef SubPe< PE_Class, PE_Enum> SP_Enum;
typedef SubPe< PE_Class, PE_Typedef> SP_Typedef;
typedef SubPe< PE_Class, PE_VarFunc> SP_VarFunc;
typedef SubPe< PE_Class, PE_Ignore > SP_Ignore;
typedef SubPe< PE_Class, PE_Defines> SP_Defines;
typedef SubPeUse< PE_Class, PE_Base> SPU_Base;
// typedef SubPeUse< PE_Class, PE_Enum> SPU_Enum;
typedef SubPeUse< PE_Class, PE_Typedef> SPU_Typedef;
typedef SubPeUse< PE_Class, PE_VarFunc> SPU_VarFunc;
typedef SubPeUse< PE_Class, PE_Ignore> SPU_Ignore;
typedef SubPeUse< PE_Class, PE_Defines> SPU_Defines;
typedef ary::cpp::List_Bases BaseList;
typedef ary::cpp::S_Classes_Base Base;
typedef ary::cpp::E_Protection E_Protection;
void Setup_StatusFunctions();
virtual void InitData();
virtual void TransferData();
void Hdl_SyntaxError( const char *);
void Init_CurObject();
void SpReturn_Base();
void On_start_class( const char * );
void On_start_struct( const char * );
void On_start_union( const char * );
void On_expectName_Identifier( const char * );
void On_expectName_SwBracket_Left( const char * );
void On_expectName_Colon( const char * );
void On_gotName_SwBracket_Left( const char * );
void On_gotName_Semicolon( const char * );
void On_gotName_Colon( const char * );
void On_gotName_Return2Type( const char * );
void On_bodyStd_VarFunc( const char * );
void On_bodyStd_ClassKey( const char * );
void On_bodyStd_enum( const char * );
void On_bodyStd_typedef( const char * );
void On_bodyStd_public( const char * );
void On_bodyStd_protected( const char * );
void On_bodyStd_private( const char * );
void On_bodyStd_template( const char * );
void On_bodyStd_friend( const char * );
void On_bodyStd_using( const char * );
void On_bodyStd_SwBracket_Right( const char * );
void On_bodyStd_DefineName(const char * );
void On_bodyStd_MacroName(const char * );
void On_inProtection_Colon( const char * );
void On_afterDecl_Semicolon( const char * );
void On_afterDecl_Return2Type( const char * );
// DATA
Dyn< PeStatusArray<PE_Class> >
pStati;
Dyn<SP_Base> pSpBase;
// Dyn<SP_Enum> pSpEnum;
Dyn<SP_Typedef> pSpTypedef;
Dyn<SP_VarFunc> pSpVarFunc;
Dyn<SP_Ignore> pSpIgnore;
Dyn<SP_Defines> pSpDefs;
Dyn<SPU_Base> pSpuBase;
// Dyn<SPU_Enum> pSpuEnum;
Dyn<SPU_Typedef> pSpuTypedef;
Dyn<SPU_VarFunc> pSpuVarFunc;
Dyn<SPU_Ignore> pSpuTemplate;
Dyn<SPU_Ignore> pSpuUsing;
Dyn<SPU_Ignore> pSpuIgnoreFailure;
Dyn<SPU_Defines> pSpuDefs;
String sLocalName;
ary::cpp::E_ClassKey
eClassKey;
ary::cpp::Class * pCurObject;
BaseList aBases;
E_KindOfResult eResult_KindOf;
};
// IMPLEMENTATION
inline PE_Class::E_KindOfResult
PE_Class::Result_KindOf() const
{
return eResult_KindOf;
}
inline const String &
PE_Class::Result_LocalName() const
{
return sLocalName;
}
inline const String &
PE_Class::Result_FirstNameSegment() const
{
return sLocalName;
}
} // namespace cpp
#if 0 // Branches
class struct union
-> Class
-> Predeclaration
typedef
-> Typedef
enum
-> Enum
TypeDeclaration
-> Function In Class
-> Variable
public, protected, private
-> Protection declaration
friend
-> Friend Class
-> Friend Function
virtual
-> Function In Class
using
-> Using Declaration
#endif // 0
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: pe_param.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: kz $ $Date: 2007-10-09 15:03:02 $
*
* 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
*
************************************************************************/
#include <precomp.h>
#include "pe_param.hxx"
// NOT FULLY DEFINED SERVICES
#include <cosv/template/tpltools.hxx>
#include <ary/cpp/c_rwgate.hxx>
#include "pe_type.hxx"
#include "pe_vari.hxx"
namespace cpp {
//*********************** PE_Parameter ***********************//
PE_Parameter::PE_Parameter( Cpp_PE * i_pParent )
: Cpp_PE(i_pParent),
pStati( new PeStatusArray<PE_Parameter> )
// pSpType,
// pSpuType,
// pSpVariable,
// pSpuVariable,
// aResultParamInfo
{
Setup_StatusFunctions();
pSpType = new SP_Type(*this);
pSpuType = new SPU_Type(*pSpType, &PE_Parameter::SpInit_Type, &PE_Parameter::SpReturn_Type);
pSpVariable = new SP_Variable(*this);
pSpuVariable = new SPU_Variable(*pSpVariable, &PE_Parameter::SpInit_Variable, &PE_Parameter::SpReturn_Variable);
}
PE_Parameter::~PE_Parameter()
{
}
void
PE_Parameter::Call_Handler( const cpp::Token & i_rTok )
{
pStati->Cur().Call_Handler(i_rTok.TypeId(), i_rTok.Text());
}
void
PE_Parameter::Setup_StatusFunctions()
{
typedef CallFunction<PE_Parameter>::F_Tok F_Tok;
static F_Tok stateF_start[] = { &PE_Parameter::On_start_Type,
&PE_Parameter::On_start_Type,
&PE_Parameter::On_start_Type,
&PE_Parameter::On_start_Type,
&PE_Parameter::On_start_Type,
&PE_Parameter::On_start_Type,
&PE_Parameter::On_start_Type,
&PE_Parameter::On_start_Bracket_Right,
&PE_Parameter::On_start_Type,
&PE_Parameter::On_start_Ellipse,
&PE_Parameter::On_start_Type,
&PE_Parameter::On_start_Type,
&PE_Parameter::On_start_Type };
static INT16 stateT_start[] = { Tid_Identifier,
Tid_class,
Tid_struct,
Tid_union,
Tid_enum,
Tid_const,
Tid_volatile,
Tid_Bracket_Right,
Tid_DoubleColon,
Tid_Ellipse,
Tid_typename,
Tid_BuiltInType,
Tid_TypeSpecializer };
static F_Tok stateF_expectName[] = { &PE_Parameter::On_expectName_Identifier,
&PE_Parameter::On_expectName_ArrayBracket_Left,
&PE_Parameter::On_expectName_Bracket_Right,
&PE_Parameter::On_expectName_Comma,
&PE_Parameter::On_afterName_Assign };
static INT16 stateT_expectName[] = { Tid_Identifier,
Tid_ArrayBracket_Left,
Tid_Bracket_Right,
Tid_Comma,
Tid_Assign };
static F_Tok stateF_afterName[] = { &PE_Parameter::On_afterName_ArrayBracket_Left,
&PE_Parameter::On_afterName_Bracket_Right,
&PE_Parameter::On_afterName_Comma,
&PE_Parameter::On_afterName_Assign };
static INT16 stateT_afterName[] = { Tid_ArrayBracket_Left,
Tid_Bracket_Right,
Tid_Comma,
Tid_Assign };
static F_Tok stateF_finished[] = { &PE_Parameter::On_finished_Comma,
&PE_Parameter::On_finished_Bracket_Right };
static INT16 stateT_finished[] = { Tid_Bracket_Right,
Tid_Comma };
SEMPARSE_CREATE_STATUS(PE_Parameter, start, Hdl_SyntaxError);
SEMPARSE_CREATE_STATUS(PE_Parameter, expectName, Hdl_SyntaxError);
SEMPARSE_CREATE_STATUS(PE_Parameter, afterName, Hdl_SyntaxError);
SEMPARSE_CREATE_STATUS(PE_Parameter, finished, Hdl_SyntaxError);
}
void
PE_Parameter::InitData()
{
pStati->SetCur(start);
aResultParamInfo.Empty();
}
void
PE_Parameter::TransferData()
{
pStati->SetCur(size_of_states);
}
void
PE_Parameter::Hdl_SyntaxError( const char * i_sText)
{
StdHandlingOfSyntaxError(i_sText);
}
void
PE_Parameter::SpInit_Type()
{
// Does nothing.
}
void
PE_Parameter::SpInit_Variable()
{
// Does nothing.
}
void
PE_Parameter::SpReturn_Type()
{
aResultParamInfo.nType = pSpuType->Child().Result_Type().Id();
pStati->SetCur(expectName);
}
void
PE_Parameter::SpReturn_Variable()
{
if (pSpuVariable->Child().Result_Pattern() > 0)
{
aResultParamInfo.sSizeExpression = pSpuVariable->Child().Result_SizeExpression();
aResultParamInfo.sInitExpression = pSpuVariable->Child().Result_InitExpression();
}
}
void
PE_Parameter::On_start_Type(const char *)
{
pSpuType->Push(not_done);
}
void
PE_Parameter::On_start_Bracket_Right(const char *)
{
SetTokenResult(not_done, pop_success);
}
void
PE_Parameter::On_start_Ellipse(const char *)
{
SetTokenResult(done, pop_success);
aResultParamInfo.nType = Env().AryGate().Tid_Ellipse();
}
void
PE_Parameter::On_expectName_Identifier(const char * i_sText)
{
SetTokenResult(done, stay);
pStati->SetCur(afterName);
aResultParamInfo.sName = i_sText;
}
void
PE_Parameter::On_expectName_ArrayBracket_Left(const char * i_sText)
{
On_afterName_ArrayBracket_Left(i_sText);
}
void
PE_Parameter::On_expectName_Bracket_Right(const char * i_sText)
{
On_afterName_Bracket_Right(i_sText);
}
void
PE_Parameter::On_expectName_Comma(const char * i_sText)
{
On_afterName_Comma(i_sText);
}
void
PE_Parameter::On_expectName_Assign(const char * i_sText)
{
On_afterName_Assign(i_sText);
}
void
PE_Parameter::On_afterName_ArrayBracket_Left(const char *)
{
pSpuVariable->Push(not_done);
}
void
PE_Parameter::On_afterName_Bracket_Right(const char *)
{
SetTokenResult(not_done, pop_success);
}
void
PE_Parameter::On_afterName_Comma(const char *)
{
SetTokenResult(not_done, pop_success);
}
void
PE_Parameter::On_afterName_Assign(const char *)
{
pSpuVariable->Push(not_done);
}
void
PE_Parameter::On_finished_Bracket_Right(const char *)
{
SetTokenResult(not_done, pop_success);
}
void
PE_Parameter::On_finished_Comma(const char *)
{
SetTokenResult(not_done, pop_success);
}
} // namespace cpp
<commit_msg>INTEGRATION: CWS adc18 (1.9.2); FILE MERGED 2007/10/18 15:23:18 np 1.9.2.1: #i81775#<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: pe_param.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: hr $ $Date: 2007-11-02 16:56:30 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <precomp.h>
#include "pe_param.hxx"
// NOT FULLY DEFINED SERVICES
#include <cosv/tpl/tpltools.hxx>
#include <ary/cpp/c_gate.hxx>
#include <ary/cpp/cp_type.hxx>
#include "pe_type.hxx"
#include "pe_vari.hxx"
namespace cpp {
//*********************** PE_Parameter ***********************//
PE_Parameter::PE_Parameter( Cpp_PE * i_pParent )
: Cpp_PE(i_pParent),
pStati( new PeStatusArray<PE_Parameter> )
// pSpType,
// pSpuType,
// pSpVariable,
// pSpuVariable,
// aResultParamInfo
{
Setup_StatusFunctions();
pSpType = new SP_Type(*this);
pSpuType = new SPU_Type(*pSpType, &PE_Parameter::SpInit_Type, &PE_Parameter::SpReturn_Type);
pSpVariable = new SP_Variable(*this);
pSpuVariable = new SPU_Variable(*pSpVariable, &PE_Parameter::SpInit_Variable, &PE_Parameter::SpReturn_Variable);
}
PE_Parameter::~PE_Parameter()
{
}
void
PE_Parameter::Call_Handler( const cpp::Token & i_rTok )
{
pStati->Cur().Call_Handler(i_rTok.TypeId(), i_rTok.Text());
}
void
PE_Parameter::Setup_StatusFunctions()
{
typedef CallFunction<PE_Parameter>::F_Tok F_Tok;
static F_Tok stateF_start[] = { &PE_Parameter::On_start_Type,
&PE_Parameter::On_start_Type,
&PE_Parameter::On_start_Type,
&PE_Parameter::On_start_Type,
&PE_Parameter::On_start_Type,
&PE_Parameter::On_start_Type,
&PE_Parameter::On_start_Type,
&PE_Parameter::On_start_Bracket_Right,
&PE_Parameter::On_start_Type,
&PE_Parameter::On_start_Ellipse,
&PE_Parameter::On_start_Type,
&PE_Parameter::On_start_Type,
&PE_Parameter::On_start_Type };
static INT16 stateT_start[] = { Tid_Identifier,
Tid_class,
Tid_struct,
Tid_union,
Tid_enum,
Tid_const,
Tid_volatile,
Tid_Bracket_Right,
Tid_DoubleColon,
Tid_Ellipse,
Tid_typename,
Tid_BuiltInType,
Tid_TypeSpecializer };
static F_Tok stateF_expectName[] = { &PE_Parameter::On_expectName_Identifier,
&PE_Parameter::On_expectName_ArrayBracket_Left,
&PE_Parameter::On_expectName_Bracket_Right,
&PE_Parameter::On_expectName_Comma,
&PE_Parameter::On_afterName_Assign };
static INT16 stateT_expectName[] = { Tid_Identifier,
Tid_ArrayBracket_Left,
Tid_Bracket_Right,
Tid_Comma,
Tid_Assign };
static F_Tok stateF_afterName[] = { &PE_Parameter::On_afterName_ArrayBracket_Left,
&PE_Parameter::On_afterName_Bracket_Right,
&PE_Parameter::On_afterName_Comma,
&PE_Parameter::On_afterName_Assign };
static INT16 stateT_afterName[] = { Tid_ArrayBracket_Left,
Tid_Bracket_Right,
Tid_Comma,
Tid_Assign };
static F_Tok stateF_finished[] = { &PE_Parameter::On_finished_Comma,
&PE_Parameter::On_finished_Bracket_Right };
static INT16 stateT_finished[] = { Tid_Bracket_Right,
Tid_Comma };
SEMPARSE_CREATE_STATUS(PE_Parameter, start, Hdl_SyntaxError);
SEMPARSE_CREATE_STATUS(PE_Parameter, expectName, Hdl_SyntaxError);
SEMPARSE_CREATE_STATUS(PE_Parameter, afterName, Hdl_SyntaxError);
SEMPARSE_CREATE_STATUS(PE_Parameter, finished, Hdl_SyntaxError);
}
void
PE_Parameter::InitData()
{
pStati->SetCur(start);
aResultParamInfo.Empty();
}
void
PE_Parameter::TransferData()
{
pStati->SetCur(size_of_states);
}
void
PE_Parameter::Hdl_SyntaxError( const char * i_sText)
{
StdHandlingOfSyntaxError(i_sText);
}
void
PE_Parameter::SpInit_Type()
{
// Does nothing.
}
void
PE_Parameter::SpInit_Variable()
{
// Does nothing.
}
void
PE_Parameter::SpReturn_Type()
{
aResultParamInfo.nType = pSpuType->Child().Result_Type().Id();
pStati->SetCur(expectName);
}
void
PE_Parameter::SpReturn_Variable()
{
if (pSpuVariable->Child().Result_Pattern() > 0)
{
aResultParamInfo.sSizeExpression = pSpuVariable->Child().Result_SizeExpression();
aResultParamInfo.sInitExpression = pSpuVariable->Child().Result_InitExpression();
}
}
void
PE_Parameter::On_start_Type(const char *)
{
pSpuType->Push(not_done);
}
void
PE_Parameter::On_start_Bracket_Right(const char *)
{
SetTokenResult(not_done, pop_success);
}
void
PE_Parameter::On_start_Ellipse(const char *)
{
SetTokenResult(done, pop_success);
aResultParamInfo.nType = Env().AryGate().Types().Tid_Ellipse();
}
void
PE_Parameter::On_expectName_Identifier(const char * i_sText)
{
SetTokenResult(done, stay);
pStati->SetCur(afterName);
aResultParamInfo.sName = i_sText;
}
void
PE_Parameter::On_expectName_ArrayBracket_Left(const char * i_sText)
{
On_afterName_ArrayBracket_Left(i_sText);
}
void
PE_Parameter::On_expectName_Bracket_Right(const char * i_sText)
{
On_afterName_Bracket_Right(i_sText);
}
void
PE_Parameter::On_expectName_Comma(const char * i_sText)
{
On_afterName_Comma(i_sText);
}
void
PE_Parameter::On_expectName_Assign(const char * i_sText)
{
On_afterName_Assign(i_sText);
}
void
PE_Parameter::On_afterName_ArrayBracket_Left(const char *)
{
pSpuVariable->Push(not_done);
}
void
PE_Parameter::On_afterName_Bracket_Right(const char *)
{
SetTokenResult(not_done, pop_success);
}
void
PE_Parameter::On_afterName_Comma(const char *)
{
SetTokenResult(not_done, pop_success);
}
void
PE_Parameter::On_afterName_Assign(const char *)
{
pSpuVariable->Push(not_done);
}
void
PE_Parameter::On_finished_Bracket_Right(const char *)
{
SetTokenResult(not_done, pop_success);
}
void
PE_Parameter::On_finished_Comma(const char *)
{
SetTokenResult(not_done, pop_success);
}
} // namespace cpp
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: cmdstrm.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-07 19:30:21 $
*
* 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 _CMDSTRM_HXX
#define _CMDSTRM_HXX
#include <objtest.hxx>
#include <testapp.hxx>
#include "cmdbasestream.hxx"
class CmdStream : public CmdBaseStream
{
public:
CmdStream();
~CmdStream();
void WriteSortedParams( SbxArray* rPar, BOOL IsKeyString = FALSE );
void GenCmdCommand( USHORT nNr, SbxArray* rPar );
void GenCmdSlot( USHORT nNr, SbxArray* rPar );
void GenCmdUNOSlot( const String &aURL );
void GenCmdControl( ULONG nUId, USHORT nMethodId, SbxArray* rPar );
void GenCmdControl( String aUId, USHORT nMethodId, SbxArray* rPar );
/* void GenCmdControl (ULONG nUId, USHORT nMethodId = 0);
void GenCmdControl (ULONG nUId, USHORT nMethodId, String aString);
void GenCmdControl (ULONG nUId, USHORT nMethodId, String aString, USHORT nNr);
void GenCmdControl (ULONG nUId, USHORT nMethodId, String aString, BOOL bBool);
void GenCmdControl (ULONG nUId, USHORT nMethodId, USHORT nNr);
void GenCmdControl (ULONG nUId, USHORT nMethodId, USHORT nNr1, USHORT nNr2);
void GenCmdControl (ULONG nUId, USHORT nMethodId, USHORT nNr, BOOL bBool);
void GenCmdControl (ULONG nUId, USHORT nMethodId, ULONG nNr);
void GenCmdControl (ULONG nUId, USHORT nMethodId, BOOL bBool);*/
void GenCmdFlow( USHORT nArt );
void GenCmdFlow( USHORT nArt, USHORT nNr1 );
void GenCmdFlow( USHORT nArt, ULONG nNr1 );
void GenCmdFlow( USHORT nArt, String aString1 );
void Reset(ULONG nSequence);
SvMemoryStream* GetStream();
static CNames *pKeyCodes; // Namen der Sondertasten MOD1, F1, LEFT ...
static ControlDefLoad __READONLY_DATA arKeyCodes [];
private:
String WandleKeyEventString( String aKeys ); // Nutzt pKeyCodes. <RETURN> <SHIFT LEFT LEFT>
// CmdBaseStream::Write;
void Write( comm_USHORT nNr ){CmdBaseStream::Write( nNr );}
void Write( comm_ULONG nNr ){CmdBaseStream::Write( nNr );}
void Write( const comm_UniChar* aString, comm_USHORT nLenInChars ){CmdBaseStream::Write( aString, nLenInChars );}
void Write( comm_BOOL bBool ){CmdBaseStream::Write( bBool );}
// new
void Write( String aString, BOOL IsKeyString = FALSE );
SvMemoryStream *pSammel;
};
#endif
<commit_msg>INTEGRATION: CWS sixtyfour05 (1.2.30); FILE MERGED 2006/04/13 10:31:54 cmc 1.2.30.1: #i63183# automation 64bit fixes<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: cmdstrm.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hr $ $Date: 2006-04-19 13:59:47 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _CMDSTRM_HXX
#define _CMDSTRM_HXX
#include <objtest.hxx>
#include <testapp.hxx>
#include "cmdbasestream.hxx"
class CmdStream : public CmdBaseStream
{
public:
CmdStream();
~CmdStream();
void WriteSortedParams( SbxArray* rPar, BOOL IsKeyString = FALSE );
void GenCmdCommand( USHORT nNr, SbxArray* rPar );
void GenCmdSlot( USHORT nNr, SbxArray* rPar );
void GenCmdUNOSlot( const String &aURL );
void GenCmdControl( comm_ULONG nUId, USHORT nMethodId, SbxArray* rPar );
void GenCmdControl( String aUId, USHORT nMethodId, SbxArray* rPar );
void GenCmdFlow( USHORT nArt );
void GenCmdFlow( USHORT nArt, USHORT nNr1 );
void GenCmdFlow( USHORT nArt, comm_ULONG nNr1 );
void GenCmdFlow( USHORT nArt, String aString1 );
void Reset(comm_ULONG nSequence);
SvMemoryStream* GetStream();
static CNames *pKeyCodes; // Namen der Sondertasten MOD1, F1, LEFT ...
static ControlDefLoad __READONLY_DATA arKeyCodes [];
private:
String WandleKeyEventString( String aKeys ); // Nutzt pKeyCodes. <RETURN> <SHIFT LEFT LEFT>
// CmdBaseStream::Write;
void Write( comm_USHORT nNr ){CmdBaseStream::Write( nNr );}
void Write( comm_ULONG nNr ){CmdBaseStream::Write( nNr );}
void Write( const comm_UniChar* aString, comm_USHORT nLenInChars ){CmdBaseStream::Write( aString, nLenInChars );}
void Write( comm_BOOL bBool ){CmdBaseStream::Write( bBool );}
// new
void Write( String aString, BOOL IsKeyString = FALSE );
SvMemoryStream *pSammel;
};
#endif
<|endoftext|> |
<commit_before><commit_msg>Windows compatibility<commit_after><|endoftext|> |
<commit_before>
#include "Internal.hpp"
#include "ALAudioDevice.hpp"
#include "AudioNode.hpp"
#include "AudioDecoder.hpp" // TODO: test
#include <Lumino/Engine/Diagnostics.hpp> // TODO: test
namespace ln {
namespace detail {
WaveDecoder wd;// TODO: test
std::vector<float> tmpBuffer;
//==============================================================================
// ALAudioDevice
ALAudioDevice::ALAudioDevice()
{
}
void ALAudioDevice::initialize()
{
m_alDevice = alcOpenDevice(nullptr);
m_alContext = alcCreateContext(m_alDevice, nullptr);
alcMakeContextCurrent(m_alContext);
alGenSources(1, &m_masterSource);
m_freeBuffers.resize(2);
alGenBuffers(2, m_freeBuffers.data());
m_masterSampleRate = 44100; // TODO
m_masterChannels = 2;
//m_finalRenderdBuffer.resize(AudioNode::ProcessingSizeInFrames * m_masterChannels);
m_finalRenderdBuffer.resize(m_masterSampleRate * m_masterChannels);
// TODO: test
auto diag = newObject<DiagnosticsManager>();
wd.initialize(FileStream::create(u"D:\\tmp\\8_MapBGM2.wav"), diag);
tmpBuffer.resize(AudioNode::ProcessingSizeInFrames * m_masterChannels);
}
void ALAudioDevice::dispose()
{
if (m_alContext)
{
alcMakeContextCurrent(nullptr);
alcDestroyContext(m_alContext);
m_alContext = nullptr;
}
if (m_alDevice)
{
alcCloseDevice(m_alDevice);
m_alDevice = nullptr;
}
}
void ALAudioDevice::updateProcess()
{
// remove the buffer that finished processing
ALint processedCount;
alGetSourcei(m_masterSource, AL_BUFFERS_PROCESSED, &processedCount);
while (processedCount > 0)
{
ALuint buffer;
alSourceUnqueueBuffers(m_masterSource, 1, &buffer);
m_freeBuffers.push_back(buffer);
--processedCount;
printf("processed\n");
}
// render data and set buffer to source
if (m_freeBuffers.size() > 0)
{
// TODO: test
wd.read((float*)m_finalRenderdBuffer.data(), m_masterSampleRate);
//wd.read(tmpBuffer.data(), tmpBuffer.size());
//AudioDecoder::convertFromFloat32(m_finalRenderdBuffer.data(), tmpBuffer.data(), m_finalRenderdBuffer.size(), PCMFormat::S16L);
alBufferData(m_freeBuffers.back(), AL_FORMAT_STEREO16, m_finalRenderdBuffer.data(), m_finalRenderdBuffer.size(), m_masterSampleRate);
alSourceQueueBuffers(m_masterSource, 1, &m_freeBuffers.back());
m_freeBuffers.pop_back();
// play if needed
ALint state;
alGetSourcei(m_masterSource, AL_SOURCE_STATE, &state);
if (state != AL_PLAYING)
{
alSourcePlay(m_masterSource);
}
printf("queue\n");
}
}
} // namespace detail
} // namespace ln
<commit_msg>buffer resize<commit_after>
#include "Internal.hpp"
#include "ALAudioDevice.hpp"
#include "AudioNode.hpp"
#include "AudioDecoder.hpp" // TODO: test
#include <Lumino/Engine/Diagnostics.hpp> // TODO: test
namespace ln {
namespace detail {
WaveDecoder wd;// TODO: test
std::vector<float> tmpBuffer;
//==============================================================================
// ALAudioDevice
ALAudioDevice::ALAudioDevice()
{
}
void ALAudioDevice::initialize()
{
m_alDevice = alcOpenDevice(nullptr);
m_alContext = alcCreateContext(m_alDevice, nullptr);
alcMakeContextCurrent(m_alContext);
alGenSources(1, &m_masterSource);
m_freeBuffers.resize(2);
alGenBuffers(2, m_freeBuffers.data());
m_masterSampleRate = 44100; // TODO
m_masterChannels = 2;
m_finalRenderdBuffer.resize(AudioNode::ProcessingSizeInFrames * m_masterChannels);
//m_finalRenderdBuffer.resize(m_masterSampleRate * m_masterChannels);
// TODO: test
auto diag = newObject<DiagnosticsManager>();
wd.initialize(FileStream::create(u"D:\\tmp\\8_MapBGM2.wav"), diag);
tmpBuffer.resize(AudioNode::ProcessingSizeInFrames * m_masterChannels);
}
void ALAudioDevice::dispose()
{
if (m_alContext)
{
alcMakeContextCurrent(nullptr);
alcDestroyContext(m_alContext);
m_alContext = nullptr;
}
if (m_alDevice)
{
alcCloseDevice(m_alDevice);
m_alDevice = nullptr;
}
}
void ALAudioDevice::updateProcess()
{
// remove the buffer that finished processing
ALint processedCount;
alGetSourcei(m_masterSource, AL_BUFFERS_PROCESSED, &processedCount);
while (processedCount > 0)
{
ALuint buffer;
alSourceUnqueueBuffers(m_masterSource, 1, &buffer);
m_freeBuffers.push_back(buffer);
--processedCount;
printf("processed\n");
}
// render data and set buffer to source
if (m_freeBuffers.size() > 0)
{
// TODO: test
//wd.read((float*)m_finalRenderdBuffer.data(), m_masterSampleRate/* * m_masterChannels*/);
wd.read((float*)m_finalRenderdBuffer.data(), m_finalRenderdBuffer.size());
//wd.read(tmpBuffer.data(), tmpBuffer.size());
//AudioDecoder::convertFromFloat32(m_finalRenderdBuffer.data(), tmpBuffer.data(), m_finalRenderdBuffer.size(), PCMFormat::S16L);
alBufferData(m_freeBuffers.back(), AL_FORMAT_STEREO16, m_finalRenderdBuffer.data(), sizeof(int16_t) * m_finalRenderdBuffer.size(), m_masterSampleRate);
alSourceQueueBuffers(m_masterSource, 1, &m_freeBuffers.back());
m_freeBuffers.pop_back();
// play if needed
ALint state;
alGetSourcei(m_masterSource, AL_SOURCE_STATE, &state);
if (state != AL_PLAYING)
{
alSourcePlay(m_masterSource);
}
printf("queue\n");
}
}
} // namespace detail
} // namespace ln
<|endoftext|> |
<commit_before>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.
Bohrium is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.
Bohrium is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the
GNU Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <cassert>
#include <numeric>
#include <set>
#include <map>
#include <chrono>
#include <bh_component.hpp>
#include <bh_extmethod.hpp>
#include <bh_util.hpp>
#include <bh_opcode.h>
#include <jitk/statistics.hpp>
#include <jitk/kernel.hpp>
#include <jitk/block.hpp>
#include <jitk/instruction.hpp>
#include <jitk/fuser.hpp>
#include <jitk/graph.hpp>
#include <jitk/transformer.hpp>
#include <jitk/fuser_cache.hpp>
#include <jitk/codegen_util.hpp>
#include <jitk/dtype.hpp>
#include <jitk/apply_fusion.hpp>
#include "engine_cuda.hpp"
using namespace bohrium;
using namespace jitk;
using namespace component;
using namespace std;
namespace {
class Impl : public ComponentImplWithChild {
private:
// Some statistics
Statistics stat;
// Fuse cache
FuseCache fcache;
// Known extension methods
map<bh_opcode, extmethod::ExtmethodFace> extmethods;
set<bh_opcode> child_extmethods;
// The OpenCL engine
EngineCUDA engine;
public:
Impl(int stack_level) : ComponentImplWithChild(stack_level), stat(config.defaultGet("prof", false)),
fcache(stat), engine(config, stat) {}
~Impl();
void execute(bh_ir *bhir);
void extmethod(const string &name, bh_opcode opcode) {
// ExtmethodFace does not have a default or copy constructor thus
// we have to use its move constructor.
try {
extmethods.insert(make_pair(opcode, extmethod::ExtmethodFace(config, name)));
} catch(extmethod::ExtmethodNotFound e) {
// I don't know this function, lets try my child
child.extmethod(name, opcode);
child_extmethods.insert(opcode);
}
}
// Write an OpenCL kernel
void write_kernel(const Kernel &kernel, const SymbolTable &symbols, const ConfigParser &config,
const vector<const LoopB *> &threaded_blocks,
const vector<const bh_view*> &offset_strides, stringstream &ss);
// Implement the handle of extension methods
void handle_extmethod(bh_ir *bhir) {
util_handle_extmethod(this, bhir, extmethods, child_extmethods, child, &engine);
}
// Returns the blocks that can be parallelized in 'kernel' (incl. sub-blocks)
vector<const LoopB*> find_threaded_blocks(Kernel &kernel) {
vector<const LoopB*> threaded_blocks;
uint64_t total_threading;
tie(threaded_blocks, total_threading) = util_find_threaded_blocks(kernel.block);
if (total_threading < config.defaultGet<uint64_t>("parallel_threshold", 1000)) {
for (const InstrPtr instr: kernel.getAllInstr()) {
if (not bh_opcode_is_system(instr->opcode)) {
stat.threading_below_threshold += bh_nelements(instr->operand[0]);
}
}
}
return threaded_blocks;
}
};
}
extern "C" ComponentImpl* create(int stack_level) {
return new Impl(stack_level);
}
extern "C" void destroy(ComponentImpl* self) {
delete self;
}
Impl::~Impl() {
if (config.defaultGet<bool>("prof", false)) {
stat.pprint("OpenCL", cout);
}
}
// Writes the OpenCL specific for-loop header
void loop_head_writer(const SymbolTable &symbols, Scope &scope, const LoopB &block, const ConfigParser &config,
bool loop_is_peeled, const vector<const LoopB *> &threaded_blocks, stringstream &out) {
// Write the for-loop header
string itername;
{stringstream t; t << "i" << block.rank; itername = t.str();}
// Notice that we use find_if() with a lambda function since 'threaded_blocks' contains pointers not objects
if (std::find_if(threaded_blocks.begin(), threaded_blocks.end(),
[&block](const LoopB* b){return *b == block;}) == threaded_blocks.end()) {
out << "for(" << write_opencl_type(BH_UINT64) << " " << itername;
if (block._sweeps.size() > 0 and loop_is_peeled) // If the for-loop has been peeled, we should start at 1
out << "=1; ";
else
out << "=0; ";
out << itername << " < " << block.size << "; ++" << itername << ") {\n";
} else {
assert(block._sweeps.size() == 0);
out << "{ // Threaded block (ID " << itername << ")\n";
}
}
const char *write_thread_id(unsigned int dim) {
switch (dim) {
case 0:
return "blockIdx.x*blockDim.x+threadIdx.x";
case 1:
return "blockIdx.x*blockDim.x+threadIdx.x";
case 2:
return "blockIdx.x*blockDim.x+threadIdx.x";
default:
throw runtime_error("CUDA only support 3 dimensions");
}
}
void Impl::write_kernel(const Kernel &kernel, const SymbolTable &symbols, const ConfigParser &config,
const vector<const LoopB *> &threaded_blocks,
const vector<const bh_view*> &offset_strides, stringstream &ss) {
// Write the need includes
ss << "#include <kernel_dependencies/complex_cuda.h>\n";
ss << "#include <kernel_dependencies/integer_operations.h>\n";
if (kernel.useRandom()) { // Write the random function
ss << "#include <kernel_dependencies/random123_cuda.h>\n";
}
ss << "\n";
// Write the header of the execute function
ss << "extern \"C\" __global__ void execute";
write_kernel_function_arguments(kernel, symbols, offset_strides, write_cuda_type, ss, NULL, false);
ss << "{\n";
// Write the IDs of the threaded blocks
if (threaded_blocks.size() > 0) {
spaces(ss, 4);
ss << "// The IDs of the threaded blocks: \n";
for (unsigned int i=0; i < threaded_blocks.size(); ++i) {
const LoopB *b = threaded_blocks[i];
spaces(ss, 4);
ss << "const size_t i" << b->rank << " = " << write_thread_id(i) << "; " \
<< "if (i" << b->rank << " >= " << b->size << ") {return;} // Prevent overflow\n";
}
ss << "\n";
}
// Write the block that makes up the body of 'execute()'
write_loop_block(symbols, NULL, kernel.block, config, threaded_blocks, true, write_opencl_type, loop_head_writer, ss);
ss << "}\n\n";
}
void Impl::execute(bh_ir *bhir) {
// Let's handle extension methods
util_handle_extmethod(this, bhir, extmethods, child_extmethods, child, &engine);
// And then the regular instructions
handle_execution(*this, bhir, engine, config, stat, fcache, &child);
}
<commit_msg>CUDA is CUDA<commit_after>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.
Bohrium is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.
Bohrium is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the
GNU Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <cassert>
#include <numeric>
#include <set>
#include <map>
#include <chrono>
#include <bh_component.hpp>
#include <bh_extmethod.hpp>
#include <bh_util.hpp>
#include <bh_opcode.h>
#include <jitk/statistics.hpp>
#include <jitk/kernel.hpp>
#include <jitk/block.hpp>
#include <jitk/instruction.hpp>
#include <jitk/fuser.hpp>
#include <jitk/graph.hpp>
#include <jitk/transformer.hpp>
#include <jitk/fuser_cache.hpp>
#include <jitk/codegen_util.hpp>
#include <jitk/dtype.hpp>
#include <jitk/apply_fusion.hpp>
#include "engine_cuda.hpp"
using namespace bohrium;
using namespace jitk;
using namespace component;
using namespace std;
namespace {
class Impl : public ComponentImplWithChild {
private:
// Some statistics
Statistics stat;
// Fuse cache
FuseCache fcache;
// Known extension methods
map<bh_opcode, extmethod::ExtmethodFace> extmethods;
set<bh_opcode> child_extmethods;
// The OpenCL engine
EngineCUDA engine;
public:
Impl(int stack_level) : ComponentImplWithChild(stack_level), stat(config.defaultGet("prof", false)),
fcache(stat), engine(config, stat) {}
~Impl();
void execute(bh_ir *bhir);
void extmethod(const string &name, bh_opcode opcode) {
// ExtmethodFace does not have a default or copy constructor thus
// we have to use its move constructor.
try {
extmethods.insert(make_pair(opcode, extmethod::ExtmethodFace(config, name)));
} catch(extmethod::ExtmethodNotFound e) {
// I don't know this function, lets try my child
child.extmethod(name, opcode);
child_extmethods.insert(opcode);
}
}
// Write an OpenCL kernel
void write_kernel(const Kernel &kernel, const SymbolTable &symbols, const ConfigParser &config,
const vector<const LoopB *> &threaded_blocks,
const vector<const bh_view*> &offset_strides, stringstream &ss);
// Implement the handle of extension methods
void handle_extmethod(bh_ir *bhir) {
util_handle_extmethod(this, bhir, extmethods, child_extmethods, child, &engine);
}
// Returns the blocks that can be parallelized in 'kernel' (incl. sub-blocks)
vector<const LoopB*> find_threaded_blocks(Kernel &kernel) {
vector<const LoopB*> threaded_blocks;
uint64_t total_threading;
tie(threaded_blocks, total_threading) = util_find_threaded_blocks(kernel.block);
if (total_threading < config.defaultGet<uint64_t>("parallel_threshold", 1000)) {
for (const InstrPtr instr: kernel.getAllInstr()) {
if (not bh_opcode_is_system(instr->opcode)) {
stat.threading_below_threshold += bh_nelements(instr->operand[0]);
}
}
}
return threaded_blocks;
}
};
}
extern "C" ComponentImpl* create(int stack_level) {
return new Impl(stack_level);
}
extern "C" void destroy(ComponentImpl* self) {
delete self;
}
Impl::~Impl() {
if (config.defaultGet<bool>("prof", false)) {
stat.pprint("CUDA", cout);
}
}
// Writes the OpenCL specific for-loop header
void loop_head_writer(const SymbolTable &symbols, Scope &scope, const LoopB &block, const ConfigParser &config,
bool loop_is_peeled, const vector<const LoopB *> &threaded_blocks, stringstream &out) {
// Write the for-loop header
string itername;
{stringstream t; t << "i" << block.rank; itername = t.str();}
// Notice that we use find_if() with a lambda function since 'threaded_blocks' contains pointers not objects
if (std::find_if(threaded_blocks.begin(), threaded_blocks.end(),
[&block](const LoopB* b){return *b == block;}) == threaded_blocks.end()) {
out << "for(" << write_opencl_type(BH_UINT64) << " " << itername;
if (block._sweeps.size() > 0 and loop_is_peeled) // If the for-loop has been peeled, we should start at 1
out << "=1; ";
else
out << "=0; ";
out << itername << " < " << block.size << "; ++" << itername << ") {\n";
} else {
assert(block._sweeps.size() == 0);
out << "{ // Threaded block (ID " << itername << ")\n";
}
}
const char *write_thread_id(unsigned int dim) {
switch (dim) {
case 0:
return "blockIdx.x*blockDim.x+threadIdx.x";
case 1:
return "blockIdx.x*blockDim.x+threadIdx.x";
case 2:
return "blockIdx.x*blockDim.x+threadIdx.x";
default:
throw runtime_error("CUDA only support 3 dimensions");
}
}
void Impl::write_kernel(const Kernel &kernel, const SymbolTable &symbols, const ConfigParser &config,
const vector<const LoopB *> &threaded_blocks,
const vector<const bh_view*> &offset_strides, stringstream &ss) {
// Write the need includes
ss << "#include <kernel_dependencies/complex_cuda.h>\n";
ss << "#include <kernel_dependencies/integer_operations.h>\n";
if (kernel.useRandom()) { // Write the random function
ss << "#include <kernel_dependencies/random123_cuda.h>\n";
}
ss << "\n";
// Write the header of the execute function
ss << "extern \"C\" __global__ void execute";
write_kernel_function_arguments(kernel, symbols, offset_strides, write_cuda_type, ss, NULL, false);
ss << "{\n";
// Write the IDs of the threaded blocks
if (threaded_blocks.size() > 0) {
spaces(ss, 4);
ss << "// The IDs of the threaded blocks: \n";
for (unsigned int i=0; i < threaded_blocks.size(); ++i) {
const LoopB *b = threaded_blocks[i];
spaces(ss, 4);
ss << "const size_t i" << b->rank << " = " << write_thread_id(i) << "; " \
<< "if (i" << b->rank << " >= " << b->size << ") {return;} // Prevent overflow\n";
}
ss << "\n";
}
// Write the block that makes up the body of 'execute()'
write_loop_block(symbols, NULL, kernel.block, config, threaded_blocks, true, write_opencl_type, loop_head_writer, ss);
ss << "}\n\n";
}
void Impl::execute(bh_ir *bhir) {
// Let's handle extension methods
util_handle_extmethod(this, bhir, extmethods, child_extmethods, child, &engine);
// And then the regular instructions
handle_execution(*this, bhir, engine, config, stat, fcache, &child);
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2015 - present Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, 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 "CUDA2HIP.h"
// Maps CUDA header names to HIP header names
const std::map<llvm::StringRef, hipCounter> CUDA_DEVICE_FUNC_MAP{
// math functions
{"umin", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"llmin", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"ullmin", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"umax", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"llmax", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"ullmax", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__isinff", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__isnanf", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__finite", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__finitef", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__signbit", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__isnan", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__isinf", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__signbitf", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__signbitl", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__finitel", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__isinfl", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__isnanl", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"_ldsign", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"_fdsign", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"_Pow_int", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
// static math functions declared in device-functions.h
{"mulhi", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"mul64hi", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"float_as_int", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"int_as_float", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"float_as_uint", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"uint_as_float", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"saturate", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"mul24", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"umul24", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"float2int", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"int2float", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"uint2float", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
// device functions
{"__prof_trigger", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__trap", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__brkpt", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__pm0", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__pm1", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__pm2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__pm3", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
// SIMD functions
{"__vabs2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vabsss2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vadd2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vaddss2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vaddss2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vaddus2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vavgs2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vavgu2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vhaddu2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vcmpeq2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vcmpges2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vcmpgeu2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vcmpgts2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vcmpgtu2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vcmples2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vcmplts2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vcmpltu2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vcmpne2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vabsdiffu2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vmaxs2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vmaxu2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vmins2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vminu2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vseteq2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsetges2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsetgeu2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsetgts2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsetles2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsetleu2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsetlts2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsetltu2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsetne2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsadu2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsub2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsubss2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsubus2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vneg2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vnegss2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vabsdiffs2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsads2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vabs4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vabsss4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vadd4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vaddss4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vaddus4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vavgs4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vavgu4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vhaddu4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vcmpeq4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vcmpges4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vcmpgeu4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vcmpgts4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vcmpgtu4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vcmples4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vcmpleu4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vcmplts4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vcmpltu4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vcmpne4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vabsdiffu4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vmaxs4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vmaxu4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vmins4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vminu4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vseteq4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsetles4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsetleu4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsetlts4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsetltu4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsetges4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsetgeu4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsetgts4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsetgtu4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsetne4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsadu4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsub4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsubss4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsubus4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vneg4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vnegss4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vabsdiffs4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsads4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
};
<commit_msg>[HIPIFY] Add unsupported fp16 functions<commit_after>/*
Copyright (c) 2015 - present Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, 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 "CUDA2HIP.h"
// Maps CUDA header names to HIP header names
const std::map<llvm::StringRef, hipCounter> CUDA_DEVICE_FUNC_MAP{
// math functions
{"umin", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"llmin", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"ullmin", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"umax", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"llmax", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"ullmax", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__isinff", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__isnanf", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__finite", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__finitef", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__signbit", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__isnan", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__isinf", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__signbitf", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__signbitl", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__finitel", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__isinfl", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__isnanl", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"_ldsign", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"_fdsign", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"_Pow_int", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
// static math functions declared in device-functions.h
{"mulhi", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"mul64hi", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"float_as_int", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"int_as_float", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"float_as_uint", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"uint_as_float", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"saturate", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"mul24", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"umul24", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"float2int", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"int2float", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"uint2float", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
// device functions
{"__prof_trigger", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__trap", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__brkpt", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__pm0", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__pm1", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__pm2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__pm3", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
// SIMD functions
{"__vabs2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vabsss2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vadd2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vaddss2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vaddss2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vaddus2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vavgs2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vavgu2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vhaddu2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vcmpeq2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vcmpges2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vcmpgeu2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vcmpgts2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vcmpgtu2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vcmples2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vcmplts2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vcmpltu2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vcmpne2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vabsdiffu2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vmaxs2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vmaxu2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vmins2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vminu2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vseteq2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsetges2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsetgeu2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsetgts2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsetles2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsetleu2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsetlts2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsetltu2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsetne2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsadu2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsub2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsubss2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsubus2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vneg2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vnegss2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vabsdiffs2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsads2", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vabs4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vabsss4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vadd4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vaddss4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vaddus4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vavgs4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vavgu4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vhaddu4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vcmpeq4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vcmpges4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vcmpgeu4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vcmpgts4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vcmpgtu4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vcmples4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vcmpleu4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vcmplts4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vcmpltu4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vcmpne4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vabsdiffu4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vmaxs4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vmaxu4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vmins4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vminu4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vseteq4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsetles4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsetleu4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsetlts4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsetltu4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsetges4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsetgeu4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsetgts4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsetgtu4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsetne4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsadu4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsub4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsubss4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsubus4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vneg4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vnegss4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vabsdiffs4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__vsads4", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
// fp16 functions
{"__shfl_sync", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__shfl_up_sync", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__shfl_down_sync",{"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__shfl_xor_sync", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__shfl_sync", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__shfl_up_sync", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__shfl_down_sync",{"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__shfl_xor_sync", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
{"__shfl_xor_sync", {"", "", CONV_DEVICE_FUNC, API_RUNTIME, UNSUPPORTED}},
};
<|endoftext|> |
<commit_before>// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef __STOUT_OS_WINDOWS_ENVIRONMENT_HPP__
#define __STOUT_OS_WINDOWS_ENVIRONMENT_HPP__
#include <map>
#include <string>
#include <stout/stringify.hpp>
namespace os {
inline std::map<std::string, std::string> environment()
{
// NOTE: The `GetEnvironmentStrings` call returns a pointer to a
// read-only block of memory with the following format (minus newlines):
// Var1=Value1\0
// Var2=Value2\0
// Var3=Value3\0
// ...
// VarN=ValueN\0\0
wchar_t* env = ::GetEnvironmentStringsW();
std::map<std::string, std::string> result;
for (size_t i = 0; env[i] != L'\0' && env[i+1] != L'\0';) {
std::wstring entry(env + i);
// Increment past the current environment string and null terminator.
i = i + entry.size() + 1;
size_t position = entry.find_first_of(L'=');
if (position == std::string::npos) {
continue; // Skip malformed environment entries.
}
result[stringify(entry.substr(0, position))] =
stringify(entry.substr(position + 1));
}
return result;
}
} // namespace os {
#endif // __STOUT_OS_WINDOWS_ENVIRONMENT_HPP__
<commit_msg>Windows: Fixed memory leak.<commit_after>// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef __STOUT_OS_WINDOWS_ENVIRONMENT_HPP__
#define __STOUT_OS_WINDOWS_ENVIRONMENT_HPP__
#include <map>
#include <memory>
#include <string>
#include <stout/stringify.hpp>
namespace os {
inline std::map<std::string, std::string> environment()
{
// NOTE: The `GetEnvironmentStrings` call returns a pointer to a
// read-only block of memory with the following format (minus newlines):
// Var1=Value1\0
// Var2=Value2\0
// Var3=Value3\0
// ...
// VarN=ValueN\0\0
const std::unique_ptr<wchar_t[], decltype(&::FreeEnvironmentStringsW)> env(
::GetEnvironmentStringsW(), &::FreeEnvironmentStringsW);
std::map<std::string, std::string> result;
for (size_t i = 0; env[i] != L'\0' && env[i+1] != L'\0';
/* incremented below */) {
std::wstring entry(&env[i]);
// Increment past the current environment string and null terminator.
i = i + entry.size() + 1;
size_t position = entry.find_first_of(L'=');
if (position == std::string::npos) {
continue; // Skip malformed environment entries.
}
result[stringify(entry.substr(0, position))] =
stringify(entry.substr(position + 1));
}
return result;
}
} // namespace os {
#endif // __STOUT_OS_WINDOWS_ENVIRONMENT_HPP__
<|endoftext|> |
<commit_before>#include "ATKUniversalVariableDelay.h"
#include "IPlug_include_in_plug_src.h"
#include "IControl.h"
#include "resource.h"
const int kNumPrograms = 1;
enum EParams
{
kDelay = 0,
kDepth,
kMod,
kBlend,
kFeedforward,
kFeedback,
kNumParams
};
enum ELayout
{
kWidth = GUI_WIDTH,
kHeight = GUI_HEIGHT,
kDelayX = 25,
kDelayY = 32,
kDepthX = 94,
kDepthY = 32,
kModX = 163,
kModY = 32,
kBlendX = 232,
kBlendY = 32,
kFeedforwardX = 301,
kFeedforwardY = 32,
kFeedbackX = 370,
kFeedbackY = 32,
kKnobFrames = 43
};
ATKUniversalVariableDelay::ATKUniversalVariableDelay(IPlugInstanceInfo instanceInfo)
: IPLUG_CTOR(kNumParams, kNumPrograms, instanceInfo), inFilter(nullptr, 1, 0, false), outFilter(nullptr, 1, 0, false), delayFilter(1000)
{
TRACE;
//arguments are: name, defaultVal, minVal, maxVal, step, label
GetParam(kDelay)->InitDouble("Delay", 0.2, 0.2, 3.0, 0.1, "ms");
GetParam(kDelay)->SetShape(2.);
GetParam(kDepth)->InitDouble("Depth", 0.1, 0.1, 3.0, 0.1, "ms");
GetParam(kDepth)->SetShape(2.);
GetParam(kMod)->InitDouble("Modulation", 1, 0.1, 5.0, 0.1, "Hz");
GetParam(kMod)->SetShape(1.);
GetParam(kBlend)->InitDouble("Blend", 100, -100, 100, 0.01, "%");
GetParam(kBlend)->SetShape(1.);
GetParam(kFeedforward)->InitDouble("Feedforward", 50., -100, 100, 0.01, "%");
GetParam(kFeedforward)->SetShape(1.);
GetParam(kFeedback)->InitDouble("Feedback", 0., -90., 90., 0.01, "%");
GetParam(kFeedback)->SetShape(1.);
IGraphics* pGraphics = MakeGraphics(this, kWidth, kHeight);
pGraphics->AttachBackground(UNIVERSALDELAY_ID, UNIVERSALDELAY_FN);
IBitmap knob = pGraphics->LoadIBitmap(KNOB_ID, KNOB_FN, kKnobFrames);
IBitmap knob1 = pGraphics->LoadIBitmap(KNOB1_ID, KNOB1_FN, kKnobFrames);
pGraphics->AttachControl(new IKnobMultiControl(this, kDelayX, kDelayY, kDelay, &knob));
pGraphics->AttachControl(new IKnobMultiControl(this, kDepthX, kDepthY, kDepth, &knob));
pGraphics->AttachControl(new IKnobMultiControl(this, kModX, kModY, kMod, &knob));
pGraphics->AttachControl(new IKnobMultiControl(this, kBlendX, kBlendY, kBlend, &knob1));
pGraphics->AttachControl(new IKnobMultiControl(this, kFeedforwardX, kFeedforwardY, kFeedforward, &knob1));
pGraphics->AttachControl(new IKnobMultiControl(this, kFeedbackX, kFeedbackY, kFeedback, &knob1));
AttachGraphics(pGraphics);
MakePreset("Vibrato", 2, 1, 2, 0, 1, 0);
MakePreset("Flanger", 2, 1, 2, 0.7, 0.7, 0.7);
delayFilter.set_input_port(0, &inFilter, 0);
delayFilter.set_input_port(1, &sinusGenerator, 0);
outFilter.set_input_port(0, &delayFilter, 0);
Reset();
}
ATKUniversalVariableDelay::~ATKUniversalVariableDelay() {}
void ATKUniversalVariableDelay::ProcessDoubleReplacing(double** inputs, double** outputs, int nFrames)
{
// Mutex is already locked for us.
inFilter.set_pointer(inputs[0], nFrames);
outFilter.set_pointer(outputs[0], nFrames);
outFilter.process(nFrames);
}
void ATKUniversalVariableDelay::Reset()
{
TRACE;
IMutexLock lock(this);
int sampling_rate = GetSampleRate();
if (sampling_rate != outFilter.get_input_sampling_rate())
{
inFilter.set_input_sampling_rate(sampling_rate);
inFilter.set_output_sampling_rate(sampling_rate);
sinusGenerator.set_output_sampling_rate(sampling_rate);
delayFilter.set_input_sampling_rate(sampling_rate);
delayFilter.set_output_sampling_rate(sampling_rate);
outFilter.set_input_sampling_rate(sampling_rate);
outFilter.set_output_sampling_rate(sampling_rate);
}
sinusGenerator.full_setup();
}
void ATKUniversalVariableDelay::OnParamChange(int paramIdx)
{
IMutexLock lock(this);
switch (paramIdx)
{
case kDelay:
if (GetParam(kDepth)->Value() > GetParam(kDelay)->Value() - 0.1)
{
GetParam(kDelay)->Set(GetParam(kDepth)->Value() + 0.1);
}
sinusGenerator.set_offset(GetParam(kDelay)->Value() / 1000. * GetSampleRate());
delayFilter.set_central_delay(GetParam(kDelay)->Value() / 1000. * GetSampleRate());
break;
case kDepth:
if (GetParam(kDepth)->Value() > GetParam(kDelay)->Value() - 0.1)
{
GetParam(kDepth)->Set(GetParam(kDelay)->Value() - 0.1);
}
sinusGenerator.set_volume(GetParam(kDepth)->Value() / 1000. * GetSampleRate());
break;
case kMod:
sinusGenerator.set_frequency(GetParam(kMod)->Value());
break;
case kBlend:
delayFilter.set_blend((GetParam(kBlend)->Value()) / 100.);
break;
case kFeedforward:
delayFilter.set_feedforward((GetParam(kFeedforward)->Value()) / 100.);
break;
case kFeedback:
delayFilter.set_feedback((GetParam(kFeedback)->Value()) / 100.);
break;
default:
break;
}
}
<commit_msg>Flush the delay line and fix the max delay line size for 192kHz.<commit_after>#include "ATKUniversalVariableDelay.h"
#include "IPlug_include_in_plug_src.h"
#include "IControl.h"
#include "resource.h"
const int kNumPrograms = 1;
enum EParams
{
kDelay = 0,
kDepth,
kMod,
kBlend,
kFeedforward,
kFeedback,
kNumParams
};
enum ELayout
{
kWidth = GUI_WIDTH,
kHeight = GUI_HEIGHT,
kDelayX = 25,
kDelayY = 32,
kDepthX = 94,
kDepthY = 32,
kModX = 163,
kModY = 32,
kBlendX = 232,
kBlendY = 32,
kFeedforwardX = 301,
kFeedforwardY = 32,
kFeedbackX = 370,
kFeedbackY = 32,
kKnobFrames = 43
};
ATKUniversalVariableDelay::ATKUniversalVariableDelay(IPlugInstanceInfo instanceInfo)
: IPLUG_CTOR(kNumParams, kNumPrograms, instanceInfo), inFilter(nullptr, 1, 0, false), outFilter(nullptr, 1, 0, false), delayFilter(1152)
{
TRACE;
//arguments are: name, defaultVal, minVal, maxVal, step, label
GetParam(kDelay)->InitDouble("Delay", 0.2, 0.2, 3.0, 0.1, "ms");
GetParam(kDelay)->SetShape(2.);
GetParam(kDepth)->InitDouble("Depth", 0.1, 0.1, 2.9, 0.1, "ms");
GetParam(kDepth)->SetShape(2.);
GetParam(kMod)->InitDouble("Modulation", 1, 0.1, 5.0, 0.1, "Hz");
GetParam(kMod)->SetShape(1.);
GetParam(kBlend)->InitDouble("Blend", 100, -100, 100, 0.01, "%");
GetParam(kBlend)->SetShape(1.);
GetParam(kFeedforward)->InitDouble("Feedforward", 50., -100, 100, 0.01, "%");
GetParam(kFeedforward)->SetShape(1.);
GetParam(kFeedback)->InitDouble("Feedback", 0., -90., 90., 0.01, "%");
GetParam(kFeedback)->SetShape(1.);
IGraphics* pGraphics = MakeGraphics(this, kWidth, kHeight);
pGraphics->AttachBackground(UNIVERSALDELAY_ID, UNIVERSALDELAY_FN);
IBitmap knob = pGraphics->LoadIBitmap(KNOB_ID, KNOB_FN, kKnobFrames);
IBitmap knob1 = pGraphics->LoadIBitmap(KNOB1_ID, KNOB1_FN, kKnobFrames);
pGraphics->AttachControl(new IKnobMultiControl(this, kDelayX, kDelayY, kDelay, &knob));
pGraphics->AttachControl(new IKnobMultiControl(this, kDepthX, kDepthY, kDepth, &knob));
pGraphics->AttachControl(new IKnobMultiControl(this, kModX, kModY, kMod, &knob));
pGraphics->AttachControl(new IKnobMultiControl(this, kBlendX, kBlendY, kBlend, &knob1));
pGraphics->AttachControl(new IKnobMultiControl(this, kFeedforwardX, kFeedforwardY, kFeedforward, &knob1));
pGraphics->AttachControl(new IKnobMultiControl(this, kFeedbackX, kFeedbackY, kFeedback, &knob1));
AttachGraphics(pGraphics);
MakePreset("Vibrato", 2, 1, 2, 0, 1, 0);
MakePreset("Flanger", 2, 1, 2, 0.7, 0.7, 0.7);
delayFilter.set_input_port(0, &inFilter, 0);
delayFilter.set_input_port(1, &sinusGenerator, 0);
outFilter.set_input_port(0, &delayFilter, 0);
Reset();
}
ATKUniversalVariableDelay::~ATKUniversalVariableDelay() {}
void ATKUniversalVariableDelay::ProcessDoubleReplacing(double** inputs, double** outputs, int nFrames)
{
// Mutex is already locked for us.
inFilter.set_pointer(inputs[0], nFrames);
outFilter.set_pointer(outputs[0], nFrames);
outFilter.process(nFrames);
}
void ATKUniversalVariableDelay::Reset()
{
TRACE;
IMutexLock lock(this);
int sampling_rate = GetSampleRate();
if (sampling_rate != outFilter.get_input_sampling_rate())
{
inFilter.set_input_sampling_rate(sampling_rate);
inFilter.set_output_sampling_rate(sampling_rate);
sinusGenerator.set_output_sampling_rate(sampling_rate);
delayFilter.set_input_sampling_rate(sampling_rate);
delayFilter.set_output_sampling_rate(sampling_rate);
outFilter.set_input_sampling_rate(sampling_rate);
outFilter.set_output_sampling_rate(sampling_rate);
}
sinusGenerator.full_setup();
delayFilter.full_setup();
}
void ATKUniversalVariableDelay::OnParamChange(int paramIdx)
{
IMutexLock lock(this);
switch (paramIdx)
{
case kDelay:
if (GetParam(kDepth)->Value() > GetParam(kDelay)->Value() - 0.1)
{
GetParam(kDelay)->Set(GetParam(kDepth)->Value() + 0.1);
}
sinusGenerator.set_offset(GetParam(kDelay)->Value() / 1000. * GetSampleRate());
delayFilter.set_central_delay(GetParam(kDelay)->Value() / 1000. * GetSampleRate());
break;
case kDepth:
if (GetParam(kDepth)->Value() > GetParam(kDelay)->Value() - 0.1)
{
GetParam(kDepth)->Set(GetParam(kDelay)->Value() - 0.1);
}
sinusGenerator.set_volume(GetParam(kDepth)->Value() / 1000. * GetSampleRate());
break;
case kMod:
sinusGenerator.set_frequency(GetParam(kMod)->Value());
break;
case kBlend:
delayFilter.set_blend((GetParam(kBlend)->Value()) / 100.);
break;
case kFeedforward:
delayFilter.set_feedforward((GetParam(kFeedforward)->Value()) / 100.);
break;
case kFeedback:
delayFilter.set_feedback((GetParam(kFeedback)->Value()) / 100.);
break;
default:
break;
}
}
<|endoftext|> |
<commit_before>/////////////////////////////////////////
//
// OpenLieroX
//
// code under LGPL, based on JasonBs work,
// enhanced by Dark Charlie and Albert Zeyer
//
//
/////////////////////////////////////////
// Profile system
// Created 13/8/02
// Jason Boettcher
#include <assert.h>
#include "LieroX.h"
#include "EndianSwap.h"
#include "Menu.h"
#include "GfxPrimitives.h"
#include "FindFile.h"
#include "StringUtils.h"
profile_t *tProfiles = NULL;
///////////////////
// Load the profiles
int LoadProfiles(void)
{
int i;
//
// Open the file
//
FILE *fp = OpenGameFile("cfg/players.dat","rb");
if(fp == NULL) {
// Add the default players
AddDefaultPlayers();
return false;
}
//
// Header
//
// Check ID
char id[32];
fread(id, sizeof(char), 32, fp);
id[10] = '\0';
if(strcmp(id, "lx:profile") != 0) {
std::string tmp = "Could not load profiles: \""+std::string(id)+"\" is not equal to \"lx:profile\"";
printf("ERROR: " + tmp + "\n");
// Add the default players
AddDefaultPlayers();
fclose(fp);
return false;
}
// Check version
int ver = 0;
fread(&ver, sizeof(int), 1, fp);
EndianSwap(ver);
if(ver != PROFILE_VERSION) {
std::string tmp = "Could not load profiles: \""+itoa(ver)+"\" is not equal to \""+itoa(PROFILE_VERSION)+"\"";
printf("ERROR: " + tmp + "\n");
// Add the default players
AddDefaultPlayers();
fclose(fp);
return false;
}
// Get number of profiles
int num = 0;
fread(&num, sizeof(int), 1, fp);
EndianSwap(num);
// Safety check
if(num < 0) {
// Just leave
fclose(fp);
// Add the default players
AddDefaultPlayers();
return true;
}
// Load the profiles
for(i=0; i<num; i++)
LoadProfile(fp, i);
fclose(fp);
return true;
}
///////////////////
// Add the default players to the list
void AddDefaultPlayers(void)
{
short i;
static std::string buf;
// Pre-set cpu colours
Uint32 cpuColours[] = { 255,0,0, 0,255,0, 0,0,255, 255,0,255, 0,255,255, 128,128,128,
128,255,0, 0,128,255, 0,128,0 };
// Pre-set cpu difficulties
int Diff[] = {AI_EASY, AI_MEDIUM, AI_MEDIUM, AI_HARD, AI_XTREME, AI_MEDIUM, AI_EASY};
// Add the default worm
AddProfile("worm", "default.png", "", "", 100,100,255, PRF_HUMAN,0);
// Add 7 ai players
for(i=0; i<7; i++) {
buf = "CPU "+itoa(i+1);
AddProfile(buf, "default.png", "", "", cpuColours[i*3], cpuColours[i*3+1], cpuColours[i*3+2], PRF_COMPUTER, Diff[i]);
}
}
///////////////////
// Save the profiles
void SaveProfiles(void)
{
profile_t *p = tProfiles;
profile_t *pf;
//
// Open the file
//
FILE *fp = OpenGameFile("cfg/players.dat","wb");
if(fp == NULL) {
printf("ERROR: could not open cfg/players.dat for writing\n");
return;
}
// ID & Version
fwrite("lx:profile", 32, fp);
int ver = PROFILE_VERSION;
fwrite(GetEndianSwapped(ver), sizeof(int), 1, fp);
// Count how many profiles we have
int Num=0;
for(;p;p=p->tNext)
Num++;
fwrite(GetEndianSwapped(Num), sizeof(int), 1, fp);
p = tProfiles;
for(; p; p = pf) {
pf = p->tNext;
// Save the profile
SaveProfile(fp, p);
}
}
///////////////////
// Shutdown & save the profiles
void ShutdownProfiles(void)
{
if (!tProfiles) // Profiles not loaded, don't write and empty file (and delete all user's prifiles!)
return;
profile_t *p = tProfiles;
profile_t *pf = NULL;
//
// Open the file
//
FILE *fp = OpenGameFile("cfg/players.dat","wb");
if(fp == NULL) {
printf("ERROR: could not open cfg/players.dat for writing\n");
return;
}
// ID & Version
fwrite("lx:profile", 32, fp);
int ver = PROFILE_VERSION;
fwrite(GetEndianSwapped(ver), sizeof(int), 1, fp);
// Count how many profiles we have
int Num=0;
for(;p;p=p->tNext)
Num++;
fwrite(GetEndianSwapped(Num), sizeof(int), 1, fp);
p = tProfiles;
for(; p; p = pf) {
pf = p->tNext;
// Save the profile
SaveProfile(fp, p);
// Free the actual profile
assert(p);
delete p;
}
fclose(fp);
tProfiles = NULL;
}
///////////////////
// Load a profile
void LoadProfile(FILE *fp, int id)
{
profile_t *p;
p = new profile_t();
if(p == NULL)
return;
p->iID = id;
p->tNext = NULL;
// Name
p->sName = freadfixedcstr(fp, 32);
p->cSkin.Change(freadfixedcstr(fp, 128));
fread(&p->iType, sizeof(int), 1, fp);
EndianSwap(p->iType);
fread(&p->nDifficulty,sizeof(int), 1, fp);
EndianSwap(p->nDifficulty);
if (p->iType == PRF_COMPUTER)
p->cSkin.setBotIcon(p->nDifficulty);
// Multiplayer
p->sUsername = freadfixedcstr(fp,16);
p->sPassword = freadfixedcstr(fp,16);
// Colour
fread(&p->R, sizeof(Uint8), 1, fp);
EndianSwap(p->R);
fread(&p->G, sizeof(Uint8), 1, fp);
EndianSwap(p->G);
fread(&p->B, sizeof(Uint8), 1, fp);
EndianSwap(p->B);
p->cSkin.setDefaultColor(MakeColour(p->R, p->G, p->B));
p->cSkin.Colorize(p->cSkin.getDefaultColor());
// Weapons
for(int i=0; i<5; i++)
p->sWeaponSlots[i] = freadfixedcstr(fp,64);
// Add the profile onto the list
if(tProfiles) {
profile_t *pf = tProfiles;
for(;pf;pf = pf->tNext) {
if(pf->tNext == NULL) {
pf->tNext = p;
break;
}
}
}
else
tProfiles = p;
}
///////////////////
// Save a profile
void SaveProfile(FILE *fp, profile_t *p)
{
// Name & Type
fwrite(p->sName, 32, fp);
fwrite(p->cSkin.getFileName(), 128,fp);
fwrite(GetEndianSwapped(p->iType), sizeof(int), 1, fp);
fwrite(GetEndianSwapped(p->nDifficulty),sizeof(int), 1, fp);
// Multiplayer
fwrite(p->sUsername, 16, fp);
fwrite(p->sPassword, 16, fp);
// Colour
fwrite(&p->R, 1, 1, fp);
fwrite(&p->G, 1, 1, fp);
fwrite(&p->B, 1, 1, fp);
// Weapons
for(int i=0; i<5; i++)
fwrite(p->sWeaponSlots[i], 64, fp);
}
///////////////////
// Delete a profile
void DeleteProfile(int id)
{
profile_t *prv = NULL;
profile_t *p = tProfiles;
// Find it's previous
for(; p; p=p->tNext) {
if(p->iID == id) {
// Set the previous profiles next to my next one
// Thus removing me from the list
if(prv)
prv->tNext = p->tNext;
else
tProfiles = p->tNext;
// Free me
delete p;
break;
}
prv = p;
}
// Reset the id's
p = tProfiles;
int i=0;
for(;p;p = p->tNext)
p->iID = i++;
}
///////////////////
// Add a profile to the list
void AddProfile(const std::string& name, const std::string& skin, const std::string& username, const std::string& password, int R, int G, int B, int type, int difficulty)
{
profile_t *p;
p = new profile_t();
if(p == NULL)
return;
// Find a free id
int id = FindProfileID();
p->iID = id;
p->iType = type;
p->nDifficulty = difficulty;
p->tNext = NULL;
p->sName = name;
p->cSkin.Change(skin);
p->R = R;
p->G = G;
p->B = B;
p->sUsername = username;
p->sPassword = password;
// Default weapons
p->sWeaponSlots[0] = "minigun";
p->sWeaponSlots[1] = "super shotgun";
p->sWeaponSlots[2] = "blaster";
p->sWeaponSlots[3] = "gauss gun";
p->sWeaponSlots[4] = "big nuke";
// Add the profile onto the list
if(tProfiles) {
profile_t *pf = tProfiles;
profile_t *prv = NULL;
for(;pf;pf = pf->tNext) {
// If we are human, we need to insert ourselves into the list before the ai players
if(p->iType == PRF_HUMAN) {
if(pf->iType == PRF_COMPUTER) {
p->tNext = pf;
if(prv)
prv->tNext = p;
else
// Must be first one
tProfiles = p;
break;
}
}
if(pf->tNext == NULL) {
pf->tNext = p;
break;
}
prv = pf;
}
}
else
tProfiles = p;
// Reset the id's
p = tProfiles;
int i=0;
for(;p;p = p->tNext)
p->iID = i++;
}
///////////////////
// Find a free profile id
int FindProfileID(void)
{
profile_t *p = tProfiles;
int id = -1;
for(; p; p=p->tNext)
id = p->iID;
return id+1;
}
///////////////////
// Get the profiles
profile_t *GetProfiles(void)
{
return tProfiles;
}
///////////////////
// Find a profile based on id
profile_t *FindProfile(int id)
{
profile_t *p = tProfiles;
for(;p;p=p->tNext) {
if(p->iID == id)
return p;
}
return NULL;
}
profile_t *FindProfile(const std::string& name) {
profile_t *p = tProfiles;
for(;p;p=p->tNext) {
if(p->sName == name)
return p;
}
return NULL;
}
<commit_msg>Fixed a little skin colorization bug when creating a new profile<commit_after>/////////////////////////////////////////
//
// OpenLieroX
//
// code under LGPL, based on JasonBs work,
// enhanced by Dark Charlie and Albert Zeyer
//
//
/////////////////////////////////////////
// Profile system
// Created 13/8/02
// Jason Boettcher
#include <assert.h>
#include "LieroX.h"
#include "EndianSwap.h"
#include "Menu.h"
#include "GfxPrimitives.h"
#include "FindFile.h"
#include "StringUtils.h"
profile_t *tProfiles = NULL;
///////////////////
// Load the profiles
int LoadProfiles(void)
{
int i;
//
// Open the file
//
FILE *fp = OpenGameFile("cfg/players.dat","rb");
if(fp == NULL) {
// Add the default players
AddDefaultPlayers();
return false;
}
//
// Header
//
// Check ID
char id[32];
fread(id, sizeof(char), 32, fp);
id[10] = '\0';
if(strcmp(id, "lx:profile") != 0) {
std::string tmp = "Could not load profiles: \""+std::string(id)+"\" is not equal to \"lx:profile\"";
printf("ERROR: " + tmp + "\n");
// Add the default players
AddDefaultPlayers();
fclose(fp);
return false;
}
// Check version
int ver = 0;
fread(&ver, sizeof(int), 1, fp);
EndianSwap(ver);
if(ver != PROFILE_VERSION) {
std::string tmp = "Could not load profiles: \""+itoa(ver)+"\" is not equal to \""+itoa(PROFILE_VERSION)+"\"";
printf("ERROR: " + tmp + "\n");
// Add the default players
AddDefaultPlayers();
fclose(fp);
return false;
}
// Get number of profiles
int num = 0;
fread(&num, sizeof(int), 1, fp);
EndianSwap(num);
// Safety check
if(num < 0) {
// Just leave
fclose(fp);
// Add the default players
AddDefaultPlayers();
return true;
}
// Load the profiles
for(i=0; i<num; i++)
LoadProfile(fp, i);
fclose(fp);
return true;
}
///////////////////
// Add the default players to the list
void AddDefaultPlayers(void)
{
short i;
static std::string buf;
// Pre-set cpu colours
Uint32 cpuColours[] = { 255,0,0, 0,255,0, 0,0,255, 255,0,255, 0,255,255, 128,128,128,
128,255,0, 0,128,255, 0,128,0 };
// Pre-set cpu difficulties
int Diff[] = {AI_EASY, AI_MEDIUM, AI_MEDIUM, AI_HARD, AI_XTREME, AI_MEDIUM, AI_EASY};
// Add the default worm
AddProfile("worm", "default.png", "", "", 100,100,255, PRF_HUMAN,0);
// Add 7 ai players
for(i=0; i<7; i++) {
buf = "CPU "+itoa(i+1);
AddProfile(buf, "default.png", "", "", cpuColours[i*3], cpuColours[i*3+1], cpuColours[i*3+2], PRF_COMPUTER, Diff[i]);
}
}
///////////////////
// Save the profiles
void SaveProfiles(void)
{
profile_t *p = tProfiles;
profile_t *pf;
//
// Open the file
//
FILE *fp = OpenGameFile("cfg/players.dat","wb");
if(fp == NULL) {
printf("ERROR: could not open cfg/players.dat for writing\n");
return;
}
// ID & Version
fwrite("lx:profile", 32, fp);
int ver = PROFILE_VERSION;
fwrite(GetEndianSwapped(ver), sizeof(int), 1, fp);
// Count how many profiles we have
int Num=0;
for(;p;p=p->tNext)
Num++;
fwrite(GetEndianSwapped(Num), sizeof(int), 1, fp);
p = tProfiles;
for(; p; p = pf) {
pf = p->tNext;
// Save the profile
SaveProfile(fp, p);
}
}
///////////////////
// Shutdown & save the profiles
void ShutdownProfiles(void)
{
if (!tProfiles) // Profiles not loaded, don't write and empty file (and delete all user's prifiles!)
return;
profile_t *p = tProfiles;
profile_t *pf = NULL;
//
// Open the file
//
FILE *fp = OpenGameFile("cfg/players.dat","wb");
if(fp == NULL) {
printf("ERROR: could not open cfg/players.dat for writing\n");
return;
}
// ID & Version
fwrite("lx:profile", 32, fp);
int ver = PROFILE_VERSION;
fwrite(GetEndianSwapped(ver), sizeof(int), 1, fp);
// Count how many profiles we have
int Num=0;
for(;p;p=p->tNext)
Num++;
fwrite(GetEndianSwapped(Num), sizeof(int), 1, fp);
p = tProfiles;
for(; p; p = pf) {
pf = p->tNext;
// Save the profile
SaveProfile(fp, p);
// Free the actual profile
assert(p);
delete p;
}
fclose(fp);
tProfiles = NULL;
}
///////////////////
// Load a profile
void LoadProfile(FILE *fp, int id)
{
profile_t *p;
p = new profile_t();
if(p == NULL)
return;
p->iID = id;
p->tNext = NULL;
// Name
p->sName = freadfixedcstr(fp, 32);
p->cSkin.Change(freadfixedcstr(fp, 128));
fread(&p->iType, sizeof(int), 1, fp);
EndianSwap(p->iType);
fread(&p->nDifficulty,sizeof(int), 1, fp);
EndianSwap(p->nDifficulty);
if (p->iType == PRF_COMPUTER)
p->cSkin.setBotIcon(p->nDifficulty);
// Multiplayer
p->sUsername = freadfixedcstr(fp,16);
p->sPassword = freadfixedcstr(fp,16);
// Colour
fread(&p->R, sizeof(Uint8), 1, fp);
EndianSwap(p->R);
fread(&p->G, sizeof(Uint8), 1, fp);
EndianSwap(p->G);
fread(&p->B, sizeof(Uint8), 1, fp);
EndianSwap(p->B);
p->cSkin.setDefaultColor(MakeColour(p->R, p->G, p->B));
p->cSkin.Colorize(p->cSkin.getDefaultColor());
// Weapons
for(int i=0; i<5; i++)
p->sWeaponSlots[i] = freadfixedcstr(fp,64);
// Add the profile onto the list
if(tProfiles) {
profile_t *pf = tProfiles;
for(;pf;pf = pf->tNext) {
if(pf->tNext == NULL) {
pf->tNext = p;
break;
}
}
}
else
tProfiles = p;
}
///////////////////
// Save a profile
void SaveProfile(FILE *fp, profile_t *p)
{
// Name & Type
fwrite(p->sName, 32, fp);
fwrite(p->cSkin.getFileName(), 128,fp);
fwrite(GetEndianSwapped(p->iType), sizeof(int), 1, fp);
fwrite(GetEndianSwapped(p->nDifficulty),sizeof(int), 1, fp);
// Multiplayer
fwrite(p->sUsername, 16, fp);
fwrite(p->sPassword, 16, fp);
// Colour
fwrite(&p->R, 1, 1, fp);
fwrite(&p->G, 1, 1, fp);
fwrite(&p->B, 1, 1, fp);
// Weapons
for(int i=0; i<5; i++)
fwrite(p->sWeaponSlots[i], 64, fp);
}
///////////////////
// Delete a profile
void DeleteProfile(int id)
{
profile_t *prv = NULL;
profile_t *p = tProfiles;
// Find it's previous
for(; p; p=p->tNext) {
if(p->iID == id) {
// Set the previous profiles next to my next one
// Thus removing me from the list
if(prv)
prv->tNext = p->tNext;
else
tProfiles = p->tNext;
// Free me
delete p;
break;
}
prv = p;
}
// Reset the id's
p = tProfiles;
int i=0;
for(;p;p = p->tNext)
p->iID = i++;
}
///////////////////
// Add a profile to the list
void AddProfile(const std::string& name, const std::string& skin, const std::string& username, const std::string& password, int R, int G, int B, int type, int difficulty)
{
profile_t *p;
p = new profile_t();
if(p == NULL)
return;
// Find a free id
int id = FindProfileID();
p->iID = id;
p->iType = type;
p->nDifficulty = difficulty;
p->tNext = NULL;
p->sName = name;
p->cSkin.Change(skin);
p->R = R;
p->G = G;
p->B = B;
p->cSkin.Colorize(MakeColour(R, G, B));
p->sUsername = username;
p->sPassword = password;
// Default weapons
p->sWeaponSlots[0] = "minigun";
p->sWeaponSlots[1] = "super shotgun";
p->sWeaponSlots[2] = "blaster";
p->sWeaponSlots[3] = "gauss gun";
p->sWeaponSlots[4] = "big nuke";
// Add the profile onto the list
if(tProfiles) {
profile_t *pf = tProfiles;
profile_t *prv = NULL;
for(;pf;pf = pf->tNext) {
// If we are human, we need to insert ourselves into the list before the ai players
if(p->iType == PRF_HUMAN) {
if(pf->iType == PRF_COMPUTER) {
p->tNext = pf;
if(prv)
prv->tNext = p;
else
// Must be first one
tProfiles = p;
break;
}
}
if(pf->tNext == NULL) {
pf->tNext = p;
break;
}
prv = pf;
}
}
else
tProfiles = p;
// Reset the id's
p = tProfiles;
int i=0;
for(;p;p = p->tNext)
p->iID = i++;
}
///////////////////
// Find a free profile id
int FindProfileID(void)
{
profile_t *p = tProfiles;
int id = -1;
for(; p; p=p->tNext)
id = p->iID;
return id+1;
}
///////////////////
// Get the profiles
profile_t *GetProfiles(void)
{
return tProfiles;
}
///////////////////
// Find a profile based on id
profile_t *FindProfile(int id)
{
profile_t *p = tProfiles;
for(;p;p=p->tNext) {
if(p->iID == id)
return p;
}
return NULL;
}
profile_t *FindProfile(const std::string& name) {
profile_t *p = tProfiles;
for(;p;p=p->tNext) {
if(p->sName == name)
return p;
}
return NULL;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbMeanShiftVectorImageFilter.h"
namespace otb
{
namespace Wrapper
{
class LargeScaleSegmentation : public Application
{
public:
/** Standard class typedefs. */
typedef LargeScaleSegmentation Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
typedef otb::MeanShiftVectorImageFilter<FloatVectorImageType, FloatVectorImageType> MSFilterType;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(LargeScaleSegmentation, otb::Application);
private:
void DoInit()
{
SetName("LargeScaleSegmentation");
SetDescription("Perform Large scale segmentation");
// Documentation
SetDocName("Large Scale segmentation");
SetDocLongDescription(".");
SetDocLimitations(" .");
SetDocAuthors("OTB-Team");
SetDocSeeAlso(" ");
AddDocTag(Tags::Segmentation);
AddParameter(ParameterType_InputImage, "in", "Input Image");
SetParameterDescription( "in", "The input image." );
AddParameter(ParameterType_InputImage, "inmask", "Mask Image");
SetParameterDescription( "inmask", "Mask image. (Pixel with 0 will not be processed)." );
MandatoryOff("inmask");
AddParameter(ParameterType_OutputVectorData,"outvd", "Output VectorData");
SetParameterDescription( "outvd", "The name of output Vector Data." );
//AddParameter(ParameterType_OutputImage, "lout", "Labeled output");
//SetParameterDescription( "lout", "The labeled output image." );
//MandatoryOff("lout");
//
AddParameter(ParameterType_Choice, "filter", "Segmentation Filter");
SetParameterDescription("filter", "Choose your segmentation filter method.");
AddChoice("filter.meanshiftedison", "EDISON MeanShift");
SetParameterDescription("filter.meanshiftedison", "EDISON based MeanShift filter. (is going to be replaced by newframework).");
// EDISON Meanshift Parameters
AddChoice("filter.meanshift", "MeanShift");
SetParameterDescription("filter.meanshiftedison", "MeanShift filter.");
// MeanShift Parameters
AddChoice("filter.connectedcomponent", "ConnectedComponentMuParser");
SetParameterDescription("filter.connectedcomponent", "connectedComponant muparser filter.");
// CC parameters
AddParameter(ParameterType_Group, "relabel", "Relabel Output.");
SetParameterDescription("relabel", "Relabel output and eliminates to small objects. Background value will be assigned instead.");
MandatoryOff("relabel");
AddParameter(ParameterType_Int, "relabel.minsize", "Minimum object size");
SetParameterDescription("relabel.minsize", "object with size under this threshold (area in pixels) will be replaced by the background value.");
SetDefaultParameterInt("relabel.minsize", 1);
SetMinimumParameterIntValue("relabel.minsize", 0);
MandatoryOff("relabel.minsize");
AddParameter(ParameterType_Int, "relabel.backgroundvalue", "Background value");
SetParameterDescription("relabel.backgroundvalue", "Background value.");
SetDefaultParameterInt("relabel.backgroundvalue", 0);
MandatoryOff("relabel.backgroundvalue");
//
AddParameter(ParameterType_String, "layername", "Layer Name");
SetParameterDescription("layername", "Layer Name.(by default : Layer )");
SetParameterString("layername", "layer");
MandatoryOff("layername");
AddParameter(ParameterType_String, "fieldname", "Field Name");
SetParameterDescription("fieldname", "field Name.(by default : DN )");
SetParameterString("fieldname", "DN");
MandatoryOff("fieldname");
AddParameter(ParameterType_Int, "tilesize", "tile size");
SetParameterDescription("tilesize", "streaming to dimension for computing vectorization.(automatic tile dimension is set "
" if tile size set to 0 (by default).)");
SetDefaultParameterInt("tilesize", 0);
MandatoryOff("tilesize");
AddParameter(ParameterType_Int, "startlabel", "start label");
SetParameterDescription("startlabel", "Start label.(1 by default)");
SetDefaultParameterInt("startlabel", 1);
MandatoryOff("startlabel");
AddParameter(ParameterType_Empty, "neighbor", "use 8connected");
SetParameterDescription("neighbor", "Pixel neighborhood vectorization strategy. 4 or 8 neighborhood .(4 neighborhood by default.)");
MandatoryOff("neighbor");
// Doc example parameter settings
SetDocExampleParameterValue("in", "QB_Toulouse_Ortho_PAN.tif");
SetDocExampleParameterValue("outvd", "SegmentationVectorData.sqlite");
SetDocExampleParameterValue("filter", "meanshift");
}
void DoUpdateParameters()
{
// Nothing to do here : all parameters are independent
}
void DoExecute()
{
}
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::LargeScaleSegmentation)
<commit_msg>ENH: LargeScaleSegmentation application, only EDISONBased meanshift choice is implemented (WIP).<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
// Segmentation filters includes
#include "otbMeanShiftVectorImageFilter.h"
#include "otbStreamingVectorizedSegmentationOGR.h"
//#include "otbPersistentImageToOGRDataFilter.h"
//#include "otbPersistentFilterStreamingDecorator.h"
#include "otbConnectedComponentMuParserFunctor.h"
#include <itkConnectedComponentFunctorImageFilter.h>
#include "otbParser.h"
#include "otbOGRDataSourceWrapper.h"
#include "otbMultiToMonoChannelExtractROI.h"
#include "otbObjectList.h"
namespace otb
{
namespace Wrapper
{
class LargeScaleSegmentation : public Application
{
public:
/** Standard class typedefs. */
typedef LargeScaleSegmentation Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
typedef UInt32ImageType LabelImageType;
typedef UInt32ImageType MaskImageType;
typedef MultiToMonoChannelExtractROI<FloatVectorImageType::InternalPixelType,
MaskImageType::PixelType> ExtractROIFilterType;
typedef ObjectList<ExtractROIFilterType> ExtractROIFilterListType;
// typedef itk::ImageToImageFilter<FloatVectorImageType,UInt32ImageType> SegmentationFilterType;
typedef otb::MeanShiftVectorImageFilter<FloatVectorImageType,FloatVectorImageType,LabelImageType> MSEDISONSegmentationFilterType;
// TODO replace by new meanshift segmentation scheme
//typedef otb::MeanShiftConnectedComponentSegmentationFilter< FloatVectorImageType, MaskImageType,LabelImageType > MeanShiftConnectedComponentsegmentationFilterType;
// typedef otb::MeanShiftImageFilter2<FloatVectorImageType, LabelImageType> MeanShiftFilterType;
typedef otb::StreamingVectorizedSegmentationOGR<FloatVectorImageType, MSEDISONSegmentationFilterType> MSEDIONStreamingVectorizedSegmentationOGRType;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(LargeScaleSegmentation, otb::Application);
private:
void DoInit()
{
SetName("LargeScaleSegmentation");
SetDescription("Perform Large scale segmentation");
// Documentation
SetDocName("Large Scale segmentation");
SetDocLongDescription(".");
SetDocLimitations(" .");
SetDocAuthors("OTB-Team");
SetDocSeeAlso(" ");
AddDocTag(Tags::Segmentation);
AddParameter(ParameterType_InputImage, "in", "Input Image");
SetParameterDescription( "in", "The input image." );
AddParameter(ParameterType_InputImage, "inmask", "Mask Image");
SetParameterDescription( "inmask", "Mask image. (Pixel with 0 will not be processed)." );
MandatoryOff("inmask");
AddParameter(ParameterType_OutputFilename,"outvd", "Output VectorData");
SetParameterDescription( "outvd", "The name of output Vector Data." );
AddParameter(ParameterType_OutputImage, "lout", "Labeled output");
SetParameterDescription( "lout", "The labeled output image." );
MandatoryOff("lout");
//
AddParameter(ParameterType_Choice, "filter", "Segmentation Filter");
SetParameterDescription("filter", "Choose your segmentation filter method.");
AddChoice("filter.meanshiftedison", "EDISON MeanShift");
SetParameterDescription("filter.meanshiftedison", "EDISON based MeanShift filter. (is going to be replaced by newframework).");
// EDISON Meanshift Parameters
AddParameter(ParameterType_Int, "filter.meanshiftedison.spatialr", "Spatial radius");
SetParameterDescription( "filter.meanshiftedison.spatialr", "Spatial radius defining neighborhood." );
AddParameter(ParameterType_Float, "filter.meanshiftedison.ranger", "Range radius");
SetParameterDescription( "filter.meanshiftedison.ranger", "Range radius defining the interval in the color space." );
AddParameter(ParameterType_Int, "filter.meanshiftedison.minsize", "Min region size");
SetParameterDescription( "filter.meanshiftedison.minsize", "Minimun size of a region to be kept after clustering." );
AddParameter(ParameterType_Float, "filter.meanshiftedison.scale", "Scale");
SetParameterDescription( "filter.meanshiftedison.scale", "Scale to stretch the image before processing." );
SetDefaultParameterInt("filter.meanshiftedison.spatialr", 5);
SetDefaultParameterFloat("filter.meanshiftedison.ranger", 15.0);
SetDefaultParameterInt("filter.meanshiftedison.minsize", 100);
SetDefaultParameterFloat("filter.meanshiftedison.scale", 100000.);
AddChoice("filter.meanshift", "MeanShift");
SetParameterDescription("filter.meanshift", "MeanShift filter.");
// MeanShift Parameters
AddChoice("filter.connectedcomponent", "ConnectedComponentMuParser");
SetParameterDescription("filter.connectedcomponent", "connectedComponant muparser filter.");
// CC parameters
AddParameter(ParameterType_String, "filter.connectedcomponent.mask", "Mask expression");
SetParameterDescription("filter.connectedcomponent.mask", "Mask mathematical expression (only if support image is given)");
MandatoryOff("filter.connectedcomponent.mask");
DisableParameter("filter.connectedcomponent.mask");
AddParameter(ParameterType_String, "filter.connectedcomponent.expr", "Connected Component Expression");
SetParameterDescription("filter.connectedcomponent.expr", "Formula used for connected component segmentation");
AddParameter(ParameterType_Group, "relabel", "Relabel Output.");
SetParameterDescription("relabel", "Relabel output and eliminates to small objects. Background value will be assigned instead.");
MandatoryOff("relabel");
AddParameter(ParameterType_Int, "relabel.minsize", "Minimum object size");
SetParameterDescription("relabel.minsize", "object with size under this threshold (area in pixels) will be replaced by the background value.");
SetDefaultParameterInt("relabel.minsize", 1);
SetMinimumParameterIntValue("relabel.minsize", 0);
MandatoryOff("relabel.minsize");
AddParameter(ParameterType_Int, "relabel.backgroundvalue", "Background value");
SetParameterDescription("relabel.backgroundvalue", "Background value.");
SetDefaultParameterInt("relabel.backgroundvalue", 0);
MandatoryOff("relabel.backgroundvalue");
//
AddParameter(ParameterType_String, "layername", "Layer Name");
SetParameterDescription("layername", "Layer Name.(by default : Layer )");
SetParameterString("layername", "layer");
MandatoryOff("layername");
AddParameter(ParameterType_String, "fieldname", "Field Name");
SetParameterDescription("fieldname", "field Name.(by default : DN )");
SetParameterString("fieldname", "DN");
MandatoryOff("fieldname");
AddParameter(ParameterType_Int, "tilesize", "tile size");
SetParameterDescription("tilesize", "streaming to dimension for computing vectorization.(automatic tile dimension is set "
" if tile size set to 0 (by default).)");
SetDefaultParameterInt("tilesize", 0);
MandatoryOff("tilesize");
AddParameter(ParameterType_Int, "startlabel", "start label");
SetParameterDescription("startlabel", "Start label.(1 by default)");
SetDefaultParameterInt("startlabel", 1);
MandatoryOff("startlabel");
AddParameter(ParameterType_Empty, "neighbor", "use 8connected");
SetParameterDescription("neighbor", "Pixel neighborhood vectorization strategy. 4 or 8 neighborhood .(4 neighborhood by default.)");
MandatoryOff("neighbor");
// Doc example parameter settings
SetDocExampleParameterValue("in", "QB_Toulouse_Ortho_PAN.tif");
SetDocExampleParameterValue("outvd", "SegmentationVectorData.sqlite");
SetDocExampleParameterValue("filter", "meanshift");
}
void DoUpdateParameters()
{
// Nothing to do here : all parameters are independent
}
void DoExecute()
{
//
std::string dataSourceName =GetParameterString("outvd");
otb::ogr::DataSource::Pointer ogrDS = otb::ogr::DataSource::New(dataSourceName, otb::ogr::DataSource::Modes::write);
//mask image transform vector image to LabelImage
if(HasValue("inmask"))
{
m_MaskImage=this->GetParameterUInt32Image("inmask");
m_MaskImage->UpdateOutputInformation();
}
const unsigned int tileSize = static_cast<unsigned int>(this->GetParameterInt("tilesize"));
std::string layerName =this->GetParameterString("layername");
std::string fieldName =this->GetParameterString("fieldname");
const unsigned int startLabel=this->GetParameterInt("startlabel");
bool use8connected=!HasValue("neighbor");
switch (GetParameterInt("filter"))
{
// MeanShiftEDISON basedfiltering
case 0:
{
MSEDIONStreamingVectorizedSegmentationOGRType::Pointer EDISONVectorizationFilter=MSEDIONStreamingVectorizedSegmentationOGRType::New();
m_VectorizationFilter=EDISONVectorizationFilter;
EDISONVectorizationFilter->SetInput(GetParameterFloatVectorImage("in"));
if(HasValue("inmask"))
{
EDISONVectorizationFilter->SetInputMask(this->GetParameterUInt32Image("inmask"));
}
EDISONVectorizationFilter->SetOGRDataSource(ogrDS);
//filter->GetStreamer()->SetNumberOfLinesStrippedStreaming(atoi(argv[3]));
if(tileSize!=0)
EDISONVectorizationFilter->GetStreamer()->SetTileDimensionTiledStreaming(tileSize);
else
EDISONVectorizationFilter->GetStreamer()->SetAutomaticTiledStreaming();
EDISONVectorizationFilter->SetLayerName(layerName);
EDISONVectorizationFilter->SetFieldName(fieldName);
EDISONVectorizationFilter->SetStartLabel(startLabel);
EDISONVectorizationFilter->SetUse8Connected(use8connected);
//segmentation paramters
const unsigned int spatialRadius=static_cast<unsigned int>(this->GetParameterInt("filter.meanshiftedison.spatialr"));
const unsigned int rangeRadius=static_cast<unsigned int>(this->GetParameterInt("filter.meanshiftedison.ranger"));
const unsigned int minimumObjectSize= static_cast<unsigned int>(this->GetParameterInt("filter.meanshiftedison.minsize"));
const float scale=this->GetParameterFloat("filter.meanshiftedison.scale");
EDISONVectorizationFilter->GetSegmentationFilter()->SetSpatialRadius(spatialRadius);
EDISONVectorizationFilter->GetSegmentationFilter()->SetRangeRadius(rangeRadius);
EDISONVectorizationFilter->GetSegmentationFilter()->SetMinimumRegionSize(minimumObjectSize);
EDISONVectorizationFilter->GetSegmentationFilter()->SetScale(scale);
EDISONVectorizationFilter->Initialize(); //must be called !
m_VectorizationFilter->Update();
m_LabelImage=EDISONVectorizationFilter->GetSegmentationFilter()->GetLabeledClusteredOutput();
break;
}
//MeanShift filter
case 1:
{
break;
}
// CC filter
case 2:
{
break;
}
default:
{
otbAppLogFATAL(<<"non defined filtering method "<<GetParameterInt("filter")<<std::endl);
break;
}
return;
}
//m_VectorizationFilter->Update();
SetParameterOutputImage<LabelImageType>("lout", m_LabelImage);
}
itk::ProcessObject::Pointer m_SegmentationFilter;
itk::ProcessObject::Pointer m_VectorizationFilter;
MaskImageType::Pointer m_MaskImage;
LabelImageType::Pointer m_LabelImage;
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::LargeScaleSegmentation)
<|endoftext|> |
<commit_before>#include "config.h"
#include "horde3dwindow.h"
#include "entity.h"
#include <Horde3DUtils.h>
#include <QtCore/QPropertyAnimation>
#include <QtCore/QDir>
#include <QtGui/QGuiApplication>
#include <QtGui/QOpenGLFunctions>
#include <QtGui/QOpenGLFramebufferObject>
#include <QtGui/QScreen>
#include <QtQuick/QQuickWindow>
#include <QtQuick/QSGSimpleTextureNode>
#ifdef __APPLE__
// Because Apple loves being a special snowflake?
# include <OpenGL/gl.h>
#else
# include <GL/gl.h>
#endif
static const bool USE_SEPARATE_CONTEXT = false;
Horde3DWindow::Horde3DWindow(QWindow* parent) :
QQuickWindow(parent),
_initialized(false),
_dirtyView(false),
_shipRot(0.0f),
_grabMouse(false),
_qtContext(NULL),
_h3dContext(NULL),
_camDolly(NULL),
_camera(NULL),
_skybox(NULL),
_logger(PLogManager::getLogger("horde3dwindow")),
_settings(PSettingsManager::instance()),
_controls(ControlsManager::instance()),
_mgr(Horde3DManager::instance())
{
lastFrameStart.start();
connect(this, SIGNAL(beforeRendering()), this, SLOT(onBeforeRendering()), Qt::DirectConnection);
connect(&_mgr, SIGNAL(initFinished()), this, SLOT(onInitFinished()), Qt::QueuedConnection);
connect(&_mgr, SIGNAL(sceneChanged(const Entity*, QString)),
this, SLOT(onSceneChanged(const Entity*, QString)),
Qt::QueuedConnection
);
_controls.setWindow(this);
_logger.debug("Available input drivers:");
foreach(const QString& driverFileName, _controls.findInputDrivers())
{
_logger.debug(QString(" - %1").arg(driverFileName));
if(!_controls.loadInputDriver(driverFileName))
{
_logger.error(QString("Error loading input driver \"%1\"!").arg(driverFileName));
} // end if
} // end foreach
} // end Horde3DWindow
Horde3DWindow::~Horde3DWindow()
{
if(_h3dContext)
{
_h3dContext->deleteLater();
_h3dContext = NULL;
} // end if
} // end ~Horde3DWindow
Entity* Horde3DWindow::camera() const
{
return _camera;
} // end camera
Entity* Horde3DWindow::camDolly() const
{
return _camDolly;
} // end camDolly
float Horde3DWindow::fps() const
{
return lastFPS;
} // end fps
float Horde3DWindow::maxViewDistance() const
{
return _settings.get(CFG_VIEW_DIST, DEFAULT_VIEW_DIST).toFloat();
} // end maxViewDistance
bool Horde3DWindow::grabMouse() const
{
return _grabMouse;
} // end maxViewDistance
QPoint Horde3DWindow::lastRecenterPos() const
{
return _lastRecenterPos;
} // end lastRecenterPos
void Horde3DWindow::setMaxViewDistance(float maxViewDist)
{
h3dSetNodeParamF(camera()->node(), H3DCamera::FarPlaneF, 0, maxViewDist);
_settings.set(CFG_VIEW_DIST, maxViewDist);
emit maxViewDistanceChanged(maxViewDist);
} // end setMaxViewDistance
void Horde3DWindow::setGrabMouse(bool grab)
{
if(_grabMouse != grab)
{
_grabMouse = grab;
setMouseGrabEnabled(grab);
if(grab)
{
_logger.debug("setGrabMouse: Grab enabled.");
// Hide mouse cursor.
QGuiApplication::setOverrideCursor(QCursor(Qt::BlankCursor));
// Re-center mouse cursor.
_lastRecenterPos = geometry().center();
QCursor::setPos(_lastRecenterPos);
}
else
{
_logger.debug("setGrabMouse: Grab disabled.");
// Unhide mouse cursor.
QGuiApplication::restoreOverrideCursor();
} // end if
emit grabMouseChanged(grab);
} // end if
} // end maxViewDistance
void Horde3DWindow::renderHorde()
{
_mgr.update();
if(_camera)
{
if(!USE_SEPARATE_CONTEXT || (_qtContext && _h3dContext))
{
restoreH3DState();
_mgr.renderScene(_camera);
saveH3DState();
} // end if
} // end if
} // end renderHorde
void Horde3DWindow::onSceneChanged(const Entity* scene, QString sceneID)
{
_logger.debug(QString("Handling onSceneChanged(%1, \"%2\")...").arg(scene->toString()).arg(sceneID));
if(_skybox)
{
_logger.debug(QString("Reparenting old skybox %1 back to its scene...").arg(_skybox->toString()));
Entity* skyboxParent = _mgr.root();
if(_mgr.skyboxes().contains(_sceneID, _skybox))
{
skyboxParent = _mgr.getScene(_sceneID);
} // end if
_skybox->setParent(skyboxParent);
_skybox = NULL;
} // end if
_sceneID = sceneID;
if(_mgr.skyboxes().contains(sceneID))
{
_logger.debug(QString("Setting up skybox for scene \"%1\"...").arg(sceneID));
_skybox = _mgr.skyboxes().value(sceneID);
_skybox->setParent(_camera);
} // end if
} // end onSceneChanged
void Horde3DWindow::resizeEvent(QResizeEvent* event)
{
qDebug() << "Horde3DWindow::resizeEvent(" << event->oldSize() << "->" << event->size() << "); devicePixelRatio:" << screen()->devicePixelRatio();
if(event->size() != event->oldSize())
{
_size = event->size() * screen()->devicePixelRatio();
_dirtyView = true;
} // end if
QQuickWindow::resizeEvent(event);
} // end resizeEvent
void Horde3DWindow::saveQtState()
{
glPushClientAttrib(GL_CLIENT_ALL_ATTRIB_BITS);
glPushAttrib(GL_ALL_ATTRIB_BITS);
glMatrixMode(GL_TEXTURE);
glPushMatrix();
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glShadeModel(GL_FLAT);
glDisable(GL_CULL_FACE);
glDisable(GL_LIGHTING);
glDisable(GL_STENCIL_TEST);
glDisable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
} // end saveQtState
void Horde3DWindow::restoreQtState()
{
glMatrixMode(GL_TEXTURE);
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
glPopAttrib();
glPopClientAttrib();
} // end restoreQtState
void Horde3DWindow::restoreH3DState()
{
if(USE_SEPARATE_CONTEXT)
{
_qtContext->doneCurrent();
_h3dContext->makeCurrent(this);
} // end if
QOpenGLFunctions glFunctions(QOpenGLContext::currentContext());
glFunctions.glUseProgram(0);
if(renderTarget())
{
renderTarget()->bind();
} // end if
} // end restoreH3DState
void Horde3DWindow::saveH3DState()
{
if(renderTarget())
{
renderTarget()->release();
} // end if
if(USE_SEPARATE_CONTEXT)
{
_h3dContext->doneCurrent();
_qtContext->makeCurrent(this);
} // end if
} // end saveH3DState
void Horde3DWindow::updateView()
{
if(_initialized)
{
qDebug() << "Horde3DWindow::updateView()";
int deviceWidth = _size.width();
int deviceHeight = _size.height();
// Resize viewport
h3dSetNodeParamI(_camera->node(), H3DCamera::ViewportXI, 0);
h3dSetNodeParamI(_camera->node(), H3DCamera::ViewportYI, 0);
h3dSetNodeParamI(_camera->node(), H3DCamera::ViewportWidthI, deviceWidth);
h3dSetNodeParamI(_camera->node(), H3DCamera::ViewportHeightI, deviceHeight);
// Set virtual camera parameters
float aspectRatio = static_cast<float>(deviceWidth) / deviceHeight;
h3dSetupCameraView(_camera->node(), 45.0f, aspectRatio, 0.01f, maxViewDistance());
//_camDolly->scheduleOnce();
_camera->scheduleOnce();
H3DRes cameraPipeRes = h3dGetNodeParamI(_camera->node(), H3DCamera::PipeResI);
h3dResizePipelineBuffers(cameraPipeRes, deviceWidth, deviceHeight);
_dirtyView = false;
} // end if
} // end updateView
void Horde3DWindow::timerEvent(QTimerEvent* event)
{
Q_UNUSED(event);
update();
} // end timerEvent
void Horde3DWindow::keyPressEvent(QKeyEvent* event)
{
QQuickWindow::keyPressEvent(event);
if(!event->isAccepted())
{
emit keyPressed(event);
event->accept();
} // end if
} // end keyPressEvent
void Horde3DWindow::keyReleaseEvent(QKeyEvent* event)
{
QQuickWindow::keyReleaseEvent(event);
if(!event->isAccepted())
{
emit keyReleased(event);
event->accept();
} // end if
} // end keyReleaseEvent
void Horde3DWindow::mouseMoveEvent(QMouseEvent* event)
{
if(_grabMouse)
{
event->accept();
QPoint screenDelta = QCursor::pos() - _lastRecenterPos;
// Ignore events with zero delta. (these are generated by recentering the cursor)
if(!screenDelta.isNull())
{
emit mouseMoved(event, screenDelta);
// Re-center mouse cursor.
_lastRecenterPos = geometry().center();
QCursor::setPos(_lastRecenterPos);
} // end if
}
else
{
QQuickWindow::mouseMoveEvent(event);
} // end if
} // end mouseMoveEvent
void Horde3DWindow::mousePressEvent(QMouseEvent* event)
{
if(_grabMouse)
{
emit mousePressed(event);
event->accept();
}
else
{
QQuickWindow::mousePressEvent(event);
} // end if
} // end mousePressEvent
void Horde3DWindow::mouseReleaseEvent(QMouseEvent* event)
{
if(_grabMouse)
{
emit mouseReleased(event);
event->accept();
}
else
{
QQuickWindow::mouseReleaseEvent(event);
} // end if
} // end mouseReleaseEvent
void Horde3DWindow::onBeforeRendering()
{
float frameTime = lastFrameStart.elapsed();
lastFrameStart.restart();
if(frameTime > 0.0000000000000000001f)
{
lastFrameTime = frameTime;
lastFPS = 1000.0 / lastFrameTime;
emit fpsChanged(lastFPS);
} // end if
saveQtState();
if(!_initialized)
{
init();
} // end if
if(_dirtyView)
{
updateView();
} // end if
if(USE_SEPARATE_CONTEXT)
{
if(_h3dContext && (_h3dContext->format() != _qtContext->format()))
{
_h3dContext->deleteLater();
_h3dContext = NULL;
} // end if
if(!_h3dContext)
{
qDebug() << "Creating new OpenGL context.";
// Create a new shared OpenGL context to be used exclusively by Horde3D
_h3dContext = new QOpenGLContext();
_h3dContext->setFormat(requestedFormat());
_h3dContext->setShareContext(_qtContext);
_h3dContext->create();
} // end if
} // end if
renderHorde();
restoreQtState();
} // end onBeforeRendering
void Horde3DWindow::onInitFinished()
{
startTimer(16);
} // end onInitFinished
void Horde3DWindow::init()
{
qDebug() << "Horde3DWindow::init()";
_mgr.init();
_qtContext = openglContext();
_mgr.setAntiAliasingSamples(_qtContext->format().samples());
_camDolly = _mgr.root()->newGroup("camera dolly");
_camera = _camDolly->newCamera("cam");
_camera->setPos(0, 20, 100);
emit cameraChanged(_camera);
setClearBeforeRendering(false);
_mgr.printHordeMessages();
qDebug() << "--------- Initialization Finished ---------";
_size = size() * screen()->devicePixelRatio();
_dirtyView = true;
_initialized = true;
} // end init
<commit_msg>Removed commented line.<commit_after>#include "config.h"
#include "horde3dwindow.h"
#include "entity.h"
#include <Horde3DUtils.h>
#include <QtCore/QPropertyAnimation>
#include <QtCore/QDir>
#include <QtGui/QGuiApplication>
#include <QtGui/QOpenGLFunctions>
#include <QtGui/QOpenGLFramebufferObject>
#include <QtGui/QScreen>
#include <QtQuick/QQuickWindow>
#include <QtQuick/QSGSimpleTextureNode>
#ifdef __APPLE__
// Because Apple loves being a special snowflake?
# include <OpenGL/gl.h>
#else
# include <GL/gl.h>
#endif
static const bool USE_SEPARATE_CONTEXT = false;
Horde3DWindow::Horde3DWindow(QWindow* parent) :
QQuickWindow(parent),
_initialized(false),
_dirtyView(false),
_shipRot(0.0f),
_grabMouse(false),
_qtContext(NULL),
_h3dContext(NULL),
_camDolly(NULL),
_camera(NULL),
_skybox(NULL),
_logger(PLogManager::getLogger("horde3dwindow")),
_settings(PSettingsManager::instance()),
_controls(ControlsManager::instance()),
_mgr(Horde3DManager::instance())
{
lastFrameStart.start();
connect(this, SIGNAL(beforeRendering()), this, SLOT(onBeforeRendering()), Qt::DirectConnection);
connect(&_mgr, SIGNAL(initFinished()), this, SLOT(onInitFinished()), Qt::QueuedConnection);
connect(&_mgr, SIGNAL(sceneChanged(const Entity*, QString)),
this, SLOT(onSceneChanged(const Entity*, QString)),
Qt::QueuedConnection
);
_controls.setWindow(this);
_logger.debug("Available input drivers:");
foreach(const QString& driverFileName, _controls.findInputDrivers())
{
_logger.debug(QString(" - %1").arg(driverFileName));
if(!_controls.loadInputDriver(driverFileName))
{
_logger.error(QString("Error loading input driver \"%1\"!").arg(driverFileName));
} // end if
} // end foreach
} // end Horde3DWindow
Horde3DWindow::~Horde3DWindow()
{
if(_h3dContext)
{
_h3dContext->deleteLater();
_h3dContext = NULL;
} // end if
} // end ~Horde3DWindow
Entity* Horde3DWindow::camera() const
{
return _camera;
} // end camera
Entity* Horde3DWindow::camDolly() const
{
return _camDolly;
} // end camDolly
float Horde3DWindow::fps() const
{
return lastFPS;
} // end fps
float Horde3DWindow::maxViewDistance() const
{
return _settings.get(CFG_VIEW_DIST, DEFAULT_VIEW_DIST).toFloat();
} // end maxViewDistance
bool Horde3DWindow::grabMouse() const
{
return _grabMouse;
} // end maxViewDistance
QPoint Horde3DWindow::lastRecenterPos() const
{
return _lastRecenterPos;
} // end lastRecenterPos
void Horde3DWindow::setMaxViewDistance(float maxViewDist)
{
h3dSetNodeParamF(camera()->node(), H3DCamera::FarPlaneF, 0, maxViewDist);
_settings.set(CFG_VIEW_DIST, maxViewDist);
emit maxViewDistanceChanged(maxViewDist);
} // end setMaxViewDistance
void Horde3DWindow::setGrabMouse(bool grab)
{
if(_grabMouse != grab)
{
_grabMouse = grab;
setMouseGrabEnabled(grab);
if(grab)
{
_logger.debug("setGrabMouse: Grab enabled.");
// Hide mouse cursor.
QGuiApplication::setOverrideCursor(QCursor(Qt::BlankCursor));
// Re-center mouse cursor.
_lastRecenterPos = geometry().center();
QCursor::setPos(_lastRecenterPos);
}
else
{
_logger.debug("setGrabMouse: Grab disabled.");
// Unhide mouse cursor.
QGuiApplication::restoreOverrideCursor();
} // end if
emit grabMouseChanged(grab);
} // end if
} // end maxViewDistance
void Horde3DWindow::renderHorde()
{
_mgr.update();
if(_camera)
{
if(!USE_SEPARATE_CONTEXT || (_qtContext && _h3dContext))
{
restoreH3DState();
_mgr.renderScene(_camera);
saveH3DState();
} // end if
} // end if
} // end renderHorde
void Horde3DWindow::onSceneChanged(const Entity* scene, QString sceneID)
{
_logger.debug(QString("Handling onSceneChanged(%1, \"%2\")...").arg(scene->toString()).arg(sceneID));
if(_skybox)
{
_logger.debug(QString("Reparenting old skybox %1 back to its scene...").arg(_skybox->toString()));
Entity* skyboxParent = _mgr.root();
if(_mgr.skyboxes().contains(_sceneID, _skybox))
{
skyboxParent = _mgr.getScene(_sceneID);
} // end if
_skybox->setParent(skyboxParent);
_skybox = NULL;
} // end if
_sceneID = sceneID;
if(_mgr.skyboxes().contains(sceneID))
{
_logger.debug(QString("Setting up skybox for scene \"%1\"...").arg(sceneID));
_skybox = _mgr.skyboxes().value(sceneID);
_skybox->setParent(_camera);
} // end if
} // end onSceneChanged
void Horde3DWindow::resizeEvent(QResizeEvent* event)
{
qDebug() << "Horde3DWindow::resizeEvent(" << event->oldSize() << "->" << event->size() << "); devicePixelRatio:" << screen()->devicePixelRatio();
if(event->size() != event->oldSize())
{
_size = event->size() * screen()->devicePixelRatio();
_dirtyView = true;
} // end if
QQuickWindow::resizeEvent(event);
} // end resizeEvent
void Horde3DWindow::saveQtState()
{
glPushClientAttrib(GL_CLIENT_ALL_ATTRIB_BITS);
glPushAttrib(GL_ALL_ATTRIB_BITS);
glMatrixMode(GL_TEXTURE);
glPushMatrix();
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glShadeModel(GL_FLAT);
glDisable(GL_CULL_FACE);
glDisable(GL_LIGHTING);
glDisable(GL_STENCIL_TEST);
glDisable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
} // end saveQtState
void Horde3DWindow::restoreQtState()
{
glMatrixMode(GL_TEXTURE);
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
glPopAttrib();
glPopClientAttrib();
} // end restoreQtState
void Horde3DWindow::restoreH3DState()
{
if(USE_SEPARATE_CONTEXT)
{
_qtContext->doneCurrent();
_h3dContext->makeCurrent(this);
} // end if
QOpenGLFunctions glFunctions(QOpenGLContext::currentContext());
glFunctions.glUseProgram(0);
if(renderTarget())
{
renderTarget()->bind();
} // end if
} // end restoreH3DState
void Horde3DWindow::saveH3DState()
{
if(renderTarget())
{
renderTarget()->release();
} // end if
if(USE_SEPARATE_CONTEXT)
{
_h3dContext->doneCurrent();
_qtContext->makeCurrent(this);
} // end if
} // end saveH3DState
void Horde3DWindow::updateView()
{
if(_initialized)
{
qDebug() << "Horde3DWindow::updateView()";
int deviceWidth = _size.width();
int deviceHeight = _size.height();
// Resize viewport
h3dSetNodeParamI(_camera->node(), H3DCamera::ViewportXI, 0);
h3dSetNodeParamI(_camera->node(), H3DCamera::ViewportYI, 0);
h3dSetNodeParamI(_camera->node(), H3DCamera::ViewportWidthI, deviceWidth);
h3dSetNodeParamI(_camera->node(), H3DCamera::ViewportHeightI, deviceHeight);
// Set virtual camera parameters
float aspectRatio = static_cast<float>(deviceWidth) / deviceHeight;
h3dSetupCameraView(_camera->node(), 45.0f, aspectRatio, 0.01f, maxViewDistance());
_camera->scheduleOnce();
H3DRes cameraPipeRes = h3dGetNodeParamI(_camera->node(), H3DCamera::PipeResI);
h3dResizePipelineBuffers(cameraPipeRes, deviceWidth, deviceHeight);
_dirtyView = false;
} // end if
} // end updateView
void Horde3DWindow::timerEvent(QTimerEvent* event)
{
Q_UNUSED(event);
update();
} // end timerEvent
void Horde3DWindow::keyPressEvent(QKeyEvent* event)
{
QQuickWindow::keyPressEvent(event);
if(!event->isAccepted())
{
emit keyPressed(event);
event->accept();
} // end if
} // end keyPressEvent
void Horde3DWindow::keyReleaseEvent(QKeyEvent* event)
{
QQuickWindow::keyReleaseEvent(event);
if(!event->isAccepted())
{
emit keyReleased(event);
event->accept();
} // end if
} // end keyReleaseEvent
void Horde3DWindow::mouseMoveEvent(QMouseEvent* event)
{
if(_grabMouse)
{
event->accept();
QPoint screenDelta = QCursor::pos() - _lastRecenterPos;
// Ignore events with zero delta. (these are generated by recentering the cursor)
if(!screenDelta.isNull())
{
emit mouseMoved(event, screenDelta);
// Re-center mouse cursor.
_lastRecenterPos = geometry().center();
QCursor::setPos(_lastRecenterPos);
} // end if
}
else
{
QQuickWindow::mouseMoveEvent(event);
} // end if
} // end mouseMoveEvent
void Horde3DWindow::mousePressEvent(QMouseEvent* event)
{
if(_grabMouse)
{
emit mousePressed(event);
event->accept();
}
else
{
QQuickWindow::mousePressEvent(event);
} // end if
} // end mousePressEvent
void Horde3DWindow::mouseReleaseEvent(QMouseEvent* event)
{
if(_grabMouse)
{
emit mouseReleased(event);
event->accept();
}
else
{
QQuickWindow::mouseReleaseEvent(event);
} // end if
} // end mouseReleaseEvent
void Horde3DWindow::onBeforeRendering()
{
float frameTime = lastFrameStart.elapsed();
lastFrameStart.restart();
if(frameTime > 0.0000000000000000001f)
{
lastFrameTime = frameTime;
lastFPS = 1000.0 / lastFrameTime;
emit fpsChanged(lastFPS);
} // end if
saveQtState();
if(!_initialized)
{
init();
} // end if
if(_dirtyView)
{
updateView();
} // end if
if(USE_SEPARATE_CONTEXT)
{
if(_h3dContext && (_h3dContext->format() != _qtContext->format()))
{
_h3dContext->deleteLater();
_h3dContext = NULL;
} // end if
if(!_h3dContext)
{
qDebug() << "Creating new OpenGL context.";
// Create a new shared OpenGL context to be used exclusively by Horde3D
_h3dContext = new QOpenGLContext();
_h3dContext->setFormat(requestedFormat());
_h3dContext->setShareContext(_qtContext);
_h3dContext->create();
} // end if
} // end if
renderHorde();
restoreQtState();
} // end onBeforeRendering
void Horde3DWindow::onInitFinished()
{
startTimer(16);
} // end onInitFinished
void Horde3DWindow::init()
{
qDebug() << "Horde3DWindow::init()";
_mgr.init();
_qtContext = openglContext();
_mgr.setAntiAliasingSamples(_qtContext->format().samples());
_camDolly = _mgr.root()->newGroup("camera dolly");
_camera = _camDolly->newCamera("cam");
_camera->setPos(0, 20, 100);
emit cameraChanged(_camera);
setClearBeforeRendering(false);
_mgr.printHordeMessages();
qDebug() << "--------- Initialization Finished ---------";
_size = size() * screen()->devicePixelRatio();
_dirtyView = true;
_initialized = true;
} // end init
<|endoftext|> |
<commit_before>#ifndef LISTHOOKEDDEVICE_HPP
#define LISTHOOKEDDEVICE_HPP
#include "base.hpp"
#include "KeyCode.hpp"
#include "List.hpp"
#include "TimerWrapper.hpp"
namespace org_pqrs_KeyRemap4MacBook {
class ListHookedDevice {
public:
class Item : public List::Item {
friend class ListHookedDevice;
public:
Item(IOHIDevice* d);
virtual ~Item(void) {};
virtual bool isReplaced(void) const = 0;
const IOHIDevice* get(void) const { return device_; }
const DeviceIdentifier& getDeviceIdentifier(void) const { return deviceIdentifier_; }
DeviceType::DeviceType getDeviceType(void) const { return deviceType_; }
protected:
IOHIDevice* device_;
DeviceIdentifier deviceIdentifier_;
DeviceType::DeviceType deviceType_;
virtual bool refresh(void) = 0;
void setDeviceIdentifier(void);
void setDeviceType(void);
static bool isConsumer(const char* name);
};
bool initialize(void);
void terminate(void);
void push_back(ListHookedDevice::Item* newp);
void erase(IOHIDevice* p);
void refresh(void);
ListHookedDevice::Item* get(const IOHIDevice* device);
ListHookedDevice::Item* get_replaced(void);
void getDeviceInformation(BridgeDeviceInformation& out, size_t index);
static void initializeAll(IOWorkLoop& workloop);
static void terminateAll(void);
static void refreshAll(void);
static void refreshAll_timer_callback(OSObject* owner, IOTimerEventSource* sender);
protected:
ListHookedDevice(void) : last_(NULL), list_(NULL) {}
virtual ~ListHookedDevice(void) {}
const IOHIDevice* last_;
List* list_;
private:
enum {
REFRESHALL_TIMER_INTERVAL = 1000,
};
static TimerWrapper refreshAll_timer_;
};
}
#endif
<commit_msg>increase REFRESHALL_TIMER_INTERVAL to 3sec (same as NoEjectDelay)<commit_after>#ifndef LISTHOOKEDDEVICE_HPP
#define LISTHOOKEDDEVICE_HPP
#include "base.hpp"
#include "KeyCode.hpp"
#include "List.hpp"
#include "TimerWrapper.hpp"
namespace org_pqrs_KeyRemap4MacBook {
class ListHookedDevice {
public:
class Item : public List::Item {
friend class ListHookedDevice;
public:
Item(IOHIDevice* d);
virtual ~Item(void) {};
virtual bool isReplaced(void) const = 0;
const IOHIDevice* get(void) const { return device_; }
const DeviceIdentifier& getDeviceIdentifier(void) const { return deviceIdentifier_; }
DeviceType::DeviceType getDeviceType(void) const { return deviceType_; }
protected:
IOHIDevice* device_;
DeviceIdentifier deviceIdentifier_;
DeviceType::DeviceType deviceType_;
virtual bool refresh(void) = 0;
void setDeviceIdentifier(void);
void setDeviceType(void);
static bool isConsumer(const char* name);
};
bool initialize(void);
void terminate(void);
void push_back(ListHookedDevice::Item* newp);
void erase(IOHIDevice* p);
void refresh(void);
ListHookedDevice::Item* get(const IOHIDevice* device);
ListHookedDevice::Item* get_replaced(void);
void getDeviceInformation(BridgeDeviceInformation& out, size_t index);
static void initializeAll(IOWorkLoop& workloop);
static void terminateAll(void);
static void refreshAll(void);
static void refreshAll_timer_callback(OSObject* owner, IOTimerEventSource* sender);
protected:
ListHookedDevice(void) : last_(NULL), list_(NULL) {}
virtual ~ListHookedDevice(void) {}
const IOHIDevice* last_;
List* list_;
private:
enum {
REFRESHALL_TIMER_INTERVAL = 3000,
};
static TimerWrapper refreshAll_timer_;
};
}
#endif
<|endoftext|> |
<commit_before>// Copyright Daniel Wallin & Arvid Norberg 2009. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <boost/python.hpp>
#include <libtorrent/create_torrent.hpp>
#include <libtorrent/file_storage.hpp>
#include "libtorrent/intrusive_ptr_base.hpp"
using namespace boost::python;
using namespace libtorrent;
namespace
{
void set_hash(create_torrent& c, int p, char const* hash)
{
c.set_hash(p, sha1_hash(hash));
}
void call_python_object(boost::python::object const& obj, int i)
{
obj(i);
}
void set_piece_hashes_callback(create_torrent& c, std::string const& p
, boost::python::object cb)
{
set_piece_hashes(c, p, boost::bind(call_python_object, cb, _1));
}
}
void bind_create_torrent()
{
void (file_storage::*add_file0)(file_entry const&) = &file_storage::add_file;
void (file_storage::*add_file1)(std::string const&, size_type, int, std::time_t, std::string const&) = &file_storage::add_file;
#if TORRENT_USE_WSTRING
void (file_storage::*add_file2)(std::wstring const&, size_type, int, std::time_t, std::string const&) = &file_storage::add_file;
#endif
void (file_storage::*set_name0)(std::string const&) = &file_storage::set_name;
#if TORRENT_USE_WSTRING
void (file_storage::*set_name1)(std::wstring const&) = &file_storage::set_name;
#endif
void (*set_piece_hashes0)(create_torrent&, std::string const&) = &set_piece_hashes;
void (*add_files0)(file_storage&, std::string const&) = add_files;
class_<file_storage>("file_storage")
.def("is_valid", &file_storage::is_valid)
.def("add_file", add_file0)
.def("add_file", add_file1, (arg("path"), arg("size"), arg("flags") = 0, arg("mtime") = 0, arg("linkpath") = ""))
#if TORRENT_USE_WSTRING
.def("add_file", add_file2, (arg("path"), arg("size"), arg("flags") = 0, arg("mtime") = 0, arg("linkpath") = ""))
#endif
.def("num_files", &file_storage::num_files)
.def("at", &file_storage::at, return_internal_reference<>())
.def("total_size", &file_storage::total_size)
.def("set_num_pieces", &file_storage::set_num_pieces)
.def("num_pieces", &file_storage::num_pieces)
.def("set_piece_length", &file_storage::set_piece_length)
.def("piece_length", &file_storage::piece_length)
.def("piece_size", &file_storage::piece_size)
.def("set_name", set_name0)
#if TORRENT_USE_WSTRING
.def("set_name", set_name1)
#endif
.def("name", &file_storage::name, return_internal_reference<>())
;
class_<create_torrent>("create_torrent", no_init)
.def(init<file_storage&>())
.def(init<file_storage&, int>())
.def("generate", &create_torrent::generate)
.def("files", &create_torrent::files, return_internal_reference<>())
.def("set_comment", &create_torrent::set_comment)
.def("set_creator", &create_torrent::set_creator)
.def("set_hash", &set_hash)
.def("add_url_seed", &create_torrent::add_url_seed)
.def("add_node", &create_torrent::add_node)
.def("add_tracker", &create_torrent::add_tracker)
.def("set_priv", &create_torrent::set_priv)
.def("num_pieces", &create_torrent::num_pieces)
.def("piece_length", &create_torrent::piece_length)
.def("piece_size", &create_torrent::piece_size)
.def("priv", &create_torrent::priv)
;
def("add_files", add_files0);
def("set_piece_hashes", set_piece_hashes0);
def("set_piece_hashes", set_piece_hashes_callback);
}
<commit_msg>fixed python binding build<commit_after>// Copyright Daniel Wallin & Arvid Norberg 2009. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <boost/python.hpp>
#include <libtorrent/create_torrent.hpp>
#include <libtorrent/file_storage.hpp>
#include "libtorrent/intrusive_ptr_base.hpp"
using namespace boost::python;
using namespace libtorrent;
namespace
{
void set_hash(create_torrent& c, int p, char const* hash)
{
c.set_hash(p, sha1_hash(hash));
}
void call_python_object(boost::python::object const& obj, int i)
{
obj(i);
}
void set_piece_hashes_callback(create_torrent& c, std::string const& p
, boost::python::object cb)
{
set_piece_hashes(c, p, boost::bind(call_python_object, cb, _1));
}
}
void bind_create_torrent()
{
void (file_storage::*add_file0)(file_entry const&) = &file_storage::add_file;
void (file_storage::*add_file1)(std::string const&, size_type, int, std::time_t, std::string const&) = &file_storage::add_file;
#if TORRENT_USE_WSTRING
void (file_storage::*add_file2)(std::wstring const&, size_type, int, std::time_t, std::string const&) = &file_storage::add_file;
#endif
void (file_storage::*set_name0)(std::string const&) = &file_storage::set_name;
#if TORRENT_USE_WSTRING
void (file_storage::*set_name1)(std::wstring const&) = &file_storage::set_name;
#endif
void (*set_piece_hashes0)(create_torrent&, std::string const&) = &set_piece_hashes;
void (*add_files0)(file_storage&, std::string const&, boost::uint32_t) = add_files;
class_<file_storage>("file_storage")
.def("is_valid", &file_storage::is_valid)
.def("add_file", add_file0)
.def("add_file", add_file1, (arg("path"), arg("size"), arg("flags") = 0, arg("mtime") = 0, arg("linkpath") = ""))
#if TORRENT_USE_WSTRING
.def("add_file", add_file2, (arg("path"), arg("size"), arg("flags") = 0, arg("mtime") = 0, arg("linkpath") = ""))
#endif
.def("num_files", &file_storage::num_files)
.def("at", &file_storage::at, return_internal_reference<>())
.def("total_size", &file_storage::total_size)
.def("set_num_pieces", &file_storage::set_num_pieces)
.def("num_pieces", &file_storage::num_pieces)
.def("set_piece_length", &file_storage::set_piece_length)
.def("piece_length", &file_storage::piece_length)
.def("piece_size", &file_storage::piece_size)
.def("set_name", set_name0)
#if TORRENT_USE_WSTRING
.def("set_name", set_name1)
#endif
.def("name", &file_storage::name, return_internal_reference<>())
;
class_<create_torrent>("create_torrent", no_init)
.def(init<file_storage&>())
.def(init<file_storage&, int>())
.def("generate", &create_torrent::generate)
.def("files", &create_torrent::files, return_internal_reference<>())
.def("set_comment", &create_torrent::set_comment)
.def("set_creator", &create_torrent::set_creator)
.def("set_hash", &set_hash)
.def("add_url_seed", &create_torrent::add_url_seed)
.def("add_node", &create_torrent::add_node)
.def("add_tracker", &create_torrent::add_tracker)
.def("set_priv", &create_torrent::set_priv)
.def("num_pieces", &create_torrent::num_pieces)
.def("piece_length", &create_torrent::piece_length)
.def("piece_size", &create_torrent::piece_size)
.def("priv", &create_torrent::priv)
;
def("add_files", add_files0);
def("set_piece_hashes", set_piece_hashes0);
def("set_piece_hashes", set_piece_hashes_callback);
}
<|endoftext|> |
<commit_before><commit_msg>SSE query_error event<commit_after><|endoftext|> |
<commit_before>// Copyright Daniel Wallin 2006. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <libtorrent/torrent_handle.hpp>
#include <boost/python.hpp>
#include <boost/python/tuple.hpp>
#include <boost/lexical_cast.hpp>
#include "gil.hpp"
using namespace boost::python;
using namespace libtorrent;
namespace
{
list url_seeds(torrent_handle& handle)
{
list ret;
std::set<std::string> urls;
{
allow_threading_guard guard;
urls = handle.url_seeds();
}
for (std::set<std::string>::iterator i(urls.begin())
, end(urls.end()); i != end; ++i)
ret.append(*i);
return ret;
}
list piece_availability(torrent_handle& handle)
{
list ret;
std::vector<int> avail;
{
allow_threading_guard guard;
handle.piece_availability(avail);
}
for (std::vector<int>::iterator i(avail.begin())
, end(avail.end()); i != end; ++i)
ret.append(*i);
return ret;
}
list piece_priorities(torrent_handle& handle)
{
list ret;
std::vector<int> prio;
{
allow_threading_guard guard;
prio = handle.piece_priorities();
}
for (std::vector<int>::iterator i(prio.begin())
, end(prio.end()); i != end; ++i)
ret.append(*i);
return ret;
}
std::vector<announce_entry>::const_iterator begin_trackers(torrent_handle& i)
{
allow_threading_guard guard;
return i.trackers().begin();
}
std::vector<announce_entry>::const_iterator end_trackers(torrent_handle& i)
{
allow_threading_guard guard;
return i.trackers().end();
}
} // namespace unnamed
list file_progress(torrent_handle& handle)
{
std::vector<size_type> p;
{
allow_threading_guard guard;
p.reserve(handle.get_torrent_info().num_files());
handle.file_progress(p);
}
list result;
for (std::vector<size_type>::iterator i(p.begin()), e(p.end()); i != e; ++i)
result.append(*i);
return result;
}
list get_peer_info(torrent_handle const& handle)
{
std::vector<peer_info> pi;
{
allow_threading_guard guard;
handle.get_peer_info(pi);
}
list result;
for (std::vector<peer_info>::iterator i = pi.begin(); i != pi.end(); ++i)
result.append(*i);
return result;
}
void prioritize_pieces(torrent_handle& info, object o)
{
std::vector<int> result;
try
{
object iter_obj = object( handle<>( PyObject_GetIter( o.ptr() ) ));
while( 1 )
{
object obj = extract<object>( iter_obj.attr( "next" )() );
result.push_back(extract<int const>( obj ));
}
}
catch( error_already_set )
{
PyErr_Clear();
info.prioritize_pieces(result);
return;
}
}
void prioritize_files(torrent_handle& info, object o)
{
std::vector<int> result;
try
{
object iter_obj = object( handle<>( PyObject_GetIter( o.ptr() ) ));
while( 1 )
{
object obj = extract<object>( iter_obj.attr( "next" )() );
result.push_back(extract<int const>( obj ));
}
}
catch( error_already_set )
{
PyErr_Clear();
info.prioritize_files(result);
return;
}
}
list file_priorities(torrent_handle& handle)
{
list ret;
std::vector<int> priorities = handle.file_priorities();
for (std::vector<int>::iterator i = priorities.begin(); i != priorities.end(); ++i)
ret.append(*i);
return ret;
}
void replace_trackers(torrent_handle& info, object trackers)
{
object iter(trackers.attr("__iter__")());
std::vector<announce_entry> result;
for (;;)
{
handle<> entry(allow_null(PyIter_Next(iter.ptr())));
if (entry == handle<>())
break;
result.push_back(extract<announce_entry const&>(object(entry)));
}
allow_threading_guard guard;
info.replace_trackers(result);
}
list get_download_queue(torrent_handle& handle)
{
using boost::python::make_tuple;
list ret;
std::vector<partial_piece_info> downloading;
{
allow_threading_guard guard;
handle.get_download_queue(downloading);
}
for (std::vector<partial_piece_info>::iterator i = downloading.begin()
, end(downloading.end()); i != end; ++i)
{
dict partial_piece;
partial_piece["piece_index"] = i->piece_index;
partial_piece["blocks_in_piece"] = i->blocks_in_piece;
list block_list;
for (int k = 0; k < i->blocks_in_piece; ++k)
{
dict block_info;
block_info["state"] = i->blocks[k].state;
block_info["num_peers"] = i->blocks[k].num_peers;
block_info["bytes_progress"] = i->blocks[k].bytes_progress;
block_info["block_size"] = i->blocks[k].block_size;
block_info["peer"] = make_tuple(
boost::lexical_cast<std::string>(i->blocks[k].peer.address()), i->blocks[k].peer.port());
block_list.append(block_info);
}
partial_piece["blocks"] = block_list;
ret.append(partial_piece);
}
return ret;
}
namespace
{
tcp::endpoint tuple_to_endpoint(tuple const& t)
{
return tcp::endpoint(address::from_string(extract<std::string>(t[0])), extract<int>(t[1]));
}
}
void force_reannounce(torrent_handle& th, int s)
{
th.force_reannounce(boost::posix_time::seconds(s));
}
void connect_peer(torrent_handle& th, tuple ip, int source)
{
th.connect_peer(tuple_to_endpoint(ip), source);
}
void set_peer_upload_limit(torrent_handle& th, tuple const& ip, int limit)
{
th.set_peer_upload_limit(tuple_to_endpoint(ip), limit);
}
void set_peer_download_limit(torrent_handle& th, tuple const& ip, int limit)
{
th.set_peer_download_limit(tuple_to_endpoint(ip), limit);
}
void add_piece(torrent_handle& th, int piece, char const *data, int flags)
{
th.add_piece(piece, data, flags);
}
void bind_torrent_handle()
{
void (torrent_handle::*force_reannounce0)() const = &torrent_handle::force_reannounce;
int (torrent_handle::*piece_priority0)(int) const = &torrent_handle::piece_priority;
void (torrent_handle::*piece_priority1)(int, int) const = &torrent_handle::piece_priority;
void (torrent_handle::*move_storage0)(fs::path const&) const = &torrent_handle::move_storage;
void (torrent_handle::*move_storage1)(fs::wpath const&) const = &torrent_handle::move_storage;
void (torrent_handle::*rename_file0)(int, fs::path const&) const = &torrent_handle::rename_file;
void (torrent_handle::*rename_file1)(int, fs::wpath const&) const = &torrent_handle::rename_file;
#ifndef TORRENT_DISABLE_RESOLVE_COUNTRIES
bool (torrent_handle::*resolve_countries0)() const = &torrent_handle::resolve_countries;
void (torrent_handle::*resolve_countries1)(bool) = &torrent_handle::resolve_countries;
#endif
return_value_policy<copy_const_reference> copy;
#define _ allow_threads
class_<torrent_handle>("torrent_handle")
.def("get_peer_info", get_peer_info)
.def("status", _(&torrent_handle::status))
.def("get_download_queue", get_download_queue)
.def("file_progress", file_progress)
.def("trackers", range(begin_trackers, end_trackers))
.def("replace_trackers", replace_trackers)
.def("add_url_seed", _(&torrent_handle::add_url_seed))
.def("remove_url_seed", _(&torrent_handle::remove_url_seed))
.def("url_seeds", url_seeds)
.def("has_metadata", _(&torrent_handle::has_metadata))
.def("get_torrent_info", _(&torrent_handle::get_torrent_info), return_internal_reference<>())
.def("is_valid", _(&torrent_handle::is_valid))
.def("is_seed", _(&torrent_handle::is_seed))
.def("is_finished", _(&torrent_handle::is_finished))
.def("is_paused", _(&torrent_handle::is_paused))
.def("pause", _(&torrent_handle::pause))
.def("resume", _(&torrent_handle::resume))
.def("clear_error", _(&torrent_handle::clear_error))
.def("is_auto_managed", _(&torrent_handle::is_auto_managed))
.def("auto_managed", _(&torrent_handle::auto_managed))
.def("queue_position", _(&torrent_handle::queue_position))
.def("queue_position_up", _(&torrent_handle::queue_position_up))
.def("queue_position_down", _(&torrent_handle::queue_position_down))
.def("queue_position_top", _(&torrent_handle::queue_position_top))
.def("queue_position_bottom", _(&torrent_handle::queue_position_bottom))
#ifndef TORRENT_DISABLE_RESOLVE_COUNTRIES
.def("resolve_countries", _(resolve_countries0))
.def("resolve_countries", _(resolve_countries1))
#endif
// deprecated
#ifndef TORRENT_NO_DEPRECATE
.def("filter_piece", _(&torrent_handle::filter_piece))
.def("is_piece_filtered", _(&torrent_handle::is_piece_filtered))
.def("write_resume_data", _(&torrent_handle::write_resume_data))
#endif
.def("add_piece", add_piece)
.def("piece_availability", piece_availability)
.def("piece_priority", _(piece_priority0))
.def("piece_priority", _(piece_priority1))
.def("prioritize_pieces", prioritize_pieces)
.def("piece_prioritize", piece_priorities)
.def("prioritize_files", prioritize_files)
.def("file_priorities", file_priorities)
.def("use_interface", &torrent_handle::use_interface)
.def("save_resume_data", _(&torrent_handle::save_resume_data))
.def("force_reannounce", _(force_reannounce0))
.def("force_reannounce", force_reannounce)
.def("scrape_tracker", _(&torrent_handle::scrape_tracker))
.def("name", _(&torrent_handle::name))
.def("set_upload_limit", _(&torrent_handle::set_upload_limit))
.def("upload_limit", _(&torrent_handle::upload_limit))
.def("set_download_limit", _(&torrent_handle::set_download_limit))
.def("download_limit", _(&torrent_handle::download_limit))
.def("set_sequential_download", _(&torrent_handle::set_sequential_download))
.def("set_peer_upload_limit", set_peer_upload_limit)
.def("set_peer_download_limit", set_peer_download_limit)
.def("connect_peer", connect_peer)
.def("set_ratio", _(&torrent_handle::set_ratio))
.def("save_path", _(&torrent_handle::save_path))
.def("set_max_uploads", _(&torrent_handle::set_max_uploads))
.def("set_max_connections", _(&torrent_handle::set_max_connections))
.def("set_tracker_login", _(&torrent_handle::set_tracker_login))
.def("move_storage", _(move_storage0))
.def("move_storage", _(move_storage1))
.def("info_hash", _(&torrent_handle::info_hash))
.def("force_recheck", _(&torrent_handle::force_recheck))
.def("rename_file", _(rename_file0))
.def("rename_file", _(rename_file1))
;
}
<commit_msg>added read_piece() to python binding<commit_after>// Copyright Daniel Wallin 2006. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <libtorrent/torrent_handle.hpp>
#include <boost/python.hpp>
#include <boost/python/tuple.hpp>
#include <boost/lexical_cast.hpp>
#include "gil.hpp"
using namespace boost::python;
using namespace libtorrent;
namespace
{
list url_seeds(torrent_handle& handle)
{
list ret;
std::set<std::string> urls;
{
allow_threading_guard guard;
urls = handle.url_seeds();
}
for (std::set<std::string>::iterator i(urls.begin())
, end(urls.end()); i != end; ++i)
ret.append(*i);
return ret;
}
list piece_availability(torrent_handle& handle)
{
list ret;
std::vector<int> avail;
{
allow_threading_guard guard;
handle.piece_availability(avail);
}
for (std::vector<int>::iterator i(avail.begin())
, end(avail.end()); i != end; ++i)
ret.append(*i);
return ret;
}
list piece_priorities(torrent_handle& handle)
{
list ret;
std::vector<int> prio;
{
allow_threading_guard guard;
prio = handle.piece_priorities();
}
for (std::vector<int>::iterator i(prio.begin())
, end(prio.end()); i != end; ++i)
ret.append(*i);
return ret;
}
std::vector<announce_entry>::const_iterator begin_trackers(torrent_handle& i)
{
allow_threading_guard guard;
return i.trackers().begin();
}
std::vector<announce_entry>::const_iterator end_trackers(torrent_handle& i)
{
allow_threading_guard guard;
return i.trackers().end();
}
} // namespace unnamed
list file_progress(torrent_handle& handle)
{
std::vector<size_type> p;
{
allow_threading_guard guard;
p.reserve(handle.get_torrent_info().num_files());
handle.file_progress(p);
}
list result;
for (std::vector<size_type>::iterator i(p.begin()), e(p.end()); i != e; ++i)
result.append(*i);
return result;
}
list get_peer_info(torrent_handle const& handle)
{
std::vector<peer_info> pi;
{
allow_threading_guard guard;
handle.get_peer_info(pi);
}
list result;
for (std::vector<peer_info>::iterator i = pi.begin(); i != pi.end(); ++i)
result.append(*i);
return result;
}
void prioritize_pieces(torrent_handle& info, object o)
{
std::vector<int> result;
try
{
object iter_obj = object( handle<>( PyObject_GetIter( o.ptr() ) ));
while( 1 )
{
object obj = extract<object>( iter_obj.attr( "next" )() );
result.push_back(extract<int const>( obj ));
}
}
catch( error_already_set )
{
PyErr_Clear();
info.prioritize_pieces(result);
return;
}
}
void prioritize_files(torrent_handle& info, object o)
{
std::vector<int> result;
try
{
object iter_obj = object( handle<>( PyObject_GetIter( o.ptr() ) ));
while( 1 )
{
object obj = extract<object>( iter_obj.attr( "next" )() );
result.push_back(extract<int const>( obj ));
}
}
catch( error_already_set )
{
PyErr_Clear();
info.prioritize_files(result);
return;
}
}
list file_priorities(torrent_handle& handle)
{
list ret;
std::vector<int> priorities = handle.file_priorities();
for (std::vector<int>::iterator i = priorities.begin(); i != priorities.end(); ++i)
ret.append(*i);
return ret;
}
void replace_trackers(torrent_handle& info, object trackers)
{
object iter(trackers.attr("__iter__")());
std::vector<announce_entry> result;
for (;;)
{
handle<> entry(allow_null(PyIter_Next(iter.ptr())));
if (entry == handle<>())
break;
result.push_back(extract<announce_entry const&>(object(entry)));
}
allow_threading_guard guard;
info.replace_trackers(result);
}
list get_download_queue(torrent_handle& handle)
{
using boost::python::make_tuple;
list ret;
std::vector<partial_piece_info> downloading;
{
allow_threading_guard guard;
handle.get_download_queue(downloading);
}
for (std::vector<partial_piece_info>::iterator i = downloading.begin()
, end(downloading.end()); i != end; ++i)
{
dict partial_piece;
partial_piece["piece_index"] = i->piece_index;
partial_piece["blocks_in_piece"] = i->blocks_in_piece;
list block_list;
for (int k = 0; k < i->blocks_in_piece; ++k)
{
dict block_info;
block_info["state"] = i->blocks[k].state;
block_info["num_peers"] = i->blocks[k].num_peers;
block_info["bytes_progress"] = i->blocks[k].bytes_progress;
block_info["block_size"] = i->blocks[k].block_size;
block_info["peer"] = make_tuple(
boost::lexical_cast<std::string>(i->blocks[k].peer.address()), i->blocks[k].peer.port());
block_list.append(block_info);
}
partial_piece["blocks"] = block_list;
ret.append(partial_piece);
}
return ret;
}
namespace
{
tcp::endpoint tuple_to_endpoint(tuple const& t)
{
return tcp::endpoint(address::from_string(extract<std::string>(t[0])), extract<int>(t[1]));
}
}
void force_reannounce(torrent_handle& th, int s)
{
th.force_reannounce(boost::posix_time::seconds(s));
}
void connect_peer(torrent_handle& th, tuple ip, int source)
{
th.connect_peer(tuple_to_endpoint(ip), source);
}
void set_peer_upload_limit(torrent_handle& th, tuple const& ip, int limit)
{
th.set_peer_upload_limit(tuple_to_endpoint(ip), limit);
}
void set_peer_download_limit(torrent_handle& th, tuple const& ip, int limit)
{
th.set_peer_download_limit(tuple_to_endpoint(ip), limit);
}
void add_piece(torrent_handle& th, int piece, char const *data, int flags)
{
th.add_piece(piece, data, flags);
}
void bind_torrent_handle()
{
void (torrent_handle::*force_reannounce0)() const = &torrent_handle::force_reannounce;
int (torrent_handle::*piece_priority0)(int) const = &torrent_handle::piece_priority;
void (torrent_handle::*piece_priority1)(int, int) const = &torrent_handle::piece_priority;
void (torrent_handle::*move_storage0)(fs::path const&) const = &torrent_handle::move_storage;
void (torrent_handle::*move_storage1)(fs::wpath const&) const = &torrent_handle::move_storage;
void (torrent_handle::*rename_file0)(int, fs::path const&) const = &torrent_handle::rename_file;
void (torrent_handle::*rename_file1)(int, fs::wpath const&) const = &torrent_handle::rename_file;
#ifndef TORRENT_DISABLE_RESOLVE_COUNTRIES
bool (torrent_handle::*resolve_countries0)() const = &torrent_handle::resolve_countries;
void (torrent_handle::*resolve_countries1)(bool) = &torrent_handle::resolve_countries;
#endif
return_value_policy<copy_const_reference> copy;
#define _ allow_threads
class_<torrent_handle>("torrent_handle")
.def("get_peer_info", get_peer_info)
.def("status", _(&torrent_handle::status))
.def("get_download_queue", get_download_queue)
.def("file_progress", file_progress)
.def("trackers", range(begin_trackers, end_trackers))
.def("replace_trackers", replace_trackers)
.def("add_url_seed", _(&torrent_handle::add_url_seed))
.def("remove_url_seed", _(&torrent_handle::remove_url_seed))
.def("url_seeds", url_seeds)
.def("has_metadata", _(&torrent_handle::has_metadata))
.def("get_torrent_info", _(&torrent_handle::get_torrent_info), return_internal_reference<>())
.def("is_valid", _(&torrent_handle::is_valid))
.def("is_seed", _(&torrent_handle::is_seed))
.def("is_finished", _(&torrent_handle::is_finished))
.def("is_paused", _(&torrent_handle::is_paused))
.def("pause", _(&torrent_handle::pause))
.def("resume", _(&torrent_handle::resume))
.def("clear_error", _(&torrent_handle::clear_error))
.def("is_auto_managed", _(&torrent_handle::is_auto_managed))
.def("auto_managed", _(&torrent_handle::auto_managed))
.def("queue_position", _(&torrent_handle::queue_position))
.def("queue_position_up", _(&torrent_handle::queue_position_up))
.def("queue_position_down", _(&torrent_handle::queue_position_down))
.def("queue_position_top", _(&torrent_handle::queue_position_top))
.def("queue_position_bottom", _(&torrent_handle::queue_position_bottom))
#ifndef TORRENT_DISABLE_RESOLVE_COUNTRIES
.def("resolve_countries", _(resolve_countries0))
.def("resolve_countries", _(resolve_countries1))
#endif
// deprecated
#ifndef TORRENT_NO_DEPRECATE
.def("filter_piece", _(&torrent_handle::filter_piece))
.def("is_piece_filtered", _(&torrent_handle::is_piece_filtered))
.def("write_resume_data", _(&torrent_handle::write_resume_data))
#endif
.def("add_piece", add_piece)
.def("read_piece", _(&torrent_handle::read_piece))
.def("piece_availability", piece_availability)
.def("piece_priority", _(piece_priority0))
.def("piece_priority", _(piece_priority1))
.def("prioritize_pieces", prioritize_pieces)
.def("piece_prioritize", piece_priorities)
.def("prioritize_files", prioritize_files)
.def("file_priorities", file_priorities)
.def("use_interface", &torrent_handle::use_interface)
.def("save_resume_data", _(&torrent_handle::save_resume_data))
.def("force_reannounce", _(force_reannounce0))
.def("force_reannounce", force_reannounce)
.def("scrape_tracker", _(&torrent_handle::scrape_tracker))
.def("name", _(&torrent_handle::name))
.def("set_upload_limit", _(&torrent_handle::set_upload_limit))
.def("upload_limit", _(&torrent_handle::upload_limit))
.def("set_download_limit", _(&torrent_handle::set_download_limit))
.def("download_limit", _(&torrent_handle::download_limit))
.def("set_sequential_download", _(&torrent_handle::set_sequential_download))
.def("set_peer_upload_limit", set_peer_upload_limit)
.def("set_peer_download_limit", set_peer_download_limit)
.def("connect_peer", connect_peer)
.def("set_ratio", _(&torrent_handle::set_ratio))
.def("save_path", _(&torrent_handle::save_path))
.def("set_max_uploads", _(&torrent_handle::set_max_uploads))
.def("set_max_connections", _(&torrent_handle::set_max_connections))
.def("set_tracker_login", _(&torrent_handle::set_tracker_login))
.def("move_storage", _(move_storage0))
.def("move_storage", _(move_storage1))
.def("info_hash", _(&torrent_handle::info_hash))
.def("force_recheck", _(&torrent_handle::force_recheck))
.def("rename_file", _(rename_file0))
.def("rename_file", _(rename_file1))
;
}
<|endoftext|> |
<commit_before>#include <TF3.h>
#include <TTree.h>
#include <TStopwatch.h>
#include "X.h"
#include "Units.h"
using namespace GeFiCa;
X::X(int nx, const char *name, const char *title) : TNamed(name,title), V0(0),
V1(2e3*volt), n1(nx), n(nx), MaxIterations(9999), Nsor(0), Csor(1.95),
Precision(1e-7*volt), fE2(0), fE3(0), fC2(0), fC3(0),
fdC2p(0), fdC2m(0), fdC3p(0), fdC3m(0)
{
if (n<10) { Warning("X","n<10, set it to 11"); n=11; n1=11; }
fV=new double[n];
fE1=new double[n];
fE2=new double[n];
fE3=new double[n];
fC1=new double[n];
fC2=new double[n];
fC3=new double[n];
fdC1p=new double[n];
fdC1m=new double[n];
fdC2m=new double[n];
fdC2p=new double[n];
fdC3p=new double[n];
fdC3m=new double[n];
fIsFixed=new bool[n];
fIsDepleted=new bool[n];
fImpurity=new double[n];
for (int i=0;i<n;i++) {
fV[i]=0;
fE1[i]=0; fE2[i]=0; fE3[i]=0;
fC1[i]=0; fC2[i]=0; fC3[i]=0;
fdC1m[i]=0; fdC1p[i]=0;
fdC2m[i]=0; fdC2p[i]=0;
fdC3m[i]=0; fdC3p[i]=0;
fIsFixed[i]=false;
fIsDepleted[i]=true;
fImpurity[i]=0;
}
fTree=NULL; fImpDist=NULL;
}
//_____________________________________________________________________________
//
X::~X()
{
if (fV) delete[] fV;
if (fE1) delete[] fE1;
if (fC1) delete[] fC1;
if (fdC1p) delete[] fdC1p;
if (fdC1m) delete[] fdC1m;
if (fIsFixed) delete[] fIsFixed;
if (fImpurity) delete[] fImpurity;
if (fIsDepleted) delete[] fIsDepleted;
}
//_____________________________________________________________________________
//
bool X::Analytic()
{
Info("Analytic", "There is no analytic solution for this setup");
return false;
}
//_____________________________________________________________________________
//
X& X::operator+=(GeFiCa::X *other)
{
if (n!=other->n) {
Warning("+=",
"Only same type of detector can be added together! Do nothing.");
return *this;
}
for (int i=0; i<n; i++) {
fV[i]=fV[i]+other->fV[i];
fImpurity[i]+=other->fImpurity[i];
}
V0+=other->V0; V1+=other->V1;
return *this;
}
//_____________________________________________________________________________
//
X& X::operator*=(double p)
{
for (int i=0; i<n; i++) fV[i]=fV[i]*p;
V0*=p; V1*=p;
return *this;
}
//_____________________________________________________________________________
//
int X::GetIdxOfMaxV()
{
double max=fV[0];
int maxn=0;
for(int i=1;i<n;i++) {
if(fV[i]>max) {
maxn=i;
max=fV[i];
}
}
return maxn;
}
//_____________________________________________________________________________
//
int X::GetIdxOfMinV()
{
double min=fV[0];
int minn=0;
for(int i=1;i<n;i++) {
if(fV[i]<min) {
minn=i;
min=fV[i];
}
}
return minn;
}
//_____________________________________________________________________________
//
bool X::IsDepleted()
{
for(int i=0;i<n;i++) {
DoSOR2(i); // calculate one more time in case of
//adding two fields together, one is depleted, the other is not
if (!fIsDepleted[i]) return false;
}
return true;
}
//_____________________________________________________________________________
//
void X::SetStepLength(double stepLength)
{
for (int i=n;i-->0;) {
fIsFixed[i]=false;
fC1[i]=i*stepLength;
fdC1p[i]=stepLength;
fdC1m[i]=stepLength;
}
}
//_____________________________________________________________________________
//
int* X::FindSurroundingMatrix(int idx)
{
int *tmp=new int[3];
tmp[0]=idx;
if(idx-1<0)tmp[1]=1;
else tmp[1]=idx-1;
if(idx+1>=n)tmp[2]=n-2;
else tmp[2]=idx+1;
return tmp;
}
//_____________________________________________________________________________
//
bool X::CalculatePotential(EMethod method)
{
if (fdC1p[0]==0) Initialize(); // setup and initialize grid if it's not done
if (fImpDist && fImpurity[0]==0) // set impurity values if it's not done yet
for (int i=n;i-->0;) fImpurity[i]=fImpDist->Eval(fC1[i], fC2[i], fC3[i]);
if (method==kAnalytic) return Analytic();
Info("CalculatePotential","Start SOR...");
TStopwatch watch; watch.Start();
double cp=1; // current presision
while (Nsor<MaxIterations) {
if (Nsor%100==0) Printf("%4d steps, precision: %.1e (target: %.0e)",
Nsor, cp, Precision);
double XUpSum=0;
double XDownSum=0;
for (int i=n-1;i>=0;i--) {
double old=fV[i];
DoSOR2(i);
if(old>0)XDownSum+=old;
else XDownSum-=old;
double diff=fV[i]-old;
if(diff>0)XUpSum+=(diff);
else XUpSum-=(diff);
}
cp = XUpSum/XDownSum;
Nsor++;
if (cp<Precision) break;
}
for (int i=0; i<n; i++) if (!CalculateField(i)) return false;
Printf("%4d steps, precision: %.1e (target: %.0e)", Nsor, cp, Precision);
Info("CalculatePotential", "CPU time: %.1f s", watch.CpuTime());
return true;
}
//_____________________________________________________________________________
//
void X::DoSOR2(int idx)
{
// 2nd-order Runge-Kutta Successive Over-Relaxation
if (fIsFixed[idx])return ;
double rho=-fImpurity[idx]*Qe;
double h2=fdC1m[idx];
double h3=fdC1p[idx];
double p2=fV[idx-1];
double p3=fV[idx+1];
double tmp=-rho/epsilon*h2*h3/2
+ (h3*fV[idx-1]+h2*fV[idx+1])/(h2+h3);
//find minmium and maxnium of all five grid, the new one should not go overthem.
//find min
double min=p2;
double max=p2;
if(min>p3)min=p3;
//find max
if(max<p3)max=p3;
//if tmp is greater or smaller than max and min, set tmp to it.
//fV[idx]=Csor*(tmp-fV[idx])+fV[idx];
double oldP=fV[idx];
tmp=Csor*(tmp-oldP)+oldP;
if(tmp<min) {
fV[idx]=min;
fIsDepleted[idx]=false;
} else if(tmp>max) {
fV[idx]=max;
fIsDepleted[idx]=false;
} else
fIsDepleted[idx]=true;
if(fIsDepleted[idx]||V0==V1) fV[idx]=tmp;
}
//_____________________________________________________________________________
//
int X::FindIdx(double tarx,int begin,int end)
{
//search using binary search
if (begin>=end)return end;
int mid=(begin+end)/2;
if(fC1[mid]>=tarx)return FindIdx(tarx,begin,mid);
else return FindIdx(tarx,mid+1,end);
}
//_____________________________________________________________________________
//
double X::GetData(double tarx, EOutput output)
{
int idx=FindIdx(tarx,0,n-1);
if (idx==n) {
switch (output) {
case 0:return fImpurity[idx];
case 2:return fE1[idx];
case 1:return fV[idx];
default: return -1;
}
}
double ab=(-tarx+fC1[idx])/fdC1p[idx];
double aa=1-ab;
switch(output) {
case 2:return fE1[idx]*ab+fE1[idx-1]*aa;
case 1:return fV[idx]*ab+fC1[idx-1]*aa;
case 0:return fImpurity[idx]*ab+fImpurity[idx-1]*aa;
default: return -1;
}
return -1;
}
//_____________________________________________________________________________
//
bool X::CalculateField(int idx)
{
if (fdC1p[idx]==0 || fdC1m[idx]==0) return false;
if (idx%n1==0) // C1 lower boundary
fE1[idx]=(fV[idx]-fV[idx+1])/fdC1p[idx];
else if (idx%n1==n1-1) // C1 upper boundary
fE1[idx]=(fV[idx]-fV[idx-1])/fdC1m[idx];
else // bulk
fE1[idx]=(fV[idx-1]-fV[idx+1])/(fdC1m[idx]+fdC1p[idx]);
return true;
}
//_____________________________________________________________________________
//
double X::GetCapacitance()
{
Info("GetCapacitance","Start...");
// set impurity to zero
double *tmpImpurity=fImpurity;
for (int i=0;i<n;i++) {
if (fImpurity[i]!=0) {
//impurity not clear,return
//return -1;
fImpurity=new double[n];
for (int j=0;j<n;j++) {
fImpurity[j]=0;
if (!fIsFixed[j] && !fIsDepleted[j]) fIsFixed[j]=true;
}
break;
}
}
// calculate potential without impurity
CalculatePotential(GeFiCa::kSOR2);
// set impurity back
if(fImpurity!=tmpImpurity) delete []fImpurity;
fImpurity=tmpImpurity;
// calculate C based on CV^2/2 = epsilon int E^2 dx^3 / 2
double dV=V0-V1; if(dV<0)dV=-dV;
double SumofElectricField=0;
for(int i=0;i<n;i++) {
SumofElectricField+=fE1[i]*fE1[i]*fdC1p[i]*cm*cm;
if (!fIsDepleted[i]) fIsFixed[i]=false;
}
Info("GetCapacitance","Done.");
return SumofElectricField*epsilon/dV/dV;
}
//_____________________________________________________________________________
//
TTree* X::GetTree(bool createNew)
{
if (fTree!=NULL) {
if (createNew) delete fTree;
else return fTree;
}
bool b,d; double e1,c1,v,dc1p,dc1m,i;
// define tree
fTree=new TTree("t","field data");
fTree->Branch("v",&v,"v/D");
fTree->Branch("e1",&e1,"e1/D");
fTree->Branch("c1",&c1,"c1/D");
fTree->Branch("dc1p",&dc1p,"dc1p/D"); // step length to next point
fTree->Branch("dc1m",&dc1m,"dc1m/D"); // step length to previous point
fTree->Branch("b",&b,"b/O"); // boundary flag
fTree->Branch("d",&d,"d/O"); // depletion flag
fTree->Branch("i",&i,"i/D"); // impurity
// fill tree
if (fdC1p[0]==0) Initialize(); // setup & initialize grid
if (fImpDist && fImpurity[0]==0) // set impurity values if it's not done yet
for (int i=n;i-->0;) fImpurity[i]=fImpDist->Eval(fC1[i], fC2[i], fC3[i]);
for (int j=0; j<n; j++) {
v = fV[j];
e1= fE1[j];
c1= fC1[j];
i = fImpurity[j];
b = fIsFixed[j];
d = fIsDepleted[j];
dc1p=fdC1p[j];
dc1m=fdC1m[j];
fTree->Fill();
}
// return tree
fTree->ResetBranchAddresses(); // disconnect from local variables
return fTree;
}
<commit_msg>set gStyle in X constructor<commit_after>#include <TF3.h>
#include <TTree.h>
#include <TStyle.h>
#include <TStopwatch.h>
#include "X.h"
#include "Units.h"
using namespace GeFiCa;
X::X(int nx, const char *name, const char *title) : TNamed(name,title), V0(0),
V1(2e3*volt), n1(nx), n(nx), MaxIterations(5000), Nsor(0), Csor(1.95),
Precision(1e-7*volt)
{
if (n<10) { Warning("X","n<10, set it to 11"); n=11; n1=11; }
fV=new double[n];
fE1=new double[n]; fE2=new double[n]; fE3=new double[n];
fC1=new double[n]; fC2=new double[n]; fC3=new double[n];
fdC1p=new double[n]; fdC1m=new double[n];
fdC2p=new double[n]; fdC2m=new double[n];
fdC3p=new double[n]; fdC3m=new double[n];
fIsFixed=new bool[n];
fIsDepleted=new bool[n];
fImpurity=new double[n];
for (int i=0;i<n;i++) {
fV[i]=0;
fE1[i]=0; fE2[i]=0; fE3[i]=0;
fC1[i]=0; fC2[i]=0; fC3[i]=0;
fdC1m[i]=0; fdC1p[i]=0;
fdC2m[i]=0; fdC2p[i]=0;
fdC3m[i]=0; fdC3p[i]=0;
fIsFixed[i]=false;
fIsDepleted[i]=true;
fImpurity[i]=0;
}
fTree=NULL; fImpDist=NULL;
gROOT->SetStyle("Plain"); // pick up a good default style to modify
gStyle->SetLegendBorderSize(0);
gStyle->SetLegendFont(132);
gStyle->SetLabelFont(132,"XYZ");
gStyle->SetTitleFont(132,"XYZ");
gStyle->SetLabelSize(0.05,"XYZ");
gStyle->SetTitleSize(0.05,"XYZ");
gStyle->SetTitleOffset(-0.4,"Z");
gStyle->SetPadTopMargin(0.02);
}
//_____________________________________________________________________________
//
X::~X()
{
if (fV) delete[] fV;
if (fE1) delete[] fE1;
if (fC1) delete[] fC1;
if (fdC1p) delete[] fdC1p;
if (fdC1m) delete[] fdC1m;
if (fIsFixed) delete[] fIsFixed;
if (fImpurity) delete[] fImpurity;
if (fIsDepleted) delete[] fIsDepleted;
}
//_____________________________________________________________________________
//
bool X::Analytic()
{
Info("Analytic", "There is no analytic solution for this setup");
return false;
}
//_____________________________________________________________________________
//
X& X::operator+=(GeFiCa::X *other)
{
if (n!=other->n) {
Warning("+=",
"Only same type of detector can be added together! Do nothing.");
return *this;
}
for (int i=0; i<n; i++) {
fV[i]=fV[i]+other->fV[i];
fImpurity[i]+=other->fImpurity[i];
}
V0+=other->V0; V1+=other->V1;
return *this;
}
//_____________________________________________________________________________
//
X& X::operator*=(double p)
{
for (int i=0; i<n; i++) fV[i]=fV[i]*p;
V0*=p; V1*=p;
return *this;
}
//_____________________________________________________________________________
//
int X::GetIdxOfMaxV()
{
double max=fV[0];
int maxn=0;
for(int i=1;i<n;i++) {
if(fV[i]>max) {
maxn=i;
max=fV[i];
}
}
return maxn;
}
//_____________________________________________________________________________
//
int X::GetIdxOfMinV()
{
double min=fV[0];
int minn=0;
for(int i=1;i<n;i++) {
if(fV[i]<min) {
minn=i;
min=fV[i];
}
}
return minn;
}
//_____________________________________________________________________________
//
bool X::IsDepleted()
{
for(int i=0;i<n;i++) {
DoSOR2(i); // calculate one more time in case of
//adding two fields together, one is depleted, the other is not
if (!fIsDepleted[i]) return false;
}
return true;
}
//_____________________________________________________________________________
//
void X::SetStepLength(double stepLength)
{
for (int i=n;i-->0;) {
fIsFixed[i]=false;
fC1[i]=i*stepLength;
fdC1p[i]=stepLength;
fdC1m[i]=stepLength;
}
}
//_____________________________________________________________________________
//
int* X::FindSurroundingMatrix(int idx)
{
int *tmp=new int[3];
tmp[0]=idx;
if(idx-1<0)tmp[1]=1;
else tmp[1]=idx-1;
if(idx+1>=n)tmp[2]=n-2;
else tmp[2]=idx+1;
return tmp;
}
//_____________________________________________________________________________
//
bool X::CalculatePotential(EMethod method)
{
if (fdC1p[0]==0) Initialize(); // setup and initialize grid if it's not done
if (fImpDist && fImpurity[0]==0) // set impurity values if it's not done yet
for (int i=n;i-->0;) fImpurity[i]=fImpDist->Eval(fC1[i], fC2[i], fC3[i]);
if (method==kAnalytic) return Analytic();
Info("CalculatePotential","Start SOR...");
TStopwatch watch; watch.Start();
double cp=1; // current presision
while (Nsor<MaxIterations) {
if (Nsor%100==0) Printf("%4d steps, precision: %.1e (target: %.0e)",
Nsor, cp, Precision);
double XUpSum=0;
double XDownSum=0;
for (int i=n-1;i>=0;i--) {
double old=fV[i];
DoSOR2(i);
if(old>0)XDownSum+=old;
else XDownSum-=old;
double diff=fV[i]-old;
if(diff>0)XUpSum+=(diff);
else XUpSum-=(diff);
}
cp = XUpSum/XDownSum;
Nsor++;
if (cp<Precision) break;
}
for (int i=0; i<n; i++) if (!CalculateField(i)) return false;
Printf("%4d steps, precision: %.1e (target: %.0e)", Nsor, cp, Precision);
Info("CalculatePotential", "CPU time: %.1f s", watch.CpuTime());
return true;
}
//_____________________________________________________________________________
//
void X::DoSOR2(int idx)
{
// 2nd-order Runge-Kutta Successive Over-Relaxation
if (fIsFixed[idx])return ;
double rho=-fImpurity[idx]*Qe;
double h2=fdC1m[idx];
double h3=fdC1p[idx];
double p2=fV[idx-1];
double p3=fV[idx+1];
double tmp=-rho/epsilon*h2*h3/2
+ (h3*fV[idx-1]+h2*fV[idx+1])/(h2+h3);
//find minmium and maxnium of all five grid, the new one should not go overthem.
//find min
double min=p2;
double max=p2;
if(min>p3)min=p3;
//find max
if(max<p3)max=p3;
//if tmp is greater or smaller than max and min, set tmp to it.
//fV[idx]=Csor*(tmp-fV[idx])+fV[idx];
double oldP=fV[idx];
tmp=Csor*(tmp-oldP)+oldP;
if(tmp<min) {
fV[idx]=min;
fIsDepleted[idx]=false;
} else if(tmp>max) {
fV[idx]=max;
fIsDepleted[idx]=false;
} else
fIsDepleted[idx]=true;
if(fIsDepleted[idx]||V0==V1) fV[idx]=tmp;
}
//_____________________________________________________________________________
//
int X::FindIdx(double tarx,int begin,int end)
{
//search using binary search
if (begin>=end)return end;
int mid=(begin+end)/2;
if(fC1[mid]>=tarx)return FindIdx(tarx,begin,mid);
else return FindIdx(tarx,mid+1,end);
}
//_____________________________________________________________________________
//
double X::GetData(double tarx, EOutput output)
{
int idx=FindIdx(tarx,0,n-1);
if (idx==n) {
switch (output) {
case 0:return fImpurity[idx];
case 2:return fE1[idx];
case 1:return fV[idx];
default: return -1;
}
}
double ab=(-tarx+fC1[idx])/fdC1p[idx];
double aa=1-ab;
switch(output) {
case 2:return fE1[idx]*ab+fE1[idx-1]*aa;
case 1:return fV[idx]*ab+fC1[idx-1]*aa;
case 0:return fImpurity[idx]*ab+fImpurity[idx-1]*aa;
default: return -1;
}
return -1;
}
//_____________________________________________________________________________
//
bool X::CalculateField(int idx)
{
if (fdC1p[idx]==0 || fdC1m[idx]==0) return false;
if (idx%n1==0) // C1 lower boundary
fE1[idx]=(fV[idx]-fV[idx+1])/fdC1p[idx];
else if (idx%n1==n1-1) // C1 upper boundary
fE1[idx]=(fV[idx]-fV[idx-1])/fdC1m[idx];
else // bulk
fE1[idx]=(fV[idx-1]-fV[idx+1])/(fdC1m[idx]+fdC1p[idx]);
return true;
}
//_____________________________________________________________________________
//
double X::GetCapacitance()
{
Info("GetCapacitance","Start...");
// set impurity to zero
double *tmpImpurity=fImpurity;
for (int i=0;i<n;i++) {
if (fImpurity[i]!=0) {
//impurity not clear,return
//return -1;
fImpurity=new double[n];
for (int j=0;j<n;j++) {
fImpurity[j]=0;
if (!fIsFixed[j] && !fIsDepleted[j]) fIsFixed[j]=true;
}
break;
}
}
// calculate potential without impurity
CalculatePotential(GeFiCa::kSOR2);
// set impurity back
if(fImpurity!=tmpImpurity) delete []fImpurity;
fImpurity=tmpImpurity;
// calculate C based on CV^2/2 = epsilon int E^2 dx^3 / 2
double dV=V0-V1; if(dV<0)dV=-dV;
double SumofElectricField=0;
for(int i=0;i<n;i++) {
SumofElectricField+=fE1[i]*fE1[i]*fdC1p[i]*cm*cm;
if (!fIsDepleted[i]) fIsFixed[i]=false;
}
Info("GetCapacitance","Done.");
return SumofElectricField*epsilon/dV/dV;
}
//_____________________________________________________________________________
//
TTree* X::GetTree(bool createNew)
{
if (fTree!=NULL) {
if (createNew) delete fTree;
else return fTree;
}
bool b,d; double e1,c1,v,dc1p,dc1m,i;
// define tree
fTree=new TTree("t","field data");
fTree->Branch("v",&v,"v/D");
fTree->Branch("e1",&e1,"e1/D");
fTree->Branch("c1",&c1,"c1/D");
fTree->Branch("dc1p",&dc1p,"dc1p/D"); // step length to next point
fTree->Branch("dc1m",&dc1m,"dc1m/D"); // step length to previous point
fTree->Branch("b",&b,"b/O"); // boundary flag
fTree->Branch("d",&d,"d/O"); // depletion flag
fTree->Branch("i",&i,"i/D"); // impurity
// fill tree
if (fdC1p[0]==0) Initialize(); // setup & initialize grid
if (fImpDist && fImpurity[0]==0) // set impurity values if it's not done yet
for (int i=n;i-->0;) fImpurity[i]=fImpDist->Eval(fC1[i], fC2[i], fC3[i]);
for (int j=0; j<n; j++) {
v = fV[j];
e1= fE1[j];
c1= fC1[j];
i = fImpurity[j];
b = fIsFixed[j];
d = fIsDepleted[j];
dc1p=fdC1p[j];
dc1m=fdC1m[j];
fTree->Fill();
}
// return tree
fTree->ResetBranchAddresses(); // disconnect from local variables
return fTree;
}
<|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 ---------------------------------------------------------------
#include "srchxtra.hxx"
#include <tools/rcid.h>
#include <vcl/msgbox.hxx>
#include <svl/cjkoptions.hxx>
#include <svl/whiter.hxx>
#include <sfx2/objsh.hxx>
#include <cuires.hrc>
#include "srchxtra.hrc"
#include <svx/svxitems.hrc> // RID_ATTR_BEGIN
#include <svx/dialmgr.hxx> // item resources
#include <editeng/flstitem.hxx>
#include "chardlg.hxx"
#include "paragrph.hxx"
#include <dialmgr.hxx>
#include "backgrnd.hxx"
#include <svx/dialogs.hrc> // RID_SVXPAGE_...
#include <tools/resary.hxx>
#include <rtl/strbuf.hxx>
// class SvxSearchFormatDialog -------------------------------------------
SvxSearchFormatDialog::SvxSearchFormatDialog( Window* pParent, const SfxItemSet& rSet ) :
SfxTabDialog( pParent, CUI_RES( RID_SVXDLG_SEARCHFORMAT ), &rSet ),
pFontList( NULL )
{
FreeResource();
AddTabPage( RID_SVXPAGE_CHAR_NAME, SvxCharNamePage::Create, 0 );
AddTabPage( RID_SVXPAGE_CHAR_EFFECTS, SvxCharEffectsPage::Create, 0 );
AddTabPage( RID_SVXPAGE_CHAR_POSITION, SvxCharPositionPage::Create, 0 );
AddTabPage( RID_SVXPAGE_CHAR_TWOLINES, SvxCharTwoLinesPage::Create, 0 );
AddTabPage( RID_SVXPAGE_STD_PARAGRAPH, SvxStdParagraphTabPage::Create, 0 );
AddTabPage( RID_SVXPAGE_ALIGN_PARAGRAPH, SvxParaAlignTabPage::Create, 0 );
AddTabPage( RID_SVXPAGE_EXT_PARAGRAPH, SvxExtParagraphTabPage::Create, 0 );
AddTabPage( RID_SVXPAGE_PARA_ASIAN, SvxAsianTabPage::Create, 0 );
AddTabPage( RID_SVXPAGE_BACKGROUND, SvxBackgroundTabPage::Create, 0 );
// remove asian tabpages if necessary
SvtCJKOptions aCJKOptions;
if ( !aCJKOptions.IsDoubleLinesEnabled() )
RemoveTabPage( RID_SVXPAGE_CHAR_TWOLINES );
if ( !aCJKOptions.IsAsianTypographyEnabled() )
RemoveTabPage( RID_SVXPAGE_PARA_ASIAN );
}
// -----------------------------------------------------------------------
SvxSearchFormatDialog::~SvxSearchFormatDialog()
{
delete pFontList;
}
// -----------------------------------------------------------------------
void SvxSearchFormatDialog::PageCreated( sal_uInt16 nId, SfxTabPage& rPage )
{
switch ( nId )
{
case RID_SVXPAGE_CHAR_NAME:
{
const FontList* pAppFontList = 0;
SfxObjectShell* pSh = SfxObjectShell::Current();
if ( pSh )
{
const SvxFontListItem* pFLItem = (const SvxFontListItem*)
pSh->GetItem( SID_ATTR_CHAR_FONTLIST );
if ( pFLItem )
pAppFontList = pFLItem->GetFontList();
}
const FontList* pList = pAppFontList;
if ( !pList )
{
if ( !pFontList )
pFontList = new FontList( this );
pList = pFontList;
}
if ( pList )
( (SvxCharNamePage&)rPage ).
SetFontList( SvxFontListItem( pList, SID_ATTR_CHAR_FONTLIST ) );
( (SvxCharNamePage&)rPage ).EnableSearchMode();
break;
}
case RID_SVXPAGE_STD_PARAGRAPH:
( (SvxStdParagraphTabPage&)rPage ).EnableAutoFirstLine();
break;
case RID_SVXPAGE_ALIGN_PARAGRAPH:
( (SvxParaAlignTabPage&)rPage ).EnableJustifyExt();
break;
case RID_SVXPAGE_BACKGROUND :
( (SvxBackgroundTabPage&)rPage ).ShowParaControl(sal_True);
break;
}
}
// class SvxSearchFormatDialog -------------------------------------------
SvxSearchAttributeDialog::SvxSearchAttributeDialog( Window* pParent,
SearchAttrItemList& rLst,
const sal_uInt16* pWhRanges ) :
ModalDialog( pParent, CUI_RES( RID_SVXDLG_SEARCHATTR ) ),
aAttrFL ( this, CUI_RES( FL_ATTR ) ),
aAttrLB ( this, CUI_RES( LB_ATTR ) ),
aOKBtn ( this, CUI_RES( BTN_ATTR_OK ) ),
aEscBtn ( this, CUI_RES( BTN_ATTR_CANCEL ) ),
aHelpBtn( this, CUI_RES( BTN_ATTR_HELP ) ),
rList( rLst )
{
FreeResource();
aAttrLB.SetStyle( GetStyle() | WB_CLIPCHILDREN | WB_HSCROLL | WB_SORT );
aAttrLB.GetModel()->SetSortMode( SortAscending );
aOKBtn.SetClickHdl( LINK( this, SvxSearchAttributeDialog, OKHdl ) );
SfxObjectShell* pSh = SfxObjectShell::Current();
DBG_ASSERT( pSh, "No DocShell" );
ResStringArray aAttrNames( SVX_RES( RID_ATTR_NAMES ) );
SfxItemPool& rPool = pSh->GetPool();
SfxItemSet aSet( rPool, pWhRanges );
SfxWhichIter aIter( aSet );
sal_uInt16 nWhich = aIter.FirstWhich();
while ( nWhich )
{
sal_uInt16 nSlot = rPool.GetSlotId( nWhich );
if ( nSlot >= SID_SVX_START )
{
sal_Bool bChecked = sal_False, bFound = sal_False;
for ( sal_uInt16 i = 0; !bFound && i < rList.Count(); ++i )
{
if ( nSlot == rList[i].nSlot )
{
bFound = sal_True;
if ( IsInvalidItem( rList[i].pItem ) )
bChecked = sal_True;
}
}
// item resources are in svx
sal_uInt32 nId = aAttrNames.FindIndex( nSlot );
SvLBoxEntry* pEntry = NULL;
if ( RESARRAY_INDEX_NOTFOUND != nId )
pEntry = aAttrLB.SvTreeListBox::InsertEntry( aAttrNames.GetString(nId) );
else
{
rtl::OStringBuffer sError(
RTL_CONSTASCII_STRINGPARAM("no resource for slot id\nslot = "));
sError.append(nSlot);
DBG_ERRORFILE(sError.getStr());
}
if ( pEntry )
{
aAttrLB.SetCheckButtonState( pEntry, bChecked ? SV_BUTTON_CHECKED : SV_BUTTON_UNCHECKED );
pEntry->SetUserData( (void*)(sal_uLong)nSlot );
}
}
nWhich = aIter.NextWhich();
}
aAttrLB.SetHighlightRange();
aAttrLB.SelectEntryPos( 0 );
}
// -----------------------------------------------------------------------
IMPL_LINK( SvxSearchAttributeDialog, OKHdl, Button *, EMPTYARG )
{
SearchAttrItem aInvalidItem;
aInvalidItem.pItem = (SfxPoolItem*)-1;
for ( sal_uInt16 i = 0; i < aAttrLB.GetEntryCount(); ++i )
{
sal_uInt16 nSlot = (sal_uInt16)(sal_uLong)aAttrLB.GetEntryData(i);
sal_Bool bChecked = aAttrLB.IsChecked(i);
sal_uInt16 j;
for ( j = rList.Count(); j; )
{
SearchAttrItem& rItem = rList[ --j ];
if( rItem.nSlot == nSlot )
{
if( bChecked )
{
if( !IsInvalidItem( rItem.pItem ) )
delete rItem.pItem;
rItem.pItem = (SfxPoolItem*)-1;
}
else if( IsInvalidItem( rItem.pItem ) )
rItem.pItem = 0;
j = 1;
break;
}
}
if ( !j && bChecked )
{
aInvalidItem.nSlot = nSlot;
rList.Insert( aInvalidItem );
}
}
// remove invalid items (pItem == NULL)
for ( sal_uInt16 n = rList.Count(); n; )
if ( !rList[ --n ].pItem )
rList.Remove( n );
EndDialog( RET_OK );
return 0;
}
// class SvxSearchSimilarityDialog ---------------------------------------
SvxSearchSimilarityDialog::SvxSearchSimilarityDialog
(
Window* pParent,
sal_Bool bRelax,
sal_uInt16 nOther,
sal_uInt16 nShorter,
sal_uInt16 nLonger
) :
ModalDialog( pParent, CUI_RES( RID_SVXDLG_SEARCHSIMILARITY ) ),
aFixedLine ( this, CUI_RES( FL_SIMILARITY ) ),
aOtherTxt ( this, CUI_RES( FT_OTHER ) ),
aOtherFld ( this, CUI_RES( NF_OTHER ) ),
aLongerTxt ( this, CUI_RES( FT_LONGER ) ),
aLongerFld ( this, CUI_RES( NF_LONGER ) ),
aShorterTxt ( this, CUI_RES( FT_SHORTER ) ),
aShorterFld ( this, CUI_RES( NF_SHORTER ) ),
aRelaxBox ( this, CUI_RES( CB_RELAX ) ),
aOKBtn ( this, CUI_RES( BTN_ATTR_OK ) ),
aEscBtn ( this, CUI_RES( BTN_ATTR_CANCEL ) ),
aHelpBtn ( this, CUI_RES( BTN_ATTR_HELP ) )
{
FreeResource();
aOtherFld.SetValue( nOther );
aShorterFld.SetValue( nShorter );
aLongerFld.SetValue( nLonger );
aRelaxBox.Check( bRelax );
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>fix ambiguity<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 ---------------------------------------------------------------
#include "srchxtra.hxx"
#include <tools/rcid.h>
#include <vcl/msgbox.hxx>
#include <svl/cjkoptions.hxx>
#include <svl/whiter.hxx>
#include <sfx2/objsh.hxx>
#include <cuires.hrc>
#include "srchxtra.hrc"
#include <svx/svxitems.hrc> // RID_ATTR_BEGIN
#include <svx/dialmgr.hxx> // item resources
#include <editeng/flstitem.hxx>
#include "chardlg.hxx"
#include "paragrph.hxx"
#include <dialmgr.hxx>
#include "backgrnd.hxx"
#include <svx/dialogs.hrc> // RID_SVXPAGE_...
#include <tools/resary.hxx>
#include <rtl/strbuf.hxx>
// class SvxSearchFormatDialog -------------------------------------------
SvxSearchFormatDialog::SvxSearchFormatDialog( Window* pParent, const SfxItemSet& rSet ) :
SfxTabDialog( pParent, CUI_RES( RID_SVXDLG_SEARCHFORMAT ), &rSet ),
pFontList( NULL )
{
FreeResource();
AddTabPage( RID_SVXPAGE_CHAR_NAME, SvxCharNamePage::Create, 0 );
AddTabPage( RID_SVXPAGE_CHAR_EFFECTS, SvxCharEffectsPage::Create, 0 );
AddTabPage( RID_SVXPAGE_CHAR_POSITION, SvxCharPositionPage::Create, 0 );
AddTabPage( RID_SVXPAGE_CHAR_TWOLINES, SvxCharTwoLinesPage::Create, 0 );
AddTabPage( RID_SVXPAGE_STD_PARAGRAPH, SvxStdParagraphTabPage::Create, 0 );
AddTabPage( RID_SVXPAGE_ALIGN_PARAGRAPH, SvxParaAlignTabPage::Create, 0 );
AddTabPage( RID_SVXPAGE_EXT_PARAGRAPH, SvxExtParagraphTabPage::Create, 0 );
AddTabPage( RID_SVXPAGE_PARA_ASIAN, SvxAsianTabPage::Create, 0 );
AddTabPage( RID_SVXPAGE_BACKGROUND, SvxBackgroundTabPage::Create, 0 );
// remove asian tabpages if necessary
SvtCJKOptions aCJKOptions;
if ( !aCJKOptions.IsDoubleLinesEnabled() )
RemoveTabPage( RID_SVXPAGE_CHAR_TWOLINES );
if ( !aCJKOptions.IsAsianTypographyEnabled() )
RemoveTabPage( RID_SVXPAGE_PARA_ASIAN );
}
// -----------------------------------------------------------------------
SvxSearchFormatDialog::~SvxSearchFormatDialog()
{
delete pFontList;
}
// -----------------------------------------------------------------------
void SvxSearchFormatDialog::PageCreated( sal_uInt16 nId, SfxTabPage& rPage )
{
switch ( nId )
{
case RID_SVXPAGE_CHAR_NAME:
{
const FontList* pAppFontList = 0;
SfxObjectShell* pSh = SfxObjectShell::Current();
if ( pSh )
{
const SvxFontListItem* pFLItem = (const SvxFontListItem*)
pSh->GetItem( SID_ATTR_CHAR_FONTLIST );
if ( pFLItem )
pAppFontList = pFLItem->GetFontList();
}
const FontList* pList = pAppFontList;
if ( !pList )
{
if ( !pFontList )
pFontList = new FontList( this );
pList = pFontList;
}
if ( pList )
( (SvxCharNamePage&)rPage ).
SetFontList( SvxFontListItem( pList, SID_ATTR_CHAR_FONTLIST ) );
( (SvxCharNamePage&)rPage ).EnableSearchMode();
break;
}
case RID_SVXPAGE_STD_PARAGRAPH:
( (SvxStdParagraphTabPage&)rPage ).EnableAutoFirstLine();
break;
case RID_SVXPAGE_ALIGN_PARAGRAPH:
( (SvxParaAlignTabPage&)rPage ).EnableJustifyExt();
break;
case RID_SVXPAGE_BACKGROUND :
( (SvxBackgroundTabPage&)rPage ).ShowParaControl(sal_True);
break;
}
}
// class SvxSearchFormatDialog -------------------------------------------
SvxSearchAttributeDialog::SvxSearchAttributeDialog( Window* pParent,
SearchAttrItemList& rLst,
const sal_uInt16* pWhRanges ) :
ModalDialog( pParent, CUI_RES( RID_SVXDLG_SEARCHATTR ) ),
aAttrFL ( this, CUI_RES( FL_ATTR ) ),
aAttrLB ( this, CUI_RES( LB_ATTR ) ),
aOKBtn ( this, CUI_RES( BTN_ATTR_OK ) ),
aEscBtn ( this, CUI_RES( BTN_ATTR_CANCEL ) ),
aHelpBtn( this, CUI_RES( BTN_ATTR_HELP ) ),
rList( rLst )
{
FreeResource();
aAttrLB.SetStyle( GetStyle() | WB_CLIPCHILDREN | WB_HSCROLL | WB_SORT );
aAttrLB.GetModel()->SetSortMode( SortAscending );
aOKBtn.SetClickHdl( LINK( this, SvxSearchAttributeDialog, OKHdl ) );
SfxObjectShell* pSh = SfxObjectShell::Current();
DBG_ASSERT( pSh, "No DocShell" );
ResStringArray aAttrNames( SVX_RES( RID_ATTR_NAMES ) );
SfxItemPool& rPool = pSh->GetPool();
SfxItemSet aSet( rPool, pWhRanges );
SfxWhichIter aIter( aSet );
sal_uInt16 nWhich = aIter.FirstWhich();
while ( nWhich )
{
sal_uInt16 nSlot = rPool.GetSlotId( nWhich );
if ( nSlot >= SID_SVX_START )
{
sal_Bool bChecked = sal_False, bFound = sal_False;
for ( sal_uInt16 i = 0; !bFound && i < rList.Count(); ++i )
{
if ( nSlot == rList[i].nSlot )
{
bFound = sal_True;
if ( IsInvalidItem( rList[i].pItem ) )
bChecked = sal_True;
}
}
// item resources are in svx
sal_uInt32 nId = aAttrNames.FindIndex( nSlot );
SvLBoxEntry* pEntry = NULL;
if ( RESARRAY_INDEX_NOTFOUND != nId )
pEntry = aAttrLB.SvTreeListBox::InsertEntry( aAttrNames.GetString(nId) );
else
{
rtl::OStringBuffer sError(
RTL_CONSTASCII_STRINGPARAM("no resource for slot id\nslot = "));
sError.append(static_cast<sal_Int32>(nSlot));
DBG_ERRORFILE(sError.getStr());
}
if ( pEntry )
{
aAttrLB.SetCheckButtonState( pEntry, bChecked ? SV_BUTTON_CHECKED : SV_BUTTON_UNCHECKED );
pEntry->SetUserData( (void*)(sal_uLong)nSlot );
}
}
nWhich = aIter.NextWhich();
}
aAttrLB.SetHighlightRange();
aAttrLB.SelectEntryPos( 0 );
}
// -----------------------------------------------------------------------
IMPL_LINK( SvxSearchAttributeDialog, OKHdl, Button *, EMPTYARG )
{
SearchAttrItem aInvalidItem;
aInvalidItem.pItem = (SfxPoolItem*)-1;
for ( sal_uInt16 i = 0; i < aAttrLB.GetEntryCount(); ++i )
{
sal_uInt16 nSlot = (sal_uInt16)(sal_uLong)aAttrLB.GetEntryData(i);
sal_Bool bChecked = aAttrLB.IsChecked(i);
sal_uInt16 j;
for ( j = rList.Count(); j; )
{
SearchAttrItem& rItem = rList[ --j ];
if( rItem.nSlot == nSlot )
{
if( bChecked )
{
if( !IsInvalidItem( rItem.pItem ) )
delete rItem.pItem;
rItem.pItem = (SfxPoolItem*)-1;
}
else if( IsInvalidItem( rItem.pItem ) )
rItem.pItem = 0;
j = 1;
break;
}
}
if ( !j && bChecked )
{
aInvalidItem.nSlot = nSlot;
rList.Insert( aInvalidItem );
}
}
// remove invalid items (pItem == NULL)
for ( sal_uInt16 n = rList.Count(); n; )
if ( !rList[ --n ].pItem )
rList.Remove( n );
EndDialog( RET_OK );
return 0;
}
// class SvxSearchSimilarityDialog ---------------------------------------
SvxSearchSimilarityDialog::SvxSearchSimilarityDialog
(
Window* pParent,
sal_Bool bRelax,
sal_uInt16 nOther,
sal_uInt16 nShorter,
sal_uInt16 nLonger
) :
ModalDialog( pParent, CUI_RES( RID_SVXDLG_SEARCHSIMILARITY ) ),
aFixedLine ( this, CUI_RES( FL_SIMILARITY ) ),
aOtherTxt ( this, CUI_RES( FT_OTHER ) ),
aOtherFld ( this, CUI_RES( NF_OTHER ) ),
aLongerTxt ( this, CUI_RES( FT_LONGER ) ),
aLongerFld ( this, CUI_RES( NF_LONGER ) ),
aShorterTxt ( this, CUI_RES( FT_SHORTER ) ),
aShorterFld ( this, CUI_RES( NF_SHORTER ) ),
aRelaxBox ( this, CUI_RES( CB_RELAX ) ),
aOKBtn ( this, CUI_RES( BTN_ATTR_OK ) ),
aEscBtn ( this, CUI_RES( BTN_ATTR_CANCEL ) ),
aHelpBtn ( this, CUI_RES( BTN_ATTR_HELP ) )
{
FreeResource();
aOtherFld.SetValue( nOther );
aShorterFld.SetValue( nShorter );
aLongerFld.SetValue( nLonger );
aRelaxBox.Check( bRelax );
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>// Copyright (C) 2001 MandrakeSoft S.A.
//
// MandrakeSoft S.A.
// 43, rue d'Aboukir
// 75002 Paris - France
// http://www.linux-mandrake.com/
// http://www.mandrakesoft.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 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// eth_arpback.cc - basic ethernet packetmover, only responds to ARP
// Various networking docs:
// http://www.graphcomp.com/info/rfc/
// rfc0826: arp
// rfc0903: rarp
#include "bochs.h"
#include "crc32.h"
#define LOG_THIS bx_ne2k.
static const Bit8u external_mac[]={0xB0, 0xC4, 0x20, 0x20, 0x00, 0x00, 0x00};
static const Bit8u external_ip[]={ 192, 168, 0, 2, 0x00 };
static const Bit8u broadcast_mac[]={0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00};
#define MAX_FRAME_SIZE 2048
//
// Define the class. This is private to this module
//
class bx_arpback_pktmover_c : public eth_pktmover_c {
public:
bx_arpback_pktmover_c(const char *netif, const char *macaddr,
eth_rx_handler_t rxh,
void *rxarg);
void sendpkt(void *buf, unsigned io_len);
private:
int rx_timer_index;
static void rx_timer_handler(void *);
void rx_timer(void);
FILE *txlog, *txlog_txt;
Bit8u arpbuf[MAX_FRAME_SIZE];
Bit32u buflen;
Boolean bufvalid;
CRC_Generator mycrc;
};
//
// Define the static class that registers the derived pktmover class,
// and allocates one on request.
//
class bx_arpback_locator_c : public eth_locator_c {
public:
bx_arpback_locator_c(void) : eth_locator_c("arpback") {}
protected:
eth_pktmover_c *allocate(const char *netif, const char *macaddr,
eth_rx_handler_t rxh,
void *rxarg) {
return (new bx_arpback_pktmover_c(netif, macaddr, rxh, rxarg));
}
} bx_arpback_match;
//
// Define the methods for the bx_arpback_pktmover derived class
//
// the constructor
bx_arpback_pktmover_c::bx_arpback_pktmover_c(const char *netif,
const char *macaddr,
eth_rx_handler_t rxh,
void *rxarg)
{
this->rx_timer_index =
bx_pc_system.register_timer(this, this->rx_timer_handler, 1000,
1, 1); // continuous, active
this->rxh = rxh;
this->rxarg = rxarg;
bufvalid=0;
#if BX_ETH_NULL_LOGGING
// Start the rx poll
// eventually Bryce wants txlog to dump in pcap format so that
// tcpdump -r FILE can read it and interpret packets.
txlog = fopen ("ne2k-tx.log", "wb");
if (!txlog) BX_PANIC (("open ne2k-tx.log failed"));
txlog_txt = fopen ("ne2k-txdump.txt", "wb");
if (!txlog_txt) BX_PANIC (("open ne2k-txdump.txt failed"));
fprintf (txlog_txt, "arpback packetmover readable log file\n");
fprintf (txlog_txt, "net IF = %s\n", netif);
fprintf (txlog_txt, "MAC address = ");
for (int i=0; i<6; i++)
fprintf (txlog_txt, "%02x%s", 0xff & macaddr[i], i<5?":" : "");
fprintf (txlog_txt, "\n--\n");
fflush (txlog_txt);
#endif
}
void
bx_arpback_pktmover_c::sendpkt(void *buf, unsigned io_len)
{
if(io_len<MAX_FRAME_SIZE) {
if((!memcmp(buf, external_mac, 6)) || (!memcmp(buf, broadcast_mac, 6)) ) {
Bit32u tempcrc;
memcpy(arpbuf,buf,io_len); //move to temporary buffer
memcpy(arpbuf, arpbuf+6, 6); //set destination to sender
memcpy(arpbuf+6, external_mac, 6); //set sender to us
memcpy(arpbuf+32, arpbuf+22, 10); //move destination to sender
memcpy(arpbuf+22, external_mac, 6); //set sender to us
memcpy(arpbuf+28, external_ip, 4); //set sender to us
arpbuf[21]=2; //make this a reply and not a request
tempcrc=mycrc.get_CRC(arpbuf,io_len);
memcpy(arpbuf+io_len, &tempcrc, 4);
buflen=io_len+4;
bufvalid=1;
}
}
#if BX_ETH_NULL_LOGGING
BX_DEBUG (("sendpkt length %u", io_len));
// dump raw bytes to a file, eventually dump in pcap format so that
// tcpdump -r FILE can interpret them for us.
int n = fwrite (buf, io_len, 1, txlog);
if (n != 1) BX_ERROR (("fwrite to txlog failed", io_len));
// dump packet in hex into an ascii log file
fprintf (txlog_txt, "NE2K transmitting a packet, length %u\n", io_len);
Bit8u *charbuf = (Bit8u *)buf;
for (n=0; n<io_len; n++) {
if (((n % 16) == 0) && n>0)
fprintf (txlog_txt, "\n");
fprintf (txlog_txt, "%02x ", charbuf[n]);
}
fprintf (txlog_txt, "\n--\n");
// flush log so that we see the packets as they arrive w/o buffering
fflush (txlog);
fflush (txlog_txt);
#endif
}
void bx_arpback_pktmover_c::rx_timer_handler (void * this_ptr)
{
#if BX_ETH_NULL_LOGGING
BX_DEBUG (("rx_timer_handler"));
#endif
bx_arpback_pktmover_c *class_ptr = ((bx_arpback_pktmover_c *)this_ptr);
class_ptr->rx_timer();
}
void bx_arpback_pktmover_c::rx_timer (void)
{
int nbytes = 0;
struct bpf_hdr *bhdr;
if(bufvalid) {
bufvalid=0;
void * buf=arpbuf;
unsigned io_len=buflen;
Bit32u n;
fprintf (txlog_txt, "NE2K receiving a packet, length %u\n", io_len);
Bit8u *charbuf = (Bit8u *)buf;
for (n=0; n<io_len; n++) {
if (((n % 16) == 0) && n>0)
fprintf (txlog_txt, "\n");
fprintf (txlog_txt, "%02x ", charbuf[n]);
}
fprintf (txlog_txt, "\n--\n");
fflush (txlog_txt);
(*rxh)(rxarg, buf, io_len);
}
}
<commit_msg>Only respond to ARP packets.<commit_after>// Copyright (C) 2001 MandrakeSoft S.A.
//
// MandrakeSoft S.A.
// 43, rue d'Aboukir
// 75002 Paris - France
// http://www.linux-mandrake.com/
// http://www.mandrakesoft.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 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// eth_arpback.cc - basic ethernet packetmover, only responds to ARP
// Various networking docs:
// http://www.graphcomp.com/info/rfc/
// rfc0826: arp
// rfc0903: rarp
#include "bochs.h"
#include "crc32.h"
#define LOG_THIS bx_ne2k.
static const Bit8u external_mac[]={0xB0, 0xC4, 0x20, 0x20, 0x00, 0x00, 0x00};
static const Bit8u external_ip[]={ 192, 168, 0, 2, 0x00 };
static const Bit8u broadcast_mac[]={0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00};
static const Bit8u ethtype_arp[]={0x08, 0x06, 0x00};
#define MAX_FRAME_SIZE 2048
//
// Define the class. This is private to this module
//
class bx_arpback_pktmover_c : public eth_pktmover_c {
public:
bx_arpback_pktmover_c(const char *netif, const char *macaddr,
eth_rx_handler_t rxh,
void *rxarg);
void sendpkt(void *buf, unsigned io_len);
private:
int rx_timer_index;
static void rx_timer_handler(void *);
void rx_timer(void);
FILE *txlog, *txlog_txt;
Bit8u arpbuf[MAX_FRAME_SIZE];
Bit32u buflen;
Boolean bufvalid;
CRC_Generator mycrc;
};
//
// Define the static class that registers the derived pktmover class,
// and allocates one on request.
//
class bx_arpback_locator_c : public eth_locator_c {
public:
bx_arpback_locator_c(void) : eth_locator_c("arpback") {}
protected:
eth_pktmover_c *allocate(const char *netif, const char *macaddr,
eth_rx_handler_t rxh,
void *rxarg) {
return (new bx_arpback_pktmover_c(netif, macaddr, rxh, rxarg));
}
} bx_arpback_match;
//
// Define the methods for the bx_arpback_pktmover derived class
//
// the constructor
bx_arpback_pktmover_c::bx_arpback_pktmover_c(const char *netif,
const char *macaddr,
eth_rx_handler_t rxh,
void *rxarg)
{
this->rx_timer_index =
bx_pc_system.register_timer(this, this->rx_timer_handler, 1000,
1, 1); // continuous, active
this->rxh = rxh;
this->rxarg = rxarg;
bufvalid=0;
#if BX_ETH_NULL_LOGGING
// Start the rx poll
// eventually Bryce wants txlog to dump in pcap format so that
// tcpdump -r FILE can read it and interpret packets.
txlog = fopen ("ne2k-tx.log", "wb");
if (!txlog) BX_PANIC (("open ne2k-tx.log failed"));
txlog_txt = fopen ("ne2k-txdump.txt", "wb");
if (!txlog_txt) BX_PANIC (("open ne2k-txdump.txt failed"));
fprintf (txlog_txt, "arpback packetmover readable log file\n");
fprintf (txlog_txt, "net IF = %s\n", netif);
fprintf (txlog_txt, "MAC address = ");
for (int i=0; i<6; i++)
fprintf (txlog_txt, "%02x%s", 0xff & macaddr[i], i<5?":" : "");
fprintf (txlog_txt, "\n--\n");
fflush (txlog_txt);
#endif
}
void
bx_arpback_pktmover_c::sendpkt(void *buf, unsigned io_len)
{
if(io_len<MAX_FRAME_SIZE) {
if(( (!memcmp(buf, external_mac, 6)) || (!memcmp(buf, broadcast_mac, 6)) )
&& (!memcmp(((Bit8u *)buf)+12, ethtype_arp, 2)) ) {
Bit32u tempcrc;
memcpy(arpbuf,buf,io_len); //move to temporary buffer
memcpy(arpbuf, arpbuf+6, 6); //set destination to sender
memcpy(arpbuf+6, external_mac, 6); //set sender to us
memcpy(arpbuf+32, arpbuf+22, 10); //move destination to sender
memcpy(arpbuf+22, external_mac, 6); //set sender to us
memcpy(arpbuf+28, external_ip, 4); //set sender to us
arpbuf[21]=2; //make this a reply and not a request
tempcrc=mycrc.get_CRC(arpbuf,io_len);
memcpy(arpbuf+io_len, &tempcrc, 4);
buflen=io_len/*+4*/;
bufvalid=1;
}
}
#if BX_ETH_NULL_LOGGING
BX_DEBUG (("sendpkt length %u", io_len));
// dump raw bytes to a file, eventually dump in pcap format so that
// tcpdump -r FILE can interpret them for us.
int n = fwrite (buf, io_len, 1, txlog);
if (n != 1) BX_ERROR (("fwrite to txlog failed", io_len));
// dump packet in hex into an ascii log file
fprintf (txlog_txt, "NE2K transmitting a packet, length %u\n", io_len);
Bit8u *charbuf = (Bit8u *)buf;
for (n=0; n<io_len; n++) {
if (((n % 16) == 0) && n>0)
fprintf (txlog_txt, "\n");
fprintf (txlog_txt, "%02x ", charbuf[n]);
}
fprintf (txlog_txt, "\n--\n");
// flush log so that we see the packets as they arrive w/o buffering
fflush (txlog);
fflush (txlog_txt);
#endif
}
void bx_arpback_pktmover_c::rx_timer_handler (void * this_ptr)
{
#if BX_ETH_NULL_LOGGING
BX_DEBUG (("rx_timer_handler"));
#endif
bx_arpback_pktmover_c *class_ptr = ((bx_arpback_pktmover_c *)this_ptr);
class_ptr->rx_timer();
}
void bx_arpback_pktmover_c::rx_timer (void)
{
int nbytes = 0;
struct bpf_hdr *bhdr;
if(bufvalid) {
bufvalid=0;
void * buf=arpbuf;
unsigned io_len=buflen;
Bit32u n;
fprintf (txlog_txt, "NE2K receiving a packet, length %u\n", io_len);
Bit8u *charbuf = (Bit8u *)buf;
for (n=0; n<io_len; n++) {
if (((n % 16) == 0) && n>0)
fprintf (txlog_txt, "\n");
fprintf (txlog_txt, "%02x ", charbuf[n]);
}
fprintf (txlog_txt, "\n--\n");
fflush (txlog_txt);
(*rxh)(rxarg, buf, io_len);
}
}
<|endoftext|> |
<commit_before>#include "Config.hpp"
#include "EventWatcher.hpp"
#include "KeyOverlaidModifier.hpp"
#include "VirtualKey.hpp"
namespace org_pqrs_KeyRemap4MacBook {
namespace RemapFunc {
TimerWrapper KeyOverlaidModifier::firerepeat_timer_;
KeyOverlaidModifier* KeyOverlaidModifier::target_ = NULL;
void
KeyOverlaidModifier::static_initialize(IOWorkLoop& workloop)
{
firerepeat_timer_.initialize(&workloop, NULL, KeyOverlaidModifier::firerepeat_timer_callback);
}
void
KeyOverlaidModifier::static_terminate(void)
{
firerepeat_timer_.terminate();
}
KeyOverlaidModifier::KeyOverlaidModifier(void) :
index_(0), isAnyEventHappen_(false), savedflags_(0), isRepeatEnabled_(false)
{
ic_.begin();
}
KeyOverlaidModifier::~KeyOverlaidModifier(void)
{
if (target_ == this) {
firerepeat_timer_.cancelTimeout();
target_ = NULL;
}
}
void
KeyOverlaidModifier::add(unsigned int datatype, unsigned int newval)
{
switch (datatype) {
case BRIDGE_DATATYPE_KEYCODE:
{
switch (index_) {
case 0:
keytokey_.add(KeyCode(newval));
keytokey_fire_.add(KeyCode::VK_PSEUDO_KEY);
break;
case 1:
toKey_.key = newval;
keytokey_.add(KeyCode(newval));
break;
default:
keytokey_fire_.add(KeyCode(newval));
break;
}
++index_;
break;
}
case BRIDGE_DATATYPE_FLAGS:
{
switch (index_) {
case 0:
IOLOG_ERROR("Invalid KeyOverlaidModifier::add\n");
break;
case 1:
keytokey_.add(Flags(newval));
break;
case 2:
toKey_.flags = newval;
keytokey_.add(Flags(newval));
break;
default:
keytokey_fire_.add(Flags(newval));
break;
}
break;
}
case BRIDGE_DATATYPE_OPTION:
{
if (Option::KEYOVERLAIDMODIFIER_REPEAT == newval) {
isRepeatEnabled_ = true;
} else {
IOLOG_ERROR("KeyOverlaidModifier::add unknown option:%d\n", newval);
}
break;
}
default:
IOLOG_ERROR("KeyOverlaidModifier::add invalid datatype:%d\n", datatype);
break;
}
}
bool
KeyOverlaidModifier::remap(RemapParams& remapParams)
{
bool savedIsAnyEventHappen = isAnyEventHappen_;
bool result = keytokey_.remap(remapParams);
if (! result) return false;
// ------------------------------------------------------------
IOLockWrapper::ScopedLock lk(firerepeat_timer_.getlock());
if (remapParams.params.ex_iskeydown) {
EventWatcher::set(isAnyEventHappen_);
ic_.begin();
// ----------------------------------------
// We store the flags when KeyDown.
// Because it lets you make a natural input when the following sequence.
//
// ex. "Space to Shift (when type only, send Space)"
// (1) KeyDown Command_L
// (2) KeyDown Space save flags (Command_L)
// (3) KeyUp Command_L
// (4) KeyUp Space fire Command_L+Space
FlagStatus::temporary_decrease(toKey_.flags | toKey_.key.getModifierFlag() | Handle_VK_LAZY::getModifierFlag(toKey_.key));
savedflags_ = FlagStatus::makeFlags();
FlagStatus::temporary_increase(toKey_.flags | toKey_.key.getModifierFlag() | Handle_VK_LAZY::getModifierFlag(toKey_.key));
// ----------------------------------------
if (isRepeatEnabled_) {
target_ = this;
isfirenormal_ = false;
isfirerepeat_ = false;
firerepeat_timer_.setTimeoutMS(Config::get_keyoverlaidmodifier_initial_wait());
}
} else {
firerepeat_timer_.cancelTimeout();
if (isfirerepeat_) {
FlagStatus::ScopedTemporaryFlagsChanger stfc(savedflags_);
keytokey_fire_.call_remap_with_VK_PSEUDO_KEY(EventType::UP);
} else {
isfirenormal_ = true;
if (savedIsAnyEventHappen == false) {
int timeout = Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_parameter_keyoverlaidmodifier_timeout);
if (timeout <= 0 || ic_.checkThreshold(timeout) == false) {
FlagStatus::ScopedTemporaryFlagsChanger stfc(savedflags_);
keytokey_fire_.call_remap_with_VK_PSEUDO_KEY(EventType::DOWN);
keytokey_fire_.call_remap_with_VK_PSEUDO_KEY(EventType::UP);
}
}
EventWatcher::unset(isAnyEventHappen_);
}
}
return true;
}
void
KeyOverlaidModifier::firerepeat_timer_callback(OSObject* owner, IOTimerEventSource* sender)
{
IOLockWrapper::ScopedLock lk(firerepeat_timer_.getlock());
if (! target_) return;
if (target_->isAnyEventHappen_) return;
if (! target_->isfirenormal_) {
target_->isfirerepeat_ = true;
FlagStatus::ScopedTemporaryFlagsChanger stfc(target_->savedflags_);
(target_->keytokey_fire_).call_remap_with_VK_PSEUDO_KEY(EventType::DOWN);
}
}
}
}
<commit_msg>remove unnecessary ScopedLock<commit_after>#include "Config.hpp"
#include "EventWatcher.hpp"
#include "KeyOverlaidModifier.hpp"
#include "VirtualKey.hpp"
namespace org_pqrs_KeyRemap4MacBook {
namespace RemapFunc {
TimerWrapper KeyOverlaidModifier::firerepeat_timer_;
KeyOverlaidModifier* KeyOverlaidModifier::target_ = NULL;
void
KeyOverlaidModifier::static_initialize(IOWorkLoop& workloop)
{
firerepeat_timer_.initialize(&workloop, NULL, KeyOverlaidModifier::firerepeat_timer_callback);
}
void
KeyOverlaidModifier::static_terminate(void)
{
firerepeat_timer_.terminate();
}
KeyOverlaidModifier::KeyOverlaidModifier(void) :
index_(0), isAnyEventHappen_(false), savedflags_(0), isRepeatEnabled_(false)
{
ic_.begin();
}
KeyOverlaidModifier::~KeyOverlaidModifier(void)
{
if (target_ == this) {
firerepeat_timer_.cancelTimeout();
target_ = NULL;
}
}
void
KeyOverlaidModifier::add(unsigned int datatype, unsigned int newval)
{
switch (datatype) {
case BRIDGE_DATATYPE_KEYCODE:
{
switch (index_) {
case 0:
keytokey_.add(KeyCode(newval));
keytokey_fire_.add(KeyCode::VK_PSEUDO_KEY);
break;
case 1:
toKey_.key = newval;
keytokey_.add(KeyCode(newval));
break;
default:
keytokey_fire_.add(KeyCode(newval));
break;
}
++index_;
break;
}
case BRIDGE_DATATYPE_FLAGS:
{
switch (index_) {
case 0:
IOLOG_ERROR("Invalid KeyOverlaidModifier::add\n");
break;
case 1:
keytokey_.add(Flags(newval));
break;
case 2:
toKey_.flags = newval;
keytokey_.add(Flags(newval));
break;
default:
keytokey_fire_.add(Flags(newval));
break;
}
break;
}
case BRIDGE_DATATYPE_OPTION:
{
if (Option::KEYOVERLAIDMODIFIER_REPEAT == newval) {
isRepeatEnabled_ = true;
} else {
IOLOG_ERROR("KeyOverlaidModifier::add unknown option:%d\n", newval);
}
break;
}
default:
IOLOG_ERROR("KeyOverlaidModifier::add invalid datatype:%d\n", datatype);
break;
}
}
bool
KeyOverlaidModifier::remap(RemapParams& remapParams)
{
bool savedIsAnyEventHappen = isAnyEventHappen_;
bool result = keytokey_.remap(remapParams);
if (! result) return false;
// ------------------------------------------------------------
if (remapParams.params.ex_iskeydown) {
EventWatcher::set(isAnyEventHappen_);
ic_.begin();
// ----------------------------------------
// We store the flags when KeyDown.
// Because it lets you make a natural input when the following sequence.
//
// ex. "Space to Shift (when type only, send Space)"
// (1) KeyDown Command_L
// (2) KeyDown Space save flags (Command_L)
// (3) KeyUp Command_L
// (4) KeyUp Space fire Command_L+Space
FlagStatus::temporary_decrease(toKey_.flags | toKey_.key.getModifierFlag() | Handle_VK_LAZY::getModifierFlag(toKey_.key));
savedflags_ = FlagStatus::makeFlags();
FlagStatus::temporary_increase(toKey_.flags | toKey_.key.getModifierFlag() | Handle_VK_LAZY::getModifierFlag(toKey_.key));
// ----------------------------------------
if (isRepeatEnabled_) {
target_ = this;
isfirenormal_ = false;
isfirerepeat_ = false;
firerepeat_timer_.setTimeoutMS(Config::get_keyoverlaidmodifier_initial_wait());
}
} else {
firerepeat_timer_.cancelTimeout();
if (isfirerepeat_) {
FlagStatus::ScopedTemporaryFlagsChanger stfc(savedflags_);
keytokey_fire_.call_remap_with_VK_PSEUDO_KEY(EventType::UP);
} else {
isfirenormal_ = true;
if (savedIsAnyEventHappen == false) {
int timeout = Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_parameter_keyoverlaidmodifier_timeout);
if (timeout <= 0 || ic_.checkThreshold(timeout) == false) {
FlagStatus::ScopedTemporaryFlagsChanger stfc(savedflags_);
keytokey_fire_.call_remap_with_VK_PSEUDO_KEY(EventType::DOWN);
keytokey_fire_.call_remap_with_VK_PSEUDO_KEY(EventType::UP);
}
}
EventWatcher::unset(isAnyEventHappen_);
}
}
return true;
}
void
KeyOverlaidModifier::firerepeat_timer_callback(OSObject* owner, IOTimerEventSource* sender)
{
if (! target_) return;
if (target_->isAnyEventHappen_) return;
if (! target_->isfirenormal_) {
target_->isfirerepeat_ = true;
FlagStatus::ScopedTemporaryFlagsChanger stfc(target_->savedflags_);
(target_->keytokey_fire_).call_remap_with_VK_PSEUDO_KEY(EventType::DOWN);
}
}
}
}
<|endoftext|> |
<commit_before>// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "riegeli/bytes/string_writer.h"
#include <stddef.h>
#include <string>
#include <utility>
#include "absl/base/optimization.h"
#include "absl/strings/string_view.h"
#include "riegeli/base/base.h"
#include "riegeli/base/chain.h"
#include "riegeli/base/memory.h"
#include "riegeli/bytes/writer.h"
namespace riegeli {
void StringWriterBase::Done() {
if (ABSL_PREDICT_TRUE(healthy())) {
std::string* const dest = dest_string();
RIEGELI_ASSERT_EQ(buffer_size(), dest->size())
<< "StringWriter destination changed unexpectedly";
SyncBuffer(dest);
}
Writer::Done();
}
bool StringWriterBase::PushSlow(size_t min_length, size_t recommended_length) {
RIEGELI_ASSERT_GT(min_length, available())
<< "Failed precondition of Writer::PushSlow(): "
"length too small, use Push() instead";
if (ABSL_PREDICT_FALSE(!healthy())) return false;
std::string* const dest = dest_string();
RIEGELI_ASSERT_EQ(buffer_size(), dest->size())
<< "StringWriter destination changed unexpectedly";
SyncBuffer(dest);
if (min_length > dest->capacity() - dest->size()) {
if (ABSL_PREDICT_FALSE(min_length > dest->max_size() - dest->size())) {
return FailOverflow();
}
dest->reserve(
UnsignedMin(UnsignedMax(SaturatingAdd(dest->size(), recommended_length),
// Double the size, and round up to one below a
// possible allocated size (for NUL terminator).
EstimatedAllocatedSize(SaturatingAdd(
dest->size(), dest->size(), size_t{1})) -
1,
dest->size() + min_length),
dest->max_size()));
}
MakeBuffer(dest);
return true;
}
bool StringWriterBase::WriteSlow(absl::string_view src) {
RIEGELI_ASSERT_GT(src.size(), available())
<< "Failed precondition of Writer::WriteSlow(string_view): "
"length too small, use Write(string_view) instead";
if (ABSL_PREDICT_FALSE(!healthy())) return false;
std::string* const dest = dest_string();
RIEGELI_ASSERT_EQ(buffer_size(), dest->size())
<< "StringWriter destination changed unexpectedly";
if (ABSL_PREDICT_FALSE(src.size() > dest->max_size() - written_to_buffer())) {
return FailOverflow();
}
SyncBuffer(dest);
dest->append(src.data(), src.size());
MakeBuffer(dest);
return true;
}
bool StringWriterBase::WriteSlow(const Chain& src) {
RIEGELI_ASSERT_GT(src.size(), UnsignedMin(available(), kMaxBytesToCopy))
<< "Failed precondition of Writer::WriteSlow(Chain): "
"length too small, use Write(Chain) instead";
if (ABSL_PREDICT_FALSE(!healthy())) return false;
std::string* const dest = dest_string();
RIEGELI_ASSERT_EQ(buffer_size(), dest->size())
<< "StringWriter destination changed unexpectedly";
if (ABSL_PREDICT_FALSE(src.size() > dest->max_size() - written_to_buffer())) {
return FailOverflow();
}
SyncBuffer(dest);
src.AppendTo(dest);
MakeBuffer(dest);
return true;
}
bool StringWriterBase::WriteSlow(Chain&& src) {
RIEGELI_ASSERT_GT(src.size(), UnsignedMin(available(), kMaxBytesToCopy))
<< "Failed precondition of Writer::WriteSlow(Chain&&): "
"length too small, use Write(Chain) instead";
if (ABSL_PREDICT_FALSE(!healthy())) return false;
std::string* const dest = dest_string();
RIEGELI_ASSERT_EQ(buffer_size(), dest->size())
<< "StringWriter destination changed unexpectedly";
if (ABSL_PREDICT_FALSE(src.size() > dest->max_size() - written_to_buffer())) {
return FailOverflow();
}
SyncBuffer(dest);
std::move(src).AppendTo(dest);
MakeBuffer(dest);
return true;
}
bool StringWriterBase::Flush(FlushType flush_type) {
if (ABSL_PREDICT_FALSE(!healthy())) return false;
std::string* const dest = dest_string();
RIEGELI_ASSERT_EQ(buffer_size(), dest->size())
<< "StringWriter destination changed unexpectedly";
SyncBuffer(dest);
return true;
}
bool StringWriterBase::Truncate(Position new_size) {
if (ABSL_PREDICT_FALSE(!healthy())) return false;
std::string* const dest = dest_string();
RIEGELI_ASSERT_EQ(buffer_size(), dest->size())
<< "StringWriter destination changed unexpectedly";
if (ABSL_PREDICT_FALSE(new_size > written_to_buffer())) return false;
cursor_ = start_ + new_size;
return true;
}
inline void StringWriterBase::SyncBuffer(std::string* dest) {
dest->erase(written_to_buffer());
start_ = &(*dest)[0];
cursor_ = start_ + dest->size();
limit_ = cursor_;
}
inline void StringWriterBase::MakeBuffer(std::string* dest) {
const size_t cursor_pos = dest->size();
dest->resize(dest->capacity());
start_ = &(*dest)[0];
cursor_ = start_ + cursor_pos;
limit_ = start_ + dest->size();
}
} // namespace riegeli
<commit_msg>Tune string sizing in StringWriter.<commit_after>// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "riegeli/bytes/string_writer.h"
#include <stddef.h>
#include <string>
#include <utility>
#include "absl/base/optimization.h"
#include "absl/strings/string_view.h"
#include "riegeli/base/base.h"
#include "riegeli/base/chain.h"
#include "riegeli/base/memory.h"
#include "riegeli/bytes/writer.h"
namespace riegeli {
void StringWriterBase::Done() {
if (ABSL_PREDICT_TRUE(healthy())) {
std::string* const dest = dest_string();
RIEGELI_ASSERT_EQ(buffer_size(), dest->size())
<< "StringWriter destination changed unexpectedly";
SyncBuffer(dest);
}
Writer::Done();
}
bool StringWriterBase::PushSlow(size_t min_length, size_t recommended_length) {
RIEGELI_ASSERT_GT(min_length, available())
<< "Failed precondition of Writer::PushSlow(): "
"length too small, use Push() instead";
if (ABSL_PREDICT_FALSE(!healthy())) return false;
std::string* const dest = dest_string();
RIEGELI_ASSERT_EQ(buffer_size(), dest->size())
<< "StringWriter destination changed unexpectedly";
SyncBuffer(dest);
if (min_length > dest->capacity() - dest->size()) {
if (ABSL_PREDICT_FALSE(min_length > dest->max_size() - dest->size())) {
return FailOverflow();
}
dest->reserve(UnsignedMin(
UnsignedMax(SaturatingAdd(dest->size(),
UnsignedMax(min_length, recommended_length)),
// Double the capacity, and round up to one below a possible
// allocated size (for NUL terminator).
EstimatedAllocatedSize(SaturatingAdd(
dest->capacity(), dest->capacity(), size_t{1})) -
1),
dest->max_size()));
}
MakeBuffer(dest);
return true;
}
bool StringWriterBase::WriteSlow(absl::string_view src) {
RIEGELI_ASSERT_GT(src.size(), available())
<< "Failed precondition of Writer::WriteSlow(string_view): "
"length too small, use Write(string_view) instead";
if (ABSL_PREDICT_FALSE(!healthy())) return false;
std::string* const dest = dest_string();
RIEGELI_ASSERT_EQ(buffer_size(), dest->size())
<< "StringWriter destination changed unexpectedly";
if (ABSL_PREDICT_FALSE(src.size() > dest->max_size() - written_to_buffer())) {
return FailOverflow();
}
SyncBuffer(dest);
dest->append(src.data(), src.size());
MakeBuffer(dest);
return true;
}
bool StringWriterBase::WriteSlow(const Chain& src) {
RIEGELI_ASSERT_GT(src.size(), UnsignedMin(available(), kMaxBytesToCopy))
<< "Failed precondition of Writer::WriteSlow(Chain): "
"length too small, use Write(Chain) instead";
if (ABSL_PREDICT_FALSE(!healthy())) return false;
std::string* const dest = dest_string();
RIEGELI_ASSERT_EQ(buffer_size(), dest->size())
<< "StringWriter destination changed unexpectedly";
if (ABSL_PREDICT_FALSE(src.size() > dest->max_size() - written_to_buffer())) {
return FailOverflow();
}
SyncBuffer(dest);
src.AppendTo(dest);
MakeBuffer(dest);
return true;
}
bool StringWriterBase::WriteSlow(Chain&& src) {
RIEGELI_ASSERT_GT(src.size(), UnsignedMin(available(), kMaxBytesToCopy))
<< "Failed precondition of Writer::WriteSlow(Chain&&): "
"length too small, use Write(Chain) instead";
if (ABSL_PREDICT_FALSE(!healthy())) return false;
std::string* const dest = dest_string();
RIEGELI_ASSERT_EQ(buffer_size(), dest->size())
<< "StringWriter destination changed unexpectedly";
if (ABSL_PREDICT_FALSE(src.size() > dest->max_size() - written_to_buffer())) {
return FailOverflow();
}
SyncBuffer(dest);
std::move(src).AppendTo(dest);
MakeBuffer(dest);
return true;
}
bool StringWriterBase::Flush(FlushType flush_type) {
if (ABSL_PREDICT_FALSE(!healthy())) return false;
std::string* const dest = dest_string();
RIEGELI_ASSERT_EQ(buffer_size(), dest->size())
<< "StringWriter destination changed unexpectedly";
SyncBuffer(dest);
return true;
}
bool StringWriterBase::Truncate(Position new_size) {
if (ABSL_PREDICT_FALSE(!healthy())) return false;
std::string* const dest = dest_string();
RIEGELI_ASSERT_EQ(buffer_size(), dest->size())
<< "StringWriter destination changed unexpectedly";
if (ABSL_PREDICT_FALSE(new_size > written_to_buffer())) return false;
cursor_ = start_ + new_size;
return true;
}
inline void StringWriterBase::SyncBuffer(std::string* dest) {
dest->erase(written_to_buffer());
start_ = &(*dest)[0];
cursor_ = start_ + dest->size();
limit_ = cursor_;
}
inline void StringWriterBase::MakeBuffer(std::string* dest) {
const size_t cursor_pos = dest->size();
dest->resize(dest->capacity());
start_ = &(*dest)[0];
cursor_ = start_ + cursor_pos;
limit_ = start_ + dest->size();
}
} // namespace riegeli
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2007-2009 Digital Bazaar, Inc. All rights reserved.
*/
#include "db/rt/DynamicObject.h"
#include "db/rt/DynamicObjectIterator.h"
#include "db/rt/DynamicObjectIterators.h"
#include <cstdlib>
#include <cctype>
using namespace db::rt;
DynamicObject::DynamicObject() :
Collectable<DynamicObjectImpl>(new DynamicObjectImpl())
{
}
DynamicObject::DynamicObject(DynamicObjectImpl* impl) :
Collectable<DynamicObjectImpl>(impl)
{
}
DynamicObject::DynamicObject(const DynamicObject& rhs) :
Collectable<DynamicObjectImpl>(rhs)
{
}
DynamicObject::~DynamicObject()
{
}
bool DynamicObject::operator==(const DynamicObject& rhs) const
{
bool rval;
const DynamicObject& lhs = *this;
rval = Collectable<DynamicObjectImpl>::operator==(rhs);
if(!rval && !lhs.isNull() && !rhs.isNull())
{
// compare heap objects
rval = (*lhs == *rhs);
}
return rval;
}
bool DynamicObject::operator!=(const DynamicObject& rhs) const
{
return !(*this == rhs);
}
bool DynamicObject::operator<(const DynamicObject& rhs) const
{
bool rval;
const DynamicObject& lhs = *this;
// NULL is always less than anything other than NULL
if(lhs.isNull())
{
rval = !rhs.isNull();
}
// lhs is not NULL, but rhs is, so rhs is not less
else if(rhs.isNull())
{
rval = false;
}
// neither lhs or rhs is NULL, compare heap objects
else
{
rval = (*lhs < *rhs);
}
return rval;
}
void DynamicObject::operator=(const char* value)
{
*mReference->ptr = value;
}
void DynamicObject::operator=(const unsigned char* value)
{
operator=((const char*)value);
}
void DynamicObject::operator=(bool value)
{
*mReference->ptr = value;
}
void DynamicObject::operator=(int32_t value)
{
*mReference->ptr = value;
}
void DynamicObject::operator=(uint32_t value)
{
*mReference->ptr = value;
}
void DynamicObject::operator=(int64_t value)
{
*mReference->ptr = value;
}
void DynamicObject::operator=(uint64_t value)
{
*mReference->ptr = value;
}
void DynamicObject::operator=(double value)
{
*mReference->ptr = value;
}
DynamicObject& DynamicObject::operator[](const char* name)
{
return (*mReference->ptr)[name];
}
DynamicObject& DynamicObject::operator[](const unsigned char* name)
{
return operator[]((const char*)name);
}
DynamicObject& DynamicObject::operator[](int index)
{
return (*mReference->ptr)[index];
}
DynamicObjectIterator DynamicObject::getIterator() const
{
DynamicObjectIteratorImpl* i;
switch((*this)->getType())
{
case Map:
i = new DynamicObjectIteratorMap((DynamicObject&)*this);
break;
case Array:
i = new DynamicObjectIteratorArray((DynamicObject&)*this);
break;
default:
i = new DynamicObjectIteratorSingle((DynamicObject&)*this);
break;
}
return DynamicObjectIterator(i);
}
DynamicObject DynamicObject::first() const
{
DynamicObject rval(NULL);
// return first result of iterator
DynamicObjectIterator i = getIterator();
if(i->hasNext())
{
rval = i->next();
}
return rval;
}
DynamicObject DynamicObject::clone()
{
DynamicObject rval;
if(isNull())
{
rval.setNull();
}
else
{
int index = 0;
rval->setType((*this)->getType());
DynamicObjectIterator i = getIterator();
while(i->hasNext())
{
DynamicObject dyno = i->next();
switch((*this)->getType())
{
case String:
rval = dyno->getString();
break;
case Boolean:
rval = dyno->getBoolean();
break;
case Int32:
rval = dyno->getInt32();
break;
case UInt32:
rval = dyno->getUInt32();
break;
case Int64:
rval = dyno->getInt64();
break;
case UInt64:
rval = dyno->getUInt64();
break;
case Double:
rval = dyno->getDouble();
break;
case Map:
rval[i->getName()] = dyno.clone();
break;
case Array:
rval[index++] = dyno.clone();
break;
}
}
}
return rval;
}
bool DynamicObject::diff(
DynamicObject& target, DynamicObject& result, uint32_t flags)
{
bool rval = false;
DynamicObject& source = (DynamicObject&)*this;
// clear any old values
result->clear();
if(source.isNull() && target.isNull())
{
// same: no diff
}
else if(!source.isNull() && target.isNull())
{
// <stuff> -> NULL: diff=NULL
rval = true;
result = "[DiffError: target object is NULL]";
}
else if(source.isNull() && !target.isNull())
{
// NULL -> <stuff> -or- types differ: diff=target
rval = true;
result = "[DiffError: source object is NULL]";
}
else
{
// not null && same type: diff=deep compare
switch(source->getType())
{
case Int32:
case Int64:
case UInt32:
case UInt64:
if(source->getType() != target->getType())
{
switch(target->getType())
{
case Int32:
case Int64:
case UInt32:
case UInt64:
// if we're comparing using 64 bit integers, ignore
// differences between 32 bit and 64 bit integers
if(flags & DiffIntegersAsInt64s)
{
// do signed comparison
if(source->getType() == Int32 ||
source->getType() == Int64)
{
if(source->getInt64() != target->getInt64())
{
rval = true;
result = target.clone();
}
}
// do unsigned comparison
else if(source->getUInt64() != target->getUInt64())
{
rval = true;
result = target.clone();
}
// only break out of case if we're comparing
// using 64 bit integers, otherwise drop to the
// default case of a type mismatch
break;
}
default:
result = "[DiffError: type mismatch]";
rval = true;
}
}
else if(source != target)
{
rval = true;
result = target.clone();
}
break;
case Double:
// compare doubles as strings if requested
if((flags & DiffDoublesAsStrings) &&
source->getType() == target->getType())
{
if(strcmp(source->getString(), target->getString()) != 0)
{
rval = true;
result = target.clone();
}
// only break out of case if comparing as strings
break;
}
case String:
case Boolean:
if(source->getType() != target->getType())
{
result = "[DiffError: type mismatch]";
rval = true;
}
else if(source != target)
{
rval = true;
result = target.clone();
}
break;
case Map:
if(source->getType() != target->getType())
{
result = "[DiffError: type mismatch, expected Map]";
rval = true;
}
else
{
// FIXME: since this code was copied from the config manager
// this only checks additions and updates not removals which
// is totally wrong... we need to fix this
DynamicObjectIterator i = target.getIterator();
while(i->hasNext())
{
DynamicObject next = i->next();
const char* name = i->getName();
if(!source->hasMember(name))
{
// source does not have property that is in target,
// so add to diff
rval = true;
result[name] = next.clone();
}
else
{
// recusively get sub-diff
DynamicObject d;
if(source[name].diff(next, d, flags))
{
// diff found, add it
rval = true;
result[name] = d;
}
}
}
}
// FIXME: search source for items that are not in target
break;
case Array:
if(source->getType() != target->getType())
{
result = "[DiffError: type mismatch, expected Array]";
rval = true;
}
else
{
// FIXME: since this code was copied from the config manager
// this only checks additions and updates not removals which
// is totally wrong... we need to fix this
DynamicObject temp;
temp->setType(Array);
DynamicObjectIterator i = target.getIterator();
for(int ii = 0; i->hasNext(); ii++)
{
DynamicObject next = i->next();
DynamicObject d;
if(source->length() < (ii + 1) ||
source[ii].diff(next, d, flags))
{
// diff found
rval = true;
temp[ii] = d;
}
else
{
// set the array value in temp to the value in source
// FIXME: should this be set to null or something else
// instead since there is no difference?
temp[ii] = source[ii];
}
}
// FIXME: check target for array indexes that are in source
// only set array to target if a diff was found
if(rval)
{
result = temp;
}
}
break;
}
}
return rval;
}
void DynamicObject::merge(DynamicObject& rhs, bool append)
{
switch(rhs->getType())
{
case String:
case Boolean:
case Int32:
case UInt32:
case Int64:
case UInt64:
case Double:
*this = rhs.clone();
break;
case Map:
{
(*this)->setType(Map);
DynamicObjectIterator i = rhs.getIterator();
while(i->hasNext())
{
DynamicObject& next = i->next();
(*this)[i->getName()].merge(next, append);
}
break;
}
case Array:
(*this)->setType(Array);
DynamicObjectIterator i = rhs.getIterator();
int offset = (append ? (*this)->length() : 0);
for(int ii = 0; i->hasNext(); ii++)
{
(*this)[offset + ii].merge(i->next(), append);
}
break;
}
}
bool DynamicObject::isSubset(const DynamicObject& rhs) const
{
bool rval;
rval = Collectable<DynamicObjectImpl>::operator==(rhs);
if(!rval && (*this)->getType() == Map && rhs->getType() == Map)
{
// ensure right map has same or greater length
if((*this)->length() <= rhs->length())
{
rval = true;
DynamicObjectIterator i = this->getIterator();
while(rval && i->hasNext())
{
DynamicObject& leftDyno = i->next();
if(rhs->hasMember(i->getName()))
{
DynamicObject& rightDyno = (*rhs)[i->getName()];
if(leftDyno->getType() == Map && rightDyno->getType() == Map)
{
rval = leftDyno.isSubset(rightDyno);
}
else
{
rval = (leftDyno == rightDyno);
}
}
else
{
rval = false;
}
}
}
}
return rval;
}
const char* DynamicObject::descriptionForType(DynamicObjectType type)
{
const char* rval = NULL;
switch(type)
{
case String:
rval = "string";
break;
case Boolean:
rval = "boolean";
break;
case Int32:
rval = "32 bit integer";
break;
case UInt32:
rval = "32 bit unsigned integer";
break;
case Int64:
rval = "64 bit integer";
break;
case UInt64:
rval = "64 bit unsigned integer";
break;
case Double:
rval = "floating point";
break;
case Map:
rval = "map";
break;
case Array:
rval = "array";
break;
}
return rval;
}
DynamicObjectType DynamicObject::determineType(const char* str)
{
DynamicObjectType rval = String;
// FIXME: this code might interpret hex/octal strings as integers
// (and other code for that matter!) and we might not want to do that
// if string starts with whitespace, forget about it
if(!isspace(str[0]))
{
// see if the number is an unsigned int
// then check signed int
// then check doubles
char* end;
strtoull(str, &end, 10);
if(end[0] == 0 && str[0] != '-')
{
// if end is NULL (and not negative) then the whole string was an int
rval = UInt64;
}
else
{
// the number may be a signed int
strtoll(str, &end, 10);
if(end[0] == 0)
{
// if end is NULL then the whole string was an int
rval = Int64;
}
else
{
// the number may be a double
strtod(str, &end);
if(end[0] == 0)
{
// end is NULL, so we've got a double,
// else we've assume a String
rval = Double;
}
}
}
}
return rval;
}
<commit_msg>Fixed diffing algorithm for DynamicObject.<commit_after>/*
* Copyright (c) 2007-2009 Digital Bazaar, Inc. All rights reserved.
*/
#include "db/rt/DynamicObject.h"
#include "db/rt/DynamicObjectIterator.h"
#include "db/rt/DynamicObjectIterators.h"
#include <cstdlib>
#include <cctype>
using namespace db::rt;
DynamicObject::DynamicObject() :
Collectable<DynamicObjectImpl>(new DynamicObjectImpl())
{
}
DynamicObject::DynamicObject(DynamicObjectImpl* impl) :
Collectable<DynamicObjectImpl>(impl)
{
}
DynamicObject::DynamicObject(const DynamicObject& rhs) :
Collectable<DynamicObjectImpl>(rhs)
{
}
DynamicObject::~DynamicObject()
{
}
bool DynamicObject::operator==(const DynamicObject& rhs) const
{
bool rval;
const DynamicObject& lhs = *this;
rval = Collectable<DynamicObjectImpl>::operator==(rhs);
if(!rval && !lhs.isNull() && !rhs.isNull())
{
// compare heap objects
rval = (*lhs == *rhs);
}
return rval;
}
bool DynamicObject::operator!=(const DynamicObject& rhs) const
{
return !(*this == rhs);
}
bool DynamicObject::operator<(const DynamicObject& rhs) const
{
bool rval;
const DynamicObject& lhs = *this;
// NULL is always less than anything other than NULL
if(lhs.isNull())
{
rval = !rhs.isNull();
}
// lhs is not NULL, but rhs is, so rhs is not less
else if(rhs.isNull())
{
rval = false;
}
// neither lhs or rhs is NULL, compare heap objects
else
{
rval = (*lhs < *rhs);
}
return rval;
}
void DynamicObject::operator=(const char* value)
{
*mReference->ptr = value;
}
void DynamicObject::operator=(const unsigned char* value)
{
operator=((const char*)value);
}
void DynamicObject::operator=(bool value)
{
*mReference->ptr = value;
}
void DynamicObject::operator=(int32_t value)
{
*mReference->ptr = value;
}
void DynamicObject::operator=(uint32_t value)
{
*mReference->ptr = value;
}
void DynamicObject::operator=(int64_t value)
{
*mReference->ptr = value;
}
void DynamicObject::operator=(uint64_t value)
{
*mReference->ptr = value;
}
void DynamicObject::operator=(double value)
{
*mReference->ptr = value;
}
DynamicObject& DynamicObject::operator[](const char* name)
{
return (*mReference->ptr)[name];
}
DynamicObject& DynamicObject::operator[](const unsigned char* name)
{
return operator[]((const char*)name);
}
DynamicObject& DynamicObject::operator[](int index)
{
return (*mReference->ptr)[index];
}
DynamicObjectIterator DynamicObject::getIterator() const
{
DynamicObjectIteratorImpl* i;
switch((*this)->getType())
{
case Map:
i = new DynamicObjectIteratorMap((DynamicObject&)*this);
break;
case Array:
i = new DynamicObjectIteratorArray((DynamicObject&)*this);
break;
default:
i = new DynamicObjectIteratorSingle((DynamicObject&)*this);
break;
}
return DynamicObjectIterator(i);
}
DynamicObject DynamicObject::first() const
{
DynamicObject rval(NULL);
// return first result of iterator
DynamicObjectIterator i = getIterator();
if(i->hasNext())
{
rval = i->next();
}
return rval;
}
DynamicObject DynamicObject::clone()
{
DynamicObject rval;
if(isNull())
{
rval.setNull();
}
else
{
int index = 0;
rval->setType((*this)->getType());
DynamicObjectIterator i = getIterator();
while(i->hasNext())
{
DynamicObject dyno = i->next();
switch((*this)->getType())
{
case String:
rval = dyno->getString();
break;
case Boolean:
rval = dyno->getBoolean();
break;
case Int32:
rval = dyno->getInt32();
break;
case UInt32:
rval = dyno->getUInt32();
break;
case Int64:
rval = dyno->getInt64();
break;
case UInt64:
rval = dyno->getUInt64();
break;
case Double:
rval = dyno->getDouble();
break;
case Map:
rval[i->getName()] = dyno.clone();
break;
case Array:
rval[index++] = dyno.clone();
break;
}
}
}
return rval;
}
/**
* The _getMapDiff helper function gets the differences between the source
* object and the target object and places the result in the result object.
* The comparison flags are passed to the diffing algorithm.
*
* @param source the source object to compare against the target object.
* @param target the target object that will be compared against the source
* object.
* @param result the result of the diffing operation.
* @param flags the flags that will be passed to the recursive diffing
* operation.
*
* @return true if there are differences, false otherwise.
*/
static bool _getMapDiff(
DynamicObject& source, DynamicObject& target, DynamicObject& result,
uint32_t flags)
{
bool rval = false;
// Find everything that is in target and not in source
DynamicObjectIterator i = target.getIterator();
while(i->hasNext())
{
DynamicObject& next = i->next();
const char* name = i->getName();
if(!source->hasMember(name))
{
// source does not have property that is in target,
// so add to diff
rval = true;
result[name] = next.clone();
}
else
{
// recusively get sub-diff
DynamicObject d;
if(source[name].diff(next, d, flags))
{
// diff found, add it
rval = true;
result[name] = d;
}
}
}
return rval;
}
bool DynamicObject::diff(
DynamicObject& target, DynamicObject& result, uint32_t flags)
{
bool rval = false;
DynamicObject& source = (DynamicObject&)*this;
// clear any old values
result->clear();
if(source.isNull() && target.isNull())
{
// same: no diff
}
else if(!source.isNull() && target.isNull())
{
// <stuff> -> NULL: diff=NULL
rval = true;
result = "[DiffError: target object is NULL]";
}
else if(source.isNull() && !target.isNull())
{
// NULL -> <stuff> -or- types differ: diff=target
rval = true;
result = "[DiffError: source object is NULL]";
}
else
{
// not null && same type: diff=deep compare
switch(source->getType())
{
case Int32:
case Int64:
case UInt32:
case UInt64:
if(source->getType() != target->getType())
{
switch(target->getType())
{
case Int32:
case Int64:
case UInt32:
case UInt64:
// if we're comparing using 64 bit integers, ignore
// differences between 32 bit and 64 bit integers
if(flags & DiffIntegersAsInt64s)
{
// do signed comparison
if(source->getType() == Int32 ||
source->getType() == Int64)
{
if(source->getInt64() != target->getInt64())
{
rval = true;
result = target.clone();
}
}
// do unsigned comparison
else if(source->getUInt64() != target->getUInt64())
{
rval = true;
result = target.clone();
}
// only break out of case if we're comparing
// using 64 bit integers, otherwise drop to the
// default case of a type mismatch
break;
}
default:
result = "[DiffError: type mismatch]";
rval = true;
}
}
else if(source != target)
{
rval = true;
result = target.clone();
}
break;
case Double:
// compare doubles as strings if requested
if((flags & DiffDoublesAsStrings) &&
source->getType() == target->getType())
{
if(strcmp(source->getString(), target->getString()) != 0)
{
rval = true;
result = target.clone();
}
// only break out of case if comparing as strings
break;
}
case String:
case Boolean:
if(source->getType() != target->getType())
{
result = "[DiffError: type mismatch]";
rval = true;
}
else if(source != target)
{
rval = true;
result = target.clone();
}
break;
case Map:
if(source->getType() != target->getType())
{
result = "[DiffError: type mismatch, expected Map]";
rval = true;
}
else
{
// get the Map differences between source and target
rval = _getMapDiff(source, target, result, flags) || rval;
// get the Map differences between target and source
rval = _getMapDiff(target, source, result, flags) || rval;
}
break;
case Array:
if(source->getType() != target->getType())
{
result = "[DiffError: type mismatch, expected Array]";
rval = true;
}
else
{
// FIXME: since this code was copied from the config manager
// this only checks additions and updates not removals which
// is totally wrong... we need to fix this
DynamicObject temp;
temp->setType(Array);
DynamicObjectIterator i = target.getIterator();
for(int ii = 0; i->hasNext(); ii++)
{
DynamicObject next = i->next();
DynamicObject d;
if(source->length() < (ii + 1) ||
source[ii].diff(next, d, flags))
{
// diff found
rval = true;
temp[ii] = d;
}
else
{
// set the array value in temp to the value in source
// FIXME: should this be set to null or something else
// instead since there is no difference?
temp[ii] = source[ii];
}
}
// FIXME: check target for array indexes that are in source
// only set array to target if a diff was found
if(rval)
{
result = temp;
}
}
break;
}
}
return rval;
}
void DynamicObject::merge(DynamicObject& rhs, bool append)
{
switch(rhs->getType())
{
case String:
case Boolean:
case Int32:
case UInt32:
case Int64:
case UInt64:
case Double:
*this = rhs.clone();
break;
case Map:
{
(*this)->setType(Map);
DynamicObjectIterator i = rhs.getIterator();
while(i->hasNext())
{
DynamicObject& next = i->next();
(*this)[i->getName()].merge(next, append);
}
break;
}
case Array:
(*this)->setType(Array);
DynamicObjectIterator i = rhs.getIterator();
int offset = (append ? (*this)->length() : 0);
for(int ii = 0; i->hasNext(); ii++)
{
(*this)[offset + ii].merge(i->next(), append);
}
break;
}
}
bool DynamicObject::isSubset(const DynamicObject& rhs) const
{
bool rval;
rval = Collectable<DynamicObjectImpl>::operator==(rhs);
if(!rval && (*this)->getType() == Map && rhs->getType() == Map)
{
// ensure right map has same or greater length
if((*this)->length() <= rhs->length())
{
rval = true;
DynamicObjectIterator i = this->getIterator();
while(rval && i->hasNext())
{
DynamicObject& leftDyno = i->next();
if(rhs->hasMember(i->getName()))
{
DynamicObject& rightDyno = (*rhs)[i->getName()];
if(leftDyno->getType() == Map && rightDyno->getType() == Map)
{
rval = leftDyno.isSubset(rightDyno);
}
else
{
rval = (leftDyno == rightDyno);
}
}
else
{
rval = false;
}
}
}
}
return rval;
}
const char* DynamicObject::descriptionForType(DynamicObjectType type)
{
const char* rval = NULL;
switch(type)
{
case String:
rval = "string";
break;
case Boolean:
rval = "boolean";
break;
case Int32:
rval = "32 bit integer";
break;
case UInt32:
rval = "32 bit unsigned integer";
break;
case Int64:
rval = "64 bit integer";
break;
case UInt64:
rval = "64 bit unsigned integer";
break;
case Double:
rval = "floating point";
break;
case Map:
rval = "map";
break;
case Array:
rval = "array";
break;
}
return rval;
}
DynamicObjectType DynamicObject::determineType(const char* str)
{
DynamicObjectType rval = String;
// FIXME: this code might interpret hex/octal strings as integers
// (and other code for that matter!) and we might not want to do that
// if string starts with whitespace, forget about it
if(!isspace(str[0]))
{
// see if the number is an unsigned int
// then check signed int
// then check doubles
char* end;
strtoull(str, &end, 10);
if(end[0] == 0 && str[0] != '-')
{
// if end is NULL (and not negative) then the whole string was an int
rval = UInt64;
}
else
{
// the number may be a signed int
strtoll(str, &end, 10);
if(end[0] == 0)
{
// if end is NULL then the whole string was an int
rval = Int64;
}
else
{
// the number may be a double
strtod(str, &end);
if(end[0] == 0)
{
// end is NULL, so we've got a double,
// else we've assume a String
rval = Double;
}
}
}
}
return rval;
}
<|endoftext|> |
<commit_before><commit_msg>fixed addevent<commit_after><|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright (c) 2019 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 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 "ISM330DLC.hpp"
#include <px4_platform_common/getopt.h>
namespace ism330dlc
{
ISM330DLC *g_dev{nullptr};
int start(enum Rotation rotation);
int stop();
int status();
void usage();
int start(enum Rotation rotation)
{
if (g_dev != nullptr) {
PX4_WARN("already started");
return 0;
}
// create the driver
g_dev = new ISM330DLC(PX4_SPI_BUS_SENSORS2, PX4_SPIDEV_ISM330, rotation); // v5x TODO: board manifest
if (g_dev == nullptr) {
PX4_ERR("driver start failed");
return -1;
}
if (!g_dev->Init()) {
PX4_ERR("driver init failed");
delete g_dev;
g_dev = nullptr;
return -1;
}
return 0;
}
int stop()
{
if (g_dev == nullptr) {
PX4_WARN("driver not running");
}
g_dev->Stop();
delete g_dev;
return 0;
}
int reset()
{
if (g_dev == nullptr) {
PX4_WARN("driver not running");
}
return g_dev->Reset();
}
int status()
{
if (g_dev == nullptr) {
PX4_WARN("driver not running");
return -1;
}
g_dev->PrintInfo();
return 0;
}
void usage()
{
PX4_INFO("missing command: try 'start', 'stop', 'reset', 'status'");
PX4_INFO("options:");
PX4_INFO(" -R rotation");
}
} // namespace ism330dlc
extern "C" __EXPORT int ism330dlc_main(int argc, char *argv[])
{
enum Rotation rotation = ROTATION_NONE;
int myoptind = 1;
int ch = 0;
const char *myoptarg = nullptr;
/* start options */
while ((ch = px4_getopt(argc, argv, "R:", &myoptind, &myoptarg)) != EOF) {
switch (ch) {
case 'R':
rotation = (enum Rotation)atoi(myoptarg);
break;
default:
ism330dlc::usage();
return 0;
}
}
const char *verb = argv[myoptind];
if (!strcmp(verb, "start")) {
return ism330dlc::start(rotation);
} else if (!strcmp(verb, "stop")) {
return ism330dlc::stop();
} else if (!strcmp(verb, "status")) {
return ism330dlc::status();
} else if (!strcmp(verb, "reset")) {
return ism330dlc::reset();
}
ism330dlc::usage();
return 0;
}
<commit_msg>Ddded cli check for ism330dlc startup to prevent hardfault if no options are given.<commit_after>/****************************************************************************
*
* Copyright (c) 2019 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 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 "ISM330DLC.hpp"
#include <px4_platform_common/getopt.h>
namespace ism330dlc
{
ISM330DLC *g_dev{nullptr};
int start(enum Rotation rotation);
int stop();
int status();
void usage();
int start(enum Rotation rotation)
{
if (g_dev != nullptr) {
PX4_WARN("already started");
return 0;
}
// create the driver
g_dev = new ISM330DLC(PX4_SPI_BUS_SENSORS2, PX4_SPIDEV_ISM330, rotation); // v5x TODO: board manifest
if (g_dev == nullptr) {
PX4_ERR("driver start failed");
return -1;
}
if (!g_dev->Init()) {
PX4_ERR("driver init failed");
delete g_dev;
g_dev = nullptr;
return -1;
}
return 0;
}
int stop()
{
if (g_dev == nullptr) {
PX4_WARN("driver not running");
}
g_dev->Stop();
delete g_dev;
return 0;
}
int reset()
{
if (g_dev == nullptr) {
PX4_WARN("driver not running");
}
return g_dev->Reset();
}
int status()
{
if (g_dev == nullptr) {
PX4_WARN("driver not running");
return -1;
}
g_dev->PrintInfo();
return 0;
}
void usage()
{
PX4_INFO("missing command: try 'start', 'stop', 'reset', 'status'");
PX4_INFO("options:");
PX4_INFO(" -R rotation");
}
} // namespace ism330dlc
extern "C" __EXPORT int ism330dlc_main(int argc, char *argv[])
{
enum Rotation rotation = ROTATION_NONE;
int myoptind = 1;
int ch = 0;
const char *myoptarg = nullptr;
/* start options */
while ((ch = px4_getopt(argc, argv, "R:", &myoptind, &myoptarg)) != EOF) {
switch (ch) {
case 'R':
rotation = (enum Rotation)atoi(myoptarg);
break;
default:
ism330dlc::usage();
return 0;
}
}
if (myoptind >= argc) {
ism330dlc::usage();
return -1;
}
const char *verb = argv[myoptind];
if (!strcmp(verb, "start")) {
return ism330dlc::start(rotation);
} else if (!strcmp(verb, "stop")) {
return ism330dlc::stop();
} else if (!strcmp(verb, "status")) {
return ism330dlc::status();
} else if (!strcmp(verb, "reset")) {
return ism330dlc::reset();
}
ism330dlc::usage();
return 0;
}
<|endoftext|> |
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vespalib/testkit/test_kit.h>
#include <vespa/eval/tensor/sparse/sparse_tensor.h>
#include <vespa/eval/tensor/sparse/sparse_tensor_builder.h>
#include <vespa/eval/tensor/types.h>
#include <vespa/eval/tensor/default_tensor.h>
#include <vespa/eval/tensor/tensor_factory.h>
#include <vespa/eval/tensor/serialization/typed_binary_format.h>
#include <vespa/eval/tensor/serialization/slime_binary_format.h>
#include <vespa/vespalib/data/slime/slime.h>
#include <iostream>
using namespace vespalib::tensor;
template <typename BuilderType>
struct Fixture
{
BuilderType _builder;
Fixture() : _builder() {}
Tensor::UP createTensor(const TensorCells &cells) {
return vespalib::tensor::TensorFactory::create(cells, _builder);
}
Tensor::UP createTensor(const TensorCells &cells, const TensorDimensions &dimensions) {
return TensorFactory::create(cells, dimensions, _builder);
}
static inline uint32_t getTensorTypeId();
void assertSerialized(const vespalib::string &exp, const TensorCells &rhs,
const TensorDimensions &rhsDimensions) {
Tensor::UP rhsTensor(createTensor(rhs, rhsDimensions));
auto slime = SlimeBinaryFormat::serialize(*rhsTensor);
vespalib::Memory memory_exp(exp);
vespalib::Slime expSlime;
size_t used = vespalib::slime::JsonFormat::decode(memory_exp, expSlime);
EXPECT_TRUE(used > 0);
EXPECT_EQUAL(expSlime, *slime);
}
};
template <>
uint32_t
Fixture<SparseTensorBuilder>::getTensorTypeId() { return 2u; }
using SparseFixture = Fixture<SparseTensorBuilder>;
namespace {
vespalib::string twoCellsJson[3] =
{
"{ dimensions: [ 'x', 'y' ],"
" cells: ["
"{ address: { y:'3'}, value: 4.0 },"
"{ address: { x:'1'}, value: 3.0 }"
"] }",
"{ dimensions: [ 'x', 'y' ],"
" cells: ["
"{ address: { x:'1'}, value: 3.0 },"
"{ address: { y:'3'}, value: 4.0 }"
"] }",
"{ dimensions: [ 'x', 'y' ],"
" cells: ["
"{ address: { y:'3'}, value: 4.0 },"
"{ address: { x:'1'}, value: 3.0 }"
"] }",
};
}
template <typename FixtureType>
void
testTensorSlimeSerialization(FixtureType &f)
{
TEST_DO(f.assertSerialized("{ dimensions: [], cells: [] }", {}, {}));
TEST_DO(f.assertSerialized("{ dimensions: [ 'x' ], cells: [] }",
{}, { "x" }));
TEST_DO(f.assertSerialized("{ dimensions: [ 'x', 'y' ], cells: [] }",
{}, { "x", "y" }));
TEST_DO(f.assertSerialized("{ dimensions: [ 'x' ],"
"cells: ["
"{ address: { x: '1' }, value: 3.0 }"
"] }",
{ {{{"x","1"}}, 3} }, { "x" }));
TEST_DO(f.assertSerialized("{ dimensions: [ 'x', 'y' ],"
" cells: ["
"{ address: { }, value: 3.0 }"
"] }",
{ {{}, 3} }, { "x", "y"}));
TEST_DO(f.assertSerialized("{ dimensions: [ 'x', 'y' ],"
" cells: ["
"{ address: { x: '1' }, value: 3.0 }"
"] }",
{ {{{"x","1"}}, 3} }, { "x", "y" }));
TEST_DO(f.assertSerialized("{ dimensions: [ 'x', 'y' ],"
" cells: ["
"{ address: { y: '3' }, value: 3.0 }"
"] }",
{ {{{"y","3"}}, 3} }, { "x", "y" }));
TEST_DO(f.assertSerialized("{ dimensions: [ 'x', 'y' ],"
" cells: ["
"{ address: { x:'2', y:'4'}, value: 3.0 }"
"] }",
{ {{{"x","2"}, {"y", "4"}}, 3} }, { "x", "y" }));
TEST_DO(f.assertSerialized("{ dimensions: [ 'x', 'y' ],"
" cells: ["
"{ address: { x:'1'}, value: 3.0 }"
"] }",
{ {{{"x","1"}}, 3} }, {"x", "y"}));
TEST_DO(f.assertSerialized(twoCellsJson[FixtureType::getTensorTypeId()],
{ {{{"x","1"}}, 3}, {{{"y","3"}}, 4} },
{"x", "y"}));
}
TEST_F("test tensor slime serialization for SparseTensor", SparseFixture)
{
testTensorSlimeSerialization(f);
}
struct DenseFixture
{
DenseFixture() {}
Tensor::UP createTensor(const DenseTensorCells &cells) {
return vespalib::tensor::TensorFactory::createDense(cells);
}
void assertSerialized(const vespalib::string &exp,
const DenseTensorCells &rhs) {
Tensor::UP rhsTensor(createTensor(rhs));
auto slime = SlimeBinaryFormat::serialize(*rhsTensor);
vespalib::Memory memory_exp(exp);
vespalib::Slime expSlime;
size_t used = vespalib::slime::JsonFormat::decode(memory_exp, expSlime);
EXPECT_TRUE(used > 0);
EXPECT_EQUAL(expSlime, *slime);
}
};
TEST_F("test tensor slime serialization for DenseTensor", DenseFixture)
{
TEST_DO(f.assertSerialized("{ dimensions: [], cells: ["
"{ address: { }, value: 0.0 }"
"] }", {}));
TEST_DO(f.assertSerialized("{ dimensions: [ 'x' ], cells: ["
"{ address: { x: '0' }, value: 0.0 }"
"] }",
{ {{{"x",0}}, 0} }));
TEST_DO(f.assertSerialized("{ dimensions: [ 'x', 'y' ], cells: ["
"{ address: { x: '0', y: '0' }, value: 0.0 }"
"] }",
{ {{{"x",0},{"y",0}}, 0} }));
TEST_DO(f.assertSerialized("{ dimensions: [ 'x' ],"
"cells: ["
"{ address: { x: '0' }, value: 0.0 },"
"{ address: { x: '1' }, value: 3.0 }"
"] }",
{ {{{"x",1}}, 3} }));
TEST_DO(f.assertSerialized("{ dimensions: [ 'x', 'y' ],"
" cells: ["
"{ address: { x: '0', y: '0' }, value: 3.0 }"
"] }",
{ {{{"x",0},{"y",0}}, 3} }));
TEST_DO(f.assertSerialized("{ dimensions: [ 'x', 'y' ],"
" cells: ["
"{ address: { x: '0', y: '0' }, value: 0.0 },"
"{ address: { x: '1', y: '0' }, value: 3.0 }"
"] }",
{ {{{"x",1},{"y", 0}}, 3} }));
TEST_DO(f.assertSerialized("{ dimensions: [ 'x', 'y' ],"
" cells: ["
"{ address: { x: '0', y: '0' }, value: 0.0 },"
"{ address: { x: '0', y: '1' }, value: 0.0 },"
"{ address: { x: '0', y: '2' }, value: 0.0 },"
"{ address: { x: '0', y: '3' }, value: 3.0 }"
"] }",
{ {{{"x",0},{"y",3}}, 3} }));
}
TEST_MAIN() { TEST_RUN_ALL(); }
<commit_msg>Revert earlier reorder.<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vespalib/testkit/test_kit.h>
#include <vespa/eval/tensor/sparse/sparse_tensor.h>
#include <vespa/eval/tensor/sparse/sparse_tensor_builder.h>
#include <vespa/eval/tensor/types.h>
#include <vespa/eval/tensor/default_tensor.h>
#include <vespa/eval/tensor/tensor_factory.h>
#include <vespa/eval/tensor/serialization/typed_binary_format.h>
#include <vespa/eval/tensor/serialization/slime_binary_format.h>
#include <vespa/vespalib/data/slime/slime.h>
#include <iostream>
using namespace vespalib::tensor;
template <typename BuilderType>
struct Fixture
{
BuilderType _builder;
Fixture() : _builder() {}
Tensor::UP createTensor(const TensorCells &cells) {
return vespalib::tensor::TensorFactory::create(cells, _builder);
}
Tensor::UP createTensor(const TensorCells &cells, const TensorDimensions &dimensions) {
return TensorFactory::create(cells, dimensions, _builder);
}
static inline uint32_t getTensorTypeId();
void assertSerialized(const vespalib::string &exp, const TensorCells &rhs,
const TensorDimensions &rhsDimensions) {
Tensor::UP rhsTensor(createTensor(rhs, rhsDimensions));
auto slime = SlimeBinaryFormat::serialize(*rhsTensor);
vespalib::Memory memory_exp(exp);
vespalib::Slime expSlime;
size_t used = vespalib::slime::JsonFormat::decode(memory_exp, expSlime);
EXPECT_TRUE(used > 0);
EXPECT_EQUAL(expSlime, *slime);
}
};
template <>
uint32_t
Fixture<SparseTensorBuilder>::getTensorTypeId() { return 2u; }
using SparseFixture = Fixture<SparseTensorBuilder>;
namespace {
vespalib::string twoCellsJson[3] =
{
"{ dimensions: [ 'x', 'y' ],"
" cells: ["
"{ address: { y:'3'}, value: 4.0 },"
"{ address: { x:'1'}, value: 3.0 }"
"] }",
"{ dimensions: [ 'x', 'y' ],"
" cells: ["
"{ address: { x:'1'}, value: 3.0 },"
"{ address: { y:'3'}, value: 4.0 }"
"] }",
"{ dimensions: [ 'x', 'y' ],"
" cells: ["
"{ address: { x:'1'}, value: 3.0 },"
"{ address: { y:'3'}, value: 4.0 }"
"] }",
};
}
template <typename FixtureType>
void
testTensorSlimeSerialization(FixtureType &f)
{
TEST_DO(f.assertSerialized("{ dimensions: [], cells: [] }", {}, {}));
TEST_DO(f.assertSerialized("{ dimensions: [ 'x' ], cells: [] }",
{}, { "x" }));
TEST_DO(f.assertSerialized("{ dimensions: [ 'x', 'y' ], cells: [] }",
{}, { "x", "y" }));
TEST_DO(f.assertSerialized("{ dimensions: [ 'x' ],"
"cells: ["
"{ address: { x: '1' }, value: 3.0 }"
"] }",
{ {{{"x","1"}}, 3} }, { "x" }));
TEST_DO(f.assertSerialized("{ dimensions: [ 'x', 'y' ],"
" cells: ["
"{ address: { }, value: 3.0 }"
"] }",
{ {{}, 3} }, { "x", "y"}));
TEST_DO(f.assertSerialized("{ dimensions: [ 'x', 'y' ],"
" cells: ["
"{ address: { x: '1' }, value: 3.0 }"
"] }",
{ {{{"x","1"}}, 3} }, { "x", "y" }));
TEST_DO(f.assertSerialized("{ dimensions: [ 'x', 'y' ],"
" cells: ["
"{ address: { y: '3' }, value: 3.0 }"
"] }",
{ {{{"y","3"}}, 3} }, { "x", "y" }));
TEST_DO(f.assertSerialized("{ dimensions: [ 'x', 'y' ],"
" cells: ["
"{ address: { x:'2', y:'4'}, value: 3.0 }"
"] }",
{ {{{"x","2"}, {"y", "4"}}, 3} }, { "x", "y" }));
TEST_DO(f.assertSerialized("{ dimensions: [ 'x', 'y' ],"
" cells: ["
"{ address: { x:'1'}, value: 3.0 }"
"] }",
{ {{{"x","1"}}, 3} }, {"x", "y"}));
TEST_DO(f.assertSerialized(twoCellsJson[FixtureType::getTensorTypeId()],
{ {{{"x","1"}}, 3}, {{{"y","3"}}, 4} },
{"x", "y"}));
}
TEST_F("test tensor slime serialization for SparseTensor", SparseFixture)
{
testTensorSlimeSerialization(f);
}
struct DenseFixture
{
DenseFixture() {}
Tensor::UP createTensor(const DenseTensorCells &cells) {
return vespalib::tensor::TensorFactory::createDense(cells);
}
void assertSerialized(const vespalib::string &exp,
const DenseTensorCells &rhs) {
Tensor::UP rhsTensor(createTensor(rhs));
auto slime = SlimeBinaryFormat::serialize(*rhsTensor);
vespalib::Memory memory_exp(exp);
vespalib::Slime expSlime;
size_t used = vespalib::slime::JsonFormat::decode(memory_exp, expSlime);
EXPECT_TRUE(used > 0);
EXPECT_EQUAL(expSlime, *slime);
}
};
TEST_F("test tensor slime serialization for DenseTensor", DenseFixture)
{
TEST_DO(f.assertSerialized("{ dimensions: [], cells: ["
"{ address: { }, value: 0.0 }"
"] }", {}));
TEST_DO(f.assertSerialized("{ dimensions: [ 'x' ], cells: ["
"{ address: { x: '0' }, value: 0.0 }"
"] }",
{ {{{"x",0}}, 0} }));
TEST_DO(f.assertSerialized("{ dimensions: [ 'x', 'y' ], cells: ["
"{ address: { x: '0', y: '0' }, value: 0.0 }"
"] }",
{ {{{"x",0},{"y",0}}, 0} }));
TEST_DO(f.assertSerialized("{ dimensions: [ 'x' ],"
"cells: ["
"{ address: { x: '0' }, value: 0.0 },"
"{ address: { x: '1' }, value: 3.0 }"
"] }",
{ {{{"x",1}}, 3} }));
TEST_DO(f.assertSerialized("{ dimensions: [ 'x', 'y' ],"
" cells: ["
"{ address: { x: '0', y: '0' }, value: 3.0 }"
"] }",
{ {{{"x",0},{"y",0}}, 3} }));
TEST_DO(f.assertSerialized("{ dimensions: [ 'x', 'y' ],"
" cells: ["
"{ address: { x: '0', y: '0' }, value: 0.0 },"
"{ address: { x: '1', y: '0' }, value: 3.0 }"
"] }",
{ {{{"x",1},{"y", 0}}, 3} }));
TEST_DO(f.assertSerialized("{ dimensions: [ 'x', 'y' ],"
" cells: ["
"{ address: { x: '0', y: '0' }, value: 0.0 },"
"{ address: { x: '0', y: '1' }, value: 0.0 },"
"{ address: { x: '0', y: '2' }, value: 0.0 },"
"{ address: { x: '0', y: '3' }, value: 3.0 }"
"] }",
{ {{{"x",0},{"y",3}}, 3} }));
}
TEST_MAIN() { TEST_RUN_ALL(); }
<|endoftext|> |
<commit_before>#include "reportqueue.h"
#include <chrono>
ReportQueue::ReportQueue(const Config& config_in, std::shared_ptr<HttpInterface> http_client)
: config(config_in), http(std::move(http_client)) {
thread_ = std::thread(std::bind(&ReportQueue::run, this));
}
ReportQueue::~ReportQueue() {
{
std::lock_guard<std::mutex> lock(m_);
shutdown_ = true;
}
cv_.notify_all();
thread_.join();
LOG_DEBUG << "Flushing report queue";
flushQueue();
}
void ReportQueue::run() {
// Check if queue is nonempty. If so, move any reports to the Json array and
// try to send it to the server. Clear the Json array only if the send
// succeeds.
std::unique_lock<std::mutex> lock(m_);
while (!shutdown_) {
flushQueue();
cv_.wait_for(lock, std::chrono::seconds(10));
}
}
void ReportQueue::enqueue(std::unique_ptr<ReportEvent> event) {
{
std::lock_guard<std::mutex> lock(m_);
report_queue_.push(std::move(event));
}
cv_.notify_all();
}
void ReportQueue::flushQueue() {
while (!report_queue_.empty()) {
report_array.append(report_queue_.front()->toJson());
report_queue_.pop();
}
if (config.tls.server.empty()) {
// Prevent a lot of unnecessary garbage output in uptane vector tests.
LOG_TRACE << "No server specified. Clearing report queue.";
report_array.clear();
}
if (!report_array.empty()) {
HttpResponse response = http->post(config.tls.server + "/events", report_array);
// 404 implies the server does not support this feature. Nothing we can
// do, just move along.
if (response.http_status_code == 404) {
LOG_TRACE << "Server does not support event reports. Clearing report queue.";
}
if (response.isOk() || response.http_status_code == 404) {
report_array.clear();
}
}
}
void ReportEvent::setEcu(const Uptane::EcuSerial& ecu) { custom["ecu"] = ecu.ToString(); }
void ReportEvent::setCorrelationId(const std::string& correlation_id) {
if (correlation_id != "") {
custom["correlationId"] = correlation_id;
}
}
Json::Value ReportEvent::toJson() {
Json::Value out;
out["id"] = id;
out["deviceTime"] = timestamp.ToString();
out["eventType"]["id"] = type;
out["eventType"]["version"] = version;
out["event"] = custom;
return out;
}
CampaignAcceptedReport::CampaignAcceptedReport(const std::string& campaign_id) : ReportEvent("campaign_accepted", 0) {
custom["campaignId"] = campaign_id;
}
CampaignDeclinedReport::CampaignDeclinedReport(const std::string& campaign_id) : ReportEvent("campaign_declined", 0) {
custom["campaignId"] = campaign_id;
}
CampaignPostponedReport::CampaignPostponedReport(const std::string& campaign_id)
: ReportEvent("campaign_postponed", 0) {
custom["campaignId"] = campaign_id;
}
DevicePausedReport::DevicePausedReport(const std::string& correlation_id) : ReportEvent("DevicePaused", 0) {
setCorrelationId(correlation_id);
}
DeviceResumedReport::DeviceResumedReport(const std::string& correlation_id) : ReportEvent("DeviceResumed", 0) {
setCorrelationId(correlation_id);
}
EcuDownloadStartedReport::EcuDownloadStartedReport(const Uptane::EcuSerial& ecu, const std::string& correlation_id)
: ReportEvent("EcuDownloadStarted", 0) {
setEcu(ecu);
setCorrelationId(correlation_id);
}
EcuDownloadCompletedReport::EcuDownloadCompletedReport(const Uptane::EcuSerial& ecu, const std::string& correlation_id,
bool success)
: ReportEvent("EcuDownloadCompleted", 0) {
setEcu(ecu);
setCorrelationId(correlation_id);
custom["success"] = success;
}
EcuInstallationStartedReport::EcuInstallationStartedReport(const Uptane::EcuSerial& ecu,
const std::string& correlation_id)
: ReportEvent("EcuInstallationStarted", 0) {
setEcu(ecu);
setCorrelationId(correlation_id);
}
EcuInstallationAppliedReport::EcuInstallationAppliedReport(const Uptane::EcuSerial& ecu,
const std::string& correlation_id)
: ReportEvent("EcuInstallationApplied", 0) {
setEcu(ecu);
setCorrelationId(correlation_id);
}
EcuInstallationCompletedReport::EcuInstallationCompletedReport(const Uptane::EcuSerial& ecu,
const std::string& correlation_id, bool success)
: ReportEvent("EcuInstallationCompleted", 0) {
setEcu(ecu);
setCorrelationId(correlation_id);
custom["success"] = success;
}
<commit_msg>Less verbose ~ReportQueue()<commit_after>#include "reportqueue.h"
#include <chrono>
ReportQueue::ReportQueue(const Config& config_in, std::shared_ptr<HttpInterface> http_client)
: config(config_in), http(std::move(http_client)) {
thread_ = std::thread(std::bind(&ReportQueue::run, this));
}
ReportQueue::~ReportQueue() {
{
std::lock_guard<std::mutex> lock(m_);
shutdown_ = true;
}
cv_.notify_all();
thread_.join();
LOG_TRACE << "Flushing report queue";
flushQueue();
}
void ReportQueue::run() {
// Check if queue is nonempty. If so, move any reports to the Json array and
// try to send it to the server. Clear the Json array only if the send
// succeeds.
std::unique_lock<std::mutex> lock(m_);
while (!shutdown_) {
flushQueue();
cv_.wait_for(lock, std::chrono::seconds(10));
}
}
void ReportQueue::enqueue(std::unique_ptr<ReportEvent> event) {
{
std::lock_guard<std::mutex> lock(m_);
report_queue_.push(std::move(event));
}
cv_.notify_all();
}
void ReportQueue::flushQueue() {
while (!report_queue_.empty()) {
report_array.append(report_queue_.front()->toJson());
report_queue_.pop();
}
if (config.tls.server.empty()) {
// Prevent a lot of unnecessary garbage output in uptane vector tests.
LOG_TRACE << "No server specified. Clearing report queue.";
report_array.clear();
}
if (!report_array.empty()) {
HttpResponse response = http->post(config.tls.server + "/events", report_array);
// 404 implies the server does not support this feature. Nothing we can
// do, just move along.
if (response.http_status_code == 404) {
LOG_TRACE << "Server does not support event reports. Clearing report queue.";
}
if (response.isOk() || response.http_status_code == 404) {
report_array.clear();
}
}
}
void ReportEvent::setEcu(const Uptane::EcuSerial& ecu) { custom["ecu"] = ecu.ToString(); }
void ReportEvent::setCorrelationId(const std::string& correlation_id) {
if (correlation_id != "") {
custom["correlationId"] = correlation_id;
}
}
Json::Value ReportEvent::toJson() {
Json::Value out;
out["id"] = id;
out["deviceTime"] = timestamp.ToString();
out["eventType"]["id"] = type;
out["eventType"]["version"] = version;
out["event"] = custom;
return out;
}
CampaignAcceptedReport::CampaignAcceptedReport(const std::string& campaign_id) : ReportEvent("campaign_accepted", 0) {
custom["campaignId"] = campaign_id;
}
CampaignDeclinedReport::CampaignDeclinedReport(const std::string& campaign_id) : ReportEvent("campaign_declined", 0) {
custom["campaignId"] = campaign_id;
}
CampaignPostponedReport::CampaignPostponedReport(const std::string& campaign_id)
: ReportEvent("campaign_postponed", 0) {
custom["campaignId"] = campaign_id;
}
DevicePausedReport::DevicePausedReport(const std::string& correlation_id) : ReportEvent("DevicePaused", 0) {
setCorrelationId(correlation_id);
}
DeviceResumedReport::DeviceResumedReport(const std::string& correlation_id) : ReportEvent("DeviceResumed", 0) {
setCorrelationId(correlation_id);
}
EcuDownloadStartedReport::EcuDownloadStartedReport(const Uptane::EcuSerial& ecu, const std::string& correlation_id)
: ReportEvent("EcuDownloadStarted", 0) {
setEcu(ecu);
setCorrelationId(correlation_id);
}
EcuDownloadCompletedReport::EcuDownloadCompletedReport(const Uptane::EcuSerial& ecu, const std::string& correlation_id,
bool success)
: ReportEvent("EcuDownloadCompleted", 0) {
setEcu(ecu);
setCorrelationId(correlation_id);
custom["success"] = success;
}
EcuInstallationStartedReport::EcuInstallationStartedReport(const Uptane::EcuSerial& ecu,
const std::string& correlation_id)
: ReportEvent("EcuInstallationStarted", 0) {
setEcu(ecu);
setCorrelationId(correlation_id);
}
EcuInstallationAppliedReport::EcuInstallationAppliedReport(const Uptane::EcuSerial& ecu,
const std::string& correlation_id)
: ReportEvent("EcuInstallationApplied", 0) {
setEcu(ecu);
setCorrelationId(correlation_id);
}
EcuInstallationCompletedReport::EcuInstallationCompletedReport(const Uptane::EcuSerial& ecu,
const std::string& correlation_id, bool success)
: ReportEvent("EcuInstallationCompleted", 0) {
setEcu(ecu);
setCorrelationId(correlation_id);
custom["success"] = success;
}
<|endoftext|> |
<commit_before>/**************************************************************************************/
/* */
/* Visualization Library */
/* http://www.visualizationlibrary.com */
/* */
/* Copyright (c) 2005-2010, Michele Bosi */
/* All rights reserved. */
/* */
/* Redistribution and use in source and binary forms, with or without modification, */
/* are permitted provided that the following conditions are met: */
/* */
/* - Redistributions of source code must retain the above copyright notice, this */
/* list of conditions and the following disclaimer. */
/* */
/* - Redistributions in binary form must reproduce the above copyright notice, this */
/* list of conditions and the following disclaimer in the documentation and/or */
/* other materials provided with the distribution. */
/* */
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND */
/* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */
/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */
/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR */
/* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */
/* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */
/* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */
/* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */
/* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS */
/* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/* */
/**************************************************************************************/
#include "BaseDemo.hpp"
#include <vlGraphics/Effect.hpp>
#include <vlGraphics/Geometry.hpp>
#include <vlGraphics/GLSL.hpp>
#include <vlGraphics/GeometryPrimitives.hpp>
#include <vlCore/FileSystem.hpp>
class App_TessellationShader: public BaseDemo
{
public:
void initEvent()
{
vl::Log::info(appletInfo());
if(!vl::Has_GL_Version_4_0)
{
vl::Log::error("This test requires OpenGL 4!\n");
vl::Time::sleep(2000);
exit(1);
}
const int patch_count = 128;
const float world_size = 2500.0;
const float height_scale = 150.0;
const float pixel_per_edge = 16.0f;
const float max_tessellation = 64.0f;
vl::ref< vl::Geometry > geom_patch = makeGrid( vl::vec3(), world_size, world_size, patch_count, patch_count, false );
geom_patch->toGenericVertexAttribs();
// patch parameter associated to the draw call
vl::ref<vl::PatchParameter> patch_param = new vl::PatchParameter;
patch_param->setPatchVertices(4);
geom_patch->drawCalls()->at(0)->setPatchParameter( patch_param.get() );
geom_patch->drawCalls()->at(0)->setPrimitiveType(vl::PT_PATCHES);
vl::ref<vl::Texture> hmap = new vl::Texture("/images/ps_height_4k.jpg", vl::TF_RED, false, false);
vl::ref<vl::Texture> tmap = new vl::Texture("/images/ps_texture_4k.jpg", vl::TF_RGBA, true, false);
hmap->getTexParameter()->setMinFilter(vl::TPF_LINEAR);
hmap->getTexParameter()->setMagFilter(vl::TPF_LINEAR);
// tessellated patches fx
vl::ref<vl::Effect> fx = new vl::Effect;
fx->shader()->enable(vl::EN_DEPTH_TEST);
fx->shader()->gocTextureUnit(0)->setTexture( hmap.get() );
fx->shader()->gocTextureUnit(1)->setTexture( tmap.get() );
// bind all the necessary stages to the GLSLProgram
mGLSL = fx->shader()->gocGLSLProgram();
mGLSL->attachShader( new vl::GLSLVertexShader("glsl/tess_grid.vs") );
mGLSL->attachShader( new vl::GLSLTessControlShader("glsl/tess_grid.tcs") );
mGLSL->attachShader( new vl::GLSLTessEvaluationShader("glsl/tess_grid.tes") );
mGLSL->attachShader( new vl::GLSLFragmentShader("glsl/tess_grid.fs") );
mGLSL->gocUniform("pixel_per_edge")->setUniformF(pixel_per_edge);
mGLSL->gocUniform("max_tessellation")->setUniformF(max_tessellation);
mGLSL->gocUniform("screen_size")->setUniform(vl::fvec2(512,512));
mGLSL->gocUniform("world_size")->setUniformF(world_size);
mGLSL->gocUniform("height_scale")->setUniformF(height_scale);
mGLSL->gocUniform("tex_heghtmap")->setUniformI(0);
mGLSL->gocUniform("tex_diffuse")->setUniformI(1);
mGLSL->addAutoAttribLocation( "vl_Position", 0 );
// tessellated patches fx_wire
vl::ref<vl::Effect> fx_wire = new vl::Effect;
fx_wire->shader()->enable(vl::EN_DEPTH_TEST);
fx_wire->shader()->gocPolygonMode()->set(vl::PM_LINE, vl::PM_LINE);
fx_wire->shader()->gocTextureUnit(0)->setTexture( hmap.get() );
fx_wire->shader()->gocPolygonOffset()->set(-1.0f, -1.0f);
fx_wire->shader()->enable(vl::EN_POLYGON_OFFSET_LINE);
// bind all the necessary stages to the GLSLProgram
mGLSLWire = fx_wire->shader()->gocGLSLProgram();
mGLSLWire->attachShader( new vl::GLSLVertexShader("glsl/tess_grid.vs") );
mGLSLWire->attachShader( new vl::GLSLTessControlShader("glsl/tess_grid.tcs") );
mGLSLWire->attachShader( new vl::GLSLTessEvaluationShader("glsl/tess_grid.tes") );
mGLSLWire->attachShader( new vl::GLSLFragmentShader("glsl/tess_grid_wire.fs") );
mGLSLWire->gocUniform("pixel_per_edge")->setUniformF(pixel_per_edge);
mGLSLWire->gocUniform("max_tessellation")->setUniformF(max_tessellation);
mGLSLWire->gocUniform("screen_size")->setUniform(vl::fvec2(512,512));
mGLSLWire->gocUniform("world_size")->setUniformF(world_size);
mGLSLWire->gocUniform("height_scale")->setUniformF(height_scale);
mGLSLWire->gocUniform("tex_heghtmap")->setUniformI(0);
mGLSLWire->gocUniform("wire_color")->setUniform(vl::lightgreen);
mGLSLWire->addAutoAttribLocation( "vl_Position", 0 );
sceneManager()->tree()->addActor( geom_patch.get(), fx.get(), NULL )->setRenderRank(0);
mWireActor = sceneManager()->tree()->addActor( geom_patch.get(), fx_wire.get(), NULL );
mWireActor->setRenderRank(1);
// debugging
#if 0
// base patch grid
vl::ref< vl::Geometry > geom_quads = makeGrid(vl::fvec3(), world_size,world_size, patch_count,patch_count, true);
geom_quads->setColor(vl::red);
// base patch grid fx
vl::ref<vl::Effect> fx_grid = new vl::Effect;
fx_grid->shader()->gocPolygonMode()->set(vl::PM_LINE, vl::PM_LINE);
// add grid
sceneManager()->tree()->addActor( geom_quads.get(), fx_grid.get(), NULL )->setRenderRank(2);
#endif
}
// interactively change the inner/outer tessellation levels
void keyPressEvent(unsigned short, vl::EKey key)
{
if (key == vl::Key_Space)
mWireActor->setEnableMask( mWireActor->enableMask() ? 0 : 1 );
}
void resizeEvent(int w, int h)
{
BaseDemo::resizeEvent(w,h);
mGLSL->gocUniform("screen_size")->setUniform(vl::fvec2((float)w,(float)h));
mGLSLWire->gocUniform("screen_size")->setUniform(vl::fvec2((float)w,(float)h));
}
protected:
vl::GLSLProgram* mGLSL;
vl::GLSLProgram* mGLSLWire;
vl::Actor* mWireActor;
};
// Have fun!
BaseDemo* Create_App_TessellationShader() { return new App_TessellationShader; }
class App_TessellationShaderTri: public BaseDemo
{
public:
void initEvent()
{
vl::Log::info(appletInfo());
// hemisphere base geometry
vl::ref< vl::Geometry > geom_patch = new vl::Geometry;
// hemisphere base geometry vertices
vl::ref<vl::ArrayFloat3 > verts = new vl::ArrayFloat3;
verts->resize(12);
verts->at(0) = vl::fvec3(1,0,0);
verts->at(1) = vl::fvec3(0,1,0);
verts->at(2) = vl::fvec3(0,0,1);
verts->at(3) = vl::fvec3(1,0,0);
verts->at(4) = vl::fvec3(0,0,-1);
verts->at(5) = vl::fvec3(0,1,0);
verts->at(6) = vl::fvec3(0,0,-1);
verts->at(7) = vl::fvec3(-1,0,0);
verts->at(8) = vl::fvec3(0,1,0);
verts->at(9) = vl::fvec3(-1,0,0);
verts->at(10) = vl::fvec3(0,0,1);
verts->at(11) = vl::fvec3(0,1,0);
// hemisphere base geometry vertex colors
vl::ref<vl::ArrayFloat3 > cols = new vl::ArrayFloat3;
cols->resize(12);
cols->at(0) = vl::fvec3(1,0,0);
cols->at(1) = vl::fvec3(1,0,0);
cols->at(2) = vl::fvec3(1,0,0);
cols->at(3) = vl::fvec3(0,1,0);
cols->at(4) = vl::fvec3(0,1,0);
cols->at(5) = vl::fvec3(0,1,0);
cols->at(6) = vl::fvec3(1,1,0);
cols->at(7) = vl::fvec3(1,1,0);
cols->at(8) = vl::fvec3(1,1,0);
cols->at(9) = vl::fvec3(0,0,1);
cols->at(10) = vl::fvec3(0,0,1);
cols->at(11) = vl::fvec3(0,0,1);
// vertex array
geom_patch->setVertexArray( verts.get() );
// color array
geom_patch->setColorArray( cols.get() );
// draw call
vl::ref< vl::DrawArrays> da = new vl::DrawArrays(vl::PT_PATCHES, 0, verts->size());
geom_patch->drawCalls()->push_back(da.get());
// patch parameter associated to the draw call
vl::ref<vl::PatchParameter> patch_param = new vl::PatchParameter;
patch_param->setPatchVertices(3);
da->setPatchParameter( patch_param.get() );
// effect: light + depth testing
vl::ref<vl::Effect> fx = new vl::Effect;
fx->shader()->enable(vl::EN_DEPTH_TEST);
// bind all the necessary stages to the GLSLProgram
mGLSL = fx->shader()->gocGLSLProgram();
mGLSL->attachShader( new vl::GLSLVertexShader("glsl/smooth_triangle.vs") );
mGLSL->attachShader( new vl::GLSLTessControlShader("glsl/smooth_triangle.tcs") );
mGLSL->attachShader( new vl::GLSLTessEvaluationShader("glsl/smooth_triangle.tes") );
mGLSL->attachShader( new vl::GLSLGeometryShader("glsl/smooth_triangle.gs") );
mGLSL->gocUniform("Outer")->setUniformF(10.0f);
mGLSL->gocUniform("Inner")->setUniformF(10.0f);
mGLSL->gocUniform("Radius")->setUniformF(1.0f);
sceneManager()->tree()->addActor( geom_patch.get(), fx.get(), NULL );
}
// interactively change the inner/outer tessellation levels
void keyPressEvent(unsigned short, vl::EKey key)
{
float outer = 0;
float inner = 0;
mGLSL->gocUniform("Outer")->getUniform(&outer);
mGLSL->gocUniform("Inner")->getUniform(&inner);
if (key == vl::Key_Left)
outer--;
else
if (key == vl::Key_Right)
outer++;
else
if (key == vl::Key_Down)
inner--;
else
if (key == vl::Key_Up)
inner++;
inner = inner < 1 ? 1 : inner;
outer = outer < 1 ? 1 : outer;
mGLSL->gocUniform("Outer")->setUniformF(outer);
mGLSL->gocUniform("Inner")->setUniformF(inner);
vl::Log::print( vl::Say("outer = %n, inner = %n\n") << outer << inner );
}
protected:
vl::GLSLProgram* mGLSL;
};
// Have fun!
BaseDemo* Create_App_TessellationShaderTri() { return new App_TessellationShaderTri; }
<commit_msg>use convertToVertexAttribs()<commit_after>/**************************************************************************************/
/* */
/* Visualization Library */
/* http://www.visualizationlibrary.com */
/* */
/* Copyright (c) 2005-2010, Michele Bosi */
/* All rights reserved. */
/* */
/* Redistribution and use in source and binary forms, with or without modification, */
/* are permitted provided that the following conditions are met: */
/* */
/* - Redistributions of source code must retain the above copyright notice, this */
/* list of conditions and the following disclaimer. */
/* */
/* - Redistributions in binary form must reproduce the above copyright notice, this */
/* list of conditions and the following disclaimer in the documentation and/or */
/* other materials provided with the distribution. */
/* */
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND */
/* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */
/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */
/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR */
/* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */
/* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */
/* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */
/* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */
/* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS */
/* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/* */
/**************************************************************************************/
#include "BaseDemo.hpp"
#include <vlGraphics/Effect.hpp>
#include <vlGraphics/Geometry.hpp>
#include <vlGraphics/GLSL.hpp>
#include <vlGraphics/GeometryPrimitives.hpp>
#include <vlCore/FileSystem.hpp>
class App_TessellationShader: public BaseDemo
{
public:
void initEvent()
{
vl::Log::info(appletInfo());
if(!vl::Has_GL_Version_4_0)
{
vl::Log::error("This test requires OpenGL 4!\n");
vl::Time::sleep(2000);
exit(1);
}
const int patch_count = 128;
const float world_size = 2500.0;
const float height_scale = 150.0;
const float pixel_per_edge = 16.0f;
const float max_tessellation = 64.0f;
vl::ref< vl::Geometry > geom_patch = makeGrid( vl::vec3(), world_size, world_size, patch_count, patch_count, false );
geom_patch->convertToVertexAttribs();
// patch parameter associated to the draw call
vl::ref<vl::PatchParameter> patch_param = new vl::PatchParameter;
patch_param->setPatchVertices(4);
geom_patch->drawCalls()->at(0)->setPatchParameter( patch_param.get() );
geom_patch->drawCalls()->at(0)->setPrimitiveType(vl::PT_PATCHES);
vl::ref<vl::Texture> hmap = new vl::Texture("/images/ps_height_4k.jpg", vl::TF_RED, false, false);
vl::ref<vl::Texture> tmap = new vl::Texture("/images/ps_texture_4k.jpg", vl::TF_RGBA, true, false);
hmap->getTexParameter()->setMinFilter(vl::TPF_LINEAR);
hmap->getTexParameter()->setMagFilter(vl::TPF_LINEAR);
// tessellated patches fx
vl::ref<vl::Effect> fx = new vl::Effect;
fx->shader()->enable(vl::EN_DEPTH_TEST);
fx->shader()->gocTextureUnit(0)->setTexture( hmap.get() );
fx->shader()->gocTextureUnit(1)->setTexture( tmap.get() );
// bind all the necessary stages to the GLSLProgram
mGLSL = fx->shader()->gocGLSLProgram();
mGLSL->attachShader( new vl::GLSLVertexShader("glsl/tess_grid.vs") );
mGLSL->attachShader( new vl::GLSLTessControlShader("glsl/tess_grid.tcs") );
mGLSL->attachShader( new vl::GLSLTessEvaluationShader("glsl/tess_grid.tes") );
mGLSL->attachShader( new vl::GLSLFragmentShader("glsl/tess_grid.fs") );
mGLSL->gocUniform("pixel_per_edge")->setUniformF(pixel_per_edge);
mGLSL->gocUniform("max_tessellation")->setUniformF(max_tessellation);
mGLSL->gocUniform("screen_size")->setUniform(vl::fvec2(512,512));
mGLSL->gocUniform("world_size")->setUniformF(world_size);
mGLSL->gocUniform("height_scale")->setUniformF(height_scale);
mGLSL->gocUniform("tex_heghtmap")->setUniformI(0);
mGLSL->gocUniform("tex_diffuse")->setUniformI(1);
mGLSL->addAutoAttribLocation( "vl_Position", 0 );
// tessellated patches fx_wire
vl::ref<vl::Effect> fx_wire = new vl::Effect;
fx_wire->shader()->enable(vl::EN_DEPTH_TEST);
fx_wire->shader()->gocPolygonMode()->set(vl::PM_LINE, vl::PM_LINE);
fx_wire->shader()->gocTextureUnit(0)->setTexture( hmap.get() );
fx_wire->shader()->gocPolygonOffset()->set(-1.0f, -1.0f);
fx_wire->shader()->enable(vl::EN_POLYGON_OFFSET_LINE);
// bind all the necessary stages to the GLSLProgram
mGLSLWire = fx_wire->shader()->gocGLSLProgram();
mGLSLWire->attachShader( new vl::GLSLVertexShader("glsl/tess_grid.vs") );
mGLSLWire->attachShader( new vl::GLSLTessControlShader("glsl/tess_grid.tcs") );
mGLSLWire->attachShader( new vl::GLSLTessEvaluationShader("glsl/tess_grid.tes") );
mGLSLWire->attachShader( new vl::GLSLFragmentShader("glsl/tess_grid_wire.fs") );
mGLSLWire->gocUniform("pixel_per_edge")->setUniformF(pixel_per_edge);
mGLSLWire->gocUniform("max_tessellation")->setUniformF(max_tessellation);
mGLSLWire->gocUniform("screen_size")->setUniform(vl::fvec2(512,512));
mGLSLWire->gocUniform("world_size")->setUniformF(world_size);
mGLSLWire->gocUniform("height_scale")->setUniformF(height_scale);
mGLSLWire->gocUniform("tex_heghtmap")->setUniformI(0);
mGLSLWire->gocUniform("wire_color")->setUniform(vl::lightgreen);
mGLSLWire->addAutoAttribLocation( "vl_Position", 0 );
sceneManager()->tree()->addActor( geom_patch.get(), fx.get(), NULL )->setRenderRank(0);
mWireActor = sceneManager()->tree()->addActor( geom_patch.get(), fx_wire.get(), NULL );
mWireActor->setRenderRank(1);
// debugging
#if 0
// base patch grid
vl::ref< vl::Geometry > geom_quads = makeGrid(vl::fvec3(), world_size,world_size, patch_count,patch_count, true);
geom_quads->setColor(vl::red);
// base patch grid fx
vl::ref<vl::Effect> fx_grid = new vl::Effect;
fx_grid->shader()->gocPolygonMode()->set(vl::PM_LINE, vl::PM_LINE);
// add grid
sceneManager()->tree()->addActor( geom_quads.get(), fx_grid.get(), NULL )->setRenderRank(2);
#endif
}
// interactively change the inner/outer tessellation levels
void keyPressEvent(unsigned short, vl::EKey key)
{
if (key == vl::Key_Space)
mWireActor->setEnableMask( mWireActor->enableMask() ? 0 : 1 );
}
void resizeEvent(int w, int h)
{
BaseDemo::resizeEvent(w,h);
mGLSL->gocUniform("screen_size")->setUniform(vl::fvec2((float)w,(float)h));
mGLSLWire->gocUniform("screen_size")->setUniform(vl::fvec2((float)w,(float)h));
}
protected:
vl::GLSLProgram* mGLSL;
vl::GLSLProgram* mGLSLWire;
vl::Actor* mWireActor;
};
// Have fun!
BaseDemo* Create_App_TessellationShader() { return new App_TessellationShader; }
class App_TessellationShaderTri: public BaseDemo
{
public:
void initEvent()
{
vl::Log::info(appletInfo());
// hemisphere base geometry
vl::ref< vl::Geometry > geom_patch = new vl::Geometry;
// hemisphere base geometry vertices
vl::ref<vl::ArrayFloat3 > verts = new vl::ArrayFloat3;
verts->resize(12);
verts->at(0) = vl::fvec3(1,0,0);
verts->at(1) = vl::fvec3(0,1,0);
verts->at(2) = vl::fvec3(0,0,1);
verts->at(3) = vl::fvec3(1,0,0);
verts->at(4) = vl::fvec3(0,0,-1);
verts->at(5) = vl::fvec3(0,1,0);
verts->at(6) = vl::fvec3(0,0,-1);
verts->at(7) = vl::fvec3(-1,0,0);
verts->at(8) = vl::fvec3(0,1,0);
verts->at(9) = vl::fvec3(-1,0,0);
verts->at(10) = vl::fvec3(0,0,1);
verts->at(11) = vl::fvec3(0,1,0);
// hemisphere base geometry vertex colors
vl::ref<vl::ArrayFloat3 > cols = new vl::ArrayFloat3;
cols->resize(12);
cols->at(0) = vl::fvec3(1,0,0);
cols->at(1) = vl::fvec3(1,0,0);
cols->at(2) = vl::fvec3(1,0,0);
cols->at(3) = vl::fvec3(0,1,0);
cols->at(4) = vl::fvec3(0,1,0);
cols->at(5) = vl::fvec3(0,1,0);
cols->at(6) = vl::fvec3(1,1,0);
cols->at(7) = vl::fvec3(1,1,0);
cols->at(8) = vl::fvec3(1,1,0);
cols->at(9) = vl::fvec3(0,0,1);
cols->at(10) = vl::fvec3(0,0,1);
cols->at(11) = vl::fvec3(0,0,1);
// vertex array
geom_patch->setVertexArray( verts.get() );
// color array
geom_patch->setColorArray( cols.get() );
// draw call
vl::ref< vl::DrawArrays> da = new vl::DrawArrays(vl::PT_PATCHES, 0, verts->size());
geom_patch->drawCalls()->push_back(da.get());
// patch parameter associated to the draw call
vl::ref<vl::PatchParameter> patch_param = new vl::PatchParameter;
patch_param->setPatchVertices(3);
da->setPatchParameter( patch_param.get() );
// effect: light + depth testing
vl::ref<vl::Effect> fx = new vl::Effect;
fx->shader()->enable(vl::EN_DEPTH_TEST);
// bind all the necessary stages to the GLSLProgram
mGLSL = fx->shader()->gocGLSLProgram();
mGLSL->attachShader( new vl::GLSLVertexShader("glsl/smooth_triangle.vs") );
mGLSL->attachShader( new vl::GLSLTessControlShader("glsl/smooth_triangle.tcs") );
mGLSL->attachShader( new vl::GLSLTessEvaluationShader("glsl/smooth_triangle.tes") );
mGLSL->attachShader( new vl::GLSLGeometryShader("glsl/smooth_triangle.gs") );
mGLSL->gocUniform("Outer")->setUniformF(10.0f);
mGLSL->gocUniform("Inner")->setUniformF(10.0f);
mGLSL->gocUniform("Radius")->setUniformF(1.0f);
sceneManager()->tree()->addActor( geom_patch.get(), fx.get(), NULL );
}
// interactively change the inner/outer tessellation levels
void keyPressEvent(unsigned short, vl::EKey key)
{
float outer = 0;
float inner = 0;
mGLSL->gocUniform("Outer")->getUniform(&outer);
mGLSL->gocUniform("Inner")->getUniform(&inner);
if (key == vl::Key_Left)
outer--;
else
if (key == vl::Key_Right)
outer++;
else
if (key == vl::Key_Down)
inner--;
else
if (key == vl::Key_Up)
inner++;
inner = inner < 1 ? 1 : inner;
outer = outer < 1 ? 1 : outer;
mGLSL->gocUniform("Outer")->setUniformF(outer);
mGLSL->gocUniform("Inner")->setUniformF(inner);
vl::Log::print( vl::Say("outer = %n, inner = %n\n") << outer << inner );
}
protected:
vl::GLSLProgram* mGLSL;
};
// Have fun!
BaseDemo* Create_App_TessellationShaderTri() { return new App_TessellationShaderTri; }
<|endoftext|> |
<commit_before><commit_msg><commit_after><|endoftext|> |
<commit_before><commit_msg>we want the b2BodyConfig typedef to be nested from within the physics class since it is physics engine specific<commit_after><|endoftext|> |
<commit_before>#include <iostream>
#include <unordered_map>
#include <utility>
using namespace std;
struct RandomListNode {
int label;
RandomListNode *next, *random;
RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
};
class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
if (head == NULL) return NULL;
unordered_map<RandomListNode*, RandomListNode*> p2p;
RandomListNode* newhead = new RandomListNode(head->label);
newhead->random = head->random;
p2p.insert(pair<RandomListNode*, RandomListNode*>(head, newhead));
RandomListNode* tail = newhead;
head = head->next;
while (head != NULL) {
RandomListNode* item = new RandomListNode(head->label);
item->random = head->random;
p2p.insert(pair<RandomListNode*, RandomListNode*>(head, item));
tail->next = item;
tail = item;
head = head->next;
}
tail = newhead;
while (tail != NULL) {
if (tail->random != NULL) {
tail->random = p2p.find(tail->random)->second;
}
tail = tail->next;
}
return newhead;
}
};
void print_list(RandomListNode* head) {
while (head != NULL) {
cout<<head->label;
if (head->next == NULL) {
cout<<", next=null";
} else {
cout<<", next="<<head->next->label;
}
if (head->random == NULL) {
cout<<", rnd=null";
} else {
cout<<", rnd="<<head->random->label;
}
cout<<endl;
head = head->next;
}
}
int main() {
RandomListNode* items[10];
for (int i=0; i<10; i++) {
items[i] = new RandomListNode(i);
}
for (int i=0; i<9; i++) {
items[i]->next = items[i+1];
}
items[0]->next = NULL;
items[2]->random = items[4];
items[5]->random = items[1];
items[8]->random = items[3];
print_list(items[0]);
Solution s;
RandomListNode* ret = s.copyRandomList(items[0]);
cout<<"==="<<endl;
print_list(ret);
return 0;
}
<commit_msg>Add another sulotion for Leetcode Problem: CopyListWithRandomPointer<commit_after>#include <iostream>
#include <unordered_map>
#include <utility>
using namespace std;
struct RandomListNode {
int label;
RandomListNode *next, *random;
RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
};
class Solution {
public:
// 1. with a map
RandomListNode *copyRandomList(RandomListNode *head) {
if (head == NULL) return NULL;
unordered_map<RandomListNode*, RandomListNode*> p2p;
RandomListNode* newhead = new RandomListNode(head->label);
newhead->random = head->random;
p2p.insert(pair<RandomListNode*, RandomListNode*>(head, newhead));
RandomListNode* tail = newhead;
head = head->next;
while (head != NULL) {
RandomListNode* item = new RandomListNode(head->label);
item->random = head->random;
p2p.insert(pair<RandomListNode*, RandomListNode*>(head, item));
tail->next = item;
tail = item;
head = head->next;
}
tail = newhead;
while (tail != NULL) {
if (tail->random != NULL) {
tail->random = p2p.find(tail->random)->second;
}
tail = tail->next;
}
return newhead;
}
// 2. without a map
RandomListNode *_copyRandomList(RandomListNode *head) {
if (head == NULL) return NULL;
RandomListNode* item = new RandomListNode(head->label);
item->random = head->random;
item->next = head->next;
head->next = item;
RandomListNode* tail = item->next;
while (tail != NULL) {
item = new RandomListNode(tail->label);
item->random = tail->random;
item->next = tail->next;
tail->next = item;
tail = item->next;
}
tail = head;
while (tail != NULL) {
tail = tail->next;
if (tail->random != NULL) tail->random = tail->random->next;
tail = tail->next;
}
RandomListNode* newhead = head->next;
RandomListNode* oldtail = head;
tail = newhead;
while (tail->next != NULL) {
oldtail->next = tail->next;
oldtail = tail->next;
tail->next = oldtail->next;
tail = oldtail->next;
}
oldtail->next = NULL;
return newhead;
}
};
void print_list(RandomListNode* head) {
while (head != NULL) {
cout<<head->label;
if (head->next == NULL) {
cout<<", next=null";
} else {
cout<<", next="<<head->next->label;
}
if (head->random == NULL) {
cout<<", rnd=null";
} else {
cout<<", rnd="<<head->random->label;
}
cout<<endl;
head = head->next;
}
}
int main() {
RandomListNode* items[10];
for (int i=0; i<10; i++) {
items[i] = new RandomListNode(i);
}
for (int i=0; i<9; i++) {
items[i]->next = items[i+1];
}
items[2]->random = items[4];
items[5]->random = items[1];
items[8]->random = items[3];
print_list(items[0]);
Solution s;
RandomListNode* ret = s._copyRandomList(items[0]);
cout<<"==="<<endl;
print_list(ret);
return 0;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#include "kernel/abstract.h"
#include "kernel/instantiate.h"
#include "kernel/inductive/inductive.h"
#include "library/locals.h"
#include "library/tactic/tactic.h"
#include "library/reducible.h"
#include "library/tactic/expr_to_tactic.h"
namespace lean {
class inversion_tac {
environment const & m_env;
io_state const & m_ios;
proof_state const & m_ps;
name_generator m_ngen;
substitution m_subst;
std::unique_ptr<type_checker> m_tc;
unsigned m_nparams;
unsigned m_nindices;
unsigned m_nminors;
declaration m_I_decl;
declaration m_cases_on_decl;
void init_inductive_info(name const & n) {
m_nindices = *inductive::get_num_indices(m_env, n);
m_nparams = *inductive::get_num_params(m_env, n);
m_nminors = *inductive::get_num_minor_premises(m_env, n);
m_I_decl = m_env.get(n);
m_cases_on_decl = m_env.get({n, "cases_on"});
}
bool is_inversion_applicable(expr const & t) {
buffer<expr> args;
expr const & fn = get_app_args(t, args);
if (!is_constant(fn))
return false;
if (!inductive::is_inductive_decl(m_env, const_name(fn)))
return false;
if (!m_env.find(name{const_name(fn), "cases_on"}) ||
!m_env.find(name("eq")) || !m_env.find(name("heq")))
return false;
init_inductive_info(const_name(fn));
if (args.size() != m_nindices + m_nparams)
return false;
return true;
}
pair<expr, expr> mk_eq(expr const & lhs, expr const & rhs) {
expr lhs_type = m_tc->infer(lhs).first;
expr rhs_type = m_tc->infer(rhs).first;
level l = sort_level(m_tc->ensure_type(lhs_type).first);
constraint_seq cs;
if (m_tc->is_def_eq(lhs_type, rhs_type, justification(), cs) && !cs) {
return mk_pair(mk_app(mk_constant("eq", to_list(l)), lhs_type, lhs, rhs),
mk_app(mk_constant({"eq", "refl"}, to_list(l)), rhs_type, rhs));
} else {
return mk_pair(mk_app(mk_constant("heq", to_list(l)), lhs_type, lhs, rhs_type, rhs),
mk_app(mk_constant({"heq", "refl"}, to_list(l)), rhs_type, rhs));
}
}
goal generalize_indices(goal const & g, expr const & h, expr const & h_type) {
buffer<expr> hyps;
g.get_hyps(hyps);
expr m = g.get_meta();
expr m_type = g.get_type();
name h_new_name = g.get_unused_name(local_pp_name(h));
buffer<expr> I_args;
expr const & I = get_app_args(h_type, I_args);
if (m_nindices > 0) {
expr h_new_type = mk_app(I, I_args.size() - m_nindices, I_args.data());
expr d = m_tc->whnf(m_tc->infer(h_new_type).first).first;
unsigned eq_idx = 1;
name eq_prefix("H");
buffer<expr> ts;
buffer<expr> eqs;
buffer<expr> refls;
name t_prefix("t");
unsigned nidx = 1;
for (unsigned i = I_args.size() - m_nindices; i < I_args.size(); i++) {
expr t_type = binding_domain(d);
expr t = mk_local(m_ngen.next(), g.get_unused_name(t_prefix, nidx), t_type, binder_info());
expr const & index = I_args[i];
pair<expr, expr> p = mk_eq(t, index);
expr new_eq = p.first;
expr new_refl = p.second;
eqs.push_back(mk_local(m_ngen.next(), g.get_unused_name(eq_prefix, eq_idx), new_eq, binder_info()));
refls.push_back(new_refl);
h_new_type = mk_app(h_new_type, t);
hyps.push_back(t);
ts.push_back(t);
d = instantiate(binding_body(d), t);
}
expr h_new = mk_local(m_ngen.next(), h_new_name, h_new_type, local_info(h));
hyps.push_back(h_new);
expr new_type = Pi(eqs, g.get_type());
expr new_meta = mk_app(mk_metavar(m_ngen.next(), Pi(hyps, new_type)), hyps);
goal new_g(new_meta, new_type);
expr val = g.abstract(mk_app(mk_app(mk_app(Fun(ts, Fun(h_new, new_meta)), m_nindices, I_args.end() - m_nindices), h), refls));
m_subst.assign(g.get_name(), val);
return new_g;
} else {
expr h_new = mk_local(m_ngen.next(), h_new_name, h_type, local_info(h));
hyps.push_back(h_new);
expr new_meta = mk_app(mk_metavar(m_ngen.next(), Pi(hyps, g.get_type())), hyps);
goal new_g(new_meta, g.get_type());
expr val = g.abstract(mk_app(new_meta, h));
m_subst.assign(g.get_name(), val);
return new_g;
}
}
list<goal> apply_cases_on(goal const & g) {
buffer<expr> hyps;
g.get_hyps(hyps);
expr const & h = hyps.back();
expr const & h_type = mlocal_type(h);
buffer<expr> I_args;
expr const & I = get_app_args(h_type, I_args);
expr g_type = g.get_type();
expr cases_on;
if (length(m_cases_on_decl.get_univ_params()) != length(m_I_decl.get_univ_params())) {
level g_lvl = sort_level(m_tc->ensure_type(g_type).first);
cases_on = mk_constant({const_name(I), "cases_on"}, cons(g_lvl, const_levels(I)));
} else {
cases_on = mk_constant({const_name(I), "cases_on"}, const_levels(I));
}
// add params
cases_on = mk_app(cases_on, m_nparams, I_args.data());
// add type former
expr type_former = Fun(m_nindices, I_args.end() - m_nindices, g_type);
cases_on = mk_app(cases_on, type_former);
// add indices
cases_on = mk_app(cases_on, m_nindices, I_args.end() - m_nindices);
// add h
cases_on = mk_app(cases_on, h);
buffer<expr> new_hyps;
new_hyps.append(hyps.size() - m_nindices - 1, hyps.data());
// add a subgoal for each minor premise of cases_on
expr cases_on_type = m_tc->whnf(m_tc->infer(cases_on).first).first;
buffer<goal> new_goals;
for (unsigned i = 0; i < m_nminors; i++) {
expr new_type = binding_domain(cases_on_type);
expr new_meta = mk_app(mk_metavar(m_ngen.next(), Pi(new_hyps, new_type)), new_hyps);
goal new_g(new_meta, new_type);
new_goals.push_back(new_g);
cases_on = mk_app(cases_on, new_meta);
cases_on_type = m_tc->whnf(binding_body(cases_on_type)).first; // the minor premises do not depend on each other
}
expr val = g.abstract(cases_on);
m_subst.assign(g.get_name(), val);
return to_list(new_goals.begin(), new_goals.end());
}
// Store in \c r the number of arguments for each cases_on minor.
void get_minors_nargs(buffer<unsigned> & r) {
expr cases_on_type = m_cases_on_decl.get_type();
for (unsigned i = 0; i < m_nparams + 1 + m_nindices + 1; i++)
cases_on_type = binding_body(cases_on_type);
for (unsigned i = 0; i < m_nminors; i++) {
expr minor_type = binding_domain(cases_on_type);
unsigned nargs = 0;
while (is_pi(minor_type)) {
nargs++;
minor_type = binding_body(minor_type);
}
r.push_back(nargs);
cases_on_type = binding_body(cases_on_type);
}
}
list<goal> intros_minors_args(list<goal> gs) {
buffer<unsigned> minors_nargs;
get_minors_nargs(minors_nargs);
lean_assert(length(gs) == minors_nargs.size());
buffer<goal> new_gs;
for (unsigned i = 0; i < minors_nargs.size(); i++) {
goal const & g = head(gs);
unsigned nargs = minors_nargs[i];
buffer<expr> hyps;
g.get_hyps(hyps);
buffer<expr> new_hyps;
new_hyps.append(hyps);
expr g_type = g.get_type();
for (unsigned i = 0; i < nargs; i++) {
expr type = binding_domain(g_type);
expr new_h = mk_local(m_ngen.next(), get_unused_name(binding_name(g_type), hyps), type, binder_info());
new_hyps.push_back(new_h);
g_type = instantiate(binding_body(g_type), new_h);
}
g_type = head_beta_reduce(g_type);
expr new_meta = mk_app(mk_metavar(m_ngen.next(), Pi(new_hyps, g_type)), new_hyps);
goal new_g(new_meta, g_type);
new_gs.push_back(new_g);
expr val = g.abstract(Fun(nargs, new_hyps.end() - nargs, new_meta));
m_subst.assign(g.get_name(), val);
gs = tail(gs);
}
return to_list(new_gs.begin(), new_gs.end());
}
public:
inversion_tac(environment const & env, io_state const & ios, proof_state const & ps):
m_env(env), m_ios(ios), m_ps(ps),
m_ngen(m_ps.get_ngen()),
m_tc(mk_type_checker(m_env, m_ngen.mk_child(), m_ps.relax_main_opaque())) {
}
optional<proof_state> execute(name const & n) {
goals const & gs = m_ps.get_goals();
if (empty(gs))
return none_proof_state();
goal g = head(gs);
goals tail_gs = tail(gs);
auto p = g.find_hyp(n);
if (!p)
return none_proof_state();
expr const & h = p->first;
expr h_type = m_tc->whnf(mlocal_type(h)).first;
if (!is_inversion_applicable(h_type))
return none_proof_state();
goal g1 = generalize_indices(g, h, h_type);
list<goal> g2s = apply_cases_on(g1);
list<goal> g3s = intros_minors_args(g2s);
proof_state new_s(m_ps, append(g3s, tail_gs), m_subst, m_ngen);
return some_proof_state(new_s);
}
};
tactic inversion_tactic(name const & n) {
auto fn = [=](environment const & env, io_state const & ios, proof_state const & ps) -> optional<proof_state> {
inversion_tac tac(env, ios, ps);
return tac.execute(n);
};
return tactic01(fn);
}
void initialize_inversion_tactic() {
register_tac(name({"tactic", "inversion"}),
[](type_checker &, elaborate_fn const &, expr const & e, pos_info_provider const *) {
name n = tactic_expr_to_id(app_arg(e), "invalid 'inversion' tactic, argument must be an identifier");
return inversion_tactic(n);
});
}
void finalize_inversion_tactic() {}
}
<commit_msg>fix(library/tactic/inversion_tactic): inversion tactic for datatypes with dependent elimination<commit_after>/*
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#include "kernel/abstract.h"
#include "kernel/instantiate.h"
#include "kernel/inductive/inductive.h"
#include "library/locals.h"
#include "library/tactic/tactic.h"
#include "library/reducible.h"
#include "library/tactic/expr_to_tactic.h"
namespace lean {
class inversion_tac {
environment const & m_env;
io_state const & m_ios;
proof_state const & m_ps;
name_generator m_ngen;
substitution m_subst;
std::unique_ptr<type_checker> m_tc;
bool m_dep_elim;
unsigned m_nparams;
unsigned m_nindices;
unsigned m_nminors;
declaration m_I_decl;
declaration m_cases_on_decl;
void init_inductive_info(name const & n) {
m_dep_elim = inductive::has_dep_elim(m_env, n);
m_nindices = *inductive::get_num_indices(m_env, n);
m_nparams = *inductive::get_num_params(m_env, n);
m_nminors = *inductive::get_num_minor_premises(m_env, n);
m_I_decl = m_env.get(n);
m_cases_on_decl = m_env.get({n, "cases_on"});
}
bool is_inversion_applicable(expr const & t) {
buffer<expr> args;
expr const & fn = get_app_args(t, args);
if (!is_constant(fn))
return false;
if (!inductive::is_inductive_decl(m_env, const_name(fn)))
return false;
if (!m_env.find(name{const_name(fn), "cases_on"}) ||
!m_env.find(name("eq")) || !m_env.find(name("heq")))
return false;
init_inductive_info(const_name(fn));
if (args.size() != m_nindices + m_nparams)
return false;
return true;
}
pair<expr, expr> mk_eq(expr const & lhs, expr const & rhs) {
expr lhs_type = m_tc->infer(lhs).first;
expr rhs_type = m_tc->infer(rhs).first;
level l = sort_level(m_tc->ensure_type(lhs_type).first);
constraint_seq cs;
if (m_tc->is_def_eq(lhs_type, rhs_type, justification(), cs) && !cs) {
return mk_pair(mk_app(mk_constant("eq", to_list(l)), lhs_type, lhs, rhs),
mk_app(mk_constant({"eq", "refl"}, to_list(l)), rhs_type, rhs));
} else {
return mk_pair(mk_app(mk_constant("heq", to_list(l)), lhs_type, lhs, rhs_type, rhs),
mk_app(mk_constant({"heq", "refl"}, to_list(l)), rhs_type, rhs));
}
}
goal generalize_indices(goal const & g, expr const & h, expr const & h_type) {
buffer<expr> hyps;
g.get_hyps(hyps);
expr m = g.get_meta();
expr m_type = g.get_type();
name h_new_name = g.get_unused_name(local_pp_name(h));
buffer<expr> I_args;
expr const & I = get_app_args(h_type, I_args);
expr h_new_type = mk_app(I, I_args.size() - m_nindices, I_args.data());
expr d = m_tc->whnf(m_tc->infer(h_new_type).first).first;
unsigned eq_idx = 1;
name eq_prefix("H");
buffer<expr> ts;
buffer<expr> eqs;
buffer<expr> refls;
name t_prefix("t");
unsigned nidx = 1;
auto add_eq = [&](expr const & lhs, expr const & rhs) {
pair<expr, expr> p = mk_eq(lhs, rhs);
expr new_eq = p.first;
expr new_refl = p.second;
eqs.push_back(mk_local(m_ngen.next(), g.get_unused_name(eq_prefix, eq_idx), new_eq, binder_info()));
refls.push_back(new_refl);
};
for (unsigned i = I_args.size() - m_nindices; i < I_args.size(); i++) {
expr t_type = binding_domain(d);
expr t = mk_local(m_ngen.next(), g.get_unused_name(t_prefix, nidx), t_type, binder_info());
expr const & index = I_args[i];
add_eq(t, index);
h_new_type = mk_app(h_new_type, t);
hyps.push_back(t);
ts.push_back(t);
d = instantiate(binding_body(d), t);
}
expr h_new = mk_local(m_ngen.next(), h_new_name, h_new_type, local_info(h));
if (m_dep_elim)
add_eq(h_new, h);
hyps.push_back(h_new);
expr new_type = Pi(eqs, g.get_type());
expr new_meta = mk_app(mk_metavar(m_ngen.next(), Pi(hyps, new_type)), hyps);
goal new_g(new_meta, new_type);
expr val = g.abstract(mk_app(mk_app(mk_app(Fun(ts, Fun(h_new, new_meta)), m_nindices, I_args.end() - m_nindices), h),
refls));
m_subst.assign(g.get_name(), val);
return new_g;
}
list<goal> apply_cases_on(goal const & g) {
buffer<expr> hyps;
g.get_hyps(hyps);
expr const & h = hyps.back();
expr const & h_type = mlocal_type(h);
buffer<expr> I_args;
expr const & I = get_app_args(h_type, I_args);
expr g_type = g.get_type();
expr cases_on;
if (length(m_cases_on_decl.get_univ_params()) != length(m_I_decl.get_univ_params())) {
level g_lvl = sort_level(m_tc->ensure_type(g_type).first);
cases_on = mk_constant({const_name(I), "cases_on"}, cons(g_lvl, const_levels(I)));
} else {
cases_on = mk_constant({const_name(I), "cases_on"}, const_levels(I));
}
// add params
cases_on = mk_app(cases_on, m_nparams, I_args.data());
// add type former
expr type_former = g_type;
if (m_dep_elim)
type_former = Fun(h, type_former);
type_former = Fun(m_nindices, I_args.end() - m_nindices, type_former);
cases_on = mk_app(cases_on, type_former);
// add indices
cases_on = mk_app(cases_on, m_nindices, I_args.end() - m_nindices);
// add h
cases_on = mk_app(cases_on, h);
buffer<expr> new_hyps;
new_hyps.append(hyps.size() - m_nindices - 1, hyps.data());
// add a subgoal for each minor premise of cases_on
expr cases_on_type = m_tc->whnf(m_tc->infer(cases_on).first).first;
buffer<goal> new_goals;
for (unsigned i = 0; i < m_nminors; i++) {
expr new_type = binding_domain(cases_on_type);
expr new_meta = mk_app(mk_metavar(m_ngen.next(), Pi(new_hyps, new_type)), new_hyps);
goal new_g(new_meta, new_type);
new_goals.push_back(new_g);
cases_on = mk_app(cases_on, new_meta);
cases_on_type = m_tc->whnf(binding_body(cases_on_type)).first; // the minor premises do not depend on each other
}
expr val = g.abstract(cases_on);
m_subst.assign(g.get_name(), val);
return to_list(new_goals.begin(), new_goals.end());
}
// Store in \c r the number of arguments for each cases_on minor.
void get_minors_nargs(buffer<unsigned> & r) {
expr cases_on_type = m_cases_on_decl.get_type();
for (unsigned i = 0; i < m_nparams + 1 + m_nindices + 1; i++)
cases_on_type = binding_body(cases_on_type);
for (unsigned i = 0; i < m_nminors; i++) {
expr minor_type = binding_domain(cases_on_type);
unsigned nargs = 0;
while (is_pi(minor_type)) {
nargs++;
minor_type = binding_body(minor_type);
}
r.push_back(nargs);
cases_on_type = binding_body(cases_on_type);
}
}
list<goal> intros_minors_args(list<goal> gs) {
buffer<unsigned> minors_nargs;
get_minors_nargs(minors_nargs);
lean_assert(length(gs) == minors_nargs.size());
buffer<goal> new_gs;
for (unsigned i = 0; i < minors_nargs.size(); i++) {
goal const & g = head(gs);
unsigned nargs = minors_nargs[i];
buffer<expr> hyps;
g.get_hyps(hyps);
buffer<expr> new_hyps;
new_hyps.append(hyps);
expr g_type = g.get_type();
for (unsigned i = 0; i < nargs; i++) {
expr type = binding_domain(g_type);
expr new_h = mk_local(m_ngen.next(), get_unused_name(binding_name(g_type), hyps), type, binder_info());
new_hyps.push_back(new_h);
g_type = instantiate(binding_body(g_type), new_h);
}
g_type = head_beta_reduce(g_type);
expr new_meta = mk_app(mk_metavar(m_ngen.next(), Pi(new_hyps, g_type)), new_hyps);
goal new_g(new_meta, g_type);
new_gs.push_back(new_g);
expr val = g.abstract(Fun(nargs, new_hyps.end() - nargs, new_meta));
m_subst.assign(g.get_name(), val);
gs = tail(gs);
}
return to_list(new_gs.begin(), new_gs.end());
}
public:
inversion_tac(environment const & env, io_state const & ios, proof_state const & ps):
m_env(env), m_ios(ios), m_ps(ps),
m_ngen(m_ps.get_ngen()),
m_tc(mk_type_checker(m_env, m_ngen.mk_child(), m_ps.relax_main_opaque())) {
}
optional<proof_state> execute(name const & n) {
goals const & gs = m_ps.get_goals();
if (empty(gs))
return none_proof_state();
goal g = head(gs);
goals tail_gs = tail(gs);
auto p = g.find_hyp(n);
if (!p)
return none_proof_state();
expr const & h = p->first;
expr h_type = m_tc->whnf(mlocal_type(h)).first;
if (!is_inversion_applicable(h_type))
return none_proof_state();
goal g1 = generalize_indices(g, h, h_type);
list<goal> gs2 = apply_cases_on(g1);
list<goal> gs3 = intros_minors_args(gs2);
proof_state new_s(m_ps, append(gs3, tail_gs), m_subst, m_ngen);
return some_proof_state(new_s);
}
};
tactic inversion_tactic(name const & n) {
auto fn = [=](environment const & env, io_state const & ios, proof_state const & ps) -> optional<proof_state> {
inversion_tac tac(env, ios, ps);
return tac.execute(n);
};
return tactic01(fn);
}
void initialize_inversion_tactic() {
register_tac(name({"tactic", "inversion"}),
[](type_checker &, elaborate_fn const &, expr const & e, pos_info_provider const *) {
name n = tactic_expr_to_id(app_arg(e), "invalid 'inversion' tactic, argument must be an identifier");
return inversion_tactic(n);
});
}
void finalize_inversion_tactic() {}
}
<|endoftext|> |
<commit_before>/*
RawSpeed - RAW file decoder.
Copyright (C) 2009-2014 Klaus Post
Copyright (C) 2014-2015 Pedro Côrte-Real
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 "decoders/MosDecoder.h"
#include "common/Common.h" // for uint32, uchar8
#include "common/Point.h" // for iPoint2D
#include "decoders/RawDecoder.h" // for RawDecoder
#include "decoders/RawDecoderException.h" // for ThrowRDE
#include "decompressors/UncompressedDecompressor.h" // for UncompressedDeco...
#include "io/BitPumpMSB32.h" // for BitPumpMSB32
#include "io/ByteStream.h" // for ByteStream
#include "io/Endianness.h" // for getU32LE, getLE
#include "tiff/TiffEntry.h" // for TiffEntry
#include "tiff/TiffIFD.h" // for TiffRootIFD, Tif...
#include "tiff/TiffTag.h" // for TiffTag::TILEOFF...
#include <algorithm> // for move
#include <cstdio> // for sscanf
#include <cstring> // for memchr
#include <memory> // for unique_ptr
#include <string> // for string, allocator
using namespace std;
namespace RawSpeed {
class CameraMetaData;
MosDecoder::MosDecoder(TiffRootIFDOwner&& rootIFD, FileMap* file)
: AbstractTiffDecoder(move(rootIFD), file)
{
black_level = 0;
if (mRootIFD->getEntryRecursive(MAKE)) {
auto id = mRootIFD->getID();
make = id.make;
model = id.model;
} else {
TiffEntry *xmp = mRootIFD->getEntryRecursive(XMP);
if (!xmp)
ThrowRDE("MOS Decoder: Couldn't find the XMP");
string xmpText = xmp->getString();
make = getXMPTag(xmpText, "Make");
model = getXMPTag(xmpText, "Model");
}
}
string MosDecoder::getXMPTag(const string &xmp, const string &tag) {
string::size_type start = xmp.find("<tiff:"+tag+">");
string::size_type end = xmp.find("</tiff:"+tag+">");
if (start == string::npos || end == string::npos || end <= start)
ThrowRDE("MOS Decoder: Couldn't find tag '%s' in the XMP", tag.c_str());
int startlen = tag.size()+7;
return xmp.substr(start+startlen, end-start-startlen);
}
RawImage MosDecoder::decodeRawInternal() {
uint32 off = 0;
uint32 base = 8;
// We get a pointer up to the end of the file as we check offset bounds later
const uchar8 *insideTiff = mFile->getData(base, mFile->getSize()-base);
if (getU32LE(insideTiff) == 0x49494949) {
uint32 offset = getU32LE(insideTiff + 8);
if (offset+base+4 > mFile->getSize())
ThrowRDE("MOS: PhaseOneC offset out of bounds");
uint32 entries = getU32LE(insideTiff + offset);
uint32 pos = 8; // Skip another 4 bytes
uint32 width=0, height=0, strip_offset=0, data_offset=0, wb_offset=0;
while (entries--) {
if (offset+base+pos+16 > mFile->getSize())
ThrowRDE("MOS: PhaseOneC offset out of bounds");
uint32 tag = getU32LE(insideTiff + offset + pos + 0);
// uint32 type = getU32LE(insideTiff + offset + pos + 4);
// uint32 len = getU32LE(insideTiff + offset + pos + 8);
uint32 data = getU32LE(insideTiff + offset + pos + 12);
pos += 16;
switch(tag) {
case 0x107: wb_offset = data+base; break;
case 0x108: width = data; break;
case 0x109: height = data; break;
case 0x10f: data_offset = data+base; break;
case 0x21c: strip_offset = data+base; break;
case 0x21d: black_level = data>>2; break;
}
}
if (width <= 0 || height <= 0)
ThrowRDE("MOS: PhaseOneC couldn't find width and height");
if (strip_offset+height*4 > mFile->getSize())
ThrowRDE("MOS: PhaseOneC strip offsets out of bounds");
if (data_offset > mFile->getSize())
ThrowRDE("MOS: PhaseOneC data offset out of bounds");
mRaw->dim = iPoint2D(width, height);
mRaw->createData();
DecodePhaseOneC(data_offset, strip_offset, width, height);
const uchar8 *data = mFile->getData(wb_offset, 12);
for(int i=0; i<3; i++) {
mRaw->metadata.wbCoeffs[i] = getLE<float>(data + i * 4);
}
return mRaw;
}
const TiffIFD *raw = nullptr;
if (mRootIFD->hasEntryRecursive(TILEOFFSETS)) {
raw = mRootIFD->getIFDWithTag(TILEOFFSETS);
off = raw->getEntry(TILEOFFSETS)->getU32();
} else {
raw = mRootIFD->getIFDWithTag(CFAPATTERN);
off = raw->getEntry(STRIPOFFSETS)->getU32();
}
uint32 width = raw->getEntry(IMAGEWIDTH)->getU32();
uint32 height = raw->getEntry(IMAGELENGTH)->getU32();
mRaw->dim = iPoint2D(width, height);
mRaw->createData();
UncompressedDecompressor u(*mFile, off, mRaw, uncorrectedRawValues);
int compression = raw->getEntry(COMPRESSION)->getU32();
if (1 == compression) {
if (getTiffEndianness(mFile) == big)
u.decode16BitRawBEunpacked(width, height);
else
u.decode16BitRawUnpacked(width, height);
}
else if (99 == compression || 7 == compression) {
ThrowRDE("MOS Decoder: Leaf LJpeg not yet supported");
//LJpegPlain l(mFile, mRaw);
//l.startDecoder(off, mFile->getSize()-off, 0, 0);
} else
ThrowRDE("MOS Decoder: Unsupported compression: %d", compression);
return mRaw;
}
void MosDecoder::DecodePhaseOneC(uint32 data_offset, uint32 strip_offset, uint32 width, uint32 height)
{
const int length[] = { 8,7,6,9,11,10,5,12,14,13 };
for (uint32 row = 0; row < height; row++) {
uint32 off =
data_offset + getU32LE(mFile->getData(strip_offset + row * 4, 4));
BitPumpMSB32 pump(mFile, off);
uint32 pred[2], len[2];
pred[0] = pred[1] = 0;
auto *img = (ushort16 *)mRaw->getData(0, row);
for (uint32 col=0; col < width; col++) {
if (col >= (width & -8))
len[0] = len[1] = 14;
else if ((col & 7) == 0) {
for (unsigned int &i : len) {
uint32 j = 0;
for (; j < 5 && !pump.getBitsSafe(1); j++);
if (j--)
i = length[j * 2 + pump.getBitsSafe(1)];
}
}
int i = len[col & 1];
if (i == 14)
img[col] = pred[col & 1] = pump.getBitsSafe(16);
else
img[col] = pred[col & 1] += pump.getBitsSafe(i) + 1 - (1 << (i - 1));
}
}
}
void MosDecoder::checkSupportInternal(CameraMetaData *meta) {
RawDecoder::checkCameraSupported(meta, make, model, "");
}
void MosDecoder::decodeMetaDataInternal(CameraMetaData *meta) {
RawDecoder::setMetaData(meta, make, model, "", 0);
// Fetch the white balance (see dcraw.c parse_mos for more metadata that can be gotten)
if (mRootIFD->hasEntryRecursive(LEAFMETADATA)) {
ByteStream bs = mRootIFD->getEntryRecursive(LEAFMETADATA)->getData();
// We need at least a couple of bytes:
// "NeutObj_neutrals" + 28 bytes binay + 4x uint as strings + 3x space + \0
const uint32 minSize = 16+28+4+3+1;
// dcraw does actual parsing, since we just want one field we bruteforce it
while (bs.getRemainSize() > minSize) {
if (bs.skipPrefix("NeutObj_neutrals", 16)) {
bs.skipBytes(28);
// check for nulltermination of string inside bounds
if (!memchr(bs.peekData(bs.getRemainSize()), 0, bs.getRemainSize()))
break;
uint32 tmp[4] = {0};
sscanf(bs.peekString(), "%u %u %u %u", &tmp[0], &tmp[1], &tmp[2], &tmp[3]);
if (tmp[0] > 0 && tmp[1] > 0 && tmp[2] > 0 && tmp[3] > 0) {
mRaw->metadata.wbCoeffs[0] = (float) tmp[0]/tmp[1];
mRaw->metadata.wbCoeffs[1] = (float) tmp[0]/tmp[2];
mRaw->metadata.wbCoeffs[2] = (float) tmp[0]/tmp[3];
}
break;
}
bs.skipBytes(1);
}
}
if (black_level)
mRaw->blackLevel = black_level;
}
} // namespace RawSpeed
<commit_msg>MosDecoder::decodeRawInternal(): UB: decrement properly<commit_after>/*
RawSpeed - RAW file decoder.
Copyright (C) 2009-2014 Klaus Post
Copyright (C) 2014-2015 Pedro Côrte-Real
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 "decoders/MosDecoder.h"
#include "common/Common.h" // for uint32, uchar8
#include "common/Point.h" // for iPoint2D
#include "decoders/RawDecoder.h" // for RawDecoder
#include "decoders/RawDecoderException.h" // for ThrowRDE
#include "decompressors/UncompressedDecompressor.h" // for UncompressedDeco...
#include "io/BitPumpMSB32.h" // for BitPumpMSB32
#include "io/ByteStream.h" // for ByteStream
#include "io/Endianness.h" // for getU32LE, getLE
#include "tiff/TiffEntry.h" // for TiffEntry
#include "tiff/TiffIFD.h" // for TiffRootIFD, Tif...
#include "tiff/TiffTag.h" // for TiffTag::TILEOFF...
#include <algorithm> // for move
#include <cstdio> // for sscanf
#include <cstring> // for memchr
#include <memory> // for unique_ptr
#include <string> // for string, allocator
using namespace std;
namespace RawSpeed {
class CameraMetaData;
MosDecoder::MosDecoder(TiffRootIFDOwner&& rootIFD, FileMap* file)
: AbstractTiffDecoder(move(rootIFD), file)
{
black_level = 0;
if (mRootIFD->getEntryRecursive(MAKE)) {
auto id = mRootIFD->getID();
make = id.make;
model = id.model;
} else {
TiffEntry *xmp = mRootIFD->getEntryRecursive(XMP);
if (!xmp)
ThrowRDE("MOS Decoder: Couldn't find the XMP");
string xmpText = xmp->getString();
make = getXMPTag(xmpText, "Make");
model = getXMPTag(xmpText, "Model");
}
}
string MosDecoder::getXMPTag(const string &xmp, const string &tag) {
string::size_type start = xmp.find("<tiff:"+tag+">");
string::size_type end = xmp.find("</tiff:"+tag+">");
if (start == string::npos || end == string::npos || end <= start)
ThrowRDE("MOS Decoder: Couldn't find tag '%s' in the XMP", tag.c_str());
int startlen = tag.size()+7;
return xmp.substr(start+startlen, end-start-startlen);
}
RawImage MosDecoder::decodeRawInternal() {
uint32 off = 0;
uint32 base = 8;
// We get a pointer up to the end of the file as we check offset bounds later
const uchar8 *insideTiff = mFile->getData(base, mFile->getSize()-base);
if (getU32LE(insideTiff) == 0x49494949) {
uint32 offset = getU32LE(insideTiff + 8);
if (offset+base+4 > mFile->getSize())
ThrowRDE("MOS: PhaseOneC offset out of bounds");
uint32 entries = getU32LE(insideTiff + offset);
uint32 pos = 8; // Skip another 4 bytes
uint32 width=0, height=0, strip_offset=0, data_offset=0, wb_offset=0;
for (; entries > 0; entries--) {
if (offset+base+pos+16 > mFile->getSize())
ThrowRDE("MOS: PhaseOneC offset out of bounds");
uint32 tag = getU32LE(insideTiff + offset + pos + 0);
// uint32 type = getU32LE(insideTiff + offset + pos + 4);
// uint32 len = getU32LE(insideTiff + offset + pos + 8);
uint32 data = getU32LE(insideTiff + offset + pos + 12);
pos += 16;
switch(tag) {
case 0x107: wb_offset = data+base; break;
case 0x108: width = data; break;
case 0x109: height = data; break;
case 0x10f: data_offset = data+base; break;
case 0x21c: strip_offset = data+base; break;
case 0x21d: black_level = data>>2; break;
}
}
if (width <= 0 || height <= 0)
ThrowRDE("MOS: PhaseOneC couldn't find width and height");
if (strip_offset+height*4 > mFile->getSize())
ThrowRDE("MOS: PhaseOneC strip offsets out of bounds");
if (data_offset > mFile->getSize())
ThrowRDE("MOS: PhaseOneC data offset out of bounds");
mRaw->dim = iPoint2D(width, height);
mRaw->createData();
DecodePhaseOneC(data_offset, strip_offset, width, height);
const uchar8 *data = mFile->getData(wb_offset, 12);
for(int i=0; i<3; i++) {
mRaw->metadata.wbCoeffs[i] = getLE<float>(data + i * 4);
}
return mRaw;
}
const TiffIFD *raw = nullptr;
if (mRootIFD->hasEntryRecursive(TILEOFFSETS)) {
raw = mRootIFD->getIFDWithTag(TILEOFFSETS);
off = raw->getEntry(TILEOFFSETS)->getU32();
} else {
raw = mRootIFD->getIFDWithTag(CFAPATTERN);
off = raw->getEntry(STRIPOFFSETS)->getU32();
}
uint32 width = raw->getEntry(IMAGEWIDTH)->getU32();
uint32 height = raw->getEntry(IMAGELENGTH)->getU32();
mRaw->dim = iPoint2D(width, height);
mRaw->createData();
UncompressedDecompressor u(*mFile, off, mRaw, uncorrectedRawValues);
int compression = raw->getEntry(COMPRESSION)->getU32();
if (1 == compression) {
if (getTiffEndianness(mFile) == big)
u.decode16BitRawBEunpacked(width, height);
else
u.decode16BitRawUnpacked(width, height);
}
else if (99 == compression || 7 == compression) {
ThrowRDE("MOS Decoder: Leaf LJpeg not yet supported");
//LJpegPlain l(mFile, mRaw);
//l.startDecoder(off, mFile->getSize()-off, 0, 0);
} else
ThrowRDE("MOS Decoder: Unsupported compression: %d", compression);
return mRaw;
}
void MosDecoder::DecodePhaseOneC(uint32 data_offset, uint32 strip_offset, uint32 width, uint32 height)
{
const int length[] = { 8,7,6,9,11,10,5,12,14,13 };
for (uint32 row = 0; row < height; row++) {
uint32 off =
data_offset + getU32LE(mFile->getData(strip_offset + row * 4, 4));
BitPumpMSB32 pump(mFile, off);
uint32 pred[2], len[2];
pred[0] = pred[1] = 0;
auto *img = (ushort16 *)mRaw->getData(0, row);
for (uint32 col=0; col < width; col++) {
if (col >= (width & -8))
len[0] = len[1] = 14;
else if ((col & 7) == 0) {
for (unsigned int &i : len) {
uint32 j = 0;
for (; j < 5 && !pump.getBitsSafe(1); j++);
if (j--)
i = length[j * 2 + pump.getBitsSafe(1)];
}
}
int i = len[col & 1];
if (i == 14)
img[col] = pred[col & 1] = pump.getBitsSafe(16);
else
img[col] = pred[col & 1] += pump.getBitsSafe(i) + 1 - (1 << (i - 1));
}
}
}
void MosDecoder::checkSupportInternal(CameraMetaData *meta) {
RawDecoder::checkCameraSupported(meta, make, model, "");
}
void MosDecoder::decodeMetaDataInternal(CameraMetaData *meta) {
RawDecoder::setMetaData(meta, make, model, "", 0);
// Fetch the white balance (see dcraw.c parse_mos for more metadata that can be gotten)
if (mRootIFD->hasEntryRecursive(LEAFMETADATA)) {
ByteStream bs = mRootIFD->getEntryRecursive(LEAFMETADATA)->getData();
// We need at least a couple of bytes:
// "NeutObj_neutrals" + 28 bytes binay + 4x uint as strings + 3x space + \0
const uint32 minSize = 16+28+4+3+1;
// dcraw does actual parsing, since we just want one field we bruteforce it
while (bs.getRemainSize() > minSize) {
if (bs.skipPrefix("NeutObj_neutrals", 16)) {
bs.skipBytes(28);
// check for nulltermination of string inside bounds
if (!memchr(bs.peekData(bs.getRemainSize()), 0, bs.getRemainSize()))
break;
uint32 tmp[4] = {0};
sscanf(bs.peekString(), "%u %u %u %u", &tmp[0], &tmp[1], &tmp[2], &tmp[3]);
if (tmp[0] > 0 && tmp[1] > 0 && tmp[2] > 0 && tmp[3] > 0) {
mRaw->metadata.wbCoeffs[0] = (float) tmp[0]/tmp[1];
mRaw->metadata.wbCoeffs[1] = (float) tmp[0]/tmp[2];
mRaw->metadata.wbCoeffs[2] = (float) tmp[0]/tmp[3];
}
break;
}
bs.skipBytes(1);
}
}
if (black_level)
mRaw->blackLevel = black_level;
}
} // namespace RawSpeed
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
///
/// \file hardware_concurrency.hpp
/// ------------------------------
///
/// (c) Copyright Domagoj Saric 2016 - 2017.
///
/// Use, modification and distribution are subject to the
/// Boost Software License, Version 1.0. (See accompanying file
/// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
///
/// See http://www.boost.org for most recent version.
///
////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------
#ifndef hardware_concurrency_hpp__070F2563_7F3C_40D5_85C9_1289E8DEEDC8
#define hardware_concurrency_hpp__070F2563_7F3C_40D5_85C9_1289E8DEEDC8
#pragma once
//------------------------------------------------------------------------------
#ifndef BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY
# if defined( __ANDROID__ )
# define BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY 8 // SGS6 has 8 cores
# elif defined( __APPLE__ )
# if defined( __aarch64__ )
# define BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY 3 // iPad 2 Air
# elif defined( __arm__ )
# define BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY 2
# else
# define BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY 0 // desktop or simulator
# endif // arch
# elif defined(__WINDOWS_PHONE__)
# define BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY 2
# else
# define BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY 0
# endif // platform
#endif // BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY
#ifdef _MSC_VER
# include <yvals.h>
# pragma detect_mismatch( "BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY", _STRINGIZE( BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY ) )
#endif // _MSC_VER
#include <boost/config_ex.hpp>
#include <cstdint>
#include <thread>
//------------------------------------------------------------------------------
namespace boost
{
//------------------------------------------------------------------------------
namespace sweater
{
//------------------------------------------------------------------------------
#if defined( __arm__ ) || defined( __aarch64__ ) || defined( __ANDROID__ ) || defined( __ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__ )
using hardware_concurrency_t = std::uint_fast8_t;
#else
using hardware_concurrency_t = std::uint_fast16_t; // e.g. Intel MIC
#endif
#ifdef BOOST_MSVC // no inline variables even in VS 15.3
BOOST_OVERRIDABLE_SYMBOL
#else
inline
#endif // BOOST_MSVC
auto const hardware_concurrency( static_cast<hardware_concurrency_t>( std::thread::hardware_concurrency() ) );
//------------------------------------------------------------------------------
} // namespace sweater
//------------------------------------------------------------------------------
} // namespace boost
//------------------------------------------------------------------------------
#endif // hardware_concurrency_hpp
<commit_msg>Android, Apple: fixed/updated BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY definition to support latest devices.<commit_after>////////////////////////////////////////////////////////////////////////////////
///
/// \file hardware_concurrency.hpp
/// ------------------------------
///
/// (c) Copyright Domagoj Saric 2016 - 2017.
///
/// Use, modification and distribution are subject to the
/// Boost Software License, Version 1.0. (See accompanying file
/// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
///
/// See http://www.boost.org for most recent version.
///
////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------
#ifndef hardware_concurrency_hpp__070F2563_7F3C_40D5_85C9_1289E8DEEDC8
#define hardware_concurrency_hpp__070F2563_7F3C_40D5_85C9_1289E8DEEDC8
#pragma once
//------------------------------------------------------------------------------
#ifndef BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY
# if defined( __ANDROID__ )
# if defined( __aarch64__ )
# define BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY 32 // SGS6 8, Meizu PRO 6 10 cores
# elif defined( __arm__ )
# define BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY 8
# endif // arch
# elif defined( __APPLE__ )
# if defined( __aarch64__ )
# define BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY 8 // iPad 2 Air 3, iPhone 8 6 cores
# elif defined( __arm__ )
# define BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY 2
# else
# define BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY 0 // desktop or simulator
# endif // arch
# elif defined(__WINDOWS_PHONE__)
# define BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY 2
# else
# define BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY 0
# endif // platform
#endif // BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY
#ifdef _MSC_VER
# include <yvals.h>
# pragma detect_mismatch( "BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY", _STRINGIZE( BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY ) )
#endif // _MSC_VER
#include <boost/config_ex.hpp>
#include <cstdint>
#include <thread>
//------------------------------------------------------------------------------
namespace boost
{
//------------------------------------------------------------------------------
namespace sweater
{
//------------------------------------------------------------------------------
#if defined( __arm__ ) || defined( __aarch64__ ) || defined( __ANDROID__ ) || defined( __ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__ )
using hardware_concurrency_t = std::uint_fast8_t;
#else
using hardware_concurrency_t = std::uint_fast16_t; // e.g. Intel MIC
#endif
#ifdef BOOST_MSVC // no inline variables even in VS 15.3
BOOST_OVERRIDABLE_SYMBOL
#else
inline
#endif // BOOST_MSVC
auto const hardware_concurrency( static_cast<hardware_concurrency_t>( std::thread::hardware_concurrency() ) );
//------------------------------------------------------------------------------
} // namespace sweater
//------------------------------------------------------------------------------
} // namespace boost
//------------------------------------------------------------------------------
#endif // hardware_concurrency_hpp
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2011 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
#ifndef MAPNIK_GEOMETRY_WKT_GENERATOR_HPP
#define MAPNIK_GEOMETRY_WKT_GENERATOR_HPP
// mapnik
#include <mapnik/global.hpp>
#include <mapnik/geometry.hpp>
#include <mapnik/util/vertex_iterator.hpp>
#include <mapnik/util/container_adapter.hpp>
// boost
#include <boost/tuple/tuple.hpp>
#include <boost/spirit/include/karma.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_fusion.hpp>
#include <boost/spirit/include/phoenix_function.hpp>
#include <boost/spirit/home/phoenix/statement/if.hpp>
#include <boost/fusion/include/boost_tuple.hpp>
//#define BOOST_SPIRIT_USE_PHOENIX_V3 1
namespace mapnik { namespace util {
namespace karma = boost::spirit::karma;
namespace phoenix = boost::phoenix;
struct get_type
{
template <typename T>
struct result { typedef int type; };
int operator() (geometry_type const& geom) const
{
return (int)geom.type();
}
};
struct get_first
{
template <typename T>
struct result { typedef geometry_type::value_type const type; };
geometry_type::value_type const operator() (geometry_type const& geom) const
{
geometry_type::value_type coord;
boost::get<0>(coord) = geom.get_vertex(0,&boost::get<1>(coord),&boost::get<2>(coord));
return coord;
}
};
template <typename T>
struct coordinate_policy : karma::real_policies<T>
{
typedef boost::spirit::karma::real_policies<T> base_type;
static int floatfield(T n) { return base_type::fmtflags::fixed; }
};
template <typename OutputIterator>
struct wkt_generator :
karma::grammar<OutputIterator, geometry_type const& ()>
{
wkt_generator()
: wkt_generator::base_type(wkt)
{
using boost::spirit::karma::uint_;
using boost::spirit::karma::_val;
using boost::spirit::karma::_1;
using boost::spirit::karma::lit;
using boost::spirit::karma::_a;
using boost::spirit::karma::_r1;
using boost::spirit::karma::eps;
wkt = point | linestring | polygon
;
point = &uint_(mapnik::Point)[_1 = _type(_val)]
<< lit("Point(") << point_coord [_1 = _first(_val)] << lit(')')
;
linestring = &uint_(mapnik::LineString)[_1 = _type(_val)]
<< lit("LineString(")
<< coords
<< lit(')')
;
polygon = &uint_(mapnik::Polygon)[_1 = _type(_val)]
<< lit("Polygon(")
<< coords2
<< lit("))")
;
point_coord = &uint_ << coord_type << lit(' ') << coord_type
;
polygon_coord %= ( &uint_(mapnik::SEG_MOVETO) << eps[_r1 += 1]
<< karma::string[ if_ (_r1 > 1) [_1 = "),("]
.else_[_1 = "("] ] | &uint_ << ",")
<< coord_type
<< lit(' ')
<< coord_type
;
coords2 %= *polygon_coord(_a)
;
coords = point_coord % lit(',')
;
}
// rules
karma::rule<OutputIterator, geometry_type const& ()> wkt;
karma::rule<OutputIterator, geometry_type const& ()> point;
karma::rule<OutputIterator, geometry_type const& ()> linestring;
karma::rule<OutputIterator, geometry_type const& ()> polygon;
karma::rule<OutputIterator, geometry_type const& ()> coords;
karma::rule<OutputIterator, karma::locals<unsigned>, geometry_type const& ()> coords2;
karma::rule<OutputIterator, geometry_type::value_type ()> point_coord;
karma::rule<OutputIterator, geometry_type::value_type const& (unsigned& )> polygon_coord;
// phoenix functions
phoenix::function<get_type > _type;
phoenix::function<get_first> _first;
//
karma::real_generator<double, coordinate_policy<double> > coord_type;
};
}}
#endif // MAPNIK_GEOMETRY_WKT_GENERATOR_HPP
<commit_msg>+ increase coordinates precision<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2011 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
#ifndef MAPNIK_GEOMETRY_WKT_GENERATOR_HPP
#define MAPNIK_GEOMETRY_WKT_GENERATOR_HPP
// mapnik
#include <mapnik/global.hpp>
#include <mapnik/geometry.hpp>
#include <mapnik/util/vertex_iterator.hpp>
#include <mapnik/util/container_adapter.hpp>
// boost
#include <boost/tuple/tuple.hpp>
#include <boost/spirit/include/karma.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_fusion.hpp>
#include <boost/spirit/include/phoenix_function.hpp>
#include <boost/spirit/home/phoenix/statement/if.hpp>
#include <boost/fusion/include/boost_tuple.hpp>
//#define BOOST_SPIRIT_USE_PHOENIX_V3 1
namespace mapnik { namespace util {
namespace karma = boost::spirit::karma;
namespace phoenix = boost::phoenix;
struct get_type
{
template <typename T>
struct result { typedef int type; };
int operator() (geometry_type const& geom) const
{
return (int)geom.type();
}
};
struct get_first
{
template <typename T>
struct result { typedef geometry_type::value_type const type; };
geometry_type::value_type const operator() (geometry_type const& geom) const
{
geometry_type::value_type coord;
boost::get<0>(coord) = geom.get_vertex(0,&boost::get<1>(coord),&boost::get<2>(coord));
return coord;
}
};
template <typename T>
struct coordinate_policy : karma::real_policies<T>
{
typedef boost::spirit::karma::real_policies<T> base_type;
static int floatfield(T n) { return base_type::fmtflags::fixed; }
static unsigned precision(T n) { return 6u ;}
};
template <typename OutputIterator>
struct wkt_generator :
karma::grammar<OutputIterator, geometry_type const& ()>
{
wkt_generator()
: wkt_generator::base_type(wkt)
{
using boost::spirit::karma::uint_;
using boost::spirit::karma::_val;
using boost::spirit::karma::_1;
using boost::spirit::karma::lit;
using boost::spirit::karma::_a;
using boost::spirit::karma::_r1;
using boost::spirit::karma::eps;
wkt = point | linestring | polygon
;
point = &uint_(mapnik::Point)[_1 = _type(_val)]
<< lit("Point(") << point_coord [_1 = _first(_val)] << lit(')')
;
linestring = &uint_(mapnik::LineString)[_1 = _type(_val)]
<< lit("LineString(")
<< coords
<< lit(')')
;
polygon = &uint_(mapnik::Polygon)[_1 = _type(_val)]
<< lit("Polygon(")
<< coords2
<< lit("))")
;
point_coord = &uint_ << coord_type << lit(' ') << coord_type
;
polygon_coord %= ( &uint_(mapnik::SEG_MOVETO) << eps[_r1 += 1]
<< karma::string[ if_ (_r1 > 1) [_1 = "),("]
.else_[_1 = "("] ] | &uint_ << ",")
<< coord_type
<< lit(' ')
<< coord_type
;
coords2 %= *polygon_coord(_a)
;
coords = point_coord % lit(',')
;
}
// rules
karma::rule<OutputIterator, geometry_type const& ()> wkt;
karma::rule<OutputIterator, geometry_type const& ()> point;
karma::rule<OutputIterator, geometry_type const& ()> linestring;
karma::rule<OutputIterator, geometry_type const& ()> polygon;
karma::rule<OutputIterator, geometry_type const& ()> coords;
karma::rule<OutputIterator, karma::locals<unsigned>, geometry_type const& ()> coords2;
karma::rule<OutputIterator, geometry_type::value_type ()> point_coord;
karma::rule<OutputIterator, geometry_type::value_type const& (unsigned& )> polygon_coord;
// phoenix functions
phoenix::function<get_type > _type;
phoenix::function<get_first> _first;
//
karma::real_generator<double, coordinate_policy<double> > coord_type;
};
}}
#endif // MAPNIK_GEOMETRY_WKT_GENERATOR_HPP
<|endoftext|> |
<commit_before>/***************************************************************
*
* Copyright (C) 1990-2020, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************/
#include "condor_common.h"
#include "condor_config.h"
#include "match_prefix.h"
#include <termios.h>
#include <unistd.h>
#include <grp.h>
#include <signal.h>
#include <algorithm>
// condor_nsenter
//
// This is a replacement for the linux nsenter command to launch a
// shell inside a container. We need this when running
// condor_ssh_to_job to a job that has been launched inside singularity
// Docker jobs use docker exec to enter the container, but there is no
// equivalent in singularity. Standard nsenter isn't sufficient, as it
// does not create a pty for the shell, and we need different command
// line arguments to enter a non-setuid singularity container. This
// is harder because the starter can't tell if singularity is setuid easily.
//
// The architecture for ssh-to-job to a contained job is to land in an sshd
// the starter forks *outside* the container. This is important because we
// never want to assume anything about the container, even that there is an sshd
// inside it. After the sshd starts, a script runs which runs condor_docker_enter
// (even for singularity), which connects to a Unix Domain Socket, passes
// stdin/out/err to the starter, which passes those to condor_nsenter, which
// is runs as root. Rootly privilege is required to enter a setuid namespace
// so this is how we acquire.
//
// condor_nsenter enters the namespace, taking care to try to enter the user
// namespace, which is only set up for non-setuid singularity, and drops
// privileges to the uid and gid passed on the command line. It sets up
// a pty for the shell to use, so all interactive processses will work.
//
// A final problem is environment variables. Singularity, especially when
// managing GPUs, sets some nvidia-related environment variables that the
// condor starter doesn't know about. So, condor_nsenter extracts the environment
// variables from the contained job process, and sets them in the shell
// it spawns.
void
usage( char *cmd )
{
fprintf(stderr,"Usage: %s [options] condor_* ....\n",cmd);
fprintf(stderr,"Where options are:\n");
fprintf(stderr,"-t target_pid:\n");
fprintf(stderr,"-S user_id:\n");
fprintf(stderr,"-G group_id:\n");
fprintf(stderr," -help Display options\n");
}
// Before we exit, we need to reset the pty back to normal
// if we put it in raw mode
bool pty_is_raw = false;
struct termios old_tio;
void reset_pty_and_exit(int signo) {
if (pty_is_raw)
tcsetattr(0, TCSAFLUSH, &old_tio);
exit(signo);
}
int main( int argc, char *argv[] )
{
std::string condor_prefix;
pid_t pid = 0;
uid_t uid = 0;
gid_t gid = 0;
// parse command line args
for( int i=1; i<argc; i++ ) {
if(is_arg_prefix(argv[i],"-help")) {
usage(argv[0]);
exit(1);
}
// target pid to enter
if(is_arg_prefix(argv[i],"-t")) {
pid = atoi(argv[i + 1]);
i++;
}
// uid to switch to
if(is_arg_prefix(argv[i],"-S")) {
uid = atoi(argv[i + 1]);
i++;
}
// gid to switch to
if(is_arg_prefix(argv[i],"-G")) {
gid = atoi(argv[i + 1]);
i++;
}
}
if (pid < 1) {
fprintf(stderr, "missing -t argument > 1\n");
exit(1);
}
if (uid == 0) {
fprintf(stderr, "missing -S argument > 1\n");
exit(1);
}
if (gid == 0) {
fprintf(stderr, "missing -G argument > 1\n");
exit(1);
}
// slurp the enviroment out of our victim
std::string env;
std::string envfile;
formatstr(envfile, "/proc/%d/environ", pid);
int e = open(envfile.c_str(), O_RDONLY);
if (e < 0) {
fprintf(stderr, "Can't open %s %s\n", envfile.c_str(), strerror(errno));
exit(1);
}
char buf[512];
int bytesRead;
while ((bytesRead = read(e, &buf, 512)) > 0) {
env.append(buf, bytesRead);
}
close(e);
// If the environment contains a string with the value of the
// path to the container's scratch directory outside the container
// replace it with the path inside the container.
std::string outsidePath;
if (getenv("_CONDOR_SCRATCH_DIR_OUTSIDE_CONTAINER")) {
outsidePath = getenv("_CONDOR_SCRATCH_DIR_OUTSIDE_CONTAINER");
}
std::string insidePath;
if (getenv("_CONDOR_SCRATCH_DIR")) {
insidePath = getenv("_CONDOR_SCRATCH_DIR");
}
if (outsidePath.length() > 0) {
size_t pos = 0;
do {
pos = env.find(outsidePath, pos);
if (pos != std::string::npos) {
env.replace(pos, outsidePath.length(), insidePath);
pos += insidePath.length();
}
} while (pos != std::string::npos);
}
// we probably replaced the value of _CONDOR_SCRATCH_DIR_OUTSIDE_CONTAINER
// with the inside value, so set that back
size_t pos = 0;
pos = env.find("_CONDOR_SCRATCH_DIR_OUTSIDE_CONTAINER=", pos);
if (pos != std::string::npos) {
size_t eqpos = env.find("=", pos);
eqpos++;
env.replace(eqpos, insidePath.length(), outsidePath);
}
// make a vector to hold all the pointers to env entries
std::vector<const char *> envp;
// copy DISPLAY from outside to inside. sshd has set this,
// it is the only one from the outside we need on the inside,
// and one way that an ssh-to-job shell is different than the job.
std::string display;
if (getenv("DISPLAY")) {
formatstr(display, "DISPLAY=%s", getenv("DISPLAY"));
envp.push_back(display.c_str());
}
// the first one
envp.push_back(env.c_str());
auto it = env.cbegin();
while (env.cend() != (it = std::find(it, env.cend(), '\0'))) {
// skip past null terminator
it++;
if (& (*it) != nullptr) {
envp.push_back(& (*it));
}
}
envp.push_back(nullptr);
envp.push_back(nullptr);
std::string filename;
// start changing namespaces. Note that once we do this, things
// get funny in this process
formatstr(filename, "/proc/%d/ns/uts", pid);
int fd = open(filename.c_str(), O_RDONLY);
if (fd < 0) {
fprintf(stderr, "Can't open uts namespace: %d %s\n", errno, strerror(errno));
exit(1);
}
int r = setns(fd, 0);
close(fd);
if (r < 0) {
// This means an unprivileged singularity, most likely
// need to set user namespace instead.
formatstr(filename, "/proc/%d/ns/user", pid);
fd = open(filename.c_str(), O_RDONLY);
if (fd < 0) {
fprintf(stderr, "Can't open user namespace: %d %s\n", errno, strerror(errno));
exit(1);
}
r = setns(fd, 0);
close(fd);
if (r < 0) {
fprintf(stderr, "Can't setns to user namespace: %s\n", strerror(errno));
exit(1);
}
}
// now the pid namespace
formatstr(filename, "/proc/%d/ns/pid", pid);
fd = open(filename.c_str(), O_RDONLY);
if (fd < 0) {
fprintf(stderr, "Can't open pid namespace: %s\n", strerror(errno));
exit(1);
}
r = setns(fd, 0);
close(fd);
if (r < 0) {
fprintf(stderr, "Can't setns to pid namespace: %s\n", strerror(errno));
exit(1);
}
// finally the mnt namespace
formatstr(filename, "/proc/%d/ns/mnt", pid);
fd = open(filename.c_str(), O_RDONLY);
if (fd < 0) {
fprintf(stderr, "Can't open mnt namespace: %s\n", strerror(errno));
exit(1);
}
r = setns(fd, 0);
close(fd);
if (r < 0) {
fprintf(stderr, "Can't setns to mnt namespace: %s\n", strerror(errno));
exit(1);
}
setgroups(0, nullptr);
// order matters!
r = setgid(gid);
if (r < 0) {
fprintf(stderr, "Can't setgid to %d\n", gid);
exit(1);
}
r = setuid(uid);
if (r < 0) {
fprintf(stderr, "Can't setuid to %d\n", uid);
exit(1);
}
struct winsize win;
ioctl(0, TIOCGWINSZ, &win);
// now the pty handling
int masterPty = -1;
int workerPty = -1;
masterPty = open("/dev/ptmx", O_RDWR);
unlockpt(masterPty);
if (masterPty < 0) {
fprintf(stderr, "Can't open master pty %s\n", strerror(errno));
exit(1);
} else {
workerPty = open(ptsname(masterPty), O_RDWR);
if (workerPty < 0) {
fprintf(stderr, "Can't open worker pty %s\n", strerror(errno));
exit(1);
}
}
int childpid = fork();
if (childpid == 0) {
// in the child --
close(0);
close(1);
close(2);
close(masterPty);
dup2(workerPty, 0);
dup2(workerPty, 1);
dup2(workerPty, 2);
if (getenv("_CONDOR_SCRATCH_DIR")) {
int r = chdir(getenv("_CONDOR_SCRATCH_DIR"));
if (r < 0) {
printf("Cannot chdir to %s: %s\n", getenv("_CONDOR_SCRATCH_DIR"), strerror(errno));
}
}
// make this process group leader so shell job control works
setsid();
// Make the pty the controlling terminal
ioctl(workerPty, TIOCSCTTY, 0);
// and make it the process group leader
tcsetpgrp(workerPty, getpid());
// and set the window size properly
ioctl(0, TIOCSWINSZ, &win);
// Finally, launch the shell
execle("/bin/sh", "/bin/sh", "-l", "-i", nullptr, envp.data());
// Only get here if exec fails
fprintf(stderr, "exec failed %d\n", errno);
exit(errno);
} else {
// the parent
fd_set readfds, writefds, exceptfds;
bool keepGoing = true;
// put the pty in raw mode
struct termios tio;
tcgetattr(0, &tio);
pty_is_raw = true;
old_tio = tio;
tio.c_iflag &= ~(ICRNL);
tio.c_oflag &= ~(OPOST);
tio.c_cflag |= (CS8);
tio.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
tio.c_cc[VMIN] = 1;
tio.c_cc[VTIME] = 0;
tcsetattr(0, TCSAFLUSH, &tio);
struct sigaction handler;
struct sigaction oldhandler;
handler.sa_handler = reset_pty_and_exit;
handler.sa_flags = 0;
sigemptyset(&handler.sa_mask);
sigaction(SIGCHLD, &handler, &oldhandler);
while (keepGoing) {
FD_ZERO(&readfds);
FD_ZERO(&writefds);
FD_ZERO(&exceptfds);
FD_SET(0, &readfds);
FD_SET(masterPty, &readfds);
select(masterPty + 1, &readfds, &writefds, &exceptfds, nullptr);
if (FD_ISSET(masterPty, &readfds)) {
char buf;
int r = read(masterPty, &buf, 1);
if (r > 0) {
int ret = write(1, &buf, 1);
if (ret < 0) {
reset_pty_and_exit(0);
}
} else {
keepGoing = false;
}
}
if (FD_ISSET(0, &readfds)) {
char buf;
int r = read(0, &buf, 1);
if (r > 0) {
int ret = write(masterPty, &buf, 1);
if (ret < 0) {
reset_pty_and_exit(0);
}
} else {
keepGoing = false;
}
}
}
int status;
waitpid(childpid, &status, 0);
}
return 0;
}
<commit_msg>nsenter: Use a buffer to forward data through TTY FDs.<commit_after>/***************************************************************
*
* Copyright (C) 1990-2020, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************/
#include "condor_common.h"
#include "condor_config.h"
#include "match_prefix.h"
#include <termios.h>
#include <unistd.h>
#include <grp.h>
#include <signal.h>
#include <algorithm>
// condor_nsenter
//
// This is a replacement for the linux nsenter command to launch a
// shell inside a container. We need this when running
// condor_ssh_to_job to a job that has been launched inside singularity
// Docker jobs use docker exec to enter the container, but there is no
// equivalent in singularity. Standard nsenter isn't sufficient, as it
// does not create a pty for the shell, and we need different command
// line arguments to enter a non-setuid singularity container. This
// is harder because the starter can't tell if singularity is setuid easily.
//
// The architecture for ssh-to-job to a contained job is to land in an sshd
// the starter forks *outside* the container. This is important because we
// never want to assume anything about the container, even that there is an sshd
// inside it. After the sshd starts, a script runs which runs condor_docker_enter
// (even for singularity), which connects to a Unix Domain Socket, passes
// stdin/out/err to the starter, which passes those to condor_nsenter, which
// is runs as root. Rootly privilege is required to enter a setuid namespace
// so this is how we acquire.
//
// condor_nsenter enters the namespace, taking care to try to enter the user
// namespace, which is only set up for non-setuid singularity, and drops
// privileges to the uid and gid passed on the command line. It sets up
// a pty for the shell to use, so all interactive processses will work.
//
// A final problem is environment variables. Singularity, especially when
// managing GPUs, sets some nvidia-related environment variables that the
// condor starter doesn't know about. So, condor_nsenter extracts the environment
// variables from the contained job process, and sets them in the shell
// it spawns.
void
usage( char *cmd )
{
fprintf(stderr,"Usage: %s [options] condor_* ....\n",cmd);
fprintf(stderr,"Where options are:\n");
fprintf(stderr,"-t target_pid:\n");
fprintf(stderr,"-S user_id:\n");
fprintf(stderr,"-G group_id:\n");
fprintf(stderr," -help Display options\n");
}
// Before we exit, we need to reset the pty back to normal
// if we put it in raw mode
bool pty_is_raw = false;
struct termios old_tio;
void reset_pty_and_exit(int signo) {
if (pty_is_raw)
tcsetattr(0, TCSAFLUSH, &old_tio);
exit(signo);
}
int main( int argc, char *argv[] )
{
std::string condor_prefix;
pid_t pid = 0;
uid_t uid = 0;
gid_t gid = 0;
// parse command line args
for( int i=1; i<argc; i++ ) {
if(is_arg_prefix(argv[i],"-help")) {
usage(argv[0]);
exit(1);
}
// target pid to enter
if(is_arg_prefix(argv[i],"-t")) {
pid = atoi(argv[i + 1]);
i++;
}
// uid to switch to
if(is_arg_prefix(argv[i],"-S")) {
uid = atoi(argv[i + 1]);
i++;
}
// gid to switch to
if(is_arg_prefix(argv[i],"-G")) {
gid = atoi(argv[i + 1]);
i++;
}
}
if (pid < 1) {
fprintf(stderr, "missing -t argument > 1\n");
exit(1);
}
if (uid == 0) {
fprintf(stderr, "missing -S argument > 1\n");
exit(1);
}
if (gid == 0) {
fprintf(stderr, "missing -G argument > 1\n");
exit(1);
}
// slurp the enviroment out of our victim
std::string env;
std::string envfile;
formatstr(envfile, "/proc/%d/environ", pid);
int e = open(envfile.c_str(), O_RDONLY);
if (e < 0) {
fprintf(stderr, "Can't open %s %s\n", envfile.c_str(), strerror(errno));
exit(1);
}
char buf[512];
int bytesRead;
while ((bytesRead = read(e, &buf, 512)) > 0) {
env.append(buf, bytesRead);
}
close(e);
// If the environment contains a string with the value of the
// path to the container's scratch directory outside the container
// replace it with the path inside the container.
std::string outsidePath;
if (getenv("_CONDOR_SCRATCH_DIR_OUTSIDE_CONTAINER")) {
outsidePath = getenv("_CONDOR_SCRATCH_DIR_OUTSIDE_CONTAINER");
}
std::string insidePath;
if (getenv("_CONDOR_SCRATCH_DIR")) {
insidePath = getenv("_CONDOR_SCRATCH_DIR");
}
if (outsidePath.length() > 0) {
size_t pos = 0;
do {
pos = env.find(outsidePath, pos);
if (pos != std::string::npos) {
env.replace(pos, outsidePath.length(), insidePath);
pos += insidePath.length();
}
} while (pos != std::string::npos);
}
// we probably replaced the value of _CONDOR_SCRATCH_DIR_OUTSIDE_CONTAINER
// with the inside value, so set that back
size_t pos = 0;
pos = env.find("_CONDOR_SCRATCH_DIR_OUTSIDE_CONTAINER=", pos);
if (pos != std::string::npos) {
size_t eqpos = env.find("=", pos);
eqpos++;
env.replace(eqpos, insidePath.length(), outsidePath);
}
// make a vector to hold all the pointers to env entries
std::vector<const char *> envp;
// copy DISPLAY from outside to inside. sshd has set this,
// it is the only one from the outside we need on the inside,
// and one way that an ssh-to-job shell is different than the job.
std::string display;
if (getenv("DISPLAY")) {
formatstr(display, "DISPLAY=%s", getenv("DISPLAY"));
envp.push_back(display.c_str());
}
// the first one
envp.push_back(env.c_str());
auto it = env.cbegin();
while (env.cend() != (it = std::find(it, env.cend(), '\0'))) {
// skip past null terminator
it++;
if (& (*it) != nullptr) {
envp.push_back(& (*it));
}
}
envp.push_back(nullptr);
envp.push_back(nullptr);
std::string filename;
// start changing namespaces. Note that once we do this, things
// get funny in this process
formatstr(filename, "/proc/%d/ns/uts", pid);
int fd = open(filename.c_str(), O_RDONLY);
if (fd < 0) {
fprintf(stderr, "Can't open uts namespace: %d %s\n", errno, strerror(errno));
exit(1);
}
int r = setns(fd, 0);
close(fd);
if (r < 0) {
// This means an unprivileged singularity, most likely
// need to set user namespace instead.
formatstr(filename, "/proc/%d/ns/user", pid);
fd = open(filename.c_str(), O_RDONLY);
if (fd < 0) {
fprintf(stderr, "Can't open user namespace: %d %s\n", errno, strerror(errno));
exit(1);
}
r = setns(fd, 0);
close(fd);
if (r < 0) {
fprintf(stderr, "Can't setns to user namespace: %s\n", strerror(errno));
exit(1);
}
}
// now the pid namespace
formatstr(filename, "/proc/%d/ns/pid", pid);
fd = open(filename.c_str(), O_RDONLY);
if (fd < 0) {
fprintf(stderr, "Can't open pid namespace: %s\n", strerror(errno));
exit(1);
}
r = setns(fd, 0);
close(fd);
if (r < 0) {
fprintf(stderr, "Can't setns to pid namespace: %s\n", strerror(errno));
exit(1);
}
// finally the mnt namespace
formatstr(filename, "/proc/%d/ns/mnt", pid);
fd = open(filename.c_str(), O_RDONLY);
if (fd < 0) {
fprintf(stderr, "Can't open mnt namespace: %s\n", strerror(errno));
exit(1);
}
r = setns(fd, 0);
close(fd);
if (r < 0) {
fprintf(stderr, "Can't setns to mnt namespace: %s\n", strerror(errno));
exit(1);
}
setgroups(0, nullptr);
// order matters!
r = setgid(gid);
if (r < 0) {
fprintf(stderr, "Can't setgid to %d\n", gid);
exit(1);
}
r = setuid(uid);
if (r < 0) {
fprintf(stderr, "Can't setuid to %d\n", uid);
exit(1);
}
struct winsize win;
ioctl(0, TIOCGWINSZ, &win);
// now the pty handling
int masterPty = -1;
int workerPty = -1;
masterPty = open("/dev/ptmx", O_RDWR);
unlockpt(masterPty);
if (masterPty < 0) {
fprintf(stderr, "Can't open master pty %s\n", strerror(errno));
exit(1);
} else {
workerPty = open(ptsname(masterPty), O_RDWR);
if (workerPty < 0) {
fprintf(stderr, "Can't open worker pty %s\n", strerror(errno));
exit(1);
}
}
int childpid = fork();
if (childpid == 0) {
// in the child --
close(0);
close(1);
close(2);
close(masterPty);
dup2(workerPty, 0);
dup2(workerPty, 1);
dup2(workerPty, 2);
if (getenv("_CONDOR_SCRATCH_DIR")) {
int r = chdir(getenv("_CONDOR_SCRATCH_DIR"));
if (r < 0) {
printf("Cannot chdir to %s: %s\n", getenv("_CONDOR_SCRATCH_DIR"), strerror(errno));
}
}
// make this process group leader so shell job control works
setsid();
// Make the pty the controlling terminal
ioctl(workerPty, TIOCSCTTY, 0);
// and make it the process group leader
tcsetpgrp(workerPty, getpid());
// and set the window size properly
ioctl(0, TIOCSWINSZ, &win);
// Finally, launch the shell
execle("/bin/sh", "/bin/sh", "-l", "-i", nullptr, envp.data());
// Only get here if exec fails
fprintf(stderr, "exec failed %d\n", errno);
exit(errno);
} else {
// the parent
fd_set readfds, writefds, exceptfds;
bool keepGoing = true;
// put the pty in raw mode
struct termios tio;
tcgetattr(0, &tio);
pty_is_raw = true;
old_tio = tio;
tio.c_iflag &= ~(ICRNL);
tio.c_oflag &= ~(OPOST);
tio.c_cflag |= (CS8);
tio.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
tio.c_cc[VMIN] = 1;
tio.c_cc[VTIME] = 0;
tcsetattr(0, TCSAFLUSH, &tio);
struct sigaction handler;
struct sigaction oldhandler;
handler.sa_handler = reset_pty_and_exit;
handler.sa_flags = 0;
sigemptyset(&handler.sa_mask);
sigaction(SIGCHLD, &handler, &oldhandler);
while (keepGoing) {
FD_ZERO(&readfds);
FD_ZERO(&writefds);
FD_ZERO(&exceptfds);
FD_SET(0, &readfds);
FD_SET(masterPty, &readfds);
select(masterPty + 1, &readfds, &writefds, &exceptfds, nullptr);
if (FD_ISSET(masterPty, &readfds)) {
char buf[4096];
int r = read(masterPty, buf, 4096);
if (r > 0) {
int ret = write(1, buf, r);
if (ret < 0) {
reset_pty_and_exit(0);
}
} else {
keepGoing = false;
}
}
if (FD_ISSET(0, &readfds)) {
char buf[4096];
int r = read(0, buf, 4096);
if (r > 0) {
int ret = write(masterPty, buf, r);
if (ret < 0) {
reset_pty_and_exit(0);
}
} else {
keepGoing = false;
}
}
}
int status;
waitpid(childpid, &status, 0);
}
return 0;
}
<|endoftext|> |
<commit_before>//
// Copyright (c) 2013-2014 Christoph Malek
// See LICENSE for more information.
//
#ifndef RJ_GAME_MAIN_MENU_SITE_HOME_HPP
#define RJ_GAME_MAIN_MENU_SITE_HOME_HPP
#include <rectojump/game/popup_manager.hpp>
#include <rectojump/ui/button.hpp>
#include <rectojump/ui/sf_widget.hpp>
#include <rectojump/ui/stacked_widget.hpp>
#include <rectojump/ui/textbox.hpp>
namespace rj
{
template<typename Overlay>
class site_home
{
Overlay& m_overlay;
data_store_type& m_datasore;
ui::stacked_widget& m_sites;
public:
site_home(Overlay& ov) :
m_overlay{ov},
m_datasore{m_overlay.mainmenu().gamehandler().datastore()},
m_sites{ov.sites()}
{ }
void construct()
{
const auto& font(m_datasore.template get<sf::Font>(glob::text_font));
// logo
auto logo_shape(m_sites.add_object<widget::rectangle_shape>("home", vec2f{128.f, 128.f}));
logo_shape->get().setTexture(&m_datasore.template get<sf::Texture>("rj_logo.png"));
logo_shape->get().setPosition({(m_sites.bounds().width - logo_shape->get().getSize().x) / 2.f, m_sites.size().y * 0.35f - logo_shape->get().getSize().y});
// textboxes
const vec2f tbsize{250.f, 30.f};
auto username(m_sites.add_object<ui::textbox>("home",
tbsize,
vec2f{(m_sites.bounds().width - tbsize.x) / 2.f, logo_shape->get().getPosition().y + 140.f},
font,
"Username"));
auto password(m_sites.add_object<ui::textbox>("home",
tbsize,
vec2f{(m_sites.bounds().width - tbsize.x) / 2.f, logo_shape->get().getPosition().y + 180.f},
font,
"Password"));
default_textbox(*username);
default_textbox(*password);
password->setPasswordMode(true);
// buttons
const vec2f btnsize{100.f, 30.f};
auto login(m_sites.add_object<ui::button>("home", btnsize, vec2f{password->getPosition().x, password->getPosition().y + 40.f}));
login->set_font(font);
login->set_text("Login");
auto register_acc(m_sites.add_object<ui::button>("home", btnsize, vec2f{password->getPosition().x + 150.f, password->getPosition().y + 40.f}));
register_acc->set_font(font);
register_acc->set_text("Register");
register_acc->on_clicked = [this]{m_overlay.mainmenu().gamehandler().popupmgr().template create_popup<popup_type::info>("Register a new account online at: http://");};
default_button(*login);
default_button(*register_acc);
}
};
}
#endif // RJ_GAME_MAIN_MENU_SITE_HOME_HPP
<commit_msg>game > main_menu > site_home: added version info text<commit_after>//
// Copyright (c) 2013-2014 Christoph Malek
// See LICENSE for more information.
//
#ifndef RJ_GAME_MAIN_MENU_SITE_HOME_HPP
#define RJ_GAME_MAIN_MENU_SITE_HOME_HPP
#include <rectojump/game/popup_manager.hpp>
#include <rectojump/ui/button.hpp>
#include <rectojump/ui/sf_widget.hpp>
#include <rectojump/ui/stacked_widget.hpp>
#include <rectojump/ui/textbox.hpp>
namespace rj
{
template<typename Overlay>
class site_home
{
Overlay& m_overlay;
data_store_type& m_datasore;
ui::stacked_widget& m_sites;
public:
site_home(Overlay& ov) :
m_overlay{ov},
m_datasore{m_overlay.mainmenu().gamehandler().datastore()},
m_sites{ov.sites()}
{ }
void construct()
{
const auto& font(m_datasore.template get<sf::Font>(glob::text_font));
// logo
auto logo_shape(m_sites.add_object<widget::rectangle_shape>("home", vec2f{128.f, 128.f}));
logo_shape->get().setTexture(&m_datasore.template get<sf::Texture>("rj_logo.png"));
logo_shape->get().setPosition((m_sites.bounds().width - logo_shape->get().getSize().x) / 2.f, m_sites.size().y * 0.35f - logo_shape->get().getSize().y);
// info text
auto text(m_sites.add_object<widget::text>("home", "", m_overlay.mainmenu().gamehandler().datastore().template get<sf::Font>(glob::text_font), glob::text_size));
text->get().setString("version " + glob::get_version());
text->get().setColor(to_rgb("#373737"));
text->get().setPosition((m_sites.bounds().width - text->get().getGlobalBounds().width) / 2.f, logo_shape->get().getPosition().y + 120.f);
// textboxes
const vec2f tbsize{250.f, 30.f};
auto username(m_sites.add_object<ui::textbox>("home",
tbsize,
vec2f{(m_sites.bounds().width - tbsize.x) / 2.f, logo_shape->get().getPosition().y + 180.f},
font,
"Username"));
auto password(m_sites.add_object<ui::textbox>("home",
tbsize,
vec2f{(m_sites.bounds().width - tbsize.x) / 2.f, logo_shape->get().getPosition().y + 220.f},
font,
"Password"));
default_textbox(*username);
default_textbox(*password);
password->setPasswordMode(true);
// buttons
const vec2f btnsize{100.f, 30.f};
auto login(m_sites.add_object<ui::button>("home", btnsize, vec2f{password->getPosition().x, password->getPosition().y + 40.f}));
login->setFont(font);
login->setText("Login");
auto register_acc(m_sites.add_object<ui::button>("home", btnsize, vec2f{password->getPosition().x + 150.f, password->getPosition().y + 40.f}));
register_acc->setFont(font);
register_acc->setText("Register");
register_acc->on_clicked = [this]{m_overlay.mainmenu().gamehandler().popupmgr().template create_popup<popup_type::info>("Register a new account online at: http://");};
default_button(*login);
default_button(*register_acc);
}
};
}
#endif // RJ_GAME_MAIN_MENU_SITE_HOME_HPP
<|endoftext|> |
<commit_before>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
* CONDOR Copyright Notice
*
* See LICENSE.TXT for additional notices and disclaimers.
*
* Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department,
* University of Wisconsin-Madison, Madison, WI. All Rights Reserved.
* No use of the CONDOR Software Program Source Code is authorized
* without the express consent of the CONDOR Team. For more information
* contact: CONDOR Team, Attention: Professor Miron Livny,
* 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685,
* (608) 262-0856 or miron@cs.wisc.edu.
*
* U.S. Government Rights Restrictions: Use, duplication, or disclosure
* by the U.S. Government is subject to restrictions as set forth in
* subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer
* Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and
* (2) of Commercial Computer Software-Restricted Rights at 48 CFR
* 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron
* Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison,
* WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/
//-----------------------------------------------------------------
#include "condor_common.h"
#include <iostream.h>
#include "condor_commands.h"
#include "condor_config.h"
#include "condor_classad.h"
#include "condor_debug.h"
#include "condor_io.h"
#include "TimeClass.h"
#include "MyString.h"
//-----------------------------------------------------------------
struct LineRec {
MyString Name;
float Priority;
int Res;
};
//-----------------------------------------------------------------
static void usage(char* name);
static void ProcessInfo(AttrList* ad);
static int CountElem(AttrList* ad);
static void CollectInfo(AttrList* ad, LineRec* LR);
static void PrintInfo(AttrList* ad, LineRec* LR, int NumElem);
//-----------------------------------------------------------------
extern "C" {
int CompPrio(LineRec* a, LineRec* b);
}
//-----------------------------------------------------------------
main(int argc, char* argv[])
{
int SetMode=0;
if (argc>1) { // set priority
if (argc!=4 || strcmp(argv[1],"-set")!=0 ) {
usage( argv[0] );
exit(1);
}
SetMode=1;
}
config( 0 );
char* NegotiatorHost = param( "NEGOTIATOR_HOST" );
if (!NegotiatorHost) {
fprintf( stderr, "No NegotiatorHost host specified in config file\n" );
exit(1);
}
if (SetMode) { // set priority
char* tmp;
if( ! (tmp = strchr(argv[2], '@')) ) {
fprintf( stderr,
"%s: You must specify the full name of the submittor you wish\n",
argv[0] );
fprintf( stderr, "\tto update the priority of (%s or %s)\n",
"user@uid.domain", "user@full.host.name" );
exit(1);
}
double Priority=atof(argv[3]);
// send request
ReliSock sock(NegotiatorHost, NEGOTIATOR_PORT);
sock.encode();
if (!sock.put(SET_PRIORITY) ||
!sock.put(argv[2]) ||
!sock.put(Priority) ||
!sock.end_of_message()) {
fprintf( stderr, "failed to send SET_PRIORITY command to negotiator\n" );
exit(1);
}
}
else { // list priorities
// send request
ReliSock sock(NegotiatorHost, NEGOTIATOR_PORT);
sock.encode();
if (!sock.put(GET_PRIORITY) ||
!sock.end_of_message()) {
fprintf( stderr, "failed to send GET_PRIORITY command to negotiator\n" );
exit(1);
}
// get reply
sock.decode();
AttrList* ad=new AttrList();
if (!ad->get(sock) ||
!sock.end_of_message()) {
fprintf( stderr, "failed to get classad from negotiator\n" );
exit(1);
}
ProcessInfo(ad);
}
exit(0);
}
//-----------------------------------------------------------------
static void ProcessInfo(AttrList* ad)
{
int NumElem=CountElem(ad);
LineRec* LR=new LineRec[NumElem];
CollectInfo(ad,LR);
qsort(LR,NumElem,sizeof(LineRec),CompPrio);
PrintInfo(ad,LR,NumElem);
}
//-----------------------------------------------------------------
static int CountElem(AttrList* ad)
{
int count=0;
ad->ResetExpr();
while(ad->NextExpr()) count++;
return (count-1)/3;
}
//-----------------------------------------------------------------
extern "C" {
int CompPrio(LineRec* a, LineRec* b)
{
if (a->Priority>b->Priority) return 1;
return -1;
}
}
//-----------------------------------------------------------------
static void CollectInfo(AttrList* ad, LineRec* LR)
{
ExprTree* exp;
ad->ResetExpr();
exp=ad->NextExpr();
int i=0;
while(exp=ad->NextExpr()) {
LR[i].Name=((String*) exp->RArg())->Value();
LR[i].Priority=((Float*) ad->NextExpr()->RArg())->Value();
LR[i].Res=((Integer*) ad->NextExpr()->RArg())->Value();
i++;
}
return;
}
//-----------------------------------------------------------------
static void PrintInfo(AttrList* ad, LineRec* LR, int NumElem)
{
// ad->AttrList::fPrint(stdout);
ExprTree* exp;
ad->ResetExpr();
exp=ad->NextExpr();
Time T=((Integer*) exp->RArg())->Value();
// printf("%f\n",d);
printf("Last Priority Update: %s\n",T.Asc());
char* Fmt1="%-30s %12.3f %4d\n";
char* Fmt2="%-30s %12s %4s\n";
char* Fmt3="%-30s %12s %4d\n";
printf(Fmt2,"Name","Priority","Resources Used");
printf(Fmt2,"----","--------","--------------");
int Res=0;
for (int i=0; i<NumElem; i++) {
printf(Fmt1,(const char*)LR[i].Name,LR[i].Priority,LR[i].Res);
Res+=LR[i].Res;
}
// printf(Fmt2,"----","--------","--------------");
// printf(Fmt3,"Total","",Res);
return;
}
//-----------------------------------------------------------------
static void usage(char* name) {
fprintf( stderr, "usage: %s [ -set user priority_value ]\n", name );
}
<commit_msg>Fixed condor_userprio to not assume attribute ordering. (This implementation assumes the "NumSubmittors" attribute fix in the accounting module.)<commit_after>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
* CONDOR Copyright Notice
*
* See LICENSE.TXT for additional notices and disclaimers.
*
* Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department,
* University of Wisconsin-Madison, Madison, WI. All Rights Reserved.
* No use of the CONDOR Software Program Source Code is authorized
* without the express consent of the CONDOR Team. For more information
* contact: CONDOR Team, Attention: Professor Miron Livny,
* 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685,
* (608) 262-0856 or miron@cs.wisc.edu.
*
* U.S. Government Rights Restrictions: Use, duplication, or disclosure
* by the U.S. Government is subject to restrictions as set forth in
* subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer
* Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and
* (2) of Commercial Computer Software-Restricted Rights at 48 CFR
* 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron
* Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison,
* WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/
//-----------------------------------------------------------------
#include "condor_common.h"
#include <iostream.h>
#include "condor_commands.h"
#include "condor_config.h"
#include "condor_classad.h"
#include "condor_debug.h"
#include "condor_io.h"
#include "TimeClass.h"
#include "MyString.h"
//-----------------------------------------------------------------
struct LineRec {
MyString Name;
float Priority;
int Res;
};
//-----------------------------------------------------------------
static void usage(char* name);
static void ProcessInfo(AttrList* ad);
static int CountElem(AttrList* ad);
static void CollectInfo(int numElem, AttrList* ad, LineRec* LR);
static void PrintInfo(AttrList* ad, LineRec* LR, int NumElem);
//-----------------------------------------------------------------
extern "C" {
int CompPrio(LineRec* a, LineRec* b);
}
//-----------------------------------------------------------------
main(int argc, char* argv[])
{
int SetMode=0;
if (argc>1) { // set priority
if (argc!=4 || strcmp(argv[1],"-set")!=0 ) {
usage( argv[0] );
exit(1);
}
SetMode=1;
}
config( 0 );
char* NegotiatorHost = param( "NEGOTIATOR_HOST" );
if (!NegotiatorHost) {
fprintf( stderr, "No NegotiatorHost host specified in config file\n" );
exit(1);
}
if (SetMode) { // set priority
char* tmp;
if( ! (tmp = strchr(argv[2], '@')) ) {
fprintf( stderr,
"%s: You must specify the full name of the submittor you wish\n",
argv[0] );
fprintf( stderr, "\tto update the priority of (%s or %s)\n",
"user@uid.domain", "user@full.host.name" );
exit(1);
}
double Priority=atof(argv[3]);
// send request
ReliSock sock(NegotiatorHost, NEGOTIATOR_PORT);
sock.encode();
if (!sock.put(SET_PRIORITY) ||
!sock.put(argv[2]) ||
!sock.put(Priority) ||
!sock.end_of_message()) {
fprintf( stderr, "failed to send SET_PRIORITY command to negotiator\n" );
exit(1);
}
}
else { // list priorities
// send request
ReliSock sock(NegotiatorHost, NEGOTIATOR_PORT);
sock.encode();
if (!sock.put(GET_PRIORITY) ||
!sock.end_of_message()) {
fprintf( stderr, "failed to send GET_PRIORITY command to negotiator\n" );
exit(1);
}
// get reply
sock.decode();
AttrList* ad=new AttrList();
if (!ad->get(sock) ||
!sock.end_of_message()) {
fprintf( stderr, "failed to get classad from negotiator\n" );
exit(1);
}
ProcessInfo(ad);
}
exit(0);
}
//-----------------------------------------------------------------
static void ProcessInfo(AttrList* ad)
{
int NumElem=CountElem(ad);
LineRec* LR=new LineRec[NumElem];
CollectInfo(NumElem,ad,LR);
qsort(LR,NumElem,sizeof(LineRec),CompPrio);
PrintInfo(ad,LR,NumElem);
}
//-----------------------------------------------------------------
static int CountElem(AttrList* ad)
{
int numSubmittors;
if( ad->LookupInteger( "NumSubmittors", numSubmittors ) )
return numSubmittors;
else
return -1;
}
//-----------------------------------------------------------------
extern "C" {
int CompPrio(LineRec* a, LineRec* b)
{
if (a->Priority>b->Priority) return 1;
return -1;
}
}
//-----------------------------------------------------------------
static void CollectInfo(int numElem, AttrList* ad, LineRec* LR)
{
char attrName[32], attrPrio[32], attrResUsed[32];
char name[128];
float priority;
int resUsed;
for( int i=1; i<=numElem; i++) {
sprintf( attrName , "Name%d", i );
sprintf( attrPrio , "Priority%d", i );
sprintf( attrResUsed , "ResourcesUsed%d", i );
if( !ad->LookupString ( attrName, name ) ||
!ad->LookupFloat ( attrPrio, priority ) ||
!ad->LookupInteger ( attrResUsed, resUsed ) )
continue;
LR[i-1].Name=name;
LR[i-1].Priority=priority;
LR[i-1].Res=resUsed;
}
return;
}
//-----------------------------------------------------------------
static void PrintInfo(AttrList* ad, LineRec* LR, int NumElem)
{
ExprTree* exp;
ad->ResetExpr();
exp=ad->NextExpr();
Time T=((Integer*) exp->RArg())->Value();
printf("Last Priority Update: %s\n",T.Asc());
char* Fmt1="%-30s %12.3f %4d\n";
char* Fmt2="%-30s %12s %4s\n";
char* Fmt3="%-30s %12s %4d\n";
printf(Fmt2,"Name","Priority","Resources Used");
printf(Fmt2,"----","--------","--------------");
int Res=0;
for (int i=0; i<NumElem; i++) {
printf(Fmt1,(const char*)LR[i].Name,LR[i].Priority,LR[i].Res);
Res+=LR[i].Res;
}
// printf(Fmt2,"----","--------","--------------");
// printf(Fmt3,"Total","",Res);
return;
}
//-----------------------------------------------------------------
static void usage(char* name) {
fprintf( stderr, "usage: %s [ -set user priority_value ]\n", name );
}
<|endoftext|> |
<commit_before>#ifndef VSMC_UNIFORM_REAL_DISTRIBUTION_HPP
#define VSMC_UNIFORM_REAL_DISTRIBUTION_HPP
#include <vsmc/internal/common.hpp>
#include <vsmc/rng/u01.h>
#define VSMC_RUNTIME_ASSERT_RNG_UNIFORM_REAL_DISTRIBUTION_ENG_MIN(eng_min) \
VSMC_RUNTIME_ASSERT((eng_min == 0), \
("**vsmc::UniformRealDistribution::operator()** " \
"ENGINE MEMBER FUNCTION min() RETURN A VALUE OTHER THAN ZERO"))
#define VSMC_RUNTIME_ASSERT_RNG_UNIFORM_REAL_DISTRIBUTION_ENG_MAX \
VSMC_RUNTIME_ASSERT(false, \
("**vsmc::UniformRealDistribution::operator()** " \
"ENGINE MEMBER FUNCTION min() RETURN A VALUE OTHER THAN " \
"THE MAXIMUM OF uint32_t OR uint64_t"))
namespace vsmc {
namespace traits {
template<uint64_t, uint64_t> struct IntegerRangeTypeTrait;
template<>
struct IntegerRangeTypeTrait<0, ~((uint32_t)0)> {typedef uint32_t type;};
template<>
struct IntegerRangeTypeTrait<0, ~((uint64_t)0)> {typedef uint64_t type;};
} // namespace vsmc::traits
/// \brief Parameter type for open interval
/// \ingroup RNG
struct Open {};
/// \brief Parameter type for closed interval
/// \ingroup RNG
struct Closed {};
/// \brief Uniform real distribution with variants open/closed variants
/// \ingroup RNG
///
/// \details
/// This distribution is almost identical to C++11
/// `std::uniform_real_distribution`. But it differs in two important aspects
/// - It allows the interval to be either open or closed on both sides.
/// - It requires that the uniform random number generator to produce integers
/// on the full range of either `uint32_t` or `uint64_t`.
template <typename FPType, typename Left, typename Right>
class UniformRealDistribution
{
private :
typedef cxx11::integral_constant<std::size_t, sizeof(float)> f24;
typedef cxx11::integral_constant<std::size_t, sizeof(double)> f53;
typedef cxx11::integral_constant<std::size_t, sizeof(uint32_t)> u32;
typedef cxx11::integral_constant<std::size_t, sizeof(uint64_t)> u64;
public :
typedef FPType result_type;
class param_type
{
public :
typedef FPType result_type;
typedef UniformRealDistribution<FPType, Left, Right>
distribution_type;
explicit param_type (result_type a = 0, result_type b = 1) :
a_(a), b_(b) {}
result_type a () const {return a_;}
result_type b () const {return b_;}
friend inline bool operator== (
const param_type ¶m1, const param_type ¶m2)
{return (param1.a() == param2.a()) && (param1.b() == param2.b());}
friend inline bool operator!= (
const param_type param1, const param_type param2)
{return (param1.a() != param2.a()) || (param1.b() != param2.b());}
template <typename CharT, typename Traits>
friend inline std::basic_ostream<CharT, Traits> &operator<< (
std::basic_ostream<CharT, Traits> &os, const param_type ¶m)
{
os << param.a() << ' ' << param.b();
return os;
}
template <typename CharT, typename Traits>
friend inline std::basic_istream<CharT, Traits> &operator>> (
std::basic_istream<CharT, Traits> &is, param_type ¶m)
{
result_type a;
result_type b;
if (is >> a >> std::ws >> b) {
if (a <= b)
param = param_type(param_type(a, b));
else
is.setstate(std::ios_base::failbit);
}
return is;
}
private :
result_type a_;
result_type b_;
}; // class param_type
explicit UniformRealDistribution (result_type a = 0, result_type b = 1) :
a_(a), b_(b) {}
UniformRealDistribution (const param_type ¶m) :
a_(param.a()), b_(param.b()) {}
param_type param () const {return param_type(a_, b_);}
void param (const param_type ¶m)
{
a_ = param.a();
b_ = param.b();
}
void reset () const {}
result_type a () const {return a_;}
result_type b () const {return b_;}
result_type min VSMC_MACRO_NO_EXPANSION () const {return a_;}
result_type max VSMC_MACRO_NO_EXPANSION () const {return b_;}
template <typename Eng>
result_type operator() (Eng &eng) const
{
typedef cxx11::integral_constant<std::size_t, sizeof(result_type)>
fp_bits;
#if VSMC_HAS_CXX11LIB_RANDOM_CONSTEXPR_MINMAX
typedef typename traits::IntegerRangeTypeTrait<
Eng::min VSMC_MACRO_NO_EXPANSION (),
Eng::max VSMC_MACRO_NO_EXPANSION ()>::type eng_uint_t;
typedef cxx11::integral_constant<std::size_t, sizeof(eng_uint_t)>
u_bits;
result_type u = u01(static_cast<eng_uint_t>(eng()), Left(), Right(),
u_bits(), fp_bits());
#else // VSMC_HAS_CXX11LIB_RANDOM_CONSTEXPR_MINMAX
static VSMC_CONSTEXPR const uint64_t eng_min = static_cast<uint64_t>(
eng.min VSMC_MACRO_NO_EXPANSION ());
VSMC_RUNTIME_ASSERT_RNG_UNIFORM_REAL_DISTRIBUTION_ENG_MIN(eng_min);
result_type u = 0;
static VSMC_CONSTEXPR const uint64_t eng_max = static_cast<uint64_t>(
eng.max VSMC_MACRO_NO_EXPANSION ());
switch (eng_max) {
case uint32_t_max_ :
u = u01(static_cast<uint32_t>(eng()), Left(), Right(),
u32(), fp_bits());
break;
case uint64_t_max_ :
u = u01(static_cast<uint64_t>(eng()), Left(), Right(),
u64(), fp_bits());
break;
default :
VSMC_RUNTIME_ASSERT_RNG_UNIFORM_REAL_DISTRIBUTION_ENG_MAX;
}
#endif // VSMC_HAS_CXX11LIB_RANDOM_CONSTEXPR_MINMAX
return u * (b_ - a_) + a_;
}
private :
result_type a_;
result_type b_;
#if !VSMC_HAS_CXX11LIB_RANDOM_CONSTEXPR_MINMAX
static VSMC_CONSTEXPR const uint64_t uint32_t_max_ = ~((uint32_t)0);
static VSMC_CONSTEXPR const uint64_t uint64_t_max_ = ~((uint64_t)0);
#endif
static float u01(uint32_t i, Open, Open, u32, f24)
{return ::u01_open_open_32_24(i);}
static float u01(uint32_t i, Open, Closed, u32, f24)
{return ::u01_open_closed_32_24(i);}
static float u01(uint32_t i, Closed, Open, u32, f24)
{return ::u01_closed_open_32_24(i);}
static float u01(uint32_t i, Closed, Closed, u32, f24)
{return ::u01_closed_closed_32_24(i);}
static double u01(uint32_t i, Open, Open, u32, f53)
{return ::u01_open_open_32_53(i);}
static double u01(uint32_t i, Open, Closed, u32, f53)
{return ::u01_open_closed_32_53(i);}
static double u01(uint32_t i, Closed, Open, u32, f53)
{return ::u01_closed_open_32_53(i);}
static double u01(uint32_t i, Closed, Closed, u32, f53)
{return ::u01_closed_closed_32_53(i);}
static float u01(uint64_t i, Open, Open, u64, f24)
{return static_cast<float>(::u01_open_open_64_53(i));}
static float u01(uint64_t i, Open, Closed, u64, f24)
{return static_cast<float>(::u01_open_closed_64_53(i));}
static float u01(uint64_t i, Closed, Open, u64, f24)
{return static_cast<float>(::u01_closed_open_64_53(i));}
static float u01(uint64_t i, Closed, Closed, u64, f24)
{return static_cast<float>(::u01_closed_closed_64_53(i));}
static double u01(uint64_t i, Open, Open, u64, f53)
{return ::u01_open_open_64_53(i);}
static double u01(uint64_t i, Open, Closed, u64, f53)
{return ::u01_open_closed_64_53(i);}
static double u01(uint64_t i, Closed, Open, u64, f53)
{return ::u01_closed_open_64_53(i);}
static double u01(uint64_t i, Closed, Closed, u64, f53)
{return ::u01_closed_closed_64_53(i);}
}; // class UniformRealDistributionBase
/// \brief UniformRealDistribution operator==
/// \ingroup RNG
template <typename FPType, typename Left, typename Right>
inline bool operator== (
const UniformRealDistribution<FPType, Left, Right> &runif1,
const UniformRealDistribution<FPType, Left, Right> &runif2)
{
return (runif1.a() == runif2.a()) && (runif1.b() == runif2.b());
}
/// \brief UniformRealDistribution operator!=
/// \ingroup RNG
template <typename FPType, typename Left, typename Right>
inline bool operator!= (
const UniformRealDistribution<FPType, Left, Right> &runif1,
const UniformRealDistribution<FPType, Left, Right> &runif2)
{
return (runif1.a() != runif2.a()) || (runif1.b() != runif2.b());
}
/// \brief UniformRealDistribution operator<<
/// \ingroup RNG
template <typename CharT, typename Traits,
typename FPType, typename Left, typename Right>
inline std::basic_ostream<CharT, Traits> &operator<< (
std::basic_ostream<CharT, Traits> &os,
const UniformRealDistribution<FPType, Left, Right> &runif)
{
os << runif.a() << ' ' << runif.b();
return os;
}
/// \brief UniformRealDistribution operator>>
/// \ingroup RNG
template <typename CharT, typename Traits,
typename FPType, typename Left, typename Right>
inline std::basic_istream<CharT, Traits> &operator>> (
std::basic_istream<CharT, Traits> &is,
UniformRealDistribution<FPType, Left, Right> &runif)
{
typedef typename UniformRealDistribution<FPType, Left, Right>::param_type
param_type;
FPType a;
FPType b;
if (is >> a >> std::ws >> b) {
if (a <= b)
runif.param(param_type(a, b));
else
is.setstate(std::ios_base::failbit);
}
return is;
}
} // namespace vsmc
#endif // VSMC_UNIFORM_REAL_DISTRIBUTION_HPP
<commit_msg>suppress garbage value warning<commit_after>#ifndef VSMC_UNIFORM_REAL_DISTRIBUTION_HPP
#define VSMC_UNIFORM_REAL_DISTRIBUTION_HPP
#include <vsmc/internal/common.hpp>
#include <vsmc/rng/u01.h>
#define VSMC_RUNTIME_ASSERT_RNG_UNIFORM_REAL_DISTRIBUTION_ENG_MIN(eng_min) \
VSMC_RUNTIME_ASSERT((eng_min == 0), \
("**vsmc::UniformRealDistribution::operator()** " \
"ENGINE MEMBER FUNCTION min() RETURN A VALUE OTHER THAN ZERO"))
#define VSMC_RUNTIME_ASSERT_RNG_UNIFORM_REAL_DISTRIBUTION_ENG_MAX \
VSMC_RUNTIME_ASSERT(false, \
("**vsmc::UniformRealDistribution::operator()** " \
"ENGINE MEMBER FUNCTION min() RETURN A VALUE OTHER THAN " \
"THE MAXIMUM OF uint32_t OR uint64_t"))
namespace vsmc {
namespace traits {
template<uint64_t, uint64_t> struct IntegerRangeTypeTrait;
template<>
struct IntegerRangeTypeTrait<0, ~((uint32_t)0)> {typedef uint32_t type;};
template<>
struct IntegerRangeTypeTrait<0, ~((uint64_t)0)> {typedef uint64_t type;};
} // namespace vsmc::traits
/// \brief Parameter type for open interval
/// \ingroup RNG
struct Open {};
/// \brief Parameter type for closed interval
/// \ingroup RNG
struct Closed {};
/// \brief Uniform real distribution with variants open/closed variants
/// \ingroup RNG
///
/// \details
/// This distribution is almost identical to C++11
/// `std::uniform_real_distribution`. But it differs in two important aspects
/// - It allows the interval to be either open or closed on both sides.
/// - It requires that the uniform random number generator to produce integers
/// on the full range of either `uint32_t` or `uint64_t`.
template <typename FPType, typename Left, typename Right>
class UniformRealDistribution
{
private :
typedef cxx11::integral_constant<std::size_t, sizeof(float)> f24;
typedef cxx11::integral_constant<std::size_t, sizeof(double)> f53;
typedef cxx11::integral_constant<std::size_t, sizeof(uint32_t)> u32;
typedef cxx11::integral_constant<std::size_t, sizeof(uint64_t)> u64;
public :
typedef FPType result_type;
class param_type
{
public :
typedef FPType result_type;
typedef UniformRealDistribution<FPType, Left, Right>
distribution_type;
explicit param_type (result_type a = 0, result_type b = 1) :
a_(a), b_(b) {}
result_type a () const {return a_;}
result_type b () const {return b_;}
friend inline bool operator== (
const param_type ¶m1, const param_type ¶m2)
{return (param1.a() == param2.a()) && (param1.b() == param2.b());}
friend inline bool operator!= (
const param_type param1, const param_type param2)
{return (param1.a() != param2.a()) || (param1.b() != param2.b());}
template <typename CharT, typename Traits>
friend inline std::basic_ostream<CharT, Traits> &operator<< (
std::basic_ostream<CharT, Traits> &os, const param_type ¶m)
{
os << param.a() << ' ' << param.b();
return os;
}
template <typename CharT, typename Traits>
friend inline std::basic_istream<CharT, Traits> &operator>> (
std::basic_istream<CharT, Traits> &is, param_type ¶m)
{
result_type a;
result_type b;
if (is >> a >> std::ws >> b) {
if (a <= b)
param = param_type(param_type(a, b));
else
is.setstate(std::ios_base::failbit);
}
return is;
}
private :
result_type a_;
result_type b_;
}; // class param_type
explicit UniformRealDistribution (result_type a = 0, result_type b = 1) :
a_(a), b_(b) {}
UniformRealDistribution (const param_type ¶m) :
a_(param.a()), b_(param.b()) {}
param_type param () const {return param_type(a_, b_);}
void param (const param_type ¶m)
{
a_ = param.a();
b_ = param.b();
}
void reset () const {}
result_type a () const {return a_;}
result_type b () const {return b_;}
result_type min VSMC_MACRO_NO_EXPANSION () const {return a_;}
result_type max VSMC_MACRO_NO_EXPANSION () const {return b_;}
template <typename Eng>
result_type operator() (Eng &eng) const
{
typedef cxx11::integral_constant<std::size_t, sizeof(result_type)>
fp_bits;
#if VSMC_HAS_CXX11LIB_RANDOM_CONSTEXPR_MINMAX
typedef typename traits::IntegerRangeTypeTrait<
Eng::min VSMC_MACRO_NO_EXPANSION (),
Eng::max VSMC_MACRO_NO_EXPANSION ()>::type eng_uint_t;
typedef cxx11::integral_constant<std::size_t, sizeof(eng_uint_t)>
u_bits;
result_type u = u01(static_cast<eng_uint_t>(eng()), Left(), Right(),
u_bits(), fp_bits());
#else // VSMC_HAS_CXX11LIB_RANDOM_CONSTEXPR_MINMAX
static VSMC_CONSTEXPR const uint64_t eng_min = static_cast<uint64_t>(
eng.min VSMC_MACRO_NO_EXPANSION ());
VSMC_RUNTIME_ASSERT_RNG_UNIFORM_REAL_DISTRIBUTION_ENG_MIN(eng_min);
result_type u = 0;
static VSMC_CONSTEXPR const uint64_t eng_max = static_cast<uint64_t>(
eng.max VSMC_MACRO_NO_EXPANSION ());
switch (eng_max) {
case uint32_t_max_ :
u = u01(static_cast<uint32_t>(eng()), Left(), Right(),
u32(), fp_bits());
break;
case uint64_t_max_ :
u = u01(static_cast<uint64_t>(eng()), Left(), Right(),
u64(), fp_bits());
break;
default :
VSMC_RUNTIME_ASSERT_RNG_UNIFORM_REAL_DISTRIBUTION_ENG_MAX;
}
#endif // VSMC_HAS_CXX11LIB_RANDOM_CONSTEXPR_MINMAX
return u * (b_ - a_) + a_;
}
private :
result_type a_;
result_type b_;
#if !VSMC_HAS_CXX11LIB_RANDOM_CONSTEXPR_MINMAX
static VSMC_CONSTEXPR const uint64_t uint32_t_max_ = ~((uint32_t)0);
static VSMC_CONSTEXPR const uint64_t uint64_t_max_ = ~((uint64_t)0);
#endif
static float u01(uint32_t i, Open, Open, u32, f24)
{return ::u01_open_open_32_24(i);}
static float u01(uint32_t i, Open, Closed, u32, f24)
{return ::u01_open_closed_32_24(i);}
static float u01(uint32_t i, Closed, Open, u32, f24)
{return ::u01_closed_open_32_24(i);}
static float u01(uint32_t i, Closed, Closed, u32, f24)
{return ::u01_closed_closed_32_24(i);}
static double u01(uint32_t i, Open, Open, u32, f53)
{return ::u01_open_open_32_53(i);}
static double u01(uint32_t i, Open, Closed, u32, f53)
{return ::u01_open_closed_32_53(i);}
static double u01(uint32_t i, Closed, Open, u32, f53)
{return ::u01_closed_open_32_53(i);}
static double u01(uint32_t i, Closed, Closed, u32, f53)
{return ::u01_closed_closed_32_53(i);}
static float u01(uint64_t i, Open, Open, u64, f24)
{return static_cast<float>(::u01_open_open_64_53(i));}
static float u01(uint64_t i, Open, Closed, u64, f24)
{return static_cast<float>(::u01_open_closed_64_53(i));}
static float u01(uint64_t i, Closed, Open, u64, f24)
{return static_cast<float>(::u01_closed_open_64_53(i));}
static float u01(uint64_t i, Closed, Closed, u64, f24)
{return static_cast<float>(::u01_closed_closed_64_53(i));}
static double u01(uint64_t i, Open, Open, u64, f53)
{return ::u01_open_open_64_53(i);}
static double u01(uint64_t i, Open, Closed, u64, f53)
{return ::u01_open_closed_64_53(i);}
static double u01(uint64_t i, Closed, Open, u64, f53)
{return ::u01_closed_open_64_53(i);}
static double u01(uint64_t i, Closed, Closed, u64, f53)
{return ::u01_closed_closed_64_53(i);}
}; // class UniformRealDistributionBase
/// \brief UniformRealDistribution operator==
/// \ingroup RNG
template <typename FPType, typename Left, typename Right>
inline bool operator== (
const UniformRealDistribution<FPType, Left, Right> &runif1,
const UniformRealDistribution<FPType, Left, Right> &runif2)
{
return (runif1.a() == runif2.a()) && (runif1.b() == runif2.b());
}
/// \brief UniformRealDistribution operator!=
/// \ingroup RNG
template <typename FPType, typename Left, typename Right>
inline bool operator!= (
const UniformRealDistribution<FPType, Left, Right> &runif1,
const UniformRealDistribution<FPType, Left, Right> &runif2)
{
return (runif1.a() != runif2.a()) || (runif1.b() != runif2.b());
}
/// \brief UniformRealDistribution operator<<
/// \ingroup RNG
template <typename CharT, typename Traits,
typename FPType, typename Left, typename Right>
inline std::basic_ostream<CharT, Traits> &operator<< (
std::basic_ostream<CharT, Traits> &os,
const UniformRealDistribution<FPType, Left, Right> &runif)
{
os << runif.a() << ' ' << runif.b();
return os;
}
/// \brief UniformRealDistribution operator>>
/// \ingroup RNG
template <typename CharT, typename Traits,
typename FPType, typename Left, typename Right>
inline std::basic_istream<CharT, Traits> &operator>> (
std::basic_istream<CharT, Traits> &is,
UniformRealDistribution<FPType, Left, Right> &runif)
{
typedef typename UniformRealDistribution<FPType, Left, Right>::param_type
param_type;
FPType a = 0;
FPType b = 0;
if (is >> a >> std::ws >> b) {
if (a <= b)
runif.param(param_type(a, b));
else
is.setstate(std::ios_base::failbit);
}
return is;
}
} // namespace vsmc
#endif // VSMC_UNIFORM_REAL_DISTRIBUTION_HPP
<|endoftext|> |
<commit_before>#include <fstream>
#include <string>
#include <string.h>
#include <iostream>
#include "io.hh"
#include "str.hh"
#include "conf.hh"
#include "HmmSet.hh"
#include "FeatureGenerator.hh"
#include "Recipe.hh"
std::string out_file;
std::string save_summary_file;
int info;
int accum_pos;
bool raw_flag;
bool transtat;
bool durstat;
float start_time, end_time;
int start_frame, end_frame;
conf::Config config;
Recipe recipe;
HmmSet model;
FeatureGenerator fea_gen;
void
train(HmmSet *model, Segmentator *segmentator)
{
int frame;
while (segmentator->next_frame()) {
// Fetch the current feature vector
frame = segmentator->current_frame();
FeatureVec feature = fea_gen.generate(frame);
model->reset_cache();
// Accumulate all possible states distributions for this frame
const std::vector<Segmentator::IndexProbPair> &pdfs
= segmentator->pdf_probs();
for (int i = 0; i < (int)pdfs.size(); i++)
model->accumulate_distribution(feature, pdfs[i].index,
pdfs[i].prob, accum_pos);
// Accumulate also transition probabilities if desired
if (transtat) {
const std::vector<Segmentator::IndexProbPair> &transitions
= segmentator->transition_probs();
for (int i = 0; i < (int)transitions.size(); i++)
model->accumulate_transition(transitions[i].index,
transitions[i].prob);
}
}
}
int
main(int argc, char *argv[])
{
Segmentator *segmentator;
try {
config("usage: stats [OPTION...]\n")
('h', "help", "", "", "display help")
('b', "base=BASENAME", "arg", "", "base filename for model files")
('g', "gk=FILE", "arg", "", "Mixture base distributions")
('m', "mc=FILE", "arg", "", "Mixture coefficients for the states")
('p', "ph=FILE", "arg", "", "HMM definitions")
('c', "config=FILE", "arg must", "", "feature configuration")
('r', "recipe=FILE", "arg must", "", "recipe file")
('O', "ophn", "", "", "use output phns for training")
('H', "hmmnet", "", "", "use HMM networks for training")
('D', "den-hmmnet", "", "", "use denominator HMM networks for training")
('o', "out=BASENAME", "arg must", "", "base filename for output statistics")
('R', "raw-input", "", "", "raw audio input")
('t', "transitions", "", "", "collect also state transition statistics")
('d', "durstat", "", "", "collect also duration statistics")
('F', "fw-beam=FLOAT", "arg", "0", "Forward beam (for lattice-based training)")
('W', "bw-beam=FLOAT", "arg", "0", "Backward beam (for lattice-based training)")
('A', "ac-scale=FLOAT", "arg", "1", "Acoustic scaling (for lattice-based training)")
('s', "savesum=FILE", "arg", "", "save summary information (loglikelihood etc.)")
('S', "speakers=FILE", "arg", "", "speaker configuration file")
('B', "batch=INT", "arg", "0", "number of batch processes with the same recipe")
('I', "bindex=INT", "arg", "0", "batch process index")
('i', "info=INT", "arg", "0", "info level")
;
config.default_parse(argc, argv);
info = config["info"].get_int();
raw_flag = config["raw-input"].specified;
fea_gen.load_configuration(io::Stream(config["config"].get_str()));
// Initialize the model for accumulating ML statistics
if (config["base"].specified)
{
model.read_all(config["base"].get_str());
}
else if (config["gk"].specified && config["mc"].specified &&
config["ph"].specified)
{
model.read_gk(config["gk"].get_str());
model.read_mc(config["mc"].get_str());
model.read_ph(config["ph"].get_str());
}
else
{
throw std::string("Must give either --base or all --gk, --mc and --ph");
}
out_file = config["out"].get_str();
if (config["savesum"].specified)
save_summary_file = config["savesum"].get_str();
if (config["batch"].specified^config["bindex"].specified)
throw std::string("Must give both --batch and --bindex");
// Check for state transition statistics
transtat = config["transitions"].specified;
if (transtat)
fprintf(stderr, "You have defined --transitions option: state transition statistics will be collected as well\n");
// Check for duration statistics
durstat = config["durstat"].specified;
if (durstat)
fprintf(stderr, "You have defined --durstat option: duration statistics will be collected as well\n");
// Check the dimension
if (model.dim() != fea_gen.dim()) {
throw str::fmt(128,
"gaussian dimension is %d but feature dimension is %d",
model.dim(), fea_gen.dim());
}
// Read recipe file
recipe.read(io::Stream(config["recipe"].get_str()),
config["batch"].get_int(), config["bindex"].get_int(),
true);
// Configure the model for accumulating
if (config["den-hmmnet"].specified) {
model.set_estimation_mode(PDF::MMI);
accum_pos=1;
}
else {
model.set_estimation_mode(PDF::ML);
accum_pos=0;
}
model.start_accumulating();
// Process each recipe line
for (int f = 0; f < (int)recipe.infos.size(); f++)
{
// Print file name, start and end times to stderr
if (info > 0)
{
fprintf(stderr, "Processing file: %s",
recipe.infos[f].audio_path.c_str());
if (recipe.infos[f].start_time || recipe.infos[f].end_time)
fprintf(stderr," (%.2f-%.2f)",recipe.infos[f].start_time,
recipe.infos[f].end_time);
fprintf(stderr,"\n");
}
if (config["hmmnet"].specified || config["den-hmmnet"].specified)
{
// Open files and configure
HmmNetBaumWelch* lattice =
recipe.infos[f].init_hmmnet_files(&model,
config["den-hmmnet"].specified,
&fea_gen, raw_flag, NULL);
lattice->set_collect_transition_probs(transtat);
lattice->set_pruning_thresholds(config["bw-beam"].get_float(), config["fw-beam"].get_float());
if (config["ac-scale"].specified)
lattice->set_acoustic_scaling(config["ac-scale"].get_float());
double orig_beam = lattice->get_backward_beam();
int counter = 1;
while (!lattice->init_utterance_segmentation())
{
if (counter >= 5)
{
throw std::string("Could not run Baum-Welch.\n") +
std::string("The HMM network may be incorrect or initial beam too low.");
}
fprintf(stderr,
"Warning: Backward phase failed, increasing beam to %.1f\n",
++counter*orig_beam);
lattice->set_pruning_thresholds(counter*orig_beam, 0);
}
segmentator = lattice;
}
else
{
PhnReader* phnreader =
recipe.infos[f].init_phn_files(&model, false, false,
config["ophn"].specified, &fea_gen,
config["raw-input"].specified, NULL);
phnreader->set_collect_transition_probs(transtat);
segmentator = phnreader;
if (!segmentator->init_utterance_segmentation())
throw std::string("Could not initialize the utterance for PhnReader");
}
// Train
train(&model, segmentator);
// Clean up
delete segmentator;
fea_gen.close();
}
if (info > 0)
{
fprintf(stderr, "Finished collecting statistics (%i/%i), writing models\n",
config["batch"].get_int(), config["bindex"].get_int());
}
// Write statistics to file dump and clean up
model.dump_statistics(out_file);
model.stop_accumulating();
}
// Handle errors
catch (HmmSet::UnknownHmm &e) {
fprintf(stderr,
"Unknown HMM in transcription, "
"writing incompletely taught models\n");
abort();
}
catch (std::exception &e) {
fprintf(stderr, "exception: %s\n", e.what());
abort();
}
catch (std::string &str) {
fprintf(stderr, "exception: %s\n", str.c_str());
abort();
}
}
<commit_msg>total log likelihood printti<commit_after>#include <fstream>
#include <string>
#include <string.h>
#include <iostream>
#include "io.hh"
#include "str.hh"
#include "conf.hh"
#include "HmmSet.hh"
#include "FeatureGenerator.hh"
#include "Recipe.hh"
#include "util.hh"
std::string out_file;
std::string save_summary_file;
int info;
int accum_pos;
bool raw_flag;
bool transtat;
bool durstat;
float start_time, end_time;
int start_frame, end_frame;
double total_log_likelihood=0;
conf::Config config;
Recipe recipe;
HmmSet model;
FeatureGenerator fea_gen;
void
train(HmmSet *model, Segmentator *segmentator)
{
int frame;
while (segmentator->next_frame()) {
// Fetch the current feature vector
frame = segmentator->current_frame();
FeatureVec feature = fea_gen.generate(frame);
model->reset_cache();
// Accumulate all possible states distributions for this frame
const std::vector<Segmentator::IndexProbPair> &pdfs
= segmentator->pdf_probs();
for (int i = 0; i < (int)pdfs.size(); i++) {
model->accumulate_distribution(feature, pdfs[i].index,
pdfs[i].prob, accum_pos);
total_log_likelihood += util::safe_log(pdfs[i].prob);
}
// Accumulate also transition probabilities if desired
if (transtat) {
const std::vector<Segmentator::IndexProbPair> &transitions
= segmentator->transition_probs();
for (int i = 0; i < (int)transitions.size(); i++) {
model->accumulate_transition(transitions[i].index,
transitions[i].prob);
total_log_likelihood += util::safe_log(transitions[i].prob);
}
}
}
}
int
main(int argc, char *argv[])
{
Segmentator *segmentator;
try {
config("usage: stats [OPTION...]\n")
('h', "help", "", "", "display help")
('b', "base=BASENAME", "arg", "", "base filename for model files")
('g', "gk=FILE", "arg", "", "Mixture base distributions")
('m', "mc=FILE", "arg", "", "Mixture coefficients for the states")
('p', "ph=FILE", "arg", "", "HMM definitions")
('c', "config=FILE", "arg must", "", "feature configuration")
('r', "recipe=FILE", "arg must", "", "recipe file")
('O', "ophn", "", "", "use output phns for training")
('H', "hmmnet", "", "", "use HMM networks for training")
('D', "den-hmmnet", "", "", "use denominator HMM networks for training")
('o', "out=BASENAME", "arg must", "", "base filename for output statistics")
('R', "raw-input", "", "", "raw audio input")
('t', "transitions", "", "", "collect also state transition statistics")
('d', "durstat", "", "", "collect also duration statistics")
('F', "fw-beam=FLOAT", "arg", "0", "Forward beam (for lattice-based training)")
('W', "bw-beam=FLOAT", "arg", "0", "Backward beam (for lattice-based training)")
('A', "ac-scale=FLOAT", "arg", "1", "Acoustic scaling (for lattice-based training)")
('s', "savesum=FILE", "arg", "", "save summary information (loglikelihood etc.)")
('S', "speakers=FILE", "arg", "", "speaker configuration file")
('B', "batch=INT", "arg", "0", "number of batch processes with the same recipe")
('I', "bindex=INT", "arg", "0", "batch process index")
('i', "info=INT", "arg", "0", "info level")
;
config.default_parse(argc, argv);
info = config["info"].get_int();
raw_flag = config["raw-input"].specified;
fea_gen.load_configuration(io::Stream(config["config"].get_str()));
// Initialize the model for accumulating ML statistics
if (config["base"].specified)
{
model.read_all(config["base"].get_str());
}
else if (config["gk"].specified && config["mc"].specified &&
config["ph"].specified)
{
model.read_gk(config["gk"].get_str());
model.read_mc(config["mc"].get_str());
model.read_ph(config["ph"].get_str());
}
else
{
throw std::string("Must give either --base or all --gk, --mc and --ph");
}
out_file = config["out"].get_str();
if (config["savesum"].specified)
save_summary_file = config["savesum"].get_str();
if (config["batch"].specified^config["bindex"].specified)
throw std::string("Must give both --batch and --bindex");
// Check for state transition statistics
transtat = config["transitions"].specified;
if (transtat)
fprintf(stderr, "You have defined --transitions option: state transition statistics will be collected as well\n");
// Check for duration statistics
durstat = config["durstat"].specified;
if (durstat)
fprintf(stderr, "You have defined --durstat option: duration statistics will be collected as well\n");
// Check the dimension
if (model.dim() != fea_gen.dim()) {
throw str::fmt(128,
"gaussian dimension is %d but feature dimension is %d",
model.dim(), fea_gen.dim());
}
// Read recipe file
recipe.read(io::Stream(config["recipe"].get_str()),
config["batch"].get_int(), config["bindex"].get_int(),
true);
// Configure the model for accumulating
if (config["den-hmmnet"].specified) {
model.set_estimation_mode(PDF::MMI);
accum_pos=1;
}
else {
model.set_estimation_mode(PDF::ML);
accum_pos=0;
}
model.start_accumulating();
// Process each recipe line
for (int f = 0; f < (int)recipe.infos.size(); f++)
{
// Print file name, start and end times to stderr
if (info > 0)
{
fprintf(stderr, "Processing file: %s",
recipe.infos[f].audio_path.c_str());
if (recipe.infos[f].start_time || recipe.infos[f].end_time)
fprintf(stderr," (%.2f-%.2f)",recipe.infos[f].start_time,
recipe.infos[f].end_time);
fprintf(stderr,"\n");
}
if (config["hmmnet"].specified || config["den-hmmnet"].specified)
{
// Open files and configure
HmmNetBaumWelch* lattice =
recipe.infos[f].init_hmmnet_files(&model,
config["den-hmmnet"].specified,
&fea_gen, raw_flag, NULL);
lattice->set_collect_transition_probs(transtat);
lattice->set_pruning_thresholds(config["bw-beam"].get_float(), config["fw-beam"].get_float());
if (config["ac-scale"].specified)
lattice->set_acoustic_scaling(config["ac-scale"].get_float());
double orig_beam = lattice->get_backward_beam();
int counter = 1;
while (!lattice->init_utterance_segmentation())
{
if (counter >= 5)
{
throw std::string("Could not run Baum-Welch.\n") +
std::string("The HMM network may be incorrect or initial beam too low.");
}
fprintf(stderr,
"Warning: Backward phase failed, increasing beam to %.1f\n",
++counter*orig_beam);
lattice->set_pruning_thresholds(counter*orig_beam, 0);
}
segmentator = lattice;
}
else
{
PhnReader* phnreader =
recipe.infos[f].init_phn_files(&model, false, false,
config["ophn"].specified, &fea_gen,
config["raw-input"].specified, NULL);
phnreader->set_collect_transition_probs(transtat);
segmentator = phnreader;
if (!segmentator->init_utterance_segmentation())
throw std::string("Could not initialize the utterance for PhnReader");
}
// Train
train(&model, segmentator);
// Clean up
delete segmentator;
fea_gen.close();
}
if (info > 0)
{
fprintf(stderr, "Finished collecting statistics (%i/%i), writing models\n",
config["batch"].get_int(), config["bindex"].get_int());
fprintf(stderr, "Total log likelihood: %f\n", total_log_likelihood);
}
// Write statistics to file dump and clean up
model.dump_statistics(out_file);
model.stop_accumulating();
}
// Handle errors
catch (HmmSet::UnknownHmm &e) {
fprintf(stderr,
"Unknown HMM in transcription, "
"writing incompletely taught models\n");
abort();
}
catch (std::exception &e) {
fprintf(stderr, "exception: %s\n", e.what());
abort();
}
catch (std::string &str) {
fprintf(stderr, "exception: %s\n", str.c_str());
abort();
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2014 Jae-jun Kang
// See the file COPYING for license details.
#ifndef X2BOOST_SINGLE_THREADED_FLOW_HPP_
#define X2BOOST_SINGLE_THREADED_FLOW_HPP_
#ifndef X2BOOST_PRE_HPP_
#include "x2boost/pre.hpp"
#endif
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include "x2boost/flows/event_based_flow.hpp"
namespace x2
{
template<class Q = synchronized_event_queue>
class X2BOOST_API single_threaded_flow : public event_based_flow<Q>
{
public:
single_threaded_flow() : thread_(NULL) {}
virtual ~single_threaded_flow() {}
virtual void startup()
{
boost::mutex::scoped_lock lock(flow::mutex_);
if (thread_) { return; }
this->setup();
flow::case_stack_.setup(shared_from_this());
thread_ = new boost::thread(boost::bind(&event_based_flow<Q>::run, this));
}
virtual void shutdown()
{
boost::mutex::scoped_lock lock(flow::mutex_);
if (!thread_) { return; }
// enqueue flow_stop
queue_.close();
thread_->join();
delete thread_;
thread_ = NULL;
flow::case_stack_.teardown(shared_from_this());
this->teardown();
}
protected:
boost::thread* thread_;
};
}
#endif // X2BOOST_SINGLE_THREADED_FLOW_HPP_
<commit_msg>fixed build errors for g++<commit_after>// Copyright (c) 2014 Jae-jun Kang
// See the file COPYING for license details.
#ifndef X2BOOST_SINGLE_THREADED_FLOW_HPP_
#define X2BOOST_SINGLE_THREADED_FLOW_HPP_
#ifndef X2BOOST_PRE_HPP_
#include "x2boost/pre.hpp"
#endif
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include "x2boost/flows/event_based_flow.hpp"
namespace x2
{
template<class Q = synchronized_event_queue>
class X2BOOST_API single_threaded_flow : public event_based_flow<Q>
{
public:
single_threaded_flow() : thread_(NULL) {}
virtual ~single_threaded_flow() {}
virtual void startup()
{
boost::mutex::scoped_lock lock(flow::mutex_);
if (thread_) { return; }
this->setup();
flow::case_stack_.setup(boost::enable_shared_from_this<flow>::shared_from_this());
thread_ = new boost::thread(boost::bind(&event_based_flow<Q>::run, this));
}
virtual void shutdown()
{
boost::mutex::scoped_lock lock(flow::mutex_);
if (!thread_) { return; }
// enqueue flow_stop
event_based_flow<Q>::queue_.close();
thread_->join();
delete thread_;
thread_ = NULL;
flow::case_stack_.teardown(boost::enable_shared_from_this<flow>::shared_from_this());
this->teardown();
}
protected:
boost::thread* thread_;
};
}
#endif // X2BOOST_SINGLE_THREADED_FLOW_HPP_
<|endoftext|> |
<commit_before>/* libwpd
* Copyright (C) 2002 William Lachance (wrlach@gmail.com)
* Copyright (C) 2002-2004 Marc Maurer (uwog@uwog.net)
*
* 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library 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
*
* For further information visit http://libwpd.sourceforge.net
*/
/* "This product is not manufactured, approved, or supported by
* Corel Corporation or Corel Corporation Limited."
*/
#include <stdio.h>
#include <stdarg.h>
#include "RawListener.h"
#define _U(M, L) \
if (!m_printCallgraphScore) \
__iuprintf M; \
else \
m_callStack.push(L);
#define _D(M, L) \
if (!m_printCallgraphScore) \
__idprintf M; \
else \
{ \
ListenerCallback lc = m_callStack.top(); \
if (lc != L) \
m_callbackMisses++; \
m_callStack.pop(); \
}
RawListenerImpl::RawListenerImpl(bool printCallgraphScore) :
m_indent(0),
m_callbackMisses(0),
m_printCallgraphScore(printCallgraphScore)
{
}
RawListenerImpl::~RawListenerImpl()
{
if (m_printCallgraphScore)
printf("%d\n", m_callStack.size() + m_callbackMisses);
}
void RawListenerImpl::__iprintf(const char *format, ...)
{
if (m_printCallgraphScore) return;
va_list args;
va_start(args, format);
for (int i=0; i<m_indent; i++)
printf(" ");
vprintf(format, args);
va_end(args);
}
void RawListenerImpl::__iuprintf(const char *format, ...)
{
va_list args;
va_start(args, format);
for (int i=0; i<m_indent; i++)
printf(" ");
vprintf(format, args);
__indentUp();
va_end(args);
}
void RawListenerImpl::__idprintf(const char *format, ...)
{
va_list args;
va_start(args, format);
__indentDown();
for (int i=0; i<m_indent; i++)
printf(" ");
vprintf(format, args);
va_end(args);
}
WPXString getPropString(const WPXPropertyList &propList)
{
WPXString propString;
WPXPropertyList::Iter i(propList);
if (!i.last())
{
WPXString prop;
prop.sprintf("%s: %s", i.key(), i()->getStr().cstr());
propString.append(prop);
for (; i.next(); )
{
prop.sprintf(", %s: %s", i.key(), i()->getStr().cstr());
propString.append(prop);
}
}
return propString;
}
WPXString getPropString(const WPXPropertyListVector &itemList)
{
WPXString propString;
propString.append("(");
WPXPropertyListVector::Iter i(itemList);
if (!i.last())
{
propString.append("(");
propString.append(getPropString(i()));
propString.append(")");
for (; i.next();)
{
propString.append(", (");
propString.append(getPropString(i()));
propString.append(")");
}
}
propString.append(")");
return propString;
}
void RawListenerImpl::setDocumentMetaData(const WPXPropertyList &propList)
{
if (m_printCallgraphScore)
return;
__iprintf("setDocumentMetaData(%s)\n", getPropString(propList).cstr());
}
void RawListenerImpl::startDocument()
{
_U(("startDocument()\n"), LC_START_DOCUMENT);
}
void RawListenerImpl::endDocument()
{
_D(("endDocument()\n"), LC_START_DOCUMENT);
}
void RawListenerImpl::openPageSpan(const WPXPropertyList &propList)
{
_U(("openPageSpan(%s)\n", getPropString(propList).cstr()),
LC_OPEN_PAGE_SPAN);
}
void RawListenerImpl::closePageSpan()
{
_D(("closePageSpan()\n"),
LC_OPEN_PAGE_SPAN);
}
void RawListenerImpl::openHeader(const WPXPropertyList &propList)
{
_U(("openHeader(%s)\n",
getPropString(propList).cstr()),
LC_OPEN_HEADER_FOOTER);
}
void RawListenerImpl::closeHeader()
{
_D(("closeHeader()\n"),
LC_OPEN_HEADER_FOOTER);
}
void RawListenerImpl::openFooter(const WPXPropertyList &propList)
{
_U(("openFooter(%s)\n",
getPropString(propList).cstr()),
LC_OPEN_HEADER_FOOTER);
}
void RawListenerImpl::closeFooter()
{
_D(("closeFooter()\n"),
LC_OPEN_HEADER_FOOTER);
}
void RawListenerImpl::openParagraph(const WPXPropertyList &propList, const WPXPropertyListVector &tabStops)
{
_U(("openParagraph(%s, tab-stops: %s)\n", getPropString(propList).cstr(), getPropString(tabStops).cstr()),
LC_OPEN_PARAGRAPH);
}
void RawListenerImpl::closeParagraph()
{
_D(("closeParagraph()\n"), LC_OPEN_PARAGRAPH);
}
void RawListenerImpl::openSpan(const WPXPropertyList &propList)
{
_U(("openSpan(%s)\n", getPropString(propList).cstr()), LC_OPEN_SPAN);
}
void RawListenerImpl::closeSpan()
{
_D(("closeSpan()\n"), LC_OPEN_SPAN);
}
void RawListenerImpl::openSection(const WPXPropertyList &propList, const WPXPropertyListVector &columns)
{
_U(("openSection(%s, columns: %s)\n", getPropString(propList).cstr(), getPropString(columns).cstr()), LC_OPEN_SECTION);
}
void RawListenerImpl::closeSection()
{
_D(("closeSection()\n"), LC_OPEN_SECTION);
}
void RawListenerImpl::insertTab()
{
__iprintf("insertTab()\n");
}
void RawListenerImpl::insertText(const WPXString &text)
{
WPXString textUTF8(text);
__iprintf("insertText(text: %s)\n", textUTF8.cstr());
}
void RawListenerImpl::insertLineBreak()
{
__iprintf("insertLineBreak()\n");
}
void RawListenerImpl::defineOrderedListLevel(const WPXPropertyList &propList)
{
__iprintf("defineOrderedListLevel(%s)\n", getPropString(propList).cstr());
}
void RawListenerImpl::defineUnorderedListLevel(const WPXPropertyList &propList)
{
__iprintf("defineUnorderedListLevel(%s)\n", getPropString(propList).cstr());
}
void RawListenerImpl::openOrderedListLevel(const WPXPropertyList &propList)
{
_U(("openOrderedListLevel(%s)\n", getPropString(propList).cstr()),
LC_OPEN_ORDERED_LIST_LEVEL);
}
void RawListenerImpl::openUnorderedListLevel(const WPXPropertyList &propList)
{
_U(("openUnorderedListLevel(%s)\n", getPropString(propList).cstr()),
LC_OPEN_UNORDERED_LIST_LEVEL);
}
void RawListenerImpl::closeOrderedListLevel()
{
_D(("closeOrderedListLevel()\n"),
LC_OPEN_ORDERED_LIST_LEVEL);
}
void RawListenerImpl::closeUnorderedListLevel()
{
_D(("closeUnorderedListLevel()\n"), LC_OPEN_UNORDERED_LIST_LEVEL);
}
void RawListenerImpl::openListElement(const WPXPropertyList &propList, const WPXPropertyListVector &tabStops)
{
_U(("openListElement(%s, tab-stops: %s)\n", getPropString(propList).cstr(), getPropString(tabStops).cstr()),
LC_OPEN_LIST_ELEMENT);
}
void RawListenerImpl::closeListElement()
{
_D(("closeListElement()\n"), LC_OPEN_LIST_ELEMENT);
}
void RawListenerImpl::openFootnote(const WPXPropertyList &propList)
{
_U(("openFootnote(%s)\n", getPropString(propList).cstr()),
LC_OPEN_FOOTNOTE);
}
void RawListenerImpl::closeFootnote()
{
_D(("closeFootnote()\n"), LC_OPEN_FOOTNOTE);
}
void RawListenerImpl::openEndnote(const WPXPropertyList &propList)
{
_U(("openEndnote(number: %s)\n", getPropString(propList).cstr()),
LC_OPEN_ENDNOTE);
}
void RawListenerImpl::closeEndnote()
{
_D(("closeEndnote()\n"), LC_OPEN_ENDNOTE);
}
void RawListenerImpl::openTable(const WPXPropertyList &propList, const WPXPropertyListVector &columns)
{
_U(("openTable(%s, columns: %s)\n", getPropString(propList).cstr(), getPropString(columns).cstr()), LC_OPEN_TABLE);
}
void RawListenerImpl::openTableRow(const WPXPropertyList &propList)
{
_U(("openTableRow(%s)\n", getPropString(propList).cstr()),
LC_OPEN_TABLE_ROW);
}
void RawListenerImpl::closeTableRow()
{
_D(("closeTableRow()\n"), LC_OPEN_TABLE_ROW);
}
void RawListenerImpl::openTableCell(const WPXPropertyList &propList)
{
_U(("openTableCell(%s)\n", getPropString(propList).cstr()),
LC_OPEN_TABLE_CELL);
}
void RawListenerImpl::closeTableCell()
{
_D(("closeTableCell()\n"), LC_OPEN_TABLE_CELL);
}
void RawListenerImpl::insertCoveredTableCell(const WPXPropertyList &propList)
{
__iprintf("insertCoveredTableCell(%s)\n", getPropString(propList).cstr());
}
void RawListenerImpl::closeTable()
{
_D(("closeTable()\n"), LC_OPEN_TABLE);
}
<commit_msg>one more warning, this time on x86_64<commit_after>/* libwpd
* Copyright (C) 2002 William Lachance (wrlach@gmail.com)
* Copyright (C) 2002-2004 Marc Maurer (uwog@uwog.net)
*
* 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library 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
*
* For further information visit http://libwpd.sourceforge.net
*/
/* "This product is not manufactured, approved, or supported by
* Corel Corporation or Corel Corporation Limited."
*/
#include <stdio.h>
#include <stdarg.h>
#include "RawListener.h"
#define _U(M, L) \
if (!m_printCallgraphScore) \
__iuprintf M; \
else \
m_callStack.push(L);
#define _D(M, L) \
if (!m_printCallgraphScore) \
__idprintf M; \
else \
{ \
ListenerCallback lc = m_callStack.top(); \
if (lc != L) \
m_callbackMisses++; \
m_callStack.pop(); \
}
RawListenerImpl::RawListenerImpl(bool printCallgraphScore) :
m_indent(0),
m_callbackMisses(0),
m_printCallgraphScore(printCallgraphScore)
{
}
RawListenerImpl::~RawListenerImpl()
{
if (m_printCallgraphScore)
printf("%d\n", (int)(m_callStack.size() + m_callbackMisses));
}
void RawListenerImpl::__iprintf(const char *format, ...)
{
if (m_printCallgraphScore) return;
va_list args;
va_start(args, format);
for (int i=0; i<m_indent; i++)
printf(" ");
vprintf(format, args);
va_end(args);
}
void RawListenerImpl::__iuprintf(const char *format, ...)
{
va_list args;
va_start(args, format);
for (int i=0; i<m_indent; i++)
printf(" ");
vprintf(format, args);
__indentUp();
va_end(args);
}
void RawListenerImpl::__idprintf(const char *format, ...)
{
va_list args;
va_start(args, format);
__indentDown();
for (int i=0; i<m_indent; i++)
printf(" ");
vprintf(format, args);
va_end(args);
}
WPXString getPropString(const WPXPropertyList &propList)
{
WPXString propString;
WPXPropertyList::Iter i(propList);
if (!i.last())
{
WPXString prop;
prop.sprintf("%s: %s", i.key(), i()->getStr().cstr());
propString.append(prop);
for (; i.next(); )
{
prop.sprintf(", %s: %s", i.key(), i()->getStr().cstr());
propString.append(prop);
}
}
return propString;
}
WPXString getPropString(const WPXPropertyListVector &itemList)
{
WPXString propString;
propString.append("(");
WPXPropertyListVector::Iter i(itemList);
if (!i.last())
{
propString.append("(");
propString.append(getPropString(i()));
propString.append(")");
for (; i.next();)
{
propString.append(", (");
propString.append(getPropString(i()));
propString.append(")");
}
}
propString.append(")");
return propString;
}
void RawListenerImpl::setDocumentMetaData(const WPXPropertyList &propList)
{
if (m_printCallgraphScore)
return;
__iprintf("setDocumentMetaData(%s)\n", getPropString(propList).cstr());
}
void RawListenerImpl::startDocument()
{
_U(("startDocument()\n"), LC_START_DOCUMENT);
}
void RawListenerImpl::endDocument()
{
_D(("endDocument()\n"), LC_START_DOCUMENT);
}
void RawListenerImpl::openPageSpan(const WPXPropertyList &propList)
{
_U(("openPageSpan(%s)\n", getPropString(propList).cstr()),
LC_OPEN_PAGE_SPAN);
}
void RawListenerImpl::closePageSpan()
{
_D(("closePageSpan()\n"),
LC_OPEN_PAGE_SPAN);
}
void RawListenerImpl::openHeader(const WPXPropertyList &propList)
{
_U(("openHeader(%s)\n",
getPropString(propList).cstr()),
LC_OPEN_HEADER_FOOTER);
}
void RawListenerImpl::closeHeader()
{
_D(("closeHeader()\n"),
LC_OPEN_HEADER_FOOTER);
}
void RawListenerImpl::openFooter(const WPXPropertyList &propList)
{
_U(("openFooter(%s)\n",
getPropString(propList).cstr()),
LC_OPEN_HEADER_FOOTER);
}
void RawListenerImpl::closeFooter()
{
_D(("closeFooter()\n"),
LC_OPEN_HEADER_FOOTER);
}
void RawListenerImpl::openParagraph(const WPXPropertyList &propList, const WPXPropertyListVector &tabStops)
{
_U(("openParagraph(%s, tab-stops: %s)\n", getPropString(propList).cstr(), getPropString(tabStops).cstr()),
LC_OPEN_PARAGRAPH);
}
void RawListenerImpl::closeParagraph()
{
_D(("closeParagraph()\n"), LC_OPEN_PARAGRAPH);
}
void RawListenerImpl::openSpan(const WPXPropertyList &propList)
{
_U(("openSpan(%s)\n", getPropString(propList).cstr()), LC_OPEN_SPAN);
}
void RawListenerImpl::closeSpan()
{
_D(("closeSpan()\n"), LC_OPEN_SPAN);
}
void RawListenerImpl::openSection(const WPXPropertyList &propList, const WPXPropertyListVector &columns)
{
_U(("openSection(%s, columns: %s)\n", getPropString(propList).cstr(), getPropString(columns).cstr()), LC_OPEN_SECTION);
}
void RawListenerImpl::closeSection()
{
_D(("closeSection()\n"), LC_OPEN_SECTION);
}
void RawListenerImpl::insertTab()
{
__iprintf("insertTab()\n");
}
void RawListenerImpl::insertText(const WPXString &text)
{
WPXString textUTF8(text);
__iprintf("insertText(text: %s)\n", textUTF8.cstr());
}
void RawListenerImpl::insertLineBreak()
{
__iprintf("insertLineBreak()\n");
}
void RawListenerImpl::defineOrderedListLevel(const WPXPropertyList &propList)
{
__iprintf("defineOrderedListLevel(%s)\n", getPropString(propList).cstr());
}
void RawListenerImpl::defineUnorderedListLevel(const WPXPropertyList &propList)
{
__iprintf("defineUnorderedListLevel(%s)\n", getPropString(propList).cstr());
}
void RawListenerImpl::openOrderedListLevel(const WPXPropertyList &propList)
{
_U(("openOrderedListLevel(%s)\n", getPropString(propList).cstr()),
LC_OPEN_ORDERED_LIST_LEVEL);
}
void RawListenerImpl::openUnorderedListLevel(const WPXPropertyList &propList)
{
_U(("openUnorderedListLevel(%s)\n", getPropString(propList).cstr()),
LC_OPEN_UNORDERED_LIST_LEVEL);
}
void RawListenerImpl::closeOrderedListLevel()
{
_D(("closeOrderedListLevel()\n"),
LC_OPEN_ORDERED_LIST_LEVEL);
}
void RawListenerImpl::closeUnorderedListLevel()
{
_D(("closeUnorderedListLevel()\n"), LC_OPEN_UNORDERED_LIST_LEVEL);
}
void RawListenerImpl::openListElement(const WPXPropertyList &propList, const WPXPropertyListVector &tabStops)
{
_U(("openListElement(%s, tab-stops: %s)\n", getPropString(propList).cstr(), getPropString(tabStops).cstr()),
LC_OPEN_LIST_ELEMENT);
}
void RawListenerImpl::closeListElement()
{
_D(("closeListElement()\n"), LC_OPEN_LIST_ELEMENT);
}
void RawListenerImpl::openFootnote(const WPXPropertyList &propList)
{
_U(("openFootnote(%s)\n", getPropString(propList).cstr()),
LC_OPEN_FOOTNOTE);
}
void RawListenerImpl::closeFootnote()
{
_D(("closeFootnote()\n"), LC_OPEN_FOOTNOTE);
}
void RawListenerImpl::openEndnote(const WPXPropertyList &propList)
{
_U(("openEndnote(number: %s)\n", getPropString(propList).cstr()),
LC_OPEN_ENDNOTE);
}
void RawListenerImpl::closeEndnote()
{
_D(("closeEndnote()\n"), LC_OPEN_ENDNOTE);
}
void RawListenerImpl::openTable(const WPXPropertyList &propList, const WPXPropertyListVector &columns)
{
_U(("openTable(%s, columns: %s)\n", getPropString(propList).cstr(), getPropString(columns).cstr()), LC_OPEN_TABLE);
}
void RawListenerImpl::openTableRow(const WPXPropertyList &propList)
{
_U(("openTableRow(%s)\n", getPropString(propList).cstr()),
LC_OPEN_TABLE_ROW);
}
void RawListenerImpl::closeTableRow()
{
_D(("closeTableRow()\n"), LC_OPEN_TABLE_ROW);
}
void RawListenerImpl::openTableCell(const WPXPropertyList &propList)
{
_U(("openTableCell(%s)\n", getPropString(propList).cstr()),
LC_OPEN_TABLE_CELL);
}
void RawListenerImpl::closeTableCell()
{
_D(("closeTableCell()\n"), LC_OPEN_TABLE_CELL);
}
void RawListenerImpl::insertCoveredTableCell(const WPXPropertyList &propList)
{
__iprintf("insertCoveredTableCell(%s)\n", getPropString(propList).cstr());
}
void RawListenerImpl::closeTable()
{
_D(("closeTable()\n"), LC_OPEN_TABLE);
}
<|endoftext|> |
<commit_before>/*
* Copyright 2017 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkArenaAlloc.h"
#include "SkAutoBlitterChoose.h"
#include "SkComposeShader.h"
#include "SkDraw.h"
#include "SkNx.h"
#include "SkPM4fPriv.h"
#include "SkRasterClip.h"
#include "SkScan.h"
#include "SkShaderBase.h"
#include "SkString.h"
#include "SkVertState.h"
#include "SkArenaAlloc.h"
#include "SkCoreBlitters.h"
#include "SkColorSpaceXform.h"
#include "SkColorSpace_Base.h"
struct Matrix43 {
float fMat[12]; // column major
Sk4f map(float x, float y) const {
return Sk4f::Load(&fMat[0]) * x + Sk4f::Load(&fMat[4]) * y + Sk4f::Load(&fMat[8]);
}
void setConcat(const Matrix43& a, const SkMatrix& b) {
fMat[ 0] = a.dot(0, b.getScaleX(), b.getSkewY());
fMat[ 1] = a.dot(1, b.getScaleX(), b.getSkewY());
fMat[ 2] = a.dot(2, b.getScaleX(), b.getSkewY());
fMat[ 3] = a.dot(3, b.getScaleX(), b.getSkewY());
fMat[ 4] = a.dot(0, b.getSkewX(), b.getScaleY());
fMat[ 5] = a.dot(1, b.getSkewX(), b.getScaleY());
fMat[ 6] = a.dot(2, b.getSkewX(), b.getScaleY());
fMat[ 7] = a.dot(3, b.getSkewX(), b.getScaleY());
fMat[ 8] = a.dot(0, b.getTranslateX(), b.getTranslateY()) + a.fMat[ 8];
fMat[ 9] = a.dot(1, b.getTranslateX(), b.getTranslateY()) + a.fMat[ 9];
fMat[10] = a.dot(2, b.getTranslateX(), b.getTranslateY()) + a.fMat[10];
fMat[11] = a.dot(3, b.getTranslateX(), b.getTranslateY()) + a.fMat[11];
}
private:
float dot(int index, float x, float y) const {
return fMat[index + 0] * x + fMat[index + 4] * y;
}
};
static SkScan::HairRCProc ChooseHairProc(bool doAntiAlias) {
return doAntiAlias ? SkScan::AntiHairLine : SkScan::HairLine;
}
static bool texture_to_matrix(const VertState& state, const SkPoint verts[],
const SkPoint texs[], SkMatrix* matrix) {
SkPoint src[3], dst[3];
src[0] = texs[state.f0];
src[1] = texs[state.f1];
src[2] = texs[state.f2];
dst[0] = verts[state.f0];
dst[1] = verts[state.f1];
dst[2] = verts[state.f2];
return matrix->setPolyToPoly(src, dst, 3);
}
class SkTriColorShader : public SkShaderBase {
public:
SkTriColorShader(bool isOpaque) : fIsOpaque(isOpaque) {}
Matrix43* getMatrix43() { return &fM43; }
bool isOpaque() const override { return fIsOpaque; }
SK_TO_STRING_OVERRIDE()
// For serialization. This will never be called.
Factory getFactory() const override { SK_ABORT("not reached"); return nullptr; }
protected:
Context* onMakeContext(const ContextRec& rec, SkArenaAlloc* alloc) const override {
return nullptr;
}
bool onAppendStages(const StageRec& rec) const override {
rec.fPipeline->append_seed_shader();
rec.fPipeline->append(SkRasterPipeline::matrix_4x3, &fM43);
// In theory we should never need to clamp. However, either due to imprecision in our
// matrix43, or the scan converter passing us pixel centers that in fact are not within
// the triangle, we do see occasional (slightly) out-of-range values, so we add these
// clamp stages. It would be nice to find a way to detect when these are not needed.
rec.fPipeline->append(SkRasterPipeline::clamp_0);
rec.fPipeline->append(SkRasterPipeline::clamp_a);
return true;
}
private:
Matrix43 fM43;
const bool fIsOpaque;
typedef SkShaderBase INHERITED;
};
#ifndef SK_IGNORE_TO_STRING
void SkTriColorShader::toString(SkString* str) const {
str->append("SkTriColorShader: (");
this->INHERITED::toString(str);
str->append(")");
}
#endif
static bool update_tricolor_matrix(const SkMatrix& ctmInv,
const SkPoint pts[], const SkPM4f colors[],
int index0, int index1, int index2, Matrix43* result) {
SkMatrix m, im;
m.reset();
m.set(0, pts[index1].fX - pts[index0].fX);
m.set(1, pts[index2].fX - pts[index0].fX);
m.set(2, pts[index0].fX);
m.set(3, pts[index1].fY - pts[index0].fY);
m.set(4, pts[index2].fY - pts[index0].fY);
m.set(5, pts[index0].fY);
if (!m.invert(&im)) {
return false;
}
SkMatrix dstToUnit;
dstToUnit.setConcat(im, ctmInv);
Sk4f c0 = colors[index0].to4f(),
c1 = colors[index1].to4f(),
c2 = colors[index2].to4f();
Matrix43 colorm;
(c1 - c0).store(&colorm.fMat[0]);
(c2 - c0).store(&colorm.fMat[4]);
c0.store(&colorm.fMat[8]);
result->setConcat(colorm, dstToUnit);
return true;
}
// Convert the SkColors into float colors. The conversion depends on some conditions:
// - If the pixmap has a dst colorspace, we have to be "color-correct".
// Do we map into dst-colorspace before or after we interpolate?
// - We have to decide when to apply per-color alpha (before or after we interpolate)
//
// For now, we will take a simple approach, but recognize this is just a start:
// - convert colors into dst colorspace before interpolation (matches gradients)
// - apply per-color alpha before interpolation (matches old version of vertices)
//
static SkPM4f* convert_colors(const SkColor src[], int count, SkColorSpace* deviceCS,
SkArenaAlloc* alloc) {
SkPM4f* dst = alloc->makeArray<SkPM4f>(count);
if (!deviceCS) {
for (int i = 0; i < count; ++i) {
dst[i] = SkPM4f_from_SkColor(src[i], nullptr);
}
} else {
auto srcCS = SkColorSpace::MakeSRGB();
auto dstCS = deviceCS->makeLinearGamma();
SkColorSpaceXform::Apply(dstCS.get(), SkColorSpaceXform::kRGBA_F32_ColorFormat, dst,
srcCS.get(), SkColorSpaceXform::kBGRA_8888_ColorFormat, src,
count, SkColorSpaceXform::kPremul_AlphaOp);
}
return dst;
}
static bool compute_is_opaque(const SkColor colors[], int count) {
uint32_t c = ~0;
for (int i = 0; i < count; ++i) {
c &= colors[i];
}
return SkColorGetA(c) == 0xFF;
}
void SkDraw::drawVertices(SkVertices::VertexMode vmode, int count,
const SkPoint vertices[], const SkPoint textures[],
const SkColor colors[], SkBlendMode bmode,
const uint16_t indices[], int indexCount,
const SkPaint& paint) const {
SkASSERT(0 == count || vertices);
// abort early if there is nothing to draw
if (count < 3 || (indices && indexCount < 3) || fRC->isEmpty()) {
return;
}
SkMatrix ctmInv;
if (!fMatrix->invert(&ctmInv)) {
return;
}
// make textures and shader mutually consistent
SkShader* shader = paint.getShader();
if (!(shader && textures)) {
shader = nullptr;
textures = nullptr;
}
// We can simplify things for certain blendmodes. This is for speed, and SkComposeShader
// itself insists we don't pass kSrc or kDst to it.
//
if (colors && textures) {
switch (bmode) {
case SkBlendMode::kSrc:
colors = nullptr;
break;
case SkBlendMode::kDst:
textures = nullptr;
break;
default: break;
}
}
// we don't use the shader if there are no textures
if (!textures) {
shader = nullptr;
}
constexpr size_t defCount = 16;
constexpr size_t outerSize = sizeof(SkTriColorShader) +
sizeof(SkComposeShader) +
(sizeof(SkPoint) + sizeof(SkPM4f)) * defCount;
SkSTArenaAlloc<outerSize> outerAlloc;
SkPoint* devVerts = outerAlloc.makeArray<SkPoint>(count);
fMatrix->mapPoints(devVerts, vertices, count);
VertState state(count, indices, indexCount);
VertState::Proc vertProc = state.chooseProc(vmode);
if (colors || textures) {
SkPM4f* dstColors = nullptr;
Matrix43* matrix43 = nullptr;
if (colors) {
dstColors = convert_colors(colors, count, fDst.colorSpace(), &outerAlloc);
SkTriColorShader* triShader = outerAlloc.make<SkTriColorShader>(
compute_is_opaque(colors, count));
matrix43 = triShader->getMatrix43();
if (shader) {
shader = outerAlloc.make<SkComposeShader>(sk_ref_sp(triShader), sk_ref_sp(shader),
bmode, 1);
} else {
shader = triShader;
}
}
SkPaint p(paint);
p.setShader(sk_ref_sp(shader));
if (!textures) { // only tricolor shader
SkASSERT(matrix43);
auto blitter = SkCreateRasterPipelineBlitter(fDst, p, *fMatrix, &outerAlloc);
while (vertProc(&state)) {
if (!update_tricolor_matrix(ctmInv, vertices, dstColors,
state.f0, state.f1, state.f2,
matrix43)) {
continue;
}
SkPoint tmp[] = {
devVerts[state.f0], devVerts[state.f1], devVerts[state.f2]
};
SkScan::FillTriangle(tmp, *fRC, blitter);
}
} else {
while (vertProc(&state)) {
SkSTArenaAlloc<2048> innerAlloc;
const SkMatrix* ctm = fMatrix;
SkMatrix tmpCtm;
if (textures) {
SkMatrix localM;
texture_to_matrix(state, vertices, textures, &localM);
tmpCtm = SkMatrix::Concat(*fMatrix, localM);
ctm = &tmpCtm;
}
if (matrix43 && !update_tricolor_matrix(ctmInv, vertices, dstColors,
state.f0, state.f1, state.f2,
matrix43)) {
continue;
}
SkPoint tmp[] = {
devVerts[state.f0], devVerts[state.f1], devVerts[state.f2]
};
auto blitter = SkCreateRasterPipelineBlitter(fDst, p, *ctm, &innerAlloc);
SkScan::FillTriangle(tmp, *fRC, blitter);
}
}
} else {
// no colors[] and no texture, stroke hairlines with paint's color.
SkPaint p;
p.setStyle(SkPaint::kStroke_Style);
SkAutoBlitterChoose blitter(fDst, *fMatrix, p);
// Abort early if we failed to create a shader context.
if (blitter->isNullBlitter()) {
return;
}
SkScan::HairRCProc hairProc = ChooseHairProc(paint.isAntiAlias());
const SkRasterClip& clip = *fRC;
while (vertProc(&state)) {
SkPoint array[] = {
devVerts[state.f0], devVerts[state.f1], devVerts[state.f2], devVerts[state.f0]
};
hairProc(array, 4, clip, blitter.get());
}
}
}
<commit_msg>Remove another stray pair of clamps.<commit_after>/*
* Copyright 2017 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkArenaAlloc.h"
#include "SkAutoBlitterChoose.h"
#include "SkComposeShader.h"
#include "SkDraw.h"
#include "SkNx.h"
#include "SkPM4fPriv.h"
#include "SkRasterClip.h"
#include "SkScan.h"
#include "SkShaderBase.h"
#include "SkString.h"
#include "SkVertState.h"
#include "SkArenaAlloc.h"
#include "SkCoreBlitters.h"
#include "SkColorSpaceXform.h"
#include "SkColorSpace_Base.h"
struct Matrix43 {
float fMat[12]; // column major
Sk4f map(float x, float y) const {
return Sk4f::Load(&fMat[0]) * x + Sk4f::Load(&fMat[4]) * y + Sk4f::Load(&fMat[8]);
}
void setConcat(const Matrix43& a, const SkMatrix& b) {
fMat[ 0] = a.dot(0, b.getScaleX(), b.getSkewY());
fMat[ 1] = a.dot(1, b.getScaleX(), b.getSkewY());
fMat[ 2] = a.dot(2, b.getScaleX(), b.getSkewY());
fMat[ 3] = a.dot(3, b.getScaleX(), b.getSkewY());
fMat[ 4] = a.dot(0, b.getSkewX(), b.getScaleY());
fMat[ 5] = a.dot(1, b.getSkewX(), b.getScaleY());
fMat[ 6] = a.dot(2, b.getSkewX(), b.getScaleY());
fMat[ 7] = a.dot(3, b.getSkewX(), b.getScaleY());
fMat[ 8] = a.dot(0, b.getTranslateX(), b.getTranslateY()) + a.fMat[ 8];
fMat[ 9] = a.dot(1, b.getTranslateX(), b.getTranslateY()) + a.fMat[ 9];
fMat[10] = a.dot(2, b.getTranslateX(), b.getTranslateY()) + a.fMat[10];
fMat[11] = a.dot(3, b.getTranslateX(), b.getTranslateY()) + a.fMat[11];
}
private:
float dot(int index, float x, float y) const {
return fMat[index + 0] * x + fMat[index + 4] * y;
}
};
static SkScan::HairRCProc ChooseHairProc(bool doAntiAlias) {
return doAntiAlias ? SkScan::AntiHairLine : SkScan::HairLine;
}
static bool texture_to_matrix(const VertState& state, const SkPoint verts[],
const SkPoint texs[], SkMatrix* matrix) {
SkPoint src[3], dst[3];
src[0] = texs[state.f0];
src[1] = texs[state.f1];
src[2] = texs[state.f2];
dst[0] = verts[state.f0];
dst[1] = verts[state.f1];
dst[2] = verts[state.f2];
return matrix->setPolyToPoly(src, dst, 3);
}
class SkTriColorShader : public SkShaderBase {
public:
SkTriColorShader(bool isOpaque) : fIsOpaque(isOpaque) {}
Matrix43* getMatrix43() { return &fM43; }
bool isOpaque() const override { return fIsOpaque; }
SK_TO_STRING_OVERRIDE()
// For serialization. This will never be called.
Factory getFactory() const override { SK_ABORT("not reached"); return nullptr; }
protected:
Context* onMakeContext(const ContextRec& rec, SkArenaAlloc* alloc) const override {
return nullptr;
}
bool onAppendStages(const StageRec& rec) const override {
rec.fPipeline->append_seed_shader();
rec.fPipeline->append(SkRasterPipeline::matrix_4x3, &fM43);
return true;
}
private:
Matrix43 fM43;
const bool fIsOpaque;
typedef SkShaderBase INHERITED;
};
#ifndef SK_IGNORE_TO_STRING
void SkTriColorShader::toString(SkString* str) const {
str->append("SkTriColorShader: (");
this->INHERITED::toString(str);
str->append(")");
}
#endif
static bool update_tricolor_matrix(const SkMatrix& ctmInv,
const SkPoint pts[], const SkPM4f colors[],
int index0, int index1, int index2, Matrix43* result) {
SkMatrix m, im;
m.reset();
m.set(0, pts[index1].fX - pts[index0].fX);
m.set(1, pts[index2].fX - pts[index0].fX);
m.set(2, pts[index0].fX);
m.set(3, pts[index1].fY - pts[index0].fY);
m.set(4, pts[index2].fY - pts[index0].fY);
m.set(5, pts[index0].fY);
if (!m.invert(&im)) {
return false;
}
SkMatrix dstToUnit;
dstToUnit.setConcat(im, ctmInv);
Sk4f c0 = colors[index0].to4f(),
c1 = colors[index1].to4f(),
c2 = colors[index2].to4f();
Matrix43 colorm;
(c1 - c0).store(&colorm.fMat[0]);
(c2 - c0).store(&colorm.fMat[4]);
c0.store(&colorm.fMat[8]);
result->setConcat(colorm, dstToUnit);
return true;
}
// Convert the SkColors into float colors. The conversion depends on some conditions:
// - If the pixmap has a dst colorspace, we have to be "color-correct".
// Do we map into dst-colorspace before or after we interpolate?
// - We have to decide when to apply per-color alpha (before or after we interpolate)
//
// For now, we will take a simple approach, but recognize this is just a start:
// - convert colors into dst colorspace before interpolation (matches gradients)
// - apply per-color alpha before interpolation (matches old version of vertices)
//
static SkPM4f* convert_colors(const SkColor src[], int count, SkColorSpace* deviceCS,
SkArenaAlloc* alloc) {
SkPM4f* dst = alloc->makeArray<SkPM4f>(count);
if (!deviceCS) {
for (int i = 0; i < count; ++i) {
dst[i] = SkPM4f_from_SkColor(src[i], nullptr);
}
} else {
auto srcCS = SkColorSpace::MakeSRGB();
auto dstCS = deviceCS->makeLinearGamma();
SkColorSpaceXform::Apply(dstCS.get(), SkColorSpaceXform::kRGBA_F32_ColorFormat, dst,
srcCS.get(), SkColorSpaceXform::kBGRA_8888_ColorFormat, src,
count, SkColorSpaceXform::kPremul_AlphaOp);
}
return dst;
}
static bool compute_is_opaque(const SkColor colors[], int count) {
uint32_t c = ~0;
for (int i = 0; i < count; ++i) {
c &= colors[i];
}
return SkColorGetA(c) == 0xFF;
}
void SkDraw::drawVertices(SkVertices::VertexMode vmode, int count,
const SkPoint vertices[], const SkPoint textures[],
const SkColor colors[], SkBlendMode bmode,
const uint16_t indices[], int indexCount,
const SkPaint& paint) const {
SkASSERT(0 == count || vertices);
// abort early if there is nothing to draw
if (count < 3 || (indices && indexCount < 3) || fRC->isEmpty()) {
return;
}
SkMatrix ctmInv;
if (!fMatrix->invert(&ctmInv)) {
return;
}
// make textures and shader mutually consistent
SkShader* shader = paint.getShader();
if (!(shader && textures)) {
shader = nullptr;
textures = nullptr;
}
// We can simplify things for certain blendmodes. This is for speed, and SkComposeShader
// itself insists we don't pass kSrc or kDst to it.
//
if (colors && textures) {
switch (bmode) {
case SkBlendMode::kSrc:
colors = nullptr;
break;
case SkBlendMode::kDst:
textures = nullptr;
break;
default: break;
}
}
// we don't use the shader if there are no textures
if (!textures) {
shader = nullptr;
}
constexpr size_t defCount = 16;
constexpr size_t outerSize = sizeof(SkTriColorShader) +
sizeof(SkComposeShader) +
(sizeof(SkPoint) + sizeof(SkPM4f)) * defCount;
SkSTArenaAlloc<outerSize> outerAlloc;
SkPoint* devVerts = outerAlloc.makeArray<SkPoint>(count);
fMatrix->mapPoints(devVerts, vertices, count);
VertState state(count, indices, indexCount);
VertState::Proc vertProc = state.chooseProc(vmode);
if (colors || textures) {
SkPM4f* dstColors = nullptr;
Matrix43* matrix43 = nullptr;
if (colors) {
dstColors = convert_colors(colors, count, fDst.colorSpace(), &outerAlloc);
SkTriColorShader* triShader = outerAlloc.make<SkTriColorShader>(
compute_is_opaque(colors, count));
matrix43 = triShader->getMatrix43();
if (shader) {
shader = outerAlloc.make<SkComposeShader>(sk_ref_sp(triShader), sk_ref_sp(shader),
bmode, 1);
} else {
shader = triShader;
}
}
SkPaint p(paint);
p.setShader(sk_ref_sp(shader));
if (!textures) { // only tricolor shader
SkASSERT(matrix43);
auto blitter = SkCreateRasterPipelineBlitter(fDst, p, *fMatrix, &outerAlloc);
while (vertProc(&state)) {
if (!update_tricolor_matrix(ctmInv, vertices, dstColors,
state.f0, state.f1, state.f2,
matrix43)) {
continue;
}
SkPoint tmp[] = {
devVerts[state.f0], devVerts[state.f1], devVerts[state.f2]
};
SkScan::FillTriangle(tmp, *fRC, blitter);
}
} else {
while (vertProc(&state)) {
SkSTArenaAlloc<2048> innerAlloc;
const SkMatrix* ctm = fMatrix;
SkMatrix tmpCtm;
if (textures) {
SkMatrix localM;
texture_to_matrix(state, vertices, textures, &localM);
tmpCtm = SkMatrix::Concat(*fMatrix, localM);
ctm = &tmpCtm;
}
if (matrix43 && !update_tricolor_matrix(ctmInv, vertices, dstColors,
state.f0, state.f1, state.f2,
matrix43)) {
continue;
}
SkPoint tmp[] = {
devVerts[state.f0], devVerts[state.f1], devVerts[state.f2]
};
auto blitter = SkCreateRasterPipelineBlitter(fDst, p, *ctm, &innerAlloc);
SkScan::FillTriangle(tmp, *fRC, blitter);
}
}
} else {
// no colors[] and no texture, stroke hairlines with paint's color.
SkPaint p;
p.setStyle(SkPaint::kStroke_Style);
SkAutoBlitterChoose blitter(fDst, *fMatrix, p);
// Abort early if we failed to create a shader context.
if (blitter->isNullBlitter()) {
return;
}
SkScan::HairRCProc hairProc = ChooseHairProc(paint.isAntiAlias());
const SkRasterClip& clip = *fRC;
while (vertProc(&state)) {
SkPoint array[] = {
devVerts[state.f0], devVerts[state.f1], devVerts[state.f2], devVerts[state.f0]
};
hairProc(array, 4, clip, blitter.get());
}
}
}
<|endoftext|> |
<commit_before>/*
*
* Copyright 2017 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "src/core/lib/support/fork.h"
#include <string.h>
#include <grpc/support/alloc.h>
#include <grpc/support/useful.h>
#include "src/core/lib/support/env.h"
/*
* NOTE: FORKING IS NOT GENERALLY SUPPORTED, THIS IS ONLY INTENDED TO WORK
* AROUND VERY SPECIFIC USE CASES.
*/
static int override_fork_support_enabled = -1;
static int fork_support_enabled;
void grpc_fork_support_init() {
#ifdef GRPC_ENABLE_FORK_SUPPORT
fork_support_enabled = 1;
#else
fork_support_enabled = 0;
char* env = gpr_getenv("GRPC_ENABLE_FORK_SUPPORT");
if (env != nullptr) {
static const char* truthy[] = {"yes", "Yes", "YES", "true",
"True", "TRUE", "1"};
for (size_t i = 0; i < GPR_ARRAY_SIZE(truthy); i++) {
if (0 == strcmp(env, truthy[i])) {
fork_support_enabled = 1;
}
}
gpr_free(env);
}
#endif
if (override_fork_support_enabled != -1) {
fork_support_enabled = override_fork_support_enabled;
}
}
int grpc_fork_support_enabled() { return fork_support_enabled; }
void grpc_enable_fork_support(int enable) {
override_fork_support_enabled = enable;
}
<commit_msg>Allow turning off fork support with env variable<commit_after>/*
*
* Copyright 2017 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "src/core/lib/support/fork.h"
#include <string.h>
#include <grpc/support/alloc.h>
#include <grpc/support/useful.h>
#include "src/core/lib/support/env.h"
/*
* NOTE: FORKING IS NOT GENERALLY SUPPORTED, THIS IS ONLY INTENDED TO WORK
* AROUND VERY SPECIFIC USE CASES.
*/
static int override_fork_support_enabled = -1;
static int fork_support_enabled;
void grpc_fork_support_init() {
#ifdef GRPC_ENABLE_FORK_SUPPORT
fork_support_enabled = 1;
#else
fork_support_enabled = 0;
#endif
char* env = gpr_getenv("GRPC_ENABLE_FORK_SUPPORT");
if (env != nullptr) {
static const char* truthy[] = {"yes", "Yes", "YES", "true",
"True", "TRUE", "1"};
static const char* falsey[] = {"no", "No", "NO", "false",
"False", "FALSE", "0"};
for (size_t i = 0; i < GPR_ARRAY_SIZE(truthy); i++) {
if (0 == strcmp(env, truthy[i])) {
fork_support_enabled = 1;
}
}
for (size_t i = 0; i < GPR_ARRAY_SIZE(falsey); i++) {
if (0 == strcmp(env, falsey[i])) {
fork_support_enabled = 0;
}
}
gpr_free(env);
}
if (override_fork_support_enabled != -1) {
fork_support_enabled = override_fork_support_enabled;
}
}
int grpc_fork_support_enabled() { return fork_support_enabled; }
void grpc_enable_fork_support(int enable) {
override_fork_support_enabled = enable;
}
<|endoftext|> |
<commit_before>// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef __STOUT_WINDOWS_OS_HPP__
#define __STOUT_WINDOWS_OS_HPP__
#include <direct.h>
#include <io.h>
#include <sys/utime.h>
#include <list>
#include <map>
#include <set>
#include <string>
#include <stout/duration.hpp>
#include <stout/none.hpp>
#include <stout/nothing.hpp>
#include <stout/option.hpp>
#include <stout/path.hpp>
#include <stout/try.hpp>
#include <stout/windows.hpp>
#include <stout/os/os.hpp>
#include <stout/os/read.hpp>
#include <stout/os/raw/environment.hpp>
namespace os {
inline int pagesize()
{
SYSTEM_INFO si = {0};
GetSystemInfo(&si);
return si.dwPageSize;
}
// Sets the value associated with the specified key in the set of
// environment variables.
inline void setenv(
const std::string& key,
const std::string& value,
bool overwrite = true)
{
// Do not set the variable if already set and `overwrite` was not specified.
//
// Per MSDN[1], `GetEnvironmentVariable` returns 0 on error and sets the
// error code to `ERROR_ENVVAR_NOT_FOUND` if the variable was not found.
//
// [1] https://msdn.microsoft.com/en-us/library/windows/desktop/ms683188(v=vs.85).aspx
if (!overwrite &&
::GetEnvironmentVariable(key.c_str(), NULL, 0) != 0 &&
::GetLastError() == ERROR_ENVVAR_NOT_FOUND) {
return;
}
// `SetEnvironmentVariable` returns an error code, but we can't act on it.
::SetEnvironmentVariable(key.c_str(), value.c_str());
}
/*
// Unsets the value associated with the specified key in the set of
// environment variables.
inline void unsetenv(const std::string& key)
{
UNIMPLEMENTED;
}
// Executes a command by calling "/bin/sh -c <command>", and returns
// after the command has been completed. Returns 0 if succeeds, and
// return -1 on error (e.g., fork/exec/waitpid failed). This function
// is async signal safe. We return int instead of returning a Try
// because Try involves 'new', which is not async signal safe.
inline int system(const std::string& command)
{
UNIMPLEMENTED;
}
// This function is a portable version of execvpe ('p' means searching
// executable from PATH and 'e' means setting environments). We add
// this function because it is not available on all systems.
//
// NOTE: This function is not thread safe. It is supposed to be used
// only after fork (when there is only one thread). This function is
// async signal safe.
inline int execvpe(const char* file, char** argv, char** envp)
{
UNIMPLEMENTED;
}
inline Try<Nothing> chown(
uid_t uid,
gid_t gid,
const std::string& path,
bool recursive)
{
UNIMPLEMENTED;
}
inline Try<Nothing> chmod(const std::string& path, int mode)
{
UNIMPLEMENTED;
}
inline Try<Nothing> mknod(
const std::string& path,
mode_t mode,
dev_t dev)
{
UNIMPLEMENTED;
}
// Suspends execution for the given duration.
inline Try<Nothing> sleep(const Duration& duration)
{
UNIMPLEMENTED;
}
// Returns the list of files that match the given (shell) pattern.
inline Try<std::list<std::string>> glob(const std::string& pattern)
{
UNIMPLEMENTED;
}
// Returns the total number of cpus (cores).
inline Try<long> cpus()
{
UNIMPLEMENTED;
}
// Returns load struct with average system loads for the last
// 1, 5 and 15 minutes respectively.
// Load values should be interpreted as usual average loads from
// uptime(1).
inline Try<Load> loadavg()
{
UNIMPLEMENTED;
}
// Returns the total size of main and free memory.
inline Try<Memory> memory()
{
UNIMPLEMENTED;
}
// Return the system information.
inline Try<UTSInfo> uname()
{
UNIMPLEMENTED;
}
inline Try<std::list<Process>> processes()
{
UNIMPLEMENTED;
}
// Overload of os::pids for filtering by groups and sessions.
// A group / session id of 0 will fitler on the group / session ID
// of the calling process.
inline Try<std::set<pid_t>> pids(Option<pid_t> group, Option<pid_t> session)
{
UNIMPLEMENTED;
}
*/
inline tm* gmtime_r(const time_t* timep, tm* result)
{
return ::gmtime_s(result, timep) == ERROR_SUCCESS ? result : NULL;
}
} // namespace os {
#endif // __STOUT_WINDOWS_OS_HPP__
<commit_msg>Stout: Uncommented functions and marked them as `= delete` instead.<commit_after>// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef __STOUT_WINDOWS_OS_HPP__
#define __STOUT_WINDOWS_OS_HPP__
#include <direct.h>
#include <io.h>
#include <sys/utime.h>
#include <list>
#include <map>
#include <set>
#include <string>
#include <stout/duration.hpp>
#include <stout/none.hpp>
#include <stout/nothing.hpp>
#include <stout/option.hpp>
#include <stout/path.hpp>
#include <stout/try.hpp>
#include <stout/windows.hpp>
#include <stout/os/os.hpp>
#include <stout/os/read.hpp>
#include <stout/os/raw/environment.hpp>
namespace os {
inline int pagesize()
{
SYSTEM_INFO si = {0};
GetSystemInfo(&si);
return si.dwPageSize;
}
// Sets the value associated with the specified key in the set of
// environment variables.
inline void setenv(
const std::string& key,
const std::string& value,
bool overwrite = true)
{
// Do not set the variable if already set and `overwrite` was not specified.
//
// Per MSDN[1], `GetEnvironmentVariable` returns 0 on error and sets the
// error code to `ERROR_ENVVAR_NOT_FOUND` if the variable was not found.
//
// [1] https://msdn.microsoft.com/en-us/library/windows/desktop/ms683188(v=vs.85).aspx
if (!overwrite &&
::GetEnvironmentVariable(key.c_str(), NULL, 0) != 0 &&
::GetLastError() == ERROR_ENVVAR_NOT_FOUND) {
return;
}
// `SetEnvironmentVariable` returns an error code, but we can't act on it.
::SetEnvironmentVariable(key.c_str(), value.c_str());
}
// Unsets the value associated with the specified key in the set of
// environment variables.
inline void unsetenv(const std::string& key) = delete;
// Executes a command by calling "/bin/sh -c <command>", and returns
// after the command has been completed. Returns 0 if succeeds, and
// return -1 on error (e.g., fork/exec/waitpid failed). This function
// is async signal safe. We return int instead of returning a Try
// because Try involves 'new', which is not async signal safe.
inline int system(const std::string& command) = delete;
// This function is a portable version of execvpe ('p' means searching
// executable from PATH and 'e' means setting environments). We add
// this function because it is not available on all systems.
//
// NOTE: This function is not thread safe. It is supposed to be used
// only after fork (when there is only one thread). This function is
// async signal safe.
inline int execvpe(const char* file, char** argv, char** envp) = delete;
inline Try<Nothing> chown(
uid_t uid,
gid_t gid,
const std::string& path,
bool recursive) = delete;
inline Try<Nothing> chmod(const std::string& path, int mode) = delete;
inline Try<Nothing> mknod(
const std::string& path,
mode_t mode,
dev_t dev) = delete;
// Suspends execution for the given duration.
inline Try<Nothing> sleep(const Duration& duration) = delete;
// Returns the list of files that match the given (shell) pattern.
inline Try<std::list<std::string>> glob(const std::string& pattern) = delete;
// Returns the total number of cpus (cores).
inline Try<long> cpus() = delete;
// Returns load struct with average system loads for the last
// 1, 5 and 15 minutes respectively.
// Load values should be interpreted as usual average loads from
// uptime(1).
inline Try<Load> loadavg() = delete;
// Returns the total size of main and free memory.
inline Try<Memory> memory() = delete;
// Return the system information.
inline Try<UTSInfo> uname() = delete;
inline Try<std::list<Process>> processes() = delete;
// Overload of os::pids for filtering by groups and sessions.
// A group / session id of 0 will fitler on the group / session ID
// of the calling process.
inline Try<std::set<pid_t>> pids(
Option<pid_t> group,
Option<pid_t> session) = delete;
inline tm* gmtime_r(const time_t* timep, tm* result)
{
return ::gmtime_s(result, timep) == ERROR_SUCCESS ? result : NULL;
}
} // namespace os {
#endif // __STOUT_WINDOWS_OS_HPP__
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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
///
/// vpp://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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Christoph Uhde
////////////////////////////////////////////////////////////////////////////////
#include "VppCommTask.h"
#include "Basics/StringBuffer.h"
#include "Basics/HybridLogicalClock.h"
#include "Basics/VelocyPackHelper.h"
#include "GeneralServer/GeneralServer.h"
#include "GeneralServer/GeneralServerFeature.h"
#include "GeneralServer/RestHandler.h"
#include "GeneralServer/RestHandlerFactory.h"
#include "Scheduler/Scheduler.h"
#include "Scheduler/SchedulerFeature.h"
#include "Logger/LoggerFeature.h"
#include "VocBase/ticks.h"
#include <velocypack/Validator.h>
#include <velocypack/velocypack-aliases.h>
#include <iostream>
#include <stdexcept>
using namespace arangodb;
using namespace arangodb::basics;
using namespace arangodb::rest;
namespace {
std::size_t findAndValidateVPacks(char const* vpHeaderStart,
char const* chunkEnd) {
VPackValidator validator;
// check for slice start to the end of Chunk
// isSubPart allows the slice to be shorter than the checked buffer.
validator.validate(vpHeaderStart, std::distance(vpHeaderStart, chunkEnd),
/*isSubPart =*/true);
// check if there is payload and locate the start
VPackSlice vpHeader(vpHeaderStart);
auto vpHeaderLen = vpHeader.byteSize();
auto vpPayloadStart = vpHeaderStart + vpHeaderLen;
if (vpPayloadStart == chunkEnd) {
return 0; // no payload available
}
// validate Payload VelocyPack
validator.validate(vpPayloadStart, std::distance(vpPayloadStart, chunkEnd),
/*isSubPart =*/false);
return std::distance(vpHeaderStart, vpPayloadStart);
}
std::unique_ptr<basics::StringBuffer> createChunkForNetworkDetail(
std::vector<VPackSlice> const& slices, bool isFirstChunk, uint32_t chunk,
uint64_t id, uint32_t totalMessageLength = 0) {
using basics::StringBuffer;
bool firstOfMany = false;
// if we have more than one chunk and the chunk is the first
// then we are sending the first in a series. if this condition
// is true we also send extra 8 bytes for the messageLength
// (length of all VPackData)
if (isFirstChunk && chunk > 1) {
firstOfMany = true;
}
// build chunkX -- see VelocyStream Documentaion
chunk <<= 1;
chunk |= isFirstChunk ? 0x1 : 0x0;
// get the lenght of VPack data
uint32_t dataLength = 0;
for (auto& slice : slices) {
dataLength += slice.byteSize();
}
// calculate length of current chunk
uint32_t chunkLength = dataLength;
chunkLength += (sizeof(chunkLength) + sizeof(chunk) + sizeof(id));
if (firstOfMany) {
chunkLength += sizeof(totalMessageLength);
}
auto buffer =
std::make_unique<StringBuffer>(TRI_UNKNOWN_MEM_ZONE, chunkLength, false);
char cChunkLength[sizeof(chunkLength)];
char const* cChunkLengthPtr = cChunkLength;
std::memcpy(&cChunkLength, &chunkLength, sizeof(chunkLength));
buffer->appendText(cChunkLengthPtr, sizeof(chunkLength));
char cChunk[sizeof(chunk)];
char const* cChunkPtr = cChunk;
std::memcpy(&cChunk, &chunk, sizeof(chunk));
buffer->appendText(cChunkPtr, sizeof(chunk));
char cId[sizeof(id)];
char const* cIdPtr = cId;
std::memcpy(&cId, &id, sizeof(id));
buffer->appendText(cIdPtr, sizeof(id));
if (firstOfMany) {
char cTotalMessageLength[sizeof(totalMessageLength)];
char const* cTotalMessageLengthPtr = cTotalMessageLength;
std::memcpy(&cTotalMessageLength, &totalMessageLength,
sizeof(totalMessageLength));
buffer->appendText(cTotalMessageLengthPtr, sizeof(totalMessageLength));
}
// append data in slices
for (auto const& slice : slices) {
buffer->appendText(std::string(slice.startAs<char>(), slice.byteSize()));
}
return buffer;
}
std::unique_ptr<basics::StringBuffer> createChunkForNetworkSingle(
std::vector<VPackSlice> const& slices, uint64_t id) {
return createChunkForNetworkDetail(slices, true, 1, id, 0 /*unused*/);
}
// TODO FIXME make use of these functions
// std::unique_ptr<basics::StringBuffer> createChunkForNetworkMultiFirst(
// std::vector<VPackSlice> const& slices, uint64_t id, uint32_t
// numberOfChunks,
// uint32_t totalMessageLength) {
// return createChunkForNetworkDetail(slices, true, numberOfChunks, id,
// totalMessageLength);
// }
//
// std::unique_ptr<basics::StringBuffer> createChunkForNetworkMultiFollow(
// std::vector<VPackSlice> const& slices, uint64_t id, uint32_t chunkNumber,
// uint32_t totalMessageLength) {
// return createChunkForNetworkDetail(slices, false, chunkNumber, id, 0);
// }
}
VppCommTask::VppCommTask(GeneralServer* server, TRI_socket_t sock,
ConnectionInfo&& info, double timeout)
: Task("VppCommTask"),
GeneralCommTask(server, sock, std::move(info), timeout) {
_protocol = "vpp";
_readBuffer->reserve(
_bufferLength); // ATTENTION <- this is required so we do not
// loose information during a resize
// connectionStatisticsAgentSetVpp();
}
void VppCommTask::addResponse(VppResponse* response, bool isError) {
if (isError) {
// FIXME (obi)
// what do we need to do?
// clean read buffer? reset process read cursor
}
VPackMessageNoOwnBuffer response_message = response->prepareForNetwork();
uint64_t& id = response_message._id;
std::vector<VPackSlice> slices;
slices.push_back(response_message._header);
VPackBuilder builder;
if (response_message._generateBody) {
builder = basics::VelocyPackHelper::stanitizeExternalsChecked(
response_message._payload);
slices.push_back(builder.slice());
}
// FIXME (obi)
// If the message is big we will create many small chunks in a loop.
// For the first tests we just send single Messages
LOG_TOPIC(DEBUG, Logger::COMMUNICATION) << "got response:";
for (auto const& slice : slices) {
try {
LOG_TOPIC(DEBUG, Logger::COMMUNICATION) << slice.toJson();
} catch (arangodb::velocypack::Exception const& e) {
std::cout << "obi exception" << e.what();
}
}
// adds chunk header infromation and creates SingBuffer* that can be
// used with _writeBuffers
auto buffer = createChunkForNetworkSingle(slices, id);
_writeBuffers.push_back(buffer.get());
buffer.release();
fillWriteBuffer(); // move data from _writebuffers to _writebuffer
// implemented in base
}
VppCommTask::ChunkHeader VppCommTask::readChunkHeader() {
VppCommTask::ChunkHeader header;
auto cursor = _processReadVariables._readBufferCursor;
std::memcpy(&header._chunkLength, cursor, sizeof(header._chunkLength));
cursor += sizeof(header._chunkLength);
uint32_t chunkX;
std::memcpy(&chunkX, cursor, sizeof(chunkX));
cursor += sizeof(chunkX);
header._isFirst = chunkX & 0x1;
header._chunk = chunkX >> 1;
std::memcpy(&header._messageID, cursor, sizeof(header._messageID));
cursor += sizeof(header._messageID);
// extract total len of message
if (header._isFirst && header._chunk > 1) {
std::memcpy(&header._messageLength, cursor, sizeof(header._messageLength));
cursor += sizeof(header._messageLength);
} else {
header._messageLength = 0; // not needed
}
header._headerLength =
std::distance(_processReadVariables._readBufferCursor, cursor);
return header;
}
bool VppCommTask::isChunkComplete(char* start) {
std::size_t length = std::distance(start, _readBuffer->end());
auto& prv = _processReadVariables;
if (!prv._currentChunkLength && length < sizeof(uint32_t)) {
return false;
}
if (!prv._currentChunkLength) {
// read chunk length
std::memcpy(&prv._currentChunkLength, start, sizeof(uint32_t));
}
if (length < prv._currentChunkLength) {
// chunk not complete
return false;
}
return true;
}
// reads data from the socket
bool VppCommTask::processRead() {
// TODO FIXME
// - in case of error send an operation failed to all incomplete messages /
// operation and close connection (implement resetState/resetCommtask)
auto& prv = _processReadVariables;
if (!prv._readBufferCursor) {
prv._readBufferCursor = _readBuffer->begin();
}
auto chunkBegin = prv._readBufferCursor;
if (chunkBegin == nullptr || !isChunkComplete(chunkBegin)) {
return false; // no data or incomplete
}
ChunkHeader chunkHeader = readChunkHeader();
auto chunkEnd = chunkBegin + chunkHeader._chunkLength;
auto vpackBegin = chunkBegin + chunkHeader._headerLength;
bool doExecute = false;
bool read_maybe_only_part_of_buffer = false;
VPackMessage message; // filled in CASE 1 or CASE 2b
// CASE 1: message is in one chunk
if (chunkHeader._isFirst && chunkHeader._chunk == 1) {
std::size_t payloadOffset = findAndValidateVPacks(vpackBegin, chunkEnd);
message._id = chunkHeader._messageID;
message._buffer.append(vpackBegin, std::distance(vpackBegin, chunkEnd));
message._header = VPackSlice(message._buffer.data());
if (payloadOffset) {
message._payload = VPackSlice(message._buffer.data() + payloadOffset);
}
VPackValidator val;
val.validate(message._header.begin(), message._header.byteSize());
doExecute = true;
LOG_TOPIC(DEBUG, Logger::COMMUNICATION) << "CASE 1";
}
// CASE 2: message is in multiple chunks
auto incompleteMessageItr = _incompleteMessages.find(chunkHeader._messageID);
// CASE 2a: chunk starts new message
if (chunkHeader._isFirst) { // first chunk of multi chunk message
if (incompleteMessageItr != _incompleteMessages.end()) {
throw std::logic_error(
"Message should be first but is already in the Map of incomplete "
"messages");
}
IncompleteVPackMessage message(chunkHeader._messageLength,
chunkHeader._chunk /*number of chunks*/);
message._buffer.append(vpackBegin, std::distance(vpackBegin, chunkEnd));
auto insertPair = _incompleteMessages.emplace(
std::make_pair(chunkHeader._messageID, std::move(message)));
if (!insertPair.second) {
throw std::logic_error("insert failed");
}
LOG_TOPIC(DEBUG, Logger::COMMUNICATION) << "CASE 2a";
// CASE 2b: chunk continues a message
} else { // followup chunk of some mesage
if (incompleteMessageItr == _incompleteMessages.end()) {
throw std::logic_error("found message without previous part");
}
auto& im = incompleteMessageItr->second; // incomplete Message
im._currentChunk++;
assert(im._currentChunk == chunkHeader._chunk);
im._buffer.append(vpackBegin, std::distance(vpackBegin, chunkEnd));
// check buffer longer than length
// MESSAGE COMPLETE
if (im._currentChunk == im._numberOfChunks - 1 /* zero based counting */) {
std::size_t payloadOffset = findAndValidateVPacks(
reinterpret_cast<char const*>(im._buffer.data()),
reinterpret_cast<char const*>(im._buffer.data() +
im._buffer.byteSize()));
message._id = chunkHeader._messageID;
message._buffer = std::move(im._buffer);
message._header = VPackSlice(message._buffer.data());
if (payloadOffset) {
message._payload = VPackSlice(message._buffer.data() + payloadOffset);
}
_incompleteMessages.erase(incompleteMessageItr);
// check length
doExecute = true;
LOG_TOPIC(DEBUG, Logger::COMMUNICATION) << "CASE 2b - complete";
}
LOG_TOPIC(DEBUG, Logger::COMMUNICATION) << "CASE 2b - still incomplete";
}
// clean buffer up to length of chunk
read_maybe_only_part_of_buffer = true;
prv._currentChunkLength = 0;
prv._readBufferCursor = chunkEnd;
std::size_t processedDataLen =
std::distance(_readBuffer->begin(), prv._readBufferCursor);
if (processedDataLen > prv._cleanupLength) {
_readBuffer->move_front(prv._cleanupLength);
prv._readBufferCursor = nullptr; // the positon will be set at the
// begin of this function
}
if (doExecute) {
// return false; // we have no complete request, so we return early
// for now we can handle only one request at a time
// lock _request???? REVIEW (fc)
LOG_TOPIC(DEBUG, Logger::COMMUNICATION)
<< "got request:" << message._header.toJson();
_request = new VppRequest(_connectionInfo, std::move(message));
GeneralServerFeature::HANDLER_FACTORY->setRequestContext(_request);
if (_request->requestContext() == nullptr) {
handleSimpleError(GeneralResponse::ResponseCode::NOT_FOUND,
TRI_ERROR_ARANGO_DATABASE_NOT_FOUND,
TRI_errno_string(TRI_ERROR_ARANGO_DATABASE_NOT_FOUND));
} else {
_request->setClientTaskId(_taskId);
_protocolVersion = _request->protocolVersion();
executeRequest(
_request, new VppResponse(GeneralResponse::ResponseCode::SERVER_ERROR,
chunkHeader._messageID));
}
}
if (read_maybe_only_part_of_buffer) {
if (prv._readBufferCursor == _readBuffer->end()) {
return false;
}
return true;
}
return doExecute;
}
void VppCommTask::completedWriteBuffer() {
// REVIEW (fc)
}
void VppCommTask::resetState(bool close) {
// REVIEW (fc)
// is there a case where we do not want to close the connection
replyToIncompleteMessages();
}
// GeneralResponse::ResponseCode VppCommTask::authenticateRequest() {
// auto context = (_request == nullptr) ? nullptr :
// _request->requestContext();
//
// if (context == nullptr && _request != nullptr) {
// bool res =
// GeneralServerFeature::HANDLER_FACTORY->setRequestContext(_request);
//
// if (!res) {
// return GeneralResponse::ResponseCode::NOT_FOUND;
// }
//
// context = _request->requestContext();
// }
//
// if (context == nullptr) {
// return GeneralResponse::ResponseCode::SERVER_ERROR;
// }
//
// return context->authenticate();
// }
// convert internal GeneralRequest to VppRequest
VppRequest* VppCommTask::requestAsVpp() {
VppRequest* request = dynamic_cast<VppRequest*>(_request);
if (request == nullptr) {
THROW_ARANGO_EXCEPTION(TRI_ERROR_INTERNAL);
}
return request;
};
<commit_msg>fix buffer clean up<commit_after>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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
///
/// vpp://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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Christoph Uhde
////////////////////////////////////////////////////////////////////////////////
#include "VppCommTask.h"
#include "Basics/StringBuffer.h"
#include "Basics/HybridLogicalClock.h"
#include "Basics/VelocyPackHelper.h"
#include "GeneralServer/GeneralServer.h"
#include "GeneralServer/GeneralServerFeature.h"
#include "GeneralServer/RestHandler.h"
#include "GeneralServer/RestHandlerFactory.h"
#include "Scheduler/Scheduler.h"
#include "Scheduler/SchedulerFeature.h"
#include "Logger/LoggerFeature.h"
#include "VocBase/ticks.h"
#include <velocypack/Validator.h>
#include <velocypack/velocypack-aliases.h>
#include <iostream>
#include <stdexcept>
using namespace arangodb;
using namespace arangodb::basics;
using namespace arangodb::rest;
namespace {
std::size_t findAndValidateVPacks(char const* vpHeaderStart,
char const* chunkEnd) {
VPackValidator validator;
// check for slice start to the end of Chunk
// isSubPart allows the slice to be shorter than the checked buffer.
validator.validate(vpHeaderStart, std::distance(vpHeaderStart, chunkEnd),
/*isSubPart =*/true);
// check if there is payload and locate the start
VPackSlice vpHeader(vpHeaderStart);
auto vpHeaderLen = vpHeader.byteSize();
auto vpPayloadStart = vpHeaderStart + vpHeaderLen;
if (vpPayloadStart == chunkEnd) {
return 0; // no payload available
}
// validate Payload VelocyPack
validator.validate(vpPayloadStart, std::distance(vpPayloadStart, chunkEnd),
/*isSubPart =*/false);
return std::distance(vpHeaderStart, vpPayloadStart);
}
std::unique_ptr<basics::StringBuffer> createChunkForNetworkDetail(
std::vector<VPackSlice> const& slices, bool isFirstChunk, uint32_t chunk,
uint64_t id, uint32_t totalMessageLength = 0) {
using basics::StringBuffer;
bool firstOfMany = false;
// if we have more than one chunk and the chunk is the first
// then we are sending the first in a series. if this condition
// is true we also send extra 8 bytes for the messageLength
// (length of all VPackData)
if (isFirstChunk && chunk > 1) {
firstOfMany = true;
}
// build chunkX -- see VelocyStream Documentaion
chunk <<= 1;
chunk |= isFirstChunk ? 0x1 : 0x0;
// get the lenght of VPack data
uint32_t dataLength = 0;
for (auto& slice : slices) {
dataLength += slice.byteSize();
}
// calculate length of current chunk
uint32_t chunkLength = dataLength;
chunkLength += (sizeof(chunkLength) + sizeof(chunk) + sizeof(id));
if (firstOfMany) {
chunkLength += sizeof(totalMessageLength);
}
auto buffer =
std::make_unique<StringBuffer>(TRI_UNKNOWN_MEM_ZONE, chunkLength, false);
char cChunkLength[sizeof(chunkLength)];
char const* cChunkLengthPtr = cChunkLength;
std::memcpy(&cChunkLength, &chunkLength, sizeof(chunkLength));
buffer->appendText(cChunkLengthPtr, sizeof(chunkLength));
char cChunk[sizeof(chunk)];
char const* cChunkPtr = cChunk;
std::memcpy(&cChunk, &chunk, sizeof(chunk));
buffer->appendText(cChunkPtr, sizeof(chunk));
char cId[sizeof(id)];
char const* cIdPtr = cId;
std::memcpy(&cId, &id, sizeof(id));
buffer->appendText(cIdPtr, sizeof(id));
if (firstOfMany) {
char cTotalMessageLength[sizeof(totalMessageLength)];
char const* cTotalMessageLengthPtr = cTotalMessageLength;
std::memcpy(&cTotalMessageLength, &totalMessageLength,
sizeof(totalMessageLength));
buffer->appendText(cTotalMessageLengthPtr, sizeof(totalMessageLength));
}
// append data in slices
for (auto const& slice : slices) {
buffer->appendText(std::string(slice.startAs<char>(), slice.byteSize()));
}
return buffer;
}
std::unique_ptr<basics::StringBuffer> createChunkForNetworkSingle(
std::vector<VPackSlice> const& slices, uint64_t id) {
return createChunkForNetworkDetail(slices, true, 1, id, 0 /*unused*/);
}
// TODO FIXME make use of these functions
// std::unique_ptr<basics::StringBuffer> createChunkForNetworkMultiFirst(
// std::vector<VPackSlice> const& slices, uint64_t id, uint32_t
// numberOfChunks,
// uint32_t totalMessageLength) {
// return createChunkForNetworkDetail(slices, true, numberOfChunks, id,
// totalMessageLength);
// }
//
// std::unique_ptr<basics::StringBuffer> createChunkForNetworkMultiFollow(
// std::vector<VPackSlice> const& slices, uint64_t id, uint32_t chunkNumber,
// uint32_t totalMessageLength) {
// return createChunkForNetworkDetail(slices, false, chunkNumber, id, 0);
// }
}
VppCommTask::VppCommTask(GeneralServer* server, TRI_socket_t sock,
ConnectionInfo&& info, double timeout)
: Task("VppCommTask"),
GeneralCommTask(server, sock, std::move(info), timeout) {
_protocol = "vpp";
_readBuffer->reserve(
_bufferLength); // ATTENTION <- this is required so we do not
// loose information during a resize
// connectionStatisticsAgentSetVpp();
}
void VppCommTask::addResponse(VppResponse* response, bool isError) {
if (isError) {
// FIXME (obi)
// what do we need to do?
// clean read buffer? reset process read cursor
}
VPackMessageNoOwnBuffer response_message = response->prepareForNetwork();
uint64_t& id = response_message._id;
std::vector<VPackSlice> slices;
slices.push_back(response_message._header);
VPackBuilder builder;
if (response_message._generateBody) {
builder = basics::VelocyPackHelper::stanitizeExternalsChecked(
response_message._payload);
slices.push_back(builder.slice());
}
// FIXME (obi)
// If the message is big we will create many small chunks in a loop.
// For the first tests we just send single Messages
LOG_TOPIC(DEBUG, Logger::COMMUNICATION) << "got response:";
for (auto const& slice : slices) {
try {
LOG_TOPIC(DEBUG, Logger::COMMUNICATION) << slice.toJson();
} catch (arangodb::velocypack::Exception const& e) {
std::cout << "obi exception" << e.what();
}
}
// adds chunk header infromation and creates SingBuffer* that can be
// used with _writeBuffers
auto buffer = createChunkForNetworkSingle(slices, id);
_writeBuffers.push_back(buffer.get());
buffer.release();
fillWriteBuffer(); // move data from _writebuffers to _writebuffer
// implemented in base
}
VppCommTask::ChunkHeader VppCommTask::readChunkHeader() {
VppCommTask::ChunkHeader header;
auto cursor = _processReadVariables._readBufferCursor;
std::memcpy(&header._chunkLength, cursor, sizeof(header._chunkLength));
cursor += sizeof(header._chunkLength);
uint32_t chunkX;
std::memcpy(&chunkX, cursor, sizeof(chunkX));
cursor += sizeof(chunkX);
header._isFirst = chunkX & 0x1;
header._chunk = chunkX >> 1;
std::memcpy(&header._messageID, cursor, sizeof(header._messageID));
cursor += sizeof(header._messageID);
// extract total len of message
if (header._isFirst && header._chunk > 1) {
std::memcpy(&header._messageLength, cursor, sizeof(header._messageLength));
cursor += sizeof(header._messageLength);
} else {
header._messageLength = 0; // not needed
}
header._headerLength =
std::distance(_processReadVariables._readBufferCursor, cursor);
return header;
}
bool VppCommTask::isChunkComplete(char* start) {
std::size_t length = std::distance(start, _readBuffer->end());
auto& prv = _processReadVariables;
if (!prv._currentChunkLength && length < sizeof(uint32_t)) {
return false;
}
if (!prv._currentChunkLength) {
// read chunk length
std::memcpy(&prv._currentChunkLength, start, sizeof(uint32_t));
}
if (length < prv._currentChunkLength) {
// chunk not complete
return false;
}
return true;
}
// reads data from the socket
bool VppCommTask::processRead() {
// TODO FIXME
// - in case of error send an operation failed to all incomplete messages /
// operation and close connection (implement resetState/resetCommtask)
auto& prv = _processReadVariables;
if (!prv._readBufferCursor) {
prv._readBufferCursor = _readBuffer->begin();
}
auto chunkBegin = prv._readBufferCursor;
if (chunkBegin == nullptr || !isChunkComplete(chunkBegin)) {
return false; // no data or incomplete
}
ChunkHeader chunkHeader = readChunkHeader();
auto chunkEnd = chunkBegin + chunkHeader._chunkLength;
auto vpackBegin = chunkBegin + chunkHeader._headerLength;
bool doExecute = false;
bool read_maybe_only_part_of_buffer = false;
VPackMessage message; // filled in CASE 1 or CASE 2b
// CASE 1: message is in one chunk
if (chunkHeader._isFirst && chunkHeader._chunk == 1) {
std::size_t payloadOffset = findAndValidateVPacks(vpackBegin, chunkEnd);
message._id = chunkHeader._messageID;
message._buffer.append(vpackBegin, std::distance(vpackBegin, chunkEnd));
message._header = VPackSlice(message._buffer.data());
if (payloadOffset) {
message._payload = VPackSlice(message._buffer.data() + payloadOffset);
}
VPackValidator val;
val.validate(message._header.begin(), message._header.byteSize());
doExecute = true;
LOG_TOPIC(DEBUG, Logger::COMMUNICATION) << "CASE 1";
}
// CASE 2: message is in multiple chunks
auto incompleteMessageItr = _incompleteMessages.find(chunkHeader._messageID);
// CASE 2a: chunk starts new message
if (chunkHeader._isFirst) { // first chunk of multi chunk message
if (incompleteMessageItr != _incompleteMessages.end()) {
throw std::logic_error(
"Message should be first but is already in the Map of incomplete "
"messages");
}
IncompleteVPackMessage message(chunkHeader._messageLength,
chunkHeader._chunk /*number of chunks*/);
message._buffer.append(vpackBegin, std::distance(vpackBegin, chunkEnd));
auto insertPair = _incompleteMessages.emplace(
std::make_pair(chunkHeader._messageID, std::move(message)));
if (!insertPair.second) {
throw std::logic_error("insert failed");
}
LOG_TOPIC(DEBUG, Logger::COMMUNICATION) << "CASE 2a";
// CASE 2b: chunk continues a message
} else { // followup chunk of some mesage
if (incompleteMessageItr == _incompleteMessages.end()) {
throw std::logic_error("found message without previous part");
}
auto& im = incompleteMessageItr->second; // incomplete Message
im._currentChunk++;
assert(im._currentChunk == chunkHeader._chunk);
im._buffer.append(vpackBegin, std::distance(vpackBegin, chunkEnd));
// check buffer longer than length
// MESSAGE COMPLETE
if (im._currentChunk == im._numberOfChunks - 1 /* zero based counting */) {
std::size_t payloadOffset = findAndValidateVPacks(
reinterpret_cast<char const*>(im._buffer.data()),
reinterpret_cast<char const*>(im._buffer.data() +
im._buffer.byteSize()));
message._id = chunkHeader._messageID;
message._buffer = std::move(im._buffer);
message._header = VPackSlice(message._buffer.data());
if (payloadOffset) {
message._payload = VPackSlice(message._buffer.data() + payloadOffset);
}
_incompleteMessages.erase(incompleteMessageItr);
// check length
doExecute = true;
LOG_TOPIC(DEBUG, Logger::COMMUNICATION) << "CASE 2b - complete";
}
LOG_TOPIC(DEBUG, Logger::COMMUNICATION) << "CASE 2b - still incomplete";
}
// clean buffer up to length of chunk
read_maybe_only_part_of_buffer = true;
prv._currentChunkLength = 0;
prv._readBufferCursor = chunkEnd;
std::size_t processedDataLen =
std::distance(_readBuffer->begin(), prv._readBufferCursor);
if (processedDataLen > prv._cleanupLength) {
_readBuffer->move_front(processedDataLen);
prv._readBufferCursor = nullptr; // the positon will be set at the
// begin of this function
}
if (doExecute) {
// return false; // we have no complete request, so we return early
// for now we can handle only one request at a time
// lock _request???? REVIEW (fc)
LOG_TOPIC(DEBUG, Logger::COMMUNICATION)
<< "got request:" << message._header.toJson();
_request = new VppRequest(_connectionInfo, std::move(message));
GeneralServerFeature::HANDLER_FACTORY->setRequestContext(_request);
if (_request->requestContext() == nullptr) {
handleSimpleError(GeneralResponse::ResponseCode::NOT_FOUND,
TRI_ERROR_ARANGO_DATABASE_NOT_FOUND,
TRI_errno_string(TRI_ERROR_ARANGO_DATABASE_NOT_FOUND));
} else {
_request->setClientTaskId(_taskId);
_protocolVersion = _request->protocolVersion();
executeRequest(
_request, new VppResponse(GeneralResponse::ResponseCode::SERVER_ERROR,
chunkHeader._messageID));
}
}
if (read_maybe_only_part_of_buffer) {
if (prv._readBufferCursor == _readBuffer->end()) {
return false;
}
return true;
}
return doExecute;
}
void VppCommTask::completedWriteBuffer() {
// REVIEW (fc)
}
void VppCommTask::resetState(bool close) {
// REVIEW (fc)
// is there a case where we do not want to close the connection
replyToIncompleteMessages();
}
// GeneralResponse::ResponseCode VppCommTask::authenticateRequest() {
// auto context = (_request == nullptr) ? nullptr :
// _request->requestContext();
//
// if (context == nullptr && _request != nullptr) {
// bool res =
// GeneralServerFeature::HANDLER_FACTORY->setRequestContext(_request);
//
// if (!res) {
// return GeneralResponse::ResponseCode::NOT_FOUND;
// }
//
// context = _request->requestContext();
// }
//
// if (context == nullptr) {
// return GeneralResponse::ResponseCode::SERVER_ERROR;
// }
//
// return context->authenticate();
// }
// convert internal GeneralRequest to VppRequest
VppRequest* VppCommTask::requestAsVpp() {
VppRequest* request = dynamic_cast<VppRequest*>(_request);
if (request == nullptr) {
THROW_ARANGO_EXCEPTION(TRI_ERROR_INTERNAL);
}
return request;
};
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.