text
stringlengths 54
60.6k
|
---|
<commit_before>/** \copyright
* Copyright (c) 2014, Balazs Racz
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \file Receiver.hxx
*
* State flow for DCC packet reception and decoding.
*
* @author Balazs Racz
* @date 30 November 2014
*/
#ifndef _DCC_RECEIVER_HXX_
#define _DCC_RECEIVER_HXX_
#include "executor/StateFlow.hxx"
namespace dcc {
class DccDecodeFlow : public StateFlowBase {
public:
DccDecodeFlow(Service* s, const char* dev)
: StateFlowBase(s) {
fd_ = ::open(dev, O_RDONLY | O_NONBLOCK);
start_flow(STATE(register_and_sleep));
timings_[DCC_ONE].set(52, 64);
timings_[DCC_ZERO].set(95, 9900);
}
private:
Action register_and_sleep() {
::ioctl(fd_, CAN_IOC_READ_ACTIVE, this);
return wait_and_call(STATE(data_arrived));
}
Action data_arrived() {
while (true) {
uint32_t value;
int ret = ::read(fd_, &value, sizeof(value));
if (ret != 4) {
return call_immediately(STATE(register_and_sleep));
}
MAP_GPIOPinWrite(LED_GREEN, 0xff);
process_data(value);
}
}
void process_data(uint32_t value) {
switch (parseState_)
{
case UNKNOWN: {
if (timings_[DCC_ONE].match(value)) {
parseCount_ = 0;
parseState_ = DCC_PREAMBLE;
return;
}
break;
}
case DCC_PREAMBLE: {
if (timings_[DCC_ONE].match(value)) {
parseCount_++;
return;
}
if (timings_[DCC_ZERO].match(value) && (parseCount_ >= 20)) {
parseState_ = DCC_END_OF_PREAMBLE;
return;
}
break;
}
case DCC_END_OF_PREAMBLE: {
MAP_GPIOPinWrite(LED_YELLOW, 0xff);
if (timings_[DCC_ZERO].match(value)) {
parseState_ = DCC_DATA;
parseCount_ = 1<<7;
ofs_ = 0;
data_[ofs_] = 0;
return;
}
break;
}
case DCC_DATA: {
if (timings_[DCC_ONE].match(value)) {
parseState_ = DCC_DATA_ONE;
return;
}
if (timings_[DCC_ZERO].match(value)) {
parseState_ = DCC_DATA_ZERO;
return;
}
break;
}
case DCC_DATA_ONE: {
if (timings_[DCC_ONE].match(value)) {
if (parseCount_) {
data_[ofs_] |= parseCount_;
parseCount_ >>= 1;
parseState_ = DCC_DATA;
return;
} else {
// end of packet 1 bit.
dcc_packet_finished();
parseState_ = DCC_MAYBE_CUTOUT;
return;
}
return;
}
break;
}
case DCC_DATA_ZERO: {
if (timings_[DCC_ZERO].match(value)) {
if (parseCount_) {
// zero bit into data_.
parseCount_ >>= 1;
} else {
// end of byte zero bit. Packet is not finished yet.
ofs_++;
HASSERT(ofs_ < sizeof(data_));
data_[ofs_] = 0;
parseCount_ = 1<<7;
}
parseState_ = DCC_DATA;
return;
}
break;
}
case DCC_MAYBE_CUTOUT: {
if (value < timings_[DCC_ZERO].min_value) {
HWREG(UART2_BASE + UART_O_CTL) |= UART_CTL_RXE;
}
}
}
parseState_ = UNKNOWN;
return;
}
virtual void dcc_packet_finished() = 0;
int fd_;
uint32_t lastValue_ = 0;
enum State {
UNKNOWN,
DCC_PREAMBLE,
DCC_END_OF_PREAMBLE,
DCC_DATA,
DCC_DATA_ONE,
DCC_DATA_ZERO,
DCC_MAYBE_CUTOUT,
};
State parseState_ = UNKNOWN;
uint32_t parseCount_ = 0;
protected:
uint8_t data_[6];
uint8_t ofs_; // offset inside data_;
private:
struct Timing {
void set(int min_usec, int max_usec) {
if (min_usec < 0) {
min_value = 0;
} else {
min_value = usec_to_clock(min_usec);
}
if (max_usec < 0) {
max_usec = UINT_MAX;
} else {
max_value = usec_to_clock(max_usec);
}
}
bool match(uint32_t value_clocks) const {
return min_value <= value_clocks && value_clocks <= max_value;
}
static uint32_t usec_to_clock(int usec) {
return (configCPU_CLOCK_HZ / 1000000) * usec;
}
uint32_t min_value;
uint32_t max_value;
};
enum TimingInfo {
DCC_ONE = 0,
DCC_ZERO,
MAX_TIMINGS
};
Timing timings_[MAX_TIMINGS];
};
} // namespace dcc
#endif // _DCC_RECEIVER_HXX_
<commit_msg>Adds (untested) marklin-motorola decoding to the DCC state flow.<commit_after>/** \copyright
* Copyright (c) 2014, Balazs Racz
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \file Receiver.hxx
*
* State flow for DCC packet reception and decoding.
*
* @author Balazs Racz
* @date 30 November 2014
*/
#ifndef _DCC_RECEIVER_HXX_
#define _DCC_RECEIVER_HXX_
#include "executor/StateFlow.hxx"
namespace dcc {
class DccDecodeFlow : public StateFlowBase {
public:
DccDecodeFlow(Service* s, const char* dev)
: StateFlowBase(s) {
fd_ = ::open(dev, O_RDONLY | O_NONBLOCK);
start_flow(STATE(register_and_sleep));
timings_[DCC_ONE].set(52, 64);
timings_[DCC_ZERO].set(95, 9900);
timings_[MM_PREAMBLE].set(1000, -1);
timings_[MM_SHORT].set(20, 32);
timings_[MM_LONG].set(200, 216);
}
private:
Action register_and_sleep() {
::ioctl(fd_, CAN_IOC_READ_ACTIVE, this);
return wait_and_call(STATE(data_arrived));
}
Action data_arrived() {
while (true) {
uint32_t value;
int ret = ::read(fd_, &value, sizeof(value));
if (ret != 4) {
return call_immediately(STATE(register_and_sleep));
}
MAP_GPIOPinWrite(GPIO_PORTA_BASE, GPIO_PIN_0, 0xff);
debug_data(value);
process_data(value);
static uint8_t x = 0;
//MAP_GPIOPinWrite(LED_GREEN, 0);
x = ~x;
}
}
void process_data(uint32_t value) {
switch (parseState_)
{
case UNKNOWN: {
if (timings_[DCC_ONE].match(value)) {
parseCount_ = 0;
parseState_ = DCC_PREAMBLE;
return;
}
if (timings_[MM_PREAMBLE].match(value)) {
parseCount_ = 1<<2;
ofs_ = 0;
data_[ofs_] = 0;
parseState_ = MM_DATA;
}
break;
}
case DCC_PREAMBLE: {
if (timings_[DCC_ONE].match(value)) {
parseCount_++;
return;
}
if (timings_[DCC_ZERO].match(value) && (parseCount_ >= 16)) {
parseState_ = DCC_END_OF_PREAMBLE;
return;
}
break;
}
case DCC_END_OF_PREAMBLE: {
MAP_GPIOPinWrite(LED_YELLOW, 0xff);
if (timings_[DCC_ZERO].match(value)) {
parseState_ = DCC_DATA;
parseCount_ = 1<<7;
ofs_ = 0;
data_[ofs_] = 0;
return;
}
break;
}
case DCC_DATA: {
if (timings_[DCC_ONE].match(value)) {
parseState_ = DCC_DATA_ONE;
return;
}
if (timings_[DCC_ZERO].match(value)) {
parseState_ = DCC_DATA_ZERO;
return;
}
break;
}
case DCC_DATA_ONE: {
if (timings_[DCC_ONE].match(value)) {
if (parseCount_) {
data_[ofs_] |= parseCount_;
parseCount_ >>= 1;
parseState_ = DCC_DATA;
return;
} else {
// end of packet 1 bit.
parseState_ = DCC_MAYBE_CUTOUT;
return;
}
return;
}
break;
}
case DCC_DATA_ZERO: {
if (timings_[DCC_ZERO].match(value)) {
if (parseCount_) {
// zero bit into data_.
parseCount_ >>= 1;
} else {
// end of byte zero bit. Packet is not finished yet.
ofs_++;
HASSERT(ofs_ < sizeof(data_));
data_[ofs_] = 0;
parseCount_ = 1<<7;
}
parseState_ = DCC_DATA;
return;
}
break;
}
case DCC_MAYBE_CUTOUT: {
//MAP_GPIOPinWrite(LED_GREEN, 0);
if (value < timings_[DCC_ZERO].min_value) {
MAP_GPIOPinWrite(LED_GREEN, 0xff);
HWREG(UART2_BASE + UART_O_CTL) |= UART_CTL_RXE;
}
dcc_packet_finished();
break;
}
case MM_DATA: {
if (timings_[MM_LONG].match(value)) {
parseState_ = MM_ZERO;
return;
}
if (timings_[MM_SHORT].match(value)) {
parseState_ = MM_ONE;
return;
}
break;
}
case MM_ZERO: {
if (timings_[MM_SHORT].match(value)) {
//data_[ofs_] |= 0;
parseCount_ >>= 1;
if (!parseCount_) {
if (ofs_ == 2) {
mm_packet_finished();
parseState_ = UNKNOWN;
return;
} else {
ofs_++;
parseCount_ = 1<<7;
data_[ofs_] = 0;
}
}
parseState_ = MM_DATA;
return;
}
break;
}
case MM_ONE: {
if (timings_[MM_LONG].match(value)) {
data_[ofs_] |= parseCount_;
parseCount_ >>= 1;
if (!parseCount_) {
if (ofs_ == 2) {
dcc_packet_finished();
parseState_ = UNKNOWN;
return;
} else {
ofs_++;
parseCount_ = 1<<7;
data_[ofs_] = 0;
}
}
parseState_ = MM_DATA;
return;
}
break;
}
}
parseState_ = UNKNOWN;
return;
}
virtual void dcc_packet_finished() = 0;
virtual void mm_packet_finished() = 0;
virtual void debug_data(uint32_t value) {}
int fd_;
uint32_t lastValue_ = 0;
enum State {
UNKNOWN, // 0
DCC_PREAMBLE, // 1
DCC_END_OF_PREAMBLE, // 2
DCC_DATA, // 3
DCC_DATA_ONE, // 4
DCC_DATA_ZERO, // 5
DCC_MAYBE_CUTOUT, // 6
MM_DATA,
MM_ZERO,
MM_ONE,
};
uint32_t parseCount_ = 0;
protected:
// TODO(balazs.racz) make to private
State parseState_ = UNKNOWN;
uint8_t data_[6];
uint8_t ofs_; // offset inside data_;
private:
struct Timing {
void set(int min_usec, int max_usec) {
if (min_usec < 0) {
min_value = 0;
} else {
min_value = usec_to_clock(min_usec);
}
if (max_usec < 0) {
max_usec = UINT_MAX;
} else {
max_value = usec_to_clock(max_usec);
}
}
bool match(uint32_t value_clocks) const {
return min_value <= value_clocks && value_clocks <= max_value;
}
static uint32_t usec_to_clock(int usec) {
return (configCPU_CLOCK_HZ / 1000000) * usec;
}
uint32_t min_value;
uint32_t max_value;
};
enum TimingInfo {
DCC_ONE = 0,
DCC_ZERO,
MM_PREAMBLE,
MM_SHORT,
MM_LONG,
MAX_TIMINGS
};
Timing timings_[MAX_TIMINGS];
};
} // namespace dcc
#endif // _DCC_RECEIVER_HXX_
<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include <sstream>
#include <map>
#include <functional>
using namespace std;
namespace {
namespace io {
enum token_type {
REG,
NN
};
ofstream outfile;
ifstream infile;
void exit_ok() {
infile.close();
outfile.close();
exit(0);
}
void exit_err(string const& error) {
cerr << error;
infile.close();
outfile.close();
exit(1);
}
void write_bins(char lhs, char rhs) {
outfile.write(static_cast<char*>(&lhs), 1);
outfile.write(static_cast<char*>(&rhs), 1);
if (outfile.fail()) {
exit_err("Error writing to disk");
}
}
int xtoi(string const& x) {
try {
return stoi(x, 0, 16);
} catch (exception &e) {
return -1;
}
}
string next_token() {
string value;
io::infile >> value;
if (!io::infile) {
io::exit_ok();
}
return value;
}
void tok2n(string const& name, string&& value, char& n) {
int target = xtoi(value);
if (0 > target || 0xF < target) {
exit_err("Error: " + name + " needs to be supplied with a value [0-F]\n");
}
n = target;
}
void tok2nn(string const& name, string&& value, char& nn) {
int target = xtoi(value);
if (0 > target || 0xFF < target) {
exit_err("Error: " + name + " needs to be supplied with a value [0-FF]\n");
}
nn = target;
}
void tok2nnn(string const& name, string&& value, char& lhs, char& rhs) {
int target = xtoi(value);
if (0 > target || 0xFFF < target) {
exit_err("Error: " + name + " needs to be supplied with a value [0-FFF]\n");
}
lhs = target >> 8;
rhs = target & 0xFF;
}
void tok2nnnn(string const& name, string&& value, char& lhs, char& rhs) {
int target = xtoi(value);
if (0 > target || 0xFFFF < target) {
exit_err("Error: " + name + " needs to be supplied with a value [0-FFFF]\n");
}
lhs = target >> 8;
rhs = target & 0xFF;
}
void tok2reg(string const& name, string&& value, char& reg) {
if (value.at(0) != 'r') {
exit_err("Error: " + name + " needs to be supplied with a register r[0-F]\n");
}
int target = xtoi(value.substr(1));
if (0 > target || 0xF < target) {
exit_err("Error: " + name + " needs to be supplied with a register r[0-F]\n");
}
reg = target;
}
void tok2reg_or_nn(string const& name, string&& value, char& reg_or_nn, io::token_type& t) {
if (value.at(0) == 'r') {
t = REG;
tok2reg(name, forward<string>(value), reg_or_nn);
} else {
t = NN;
tok2nn(name, forward<string>(value), reg_or_nn);
}
}
} // io
namespace op {
// These variables are shared between all below functions
char lhs;
char rhs;
char rhs2;
io::token_type t;
inline void OP(char lhs, char rhs) { io::write_bins(lhs, rhs); }
inline void R(string const& name, char lop, char rop) {
io::tok2reg(name, io::next_token(), lhs);
io::write_bins(lop + lhs, rop);
}
inline void RR(string const& name, char lop, char rop) {
io::tok2reg(name, io::next_token(), lhs);
io::tok2reg(name, io::next_token(), rhs);
io::write_bins(lop + lhs, (rhs << 4) + rop);
}
inline void NNN(string const& name, char op) {
io::tok2nnn(name, io::next_token(), lhs, rhs);
io::write_bins(op + lhs, rhs);
}
inline void RNN(string const& name, char lop) {
io::tok2reg(name, io::next_token(), lhs);
io::tok2nn(name, io::next_token(), rhs);
io::write_bins(lop + lhs, rhs);
}
inline void RRN(string const& name, char lop) {
io::tok2reg(name, io::next_token(), lhs);
io::tok2reg(name, io::next_token(), rhs);
io::tok2n(name, io::next_token(), rhs2);
io::write_bins(lop + lhs, (rhs << 4) + rhs2);
}
inline void RV(string const& name, char nnop, char rlop, char rrop) {
io::tok2reg(name, io::next_token(), lhs);
io::tok2reg_or_nn(name, io::next_token(), rhs, t);
if (t == io::NN) { io::write_bins(nnop + lhs, rhs); }
else if (t == io::REG) { io::write_bins(rlop + lhs, (rhs << 4) + rrop); }
else { io::exit_err(name + ": Unknown type\n"); }
}
inline void DATA(string const& name) {
io::tok2nnnn(name, io::next_token(), lhs, rhs);
io::write_bins(lhs, rhs);
}
} // op
int help(string program_name) {
cerr
<< "Usage: " << program_name << " FILE\n\n"
<< "Available commands\n"
<< "CLS - 0x00E0\n"
<< "RET - 0x00EE\n"
<< "JMP NNN - 0x1NNN\n"
<< "CALL NNN - 0x2NNN\n"
<< "IFN rX NN - 0x3XNN\n"
<< "IF rX NN - 0x4XNN\n"
<< "IFN rX rY - 0x5XY0\n"
<< "SET rX NN - 0x6XNN\n"
<< "ADD rX NN - 0x7XNN\n"
<< "SET rX rY - 0x8XY0\n"
<< "OR rX rY - 0x8XY1\n"
<< "AND rX rY - 0x8XY2\n"
<< "XOR rX rY - 0x8XY3\n"
<< "ADD rX rY - 0x8XY4\n"
<< "SUB rX rY - 0x8XY5\n"
<< "SHR rX rY - 0x8XY6\n"
<< "RSUB rX rY - 0x8XY7\n"
<< "SHL rX rY - 0x8XYE\n"
<< "IF rX rY - 0x9XY0\n"
<< "IDX NNN - 0xANNN\n"
<< "JMP0 NNN - 0xBNNN\n"
<< "RND rX NN - 0xCXNN\n"
<< "DRAW rX rY N - 0xDXYN\n"
<< "IFK rX - 0xEX9E\n"
<< "IFNK rX - 0xEXA1\n"
<< "GDEL rX - 0xFX07\n"
<< "WKEY rX - 0xFX0A\n"
<< "SDEL rX - 0xFX15\n"
<< "SAUD rX - 0xFX18\n"
<< "IADD rX - 0xFX1E\n"
<< "CHAR rX - 0xFX29\n"
<< "SEP rX - 0xFX33\n"
<< "STOR rX - 0xFX55\n"
<< "LOAD rX - 0xFX65\n"
<< "DATA NNNN - 0xNNNN\n"
<< "; comment with semicolon\n";
return 1;
}
} // anonymous namespace
int main(int argc, char* argv[]) {
if (argc != 2 || !strcmp(argv[1], "--help") || !strcmp(argv[1], "-h")) {
return help(argv[0]);
}
io::infile = ifstream(argv[1], ios::binary);
if (!io::infile) {
cerr << argv[0] << ": Unable to open " << argv[1] << "\n";
return 1;
}
stringstream ss;
ss << argv[1] << ".out";
string const outfile_name{ss.str()};
io::outfile = ofstream(outfile_name, ios::binary);
if (!io::outfile) {
cerr << argv[0] << ": Unable to open " << outfile_name << "\n";
return 1;
}
map<string const, function<void()>> const op2fun {
{"CLS", bind(op::OP, 0x00, 0xE0) },
{"RET", bind(op::OP, 0x00, 0xEE) },
{"JMP", bind(op::NNN, "JMP", 0x10)},
{"CALL", bind(op::NNN, "CALL", 0x20)},
{"IFN", bind(op::RV, "IFN", 0x30, 0x50, 0x00)},
{"IF", bind(op::RV, "IF", 0x40, 0x90, 0x00)},
{"SET", bind(op::RV, "SET", 0x60, 0x80, 0x00)},
{"ADD", bind(op::RV, "ADD", 0x70, 0x80, 0x04)},
{"OR", bind(op::RR, "OR", 0x80, 0x01)},
{"AND", bind(op::RR, "AND", 0x80, 0x02)},
{"XOR", bind(op::RR, "XOR", 0x80, 0x03)},
{"SUB", bind(op::RR, "SUB", 0x80, 0x05)},
{"SHR", bind(op::RR, "SHR", 0x80, 0x06)},
{"RSUB", bind(op::RR, "RSUB", 0x80, 0x07)},
{"SHL", bind(op::RR, "SHL", 0x80, 0x0E)},
{"IDX", bind(op::NNN, "IDX", 0xA0)},
{"JMP0", bind(op::NNN, "JMP0", 0xB0)},
{"RND", bind(op::RNN, "RND", 0xC0)},
{"DRAW", bind(op::RRN, "DRAW", 0xD0)},
{"IFK", bind(op::R, "IFK", 0xE0, 0x9E)},
{"IFNK", bind(op::R, "IFNK", 0xE0, 0xA1)},
{"GDEL", bind(op::R, "GDEL", 0xF0, 0x07)},
{"WKEY", bind(op::R, "WKEY", 0xF0, 0x0A)},
{"SDEL", bind(op::R, "SDEL", 0xF0, 0x15)},
{"SAUD", bind(op::R, "SAUD", 0xF0, 0x18)},
{"IADD", bind(op::R, "IADD", 0xF0, 0x1E)},
{"CHAR", bind(op::R, "CHAR", 0xF0, 0x29)},
{"SEP", bind(op::R, "SEP", 0xF0, 0x33)},
{"STOR", bind(op::R, "STOR", 0xF0, 0x55)},
{"LOAD", bind(op::R, "LOAD", 0xF0, 0x65)},
{"DATA", bind(op::DATA,"DATA")},
};
for (;;) {
// This constructor will exit when no more input is received
string tok{io::next_token()};
if (tok.at(0) == ';') {
getline(io::infile, tok);
continue;
}
auto const fun{op2fun.find(tok)};
if (fun == op2fun.end()) {
io::exit_err("Unknown command '" + tok + "'\n");
}
fun->second();
}
// Not reached
}
<commit_msg>Fix LOAD and STOR accidently having registers<commit_after>#include <iostream>
#include <fstream>
#include <sstream>
#include <map>
#include <functional>
using namespace std;
namespace {
namespace io {
enum token_type {
REG,
NN
};
ofstream outfile;
ifstream infile;
void exit_ok() {
infile.close();
outfile.close();
exit(0);
}
void exit_err(string const& error) {
cerr << error;
infile.close();
outfile.close();
exit(1);
}
void write_bins(char lhs, char rhs) {
outfile.write(static_cast<char*>(&lhs), 1);
outfile.write(static_cast<char*>(&rhs), 1);
if (outfile.fail()) {
exit_err("Error writing to disk");
}
}
int xtoi(string const& x) {
try {
return stoi(x, 0, 16);
} catch (exception &e) {
return -1;
}
}
string next_token() {
string value;
io::infile >> value;
if (!io::infile) {
io::exit_ok();
}
return value;
}
void tok2n(string const& name, string&& value, char& n) {
int target = xtoi(value);
if (0 > target || 0xF < target) {
exit_err("Error: " + name + " needs to be supplied with a value [0-F]\n");
}
n = target;
}
void tok2nn(string const& name, string&& value, char& nn) {
int target = xtoi(value);
if (0 > target || 0xFF < target) {
exit_err("Error: " + name + " needs to be supplied with a value [0-FF]\n");
}
nn = target;
}
void tok2nnn(string const& name, string&& value, char& lhs, char& rhs) {
int target = xtoi(value);
if (0 > target || 0xFFF < target) {
exit_err("Error: " + name + " needs to be supplied with a value [0-FFF]\n");
}
lhs = target >> 8;
rhs = target & 0xFF;
}
void tok2nnnn(string const& name, string&& value, char& lhs, char& rhs) {
int target = xtoi(value);
if (0 > target || 0xFFFF < target) {
exit_err("Error: " + name + " needs to be supplied with a value [0-FFFF]\n");
}
lhs = target >> 8;
rhs = target & 0xFF;
}
void tok2reg(string const& name, string&& value, char& reg) {
if (value.at(0) != 'r') {
exit_err("Error: " + name + " needs to be supplied with a register r[0-F]\n");
}
int target = xtoi(value.substr(1));
if (0 > target || 0xF < target) {
exit_err("Error: " + name + " needs to be supplied with a register r[0-F]\n");
}
reg = target;
}
void tok2reg_or_nn(string const& name, string&& value, char& reg_or_nn, io::token_type& t) {
if (value.at(0) == 'r') {
t = REG;
tok2reg(name, forward<string>(value), reg_or_nn);
} else {
t = NN;
tok2nn(name, forward<string>(value), reg_or_nn);
}
}
} // io
namespace op {
// These variables are shared between all below functions
char lhs;
char rhs;
char rhs2;
io::token_type t;
inline void OP(char lhs, char rhs) { io::write_bins(lhs, rhs); }
inline void R(string const& name, char lop, char rop) {
io::tok2reg(name, io::next_token(), lhs);
io::write_bins(lop + lhs, rop);
}
inline void RR(string const& name, char lop, char rop) {
io::tok2reg(name, io::next_token(), lhs);
io::tok2reg(name, io::next_token(), rhs);
io::write_bins(lop + lhs, (rhs << 4) + rop);
}
inline void N(string const& name, char lop, char rop) {
io::tok2n(name, io::next_token(), lhs);
io::write_bins(lop + lhs, rop);
}
inline void NNN(string const& name, char op) {
io::tok2nnn(name, io::next_token(), lhs, rhs);
io::write_bins(op + lhs, rhs);
}
inline void RNN(string const& name, char lop) {
io::tok2reg(name, io::next_token(), lhs);
io::tok2nn(name, io::next_token(), rhs);
io::write_bins(lop + lhs, rhs);
}
inline void RRN(string const& name, char lop) {
io::tok2reg(name, io::next_token(), lhs);
io::tok2reg(name, io::next_token(), rhs);
io::tok2n(name, io::next_token(), rhs2);
io::write_bins(lop + lhs, (rhs << 4) + rhs2);
}
inline void RV(string const& name, char nnop, char rlop, char rrop) {
io::tok2reg(name, io::next_token(), lhs);
io::tok2reg_or_nn(name, io::next_token(), rhs, t);
if (t == io::NN) { io::write_bins(nnop + lhs, rhs); }
else if (t == io::REG) { io::write_bins(rlop + lhs, (rhs << 4) + rrop); }
else { io::exit_err(name + ": Unknown type\n"); }
}
inline void DATA(string const& name) {
io::tok2nnnn(name, io::next_token(), lhs, rhs);
io::write_bins(lhs, rhs);
}
} // op
int help(string program_name) {
cerr
<< "Usage: " << program_name << " FILE\n\n"
<< "Available commands\n"
<< "CLS - 0x00E0\n"
<< "RET - 0x00EE\n"
<< "JMP NNN - 0x1NNN\n"
<< "CALL NNN - 0x2NNN\n"
<< "IFN rX NN - 0x3XNN\n"
<< "IF rX NN - 0x4XNN\n"
<< "IFN rX rY - 0x5XY0\n"
<< "SET rX NN - 0x6XNN\n"
<< "ADD rX NN - 0x7XNN\n"
<< "SET rX rY - 0x8XY0\n"
<< "OR rX rY - 0x8XY1\n"
<< "AND rX rY - 0x8XY2\n"
<< "XOR rX rY - 0x8XY3\n"
<< "ADD rX rY - 0x8XY4\n"
<< "SUB rX rY - 0x8XY5\n"
<< "SHR rX rY - 0x8XY6\n"
<< "RSUB rX rY - 0x8XY7\n"
<< "SHL rX rY - 0x8XYE\n"
<< "IF rX rY - 0x9XY0\n"
<< "IDX NNN - 0xANNN\n"
<< "JMP0 NNN - 0xBNNN\n"
<< "RND rX NN - 0xCXNN\n"
<< "DRAW rX rY N - 0xDXYN\n"
<< "IFK rX - 0xEX9E\n"
<< "IFNK rX - 0xEXA1\n"
<< "GDEL rX - 0xFX07\n"
<< "WKEY rX - 0xFX0A\n"
<< "SDEL rX - 0xFX15\n"
<< "SAUD rX - 0xFX18\n"
<< "IADD rX - 0xFX1E\n"
<< "CHAR rX - 0xFX29\n"
<< "SEP rX - 0xFX33\n"
<< "STOR N - 0xFX55\n"
<< "LOAD N - 0xFX65\n"
<< "DATA NNNN - 0xNNNN\n"
<< "; comment with semicolon\n";
return 1;
}
} // anonymous namespace
int main(int argc, char* argv[]) {
if (argc != 2 || !strcmp(argv[1], "--help") || !strcmp(argv[1], "-h")) {
return help(argv[0]);
}
io::infile = ifstream(argv[1], ios::binary);
if (!io::infile) {
cerr << argv[0] << ": Unable to open " << argv[1] << "\n";
return 1;
}
stringstream ss;
ss << argv[1] << ".out";
string const outfile_name{ss.str()};
io::outfile = ofstream(outfile_name, ios::binary);
if (!io::outfile) {
cerr << argv[0] << ": Unable to open " << outfile_name << "\n";
return 1;
}
map<string const, function<void()>> const op2fun {
{"CLS", bind(op::OP, 0x00, 0xE0) },
{"RET", bind(op::OP, 0x00, 0xEE) },
{"JMP", bind(op::NNN, "JMP", 0x10)},
{"CALL", bind(op::NNN, "CALL", 0x20)},
{"IFN", bind(op::RV, "IFN", 0x30, 0x50, 0x00)},
{"IF", bind(op::RV, "IF", 0x40, 0x90, 0x00)},
{"SET", bind(op::RV, "SET", 0x60, 0x80, 0x00)},
{"ADD", bind(op::RV, "ADD", 0x70, 0x80, 0x04)},
{"OR", bind(op::RR, "OR", 0x80, 0x01)},
{"AND", bind(op::RR, "AND", 0x80, 0x02)},
{"XOR", bind(op::RR, "XOR", 0x80, 0x03)},
{"SUB", bind(op::RR, "SUB", 0x80, 0x05)},
{"SHR", bind(op::RR, "SHR", 0x80, 0x06)},
{"RSUB", bind(op::RR, "RSUB", 0x80, 0x07)},
{"SHL", bind(op::RR, "SHL", 0x80, 0x0E)},
{"IDX", bind(op::NNN, "IDX", 0xA0)},
{"JMP0", bind(op::NNN, "JMP0", 0xB0)},
{"RND", bind(op::RNN, "RND", 0xC0)},
{"DRAW", bind(op::RRN, "DRAW", 0xD0)},
{"IFK", bind(op::R, "IFK", 0xE0, 0x9E)},
{"IFNK", bind(op::R, "IFNK", 0xE0, 0xA1)},
{"GDEL", bind(op::R, "GDEL", 0xF0, 0x07)},
{"WKEY", bind(op::R, "WKEY", 0xF0, 0x0A)},
{"SDEL", bind(op::R, "SDEL", 0xF0, 0x15)},
{"SAUD", bind(op::R, "SAUD", 0xF0, 0x18)},
{"IADD", bind(op::R, "IADD", 0xF0, 0x1E)},
{"CHAR", bind(op::R, "CHAR", 0xF0, 0x29)},
{"SEP", bind(op::R, "SEP", 0xF0, 0x33)},
{"STOR", bind(op::N, "STOR", 0xF0, 0x55)},
{"LOAD", bind(op::N, "LOAD", 0xF0, 0x65)},
{"DATA", bind(op::DATA,"DATA")},
};
for (;;) {
// This constructor will exit when no more input is received
string tok{io::next_token()};
if (tok.at(0) == ';') {
getline(io::infile, tok);
continue;
}
auto const fun{op2fun.find(tok)};
if (fun == op2fun.end()) {
io::exit_err("Unknown command '" + tok + "'\n");
}
fun->second();
}
// Not reached
}
<|endoftext|> |
<commit_before><commit_msg>Applied patch from HARMONY-4705 [drlvm][jni] JNI transition uses ineffective TLS get<commit_after><|endoftext|> |
<commit_before>#include "simplesp.h"
using namespace sp;
int main(){
Mem2<Col3> src;
Mem2<Byte> gry;
{
SP_ASSERT(loadBMP(src, SP_DATA_DIR "/image/Lenna.bmp"));
saveBMP(src, "color.bmp");
cnvImg(gry, src);
saveBMP(gry, "gray.bmp");
}
// gaussian
{
Mem2<Byte> dst;
gaussianFilter(dst, gry, 2.0);
saveBMP(dst, "gaussian_g.bmp");
}
{
Mem2<Col3> dst;
gaussianFilter<Col3, Byte>(dst, src, 2.0);
saveBMP(dst, "gaussian_c.bmp");
}
// bilateral
{
Mem2<Byte> dst;
bilateralFilter(dst, gry, 2.0, 0.2 * SP_BYTEMAX);
saveBMP(dst, "bilateral_g.bmp");
}
{
Mem2<Col3> dst;
bilateralFilter<Col3, Byte>(dst, src, 2.0, 0.2 * SP_BYTEMAX);
saveBMP(dst, "bilateral_c.bmp");
}
// guided filter
{
Mem2<Byte> dst;
guidedFilter(dst, gry, 11, square(0.2 * SP_BYTEMAX));
saveBMP(dst, "guidedfilter_g.bmp");
}
{
Mem2<Col3> dst;
guidedFilter(dst, src, 11, square(0.2 * SP_BYTEMAX));
saveBMP(dst, "guidedfilter_c.bmp");
}
{
Mem2<Byte> test;
SP_ASSERT(loadBMP(test, "test.bmp"));
for (int i = 0; i < test.size(); i++) {
test[i] = (test[i] < 255) ? 0 : test[i];
}
Guide3 guide(src, 11, square(0.1 * SP_BYTEMAX));
Mem2<Byte> dst;
guidedFilter(dst, test, guide, 11);
saveBMP(dst, "aaa.bmp");
saveBMP(test, "test.bmp");
}
// sobel
{
Mem2<float> dstX, dstY;
sobelFilterX(dstX, gry);
sobelFilterY(dstY, gry);
Mem2<Byte> tmpX, tmpY;
cnvMem(tmpX, dstX, 0.5, -255);
cnvMem(tmpY, dstY, 0.5, -255);
saveBMP(tmpX, "sobelX.bmp");
saveBMP(tmpY, "sobelY.bmp");
}
// canny
{
Mem2<Col3> tmp;
gaussianFilter3x3<Col3, Byte>(tmp, src);
Mem2<Byte> dst;
canny(dst, tmp, 5, 10);
saveBMP(dst, "canny.bmp");
}
return 0;
}<commit_msg>delete debug code<commit_after>#include "simplesp.h"
using namespace sp;
int main(){
Mem2<Col3> src;
Mem2<Byte> gry;
{
SP_ASSERT(loadBMP(src, SP_DATA_DIR "/image/Lenna.bmp"));
saveBMP(src, "color.bmp");
cnvImg(gry, src);
saveBMP(gry, "gray.bmp");
}
// gaussian
{
Mem2<Byte> dst;
gaussianFilter(dst, gry, 2.0);
saveBMP(dst, "gaussian_g.bmp");
}
{
Mem2<Col3> dst;
gaussianFilter<Col3, Byte>(dst, src, 2.0);
saveBMP(dst, "gaussian_c.bmp");
}
// bilateral
{
Mem2<Byte> dst;
bilateralFilter(dst, gry, 2.0, 0.2 * SP_BYTEMAX);
saveBMP(dst, "bilateral_g.bmp");
}
{
Mem2<Col3> dst;
bilateralFilter<Col3, Byte>(dst, src, 2.0, 0.2 * SP_BYTEMAX);
saveBMP(dst, "bilateral_c.bmp");
}
// guided filter
{
Mem2<Byte> dst;
guidedFilter(dst, gry, 11, square(0.2 * SP_BYTEMAX));
saveBMP(dst, "guidedfilter_g.bmp");
}
{
Mem2<Col3> dst;
guidedFilter(dst, src, 11, square(0.2 * SP_BYTEMAX));
saveBMP(dst, "guidedfilter_c.bmp");
}
// sobel
{
Mem2<float> dstX, dstY;
sobelFilterX(dstX, gry);
sobelFilterY(dstY, gry);
Mem2<Byte> tmpX, tmpY;
cnvMem(tmpX, dstX, 0.5, -255);
cnvMem(tmpY, dstY, 0.5, -255);
saveBMP(tmpX, "sobelX.bmp");
saveBMP(tmpY, "sobelY.bmp");
}
// canny
{
Mem2<Col3> tmp;
gaussianFilter3x3<Col3, Byte>(tmp, src);
Mem2<Byte> dst;
canny(dst, tmp, 5, 10);
saveBMP(dst, "canny.bmp");
}
return 0;
}<|endoftext|> |
<commit_before>//
// Created by Danni on 09.06.15.
//
#include "TweeCompiler.h"
#include "ZAssemblyGenerator.h"
#include "exceptions.h"
#include <sstream>
#include <iostream>
#include <Passage/Body/Link.h>
#include <Passage/Body/Text.h>
#include <Passage/Body/Newline.h>
#include <Passage/Body/Expressions/Variable.h>
#include <Passage/Body/Macros/IfMacro.h>
#include <Passage/Body/Macros/ElseIfMacro.h>
#include <Passage/Body/Macros/ElseMacro.h>
#include <Passage/Body/Macros/EndIfMacro.h>
#include <plog/Log.h>
using namespace std;
static const string PASSAGE_GLOB = "PASSAGE_PTR",
JUMP_TABLE_LABEL = "JUMP_TABLE_START",
JUMP_TABLE_END_LABEL = "JUMP_TABLE_END",
MAIN_ROUTINE = "main",
USER_INPUT = "USER_INPUT",
READ_BEGIN = "READ_BEGIN",
IF_JUMP_LABEL = "IFJUMP",
IF_JUMP_END_LABEL = "IFJUMPEND";
static const unsigned int ZSCII_NUM_OFFSET = 49;
//#define ZAS_DEBUG
void maskString(std::string& string) {
std::replace( string.begin(), string.end(), ' ', '_');
}
string routineNameForPassageName(std::string passageName) {
stringstream ss;
maskString(passageName);
ss << "R_" << passageName;
return ss.str();
}
string routineNameForPassage(Passage& passage) {
return routineNameForPassageName(passage.getHead().getName());
}
string labelForPassage(Passage& passage) {
stringstream ss;
string passageName = passage.getHead().getName();
maskString(passageName);
ss << "L_" << passageName;
return ss.str();
}
void TweeCompiler::compile(TweeFile &tweeFile, std::ostream &out) {
ZAssemblyGenerator assgen(out);
vector<Passage> passages = tweeFile.getPassages();
int ifDepth = -1;
int ifJumpLabelID = 0;
int ifEndJumpLabelID = 0;
int possibleIfDepth = 255;
std::array<std::string,255> nextJumpLabels;
std::array<std::string,255> endJumpLabels;
std::array<int,255> precedingIfMacros;
for(auto precedingIfMacro = precedingIfMacros.begin(); precedingIfMacro != precedingIfMacros.end(); ++precedingIfMacro) {
LOG_DEBUG << precedingIfMacro;
}
{
int i = 0;
for (auto passage = passages.begin(); passage != passages.end(); ++passage) {
passageName2id[passage->getHead().getName()] = i;
i++;
}
}
// main routine
{
// globals
assgen.addGlobal(PASSAGE_GLOB)
.addGlobal(USER_INPUT);
// call start routine first
assgen.addRoutine(MAIN_ROUTINE)
.markStart()
.call(routineNameForPassageName("start"), PASSAGE_GLOB)
.addLabel(JUMP_TABLE_LABEL);
for(auto passage = passages.begin(); passage != passages.end(); ++passage) {
int passageId = passageName2id.at(passage->getHead().getName());
assgen.jumpEquals(ZAssemblyGenerator::makeArgs({std::to_string(passageId), PASSAGE_GLOB}), labelForPassage(*passage));
}
for(auto passage = passages.begin(); passage != passages.end(); ++passage) {
assgen.addLabel(labelForPassage(*passage))
.call(routineNameForPassage(*passage), PASSAGE_GLOB)
.jump(JUMP_TABLE_LABEL);
}
assgen.addLabel(JUMP_TABLE_END_LABEL);
assgen.quit();
}
// passage routines
{
for(auto passage = passages.begin(); passage != passages.end(); ++passage) {
const vector<unique_ptr<BodyPart>>& bodyParts = passage->getBody().getBodyParts();
// declare passage routine
assgen.addRoutine(routineNameForPassage(*passage));
assgen.println(string("***** ") + passage->getHead().getName() + string(" *****"));
// print passage contents
for(auto it = bodyParts.begin(); it != bodyParts.end(); it++) {
BodyPart* bodyPart = it->get();
if(Text* text = dynamic_cast<Text*>(bodyPart)) {
assgen.print(text->getContent());
} else if(Newline* text = dynamic_cast<Newline*>(bodyPart)) {
assgen.newline();
} else if (Variable * variable = dynamic_cast<Variable *>(bodyPart)) {
assgen.variable(variable->getName());
} else if (Macro * macro = dynamic_cast<Macro *>(bodyPart)) {
LOG_DEBUG << "Found a Macro";
if (IfMacro * ifmacro = dynamic_cast<IfMacro *>(macro)) {
//depth++,
//check preceding ifmacro
//set label for jump to after if block (else, else if, endif)
//evaluate expression
//make jump to set label if expression is true
ifDepth++;
if (precedingIfMacros[ifDepth] != 0) {
std::string errorMessage = "unexpected IfMacro after ";
switch(precedingIfMacros[ifDepth]) {
case 1:
errorMessage += "another if IfMacro: ";
errorMessage += "check your code for an <<[ ]*if.*>> not followed by an <<endif>> before another <<[ ]*if.*>>";
break;
case 2:
errorMessage += "an ElseIfMacro: ";
errorMessage += "check your code for an <<[ ]*else[ ]*if.*>> not followed by an <<endif>> before another <<[ ]*if.*>>";
break;
case 3:
errorMessage += "an ElseIfMacro: ";
errorMessage += "check your code for an <<[ ]*else[ ]*>> not followed by an <<endif>> before another <<[ ]*if.*>>";
break;
}
cerr << errorMessage;
throw TweeDocumentException();
}
nextJumpLabels[ifDepth] = IF_JUMP_LABEL + std::to_string(++ifJumpLabelID);
endJumpLabels[ifDepth] = IF_JUMP_END_LABEL + std::to_string(++ifEndJumpLabelID);
//TODO: evaluate expression IfMacro
std::string ifExprVal = ifmacro->getExpression()->to_string();
LOG_DEBUG << ifExprVal;
if(ifExprVal.compare("Const: 1")) {
assgen.push("1");
} else if (ifExprVal.compare("Const: 0")) {
assgen.push("0");
}
assgen.jumpNotEquals(ZAssemblyGenerator::makeArgs({"sp", "0"}) , nextJumpLabels[ifDepth]);
precedingIfMacros[ifDepth] = 1;
} else if (ElseIfMacro * elseifmacro = dynamic_cast<ElseIfMacro *>(bodyPart)) {
//check preceding ifmacro
//save label for jump to after if/else if block , in this case else
//make jump to set label if expression is true
//set label for jump to after if block (else, else if, endif)
//evaluate expression
//make jump to set label if expression is true
//else part
if (precedingIfMacros[ifDepth] != 1 || precedingIfMacros[ifDepth] != 2) {
std::string errorMessage = "unexpected ElseIfMacro ";
switch(precedingIfMacros[ifDepth]) {
case 0:
errorMessage += "without a starting ifMacro: ";
errorMessage += "check your code for an <<[ ]*else[ ]*if.*>> without an associated <<if.*>>";
break;
case 3:
errorMessage += "after an ElseMacro";
errorMessage += "check your code for an <<[ ]*else[ ]*if.*>> after an <<[ ]*else[ ]*>>";
break;
}
cerr << errorMessage;
throw TweeDocumentException();
}
assgen.jump(endJumpLabels[ifDepth]);
assgen.addLabel(nextJumpLabels[ifDepth]);
nextJumpLabels[ifDepth] = IF_JUMP_LABEL + std::to_string(++ifJumpLabelID);
//TODO: evaluate expression ElseIfMacro
std::string ifExprVal = elseifmacro->getExpression()->to_string();
LOG_DEBUG << ifExprVal;
if(ifExprVal.compare("Const: 1")) {
assgen.push("1");
} else if (ifExprVal.compare("Const: 0")) {
assgen.push("0");
}
assgen.jumpNotEquals(ZAssemblyGenerator::makeArgs({"sp", "0"}) , nextJumpLabels[ifDepth]);
precedingIfMacros[ifDepth] = 2;
} else if (ElseMacro * elsemacro = dynamic_cast<ElseMacro *>(bodyPart)) {
//check preceding ifmacro
//save label for jump to after if/else if block , in this case else
//make jump to set label if expression is true
if (precedingIfMacros[ifDepth] != 1 || precedingIfMacros[ifDepth] != 2) {
std::string errorMessage = "unexpected ElseMacro ";
switch(precedingIfMacros[ifDepth]) {
case 0:
errorMessage += "without a starting ifMacro: ";
errorMessage += "check your code for an <<[ ]*else[ ]*>> without an associated <<if.*>>";
break;
case 3:
errorMessage += "after an ElseMacro";
errorMessage += "check your code for an <<[ ]*else[ ]*>> after an <<[ ]*else[ ]*>>";
break;
}
cerr << errorMessage;
throw TweeDocumentException();
}
assgen.jump(endJumpLabels[ifDepth]);
assgen.addLabel(nextJumpLabels[ifDepth]);
precedingIfMacros[ifDepth] = 3;
} else if (EndIfMacro * endifemacro = dynamic_cast<EndIfMacro *>(bodyPart)) {
//check preceding ifmacro
//make jump to set label if expression is trueJumpLabels[ifDepth];
//decrease depth
if (precedingIfMacros[ifDepth] == 0) {
std::string errorMessage = "unexpected EndIfMacro without an if macro, look for an orphaned <<[ ]*endif[ ]*>> ";
cerr << errorMessage;
throw TweeDocumentException();
}
assgen.addLabel(endJumpLabels[ifDepth]);
ifDepth--;
precedingIfMacros[ifDepth] = 0;
}
}
}
assgen.newline();
vector<Link*> links;
// get links from passage
for(auto it = bodyParts.begin(); it != bodyParts.end(); ++it)
{
BodyPart* bodyPart = it->get();
if(Link* link = dynamic_cast<Link*>(bodyPart)) {
links.push_back(link);
}
}
// present choices to user
assgen.println("Select one of the following options");
int i = 1;
for (auto link = links.begin(); link != links.end(); link++) {
assgen.println(string(" ") + to_string(i) + string(") ") + (*link)->getTarget() );
i++;
}
assgen.addLabel(READ_BEGIN);
// read user input
assgen.read_char(USER_INPUT);
// jump to according link selection
i = 0;
for (auto link = links.begin(); link != links.end(); link++) {
string label = string("L") + to_string(i);
assgen.jumpEquals(ZAssemblyGenerator::makeArgs({to_string(ZSCII_NUM_OFFSET + i), USER_INPUT}), label);
i++;
}
// no proper selection was made
assgen.jump(READ_BEGIN);
i = 0;
for (auto link = links.begin(); link != links.end(); link++) {
string label = string("L") + to_string(i);
try {
int targetPassageId = passageName2id.at((*link)->getTarget());
assgen.addLabel(label);
#ifdef ZAS_DEBUG
assgen.print(string("selected ") + to_string(targetPassageId) );
#endif
assgen.ret(to_string(targetPassageId));
} catch (const out_of_range &err) {
cerr << "could not find passage for link target \"" << (*link)->getTarget() << "\"" << endl;
throw TweeDocumentException();
}
i++;
}
}
}
}
<commit_msg>took ifMacro validity checking out for the time<commit_after>//
// Created by Danni on 09.06.15.
//
#include "TweeCompiler.h"
#include "ZAssemblyGenerator.h"
#include "exceptions.h"
#include <sstream>
#include <iostream>
#include <Passage/Body/Link.h>
#include <Passage/Body/Text.h>
#include <Passage/Body/Newline.h>
#include <Passage/Body/Expressions/Variable.h>
#include <Passage/Body/Macros/IfMacro.h>
#include <Passage/Body/Macros/ElseIfMacro.h>
#include <Passage/Body/Macros/ElseMacro.h>
#include <Passage/Body/Macros/EndIfMacro.h>
#include <plog/Log.h>
using namespace std;
static const string PASSAGE_GLOB = "PASSAGE_PTR",
JUMP_TABLE_LABEL = "JUMP_TABLE_START",
JUMP_TABLE_END_LABEL = "JUMP_TABLE_END",
MAIN_ROUTINE = "main",
USER_INPUT = "USER_INPUT",
READ_BEGIN = "READ_BEGIN",
IF_JUMP_LABEL = "IFJUMP",
IF_JUMP_END_LABEL = "IFJUMPEND";
static const unsigned int ZSCII_NUM_OFFSET = 49;
//#define ZAS_DEBUG
void maskString(std::string& string) {
std::replace( string.begin(), string.end(), ' ', '_');
}
string routineNameForPassageName(std::string passageName) {
stringstream ss;
maskString(passageName);
ss << "R_" << passageName;
return ss.str();
}
string routineNameForPassage(Passage& passage) {
return routineNameForPassageName(passage.getHead().getName());
}
string labelForPassage(Passage& passage) {
stringstream ss;
string passageName = passage.getHead().getName();
maskString(passageName);
ss << "L_" << passageName;
return ss.str();
}
void TweeCompiler::compile(TweeFile &tweeFile, std::ostream &out) {
ZAssemblyGenerator assgen(out);
vector<Passage> passages = tweeFile.getPassages();
int ifDepth = -1;
int ifJumpLabelID = 0;
int ifEndJumpLabelID = 0;
int possibleIfDepth = 255;
std::array<std::string,12> nextJumpLabels;
std::array<std::string,12> endJumpLabels;
std::array<int,12> precedingIfMacros= {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
for(auto precedingIfMacro = precedingIfMacros.begin(); precedingIfMacro != precedingIfMacros.end(); ++precedingIfMacro) {
LOG_DEBUG << precedingIfMacro;
}
{
int i = 0;
for (auto passage = passages.begin(); passage != passages.end(); ++passage) {
passageName2id[passage->getHead().getName()] = i;
i++;
}
}
// main routine
{
// globals
assgen.addGlobal(PASSAGE_GLOB)
.addGlobal(USER_INPUT);
// call start routine first
assgen.addRoutine(MAIN_ROUTINE)
.markStart()
.call(routineNameForPassageName("start"), PASSAGE_GLOB)
.addLabel(JUMP_TABLE_LABEL);
for(auto passage = passages.begin(); passage != passages.end(); ++passage) {
int passageId = passageName2id.at(passage->getHead().getName());
assgen.jumpEquals(ZAssemblyGenerator::makeArgs({std::to_string(passageId), PASSAGE_GLOB}), labelForPassage(*passage));
}
for(auto passage = passages.begin(); passage != passages.end(); ++passage) {
assgen.addLabel(labelForPassage(*passage))
.call(routineNameForPassage(*passage), PASSAGE_GLOB)
.jump(JUMP_TABLE_LABEL);
}
assgen.addLabel(JUMP_TABLE_END_LABEL);
assgen.quit();
}
// passage routines
{
for(auto passage = passages.begin(); passage != passages.end(); ++passage) {
const vector<unique_ptr<BodyPart>>& bodyParts = passage->getBody().getBodyParts();
// declare passage routine
assgen.addRoutine(routineNameForPassage(*passage));
assgen.println(string("***** ") + passage->getHead().getName() + string(" *****"));
// print passage contents
for(auto it = bodyParts.begin(); it != bodyParts.end(); it++) {
BodyPart* bodyPart = it->get();
if(Text* text = dynamic_cast<Text*>(bodyPart)) {
assgen.print(text->getContent());
} else if(Newline* text = dynamic_cast<Newline*>(bodyPart)) {
assgen.newline();
} else if (Variable * variable = dynamic_cast<Variable *>(bodyPart)) {
assgen.variable(variable->getName());
} else if (Macro * macro = dynamic_cast<Macro *>(bodyPart)) {
LOG_DEBUG << "Found a Macro";
if (IfMacro * ifmacro = dynamic_cast<IfMacro *>(macro)) {
//depth++,
//check preceding ifmacro
//set label for jump to after if block (else, else if, endif)
//evaluate expression
//make jump to set label if expression is true
ifDepth++;
/*
if (precedingIfMacros[ifDepth] != 0) {
std::string errorMessage = "unexpected IfMacro after ";
switch(precedingIfMacros[ifDepth]) {
case 1:
errorMessage += "another if IfMacro: ";
errorMessage += "check your code for an <<[ ]*if.*>> not followed by an <<endif>> before another <<[ ]*if.*>>";
break;
case 2:
errorMessage += "an ElseIfMacro: ";
errorMessage += "check your code for an <<[ ]*else[ ]*if.*>> not followed by an <<endif>> before another <<[ ]*if.*>>";
break;
case 3:
errorMessage += "an ElseIfMacro: ";
errorMessage += "check your code for an <<[ ]*else[ ]*>> not followed by an <<endif>> before another <<[ ]*if.*>>";
break;
}
LOG_ERROR << errorMessage;
throw TweeDocumentException();
}
*/
nextJumpLabels[ifDepth] = IF_JUMP_LABEL + std::to_string(++ifJumpLabelID);
endJumpLabels[ifDepth] = IF_JUMP_END_LABEL + std::to_string(++ifEndJumpLabelID);
//TODO: evaluate expression IfMacro
std::string ifExprVal = ifmacro->getExpression()->to_string();
LOG_DEBUG << ifExprVal;
if(ifExprVal.compare("Const: 1")) {
assgen.push("1");
} else if (ifExprVal.compare("Const: 0")) {
assgen.push("0");
}
assgen.jumpNotEquals(ZAssemblyGenerator::makeArgs({"sp", "0"}) , nextJumpLabels[ifDepth]);
precedingIfMacros[ifDepth] = 1;
} else if (ElseIfMacro * elseifmacro = dynamic_cast<ElseIfMacro *>(bodyPart)) {
//check preceding ifmacro
//save label for jump to after if/else if block , in this case else
//make jump to set label if expression is true
//set label for jump to after if block (else, else if, endif)
//evaluate expression
//make jump to set label if expression is true
//else part
/*
* if (precedingIfMacros[ifDepth] != 1 || precedingIfMacros[ifDepth] != 2){
std::string errorMessage = "unexpected ElseIfMacro ";
switch(precedingIfMacros[ifDepth]) {
case 0:
errorMessage += "without a starting ifMacro: ";
errorMessage += "check your code for an <<[ ]*else[ ]*if.*>> without an associated <<if.*>>";
break;
case 3:
errorMessage += "after an ElseMacro";
errorMessage += "check your code for an <<[ ]*else[ ]*if.*>> after an <<[ ]*else[ ]*>>";
break;
}
LOG_ERROR << errorMessage;
throw TweeDocumentException();
}
*/
assgen.jump(endJumpLabels[ifDepth]);
assgen.addLabel(nextJumpLabels[ifDepth]);
nextJumpLabels[ifDepth] = IF_JUMP_LABEL + std::to_string(++ifJumpLabelID);
//TODO: evaluate expression ElseIfMacro
std::string ifExprVal = elseifmacro->getExpression()->to_string();
LOG_DEBUG << ifExprVal;
if(ifExprVal.compare("Const: 1")) {
assgen.push("1");
} else if (ifExprVal.compare("Const: 0")) {
assgen.push("0");
}
assgen.jumpNotEquals(ZAssemblyGenerator::makeArgs({"sp", "0"}) , nextJumpLabels[ifDepth]);
precedingIfMacros[ifDepth] = 2;
} else if (ElseMacro * elsemacro = dynamic_cast<ElseMacro *>(bodyPart)) {
//check preceding ifmacro
//save label for jump to after if/else if block , in this case else
//make jump to set label if expression is true
/*
if (precedingIfMacros[ifDepth] != 1 || precedingIfMacros[ifDepth] != 2) {
std::string errorMessage = "unexpected ElseMacro ";
switch(precedingIfMacros[ifDepth]) {
case 0:
errorMessage += "without a starting ifMacro: ";
errorMessage += "check your code for an <<[ ]*else[ ]*>> without an associated <<if.*>>";
break;
case 3:
errorMessage += "after an ElseMacro";
errorMessage += "check your code for an <<[ ]*else[ ]*>> after an <<[ ]*else[ ]*>>";
break;
}
LOG_ERROR << errorMessage;
throw TweeDocumentException();
}
*/
assgen.jump(endJumpLabels[ifDepth]);
assgen.addLabel(nextJumpLabels[ifDepth]);
precedingIfMacros[ifDepth] = 3;
} else if (EndIfMacro * endifemacro = dynamic_cast<EndIfMacro *>(bodyPart)) {
//check preceding ifmacro
//make jump to set label if expression is trueJumpLabels[ifDepth];
//decrease depth
/*
if (precedingIfMacros[ifDepth] == 0) {
std::string errorMessage = "unexpected EndIfMacro without an if macro, look for an orphaned <<[ ]*endif[ ]*>> ";
LOG_ERROR << errorMessage;
throw TweeDocumentException();
} else {
std::string errorMessage = "unexpected EndIfMacro without an if macro, look for an orphaned <<[ ]*endif[ ]*>> ";
LOG_ERROR << errorMessage;
}
*/
assgen.addLabel(endJumpLabels[ifDepth]);
ifDepth--;
precedingIfMacros[ifDepth] = 0;
}
}
}
assgen.newline();
vector<Link*> links;
// get links from passage
for(auto it = bodyParts.begin(); it != bodyParts.end(); ++it)
{
BodyPart* bodyPart = it->get();
if(Link* link = dynamic_cast<Link*>(bodyPart)) {
links.push_back(link);
}
}
// present choices to user
assgen.println("Select one of the following options");
int i = 1;
for (auto link = links.begin(); link != links.end(); link++) {
assgen.println(string(" ") + to_string(i) + string(") ") + (*link)->getTarget() );
i++;
}
assgen.addLabel(READ_BEGIN);
// read user input
assgen.read_char(USER_INPUT);
// jump to according link selection
i = 0;
for (auto link = links.begin(); link != links.end(); link++) {
string label = string("L") + to_string(i);
assgen.jumpEquals(ZAssemblyGenerator::makeArgs({to_string(ZSCII_NUM_OFFSET + i), USER_INPUT}), label);
i++;
}
// no proper selection was made
assgen.jump(READ_BEGIN);
i = 0;
for (auto link = links.begin(); link != links.end(); link++) {
string label = string("L") + to_string(i);
try {
int targetPassageId = passageName2id.at((*link)->getTarget());
assgen.addLabel(label);
#ifdef ZAS_DEBUG
assgen.print(string("selected ") + to_string(targetPassageId) );
#endif
assgen.ret(to_string(targetPassageId));
} catch (const out_of_range &err) {
cerr << "could not find passage for link target \"" << (*link)->getTarget() << "\"" << endl;
throw TweeDocumentException();
}
i++;
}
}
}
}
<|endoftext|> |
<commit_before>// Disable some warnings which are caused with CUDA headers
#pragma warning(disable: 4201 4408 4100)
#include <iostream>
#include <cvconfig.h>
#include "opencv2/core/core.hpp"
#include <opencv2/gpu/gpu.hpp>
#if !defined(HAVE_CUDA) || !defined(HAVE_TBB)
int main()
{
#if !defined(HAVE_CUDA)
cout << "CUDA support is required (CMake key 'WITH_CUDA' must be true).\n";
#endif
#if !defined(HAVE_TBB)
cout << "TBB support is required (CMake key 'WITH_TBB' must be true).\n";
#endif
return 0;
}
#else
#include <cuda.h>
#include <cuda_runtime.h>
#include "opencv2/core/internal.hpp" // For TBB wrappers
using namespace std;
using namespace cv;
using namespace cv::gpu;
void cuSafeCall(int code);
struct Worker { void operator()(int device_id) const; };
void destroy();
// Each GPU is associated with its own context
CUcontext contexts[2];
// Auxiliary variable, stores previusly used context
CUcontext prev_context;
int main()
{
if (getCudaEnabledDeviceCount() < 2)
{
cout << "Two or more GPUs are required\n";
return -1;
}
// Save the default context
cuSafeCall(cuCtxAttach(&contexts[0], 0));
cuSafeCall(cuCtxDetach(contexts[0]));
// Create new context for the second GPU
CUdevice device;
cuSafeCall(cuDeviceGet(&device, 1));
cuSafeCall(cuCtxCreate(&contexts[1], 0, device));
// Restore the first GPU context
cuSafeCall(cuCtxPopCurrent(&prev_context));
// Run
int devices[] = {0, 1};
parallel_do(devices, devices + 2, Worker());
// Destroy context of the second GPU
destroy();
return 0;
}
void Worker::operator()(int device_id) const
{
cout << device_id << endl;
}
void cuSafeCall(int code)
{
if (code != CUDA_SUCCESS)
{
cout << "CUDA driver API error: code " << code
<< ", file " << __FILE__
<< ", line " << __LINE__ << endl;
destroy();
exit(-1);
}
}
void destroy()
{
cuCtxDestroy(contexts[1]);
}
#endif<commit_msg>finished multi_gpu sample<commit_after>// Disable some warnings which are caused with CUDA headers
#pragma warning(disable: 4201 4408 4100)
#include <iostream>
#include <cvconfig.h>
#include "opencv2/core/core.hpp"
#include <opencv2/gpu/gpu.hpp>
#if !defined(HAVE_CUDA) || !defined(HAVE_TBB)
int main()
{
#if !defined(HAVE_CUDA)
cout << "CUDA support is required (CMake key 'WITH_CUDA' must be true).\n";
#endif
#if !defined(HAVE_TBB)
cout << "TBB support is required (CMake key 'WITH_TBB' must be true).\n";
#endif
return 0;
}
#else
#include <cuda.h>
#include <cuda_runtime.h>
#include "opencv2/core/internal.hpp" // For TBB wrappers
using namespace std;
using namespace cv;
using namespace cv::gpu;
struct Worker { void operator()(int device_id) const; };
void destroyContexts();
#define cuSafeCall(code) if (code != CUDA_SUCCESS) { \
cout << "CUDA driver API error: code " << code \
<< ", file " << __FILE__ << ", line " << __LINE__ << endl; \
destroyContexts(); \
exit(-1); \
}
// Each GPU is associated with its own context
CUcontext contexts[2];
int main()
{
if (getCudaEnabledDeviceCount() < 2)
{
cout << "Two or more GPUs are required\n";
return -1;
}
cuSafeCall(cuInit(0));
// Create context for the first GPU
CUdevice device;
cuSafeCall(cuDeviceGet(&device, 0));
cuSafeCall(cuCtxCreate(&contexts[0], 0, device));
CUcontext prev_context;
cuCtxPopCurrent(&prev_context);
// Create context for the second GPU
cuSafeCall(cuDeviceGet(&device, 1));
cuSafeCall(cuCtxCreate(&contexts[1], 1, device));
cuCtxPopCurrent(&prev_context);
// Execute calculation in two threads using two GPUs
int devices[] = {0, 1};
parallel_do(devices, devices + 2, Worker());
destroyContexts();
return 0;
}
void Worker::operator()(int device_id) const
{
cuCtxPushCurrent(contexts[device_id]);
// Generate random matrix
Mat src(1000, 1000, CV_32F);
RNG rng(0);
rng.fill(src, RNG::UNIFORM, 0, 1);
// Upload data on GPU
GpuMat d_src(src);
GpuMat d_dst;
transpose(d_src, d_dst);
// Deallocate here, otherwise deallocation will be performed
// after context is extracted from the stack
d_src.release();
d_dst.release();
CUcontext prev_context;
cuCtxPopCurrent(&prev_context);
cout << "Device " << device_id << " finished\n";
}
void destroyContexts()
{
cuCtxDestroy(contexts[0]);
cuCtxDestroy(contexts[1]);
}
#endif<|endoftext|> |
<commit_before>// Stolen from libLAS' endian.hpp
/******************************************************************************
* $Id$
*
* Project: libLAS - http://liblas.org - A BSD library for LAS format data.
* Purpose: Endian macros
* Author: Mateusz Loskot, [email protected]
*
* This file has been stolen from <boost/endian.hpp> and
* modified for libLAS purposes.
*
* (C) Copyright Mateusz Loskot 2007, [email protected]
* (C) Copyright Caleb Epstein 2005
* (C) Copyright John Maddock 2006
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*
* Revision History
* 06 Feb 2006 - Initial Revision
* 09 Nov 2006 - fixed variant and version bits for v4 guids
* 13 Nov 2006 - added serialization
* 17 Nov 2006 - added name-based guid creation
* 20 Nov 2006 - add fixes for gcc (from Tim Blechmann)
* 07 Mar 2007 - converted to header only
* 20 Jan 2008 - removed dependency of Boost and modified for libLAS (by Mateusz Loskot)
******************************************************************************
*
* Copyright (c) 1997
* Silicon Graphics Computer Systems, Inc.
*
* Permission to use, copy, modify, distribute and sell this software
* and its documentation for any purpose is hereby granted without fee,
* provided that the above copyright notice appear in all copies and
* that both that copyright notice and this permission notice appear
* in supporting documentation. Silicon Graphics makes no
* representations about the suitability of this software for any
* purpose. It is provided "as is" without express or implied warranty.
*
*
*
* Copyright notice reproduced from <boost/detail/limits.hpp>, from
* which this code was originally taken.
*
* Modified by Caleb Epstein to use <endian.h> with GNU libc and to
* defined the BOOST_ENDIAN macro.
****************************************************************************/
#ifndef INCLUDED_DRIVER_OCI_ENDIAN_HPP
#define INCLUDED_DRIVER_OCI_ENDIAN_HPP
# define SWAP_BE_TO_LE(p) \
do { \
char* first = static_cast<char*>(static_cast<void*>(&p)); \
char* last = first + sizeof(p) - 1; \
for(; first < last; ++first, --last) { \
char const x = *last; \
*last = *first; \
*first = x; \
}} while(false)
# define SWAP_BE_TO_LE_N(p, n) \
do { \
char* first = static_cast<char*>(static_cast<void*>(&p)); \
char* last = first + n - 1; \
for(; first < last; ++first, --last) { \
char const x = *last; \
*last = *first; \
*first = x; \
}} while(false)
#endif
<commit_msg>add SWAP_LE_TO_BE method. Note that this is exactly the same code as SWAP_BE_TO_LE which is merely just a byte swapping function. It is valuable to read which way we're actually going in source code, however<commit_after>// Stolen from libLAS' endian.hpp
/******************************************************************************
* $Id$
*
* Project: libLAS - http://liblas.org - A BSD library for LAS format data.
* Purpose: Endian macros
* Author: Mateusz Loskot, [email protected]
*
* This file has been stolen from <boost/endian.hpp> and
* modified for libLAS purposes.
*
* (C) Copyright Mateusz Loskot 2007, [email protected]
* (C) Copyright Caleb Epstein 2005
* (C) Copyright John Maddock 2006
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*
* Revision History
* 06 Feb 2006 - Initial Revision
* 09 Nov 2006 - fixed variant and version bits for v4 guids
* 13 Nov 2006 - added serialization
* 17 Nov 2006 - added name-based guid creation
* 20 Nov 2006 - add fixes for gcc (from Tim Blechmann)
* 07 Mar 2007 - converted to header only
* 20 Jan 2008 - removed dependency of Boost and modified for libLAS (by Mateusz Loskot)
******************************************************************************
*
* Copyright (c) 1997
* Silicon Graphics Computer Systems, Inc.
*
* Permission to use, copy, modify, distribute and sell this software
* and its documentation for any purpose is hereby granted without fee,
* provided that the above copyright notice appear in all copies and
* that both that copyright notice and this permission notice appear
* in supporting documentation. Silicon Graphics makes no
* representations about the suitability of this software for any
* purpose. It is provided "as is" without express or implied warranty.
*
*
*
* Copyright notice reproduced from <boost/detail/limits.hpp>, from
* which this code was originally taken.
*
* Modified by Caleb Epstein to use <endian.h> with GNU libc and to
* defined the BOOST_ENDIAN macro.
****************************************************************************/
#ifndef INCLUDED_DRIVER_OCI_ENDIAN_HPP
#define INCLUDED_DRIVER_OCI_ENDIAN_HPP
# define SWAP_BE_TO_LE(p) \
do { \
char* first = static_cast<char*>(static_cast<void*>(&p)); \
char* last = first + sizeof(p) - 1; \
for(; first < last; ++first, --last) { \
char const x = *last; \
*last = *first; \
*first = x; \
}} while(false)
# define SWAP_LE_TO_BE(p) \
do { \
char* first = static_cast<char*>(static_cast<void*>(&p)); \
char* last = first + sizeof(p) - 1; \
for(; first < last; ++first, --last) { \
char const x = *last; \
*last = *first; \
*first = x; \
}} while(false)
# define SWAP_BE_TO_LE_N(p, n) \
do { \
char* first = static_cast<char*>(static_cast<void*>(&p)); \
char* last = first + n - 1; \
for(; first < last; ++first, --last) { \
char const x = *last; \
*last = *first; \
*first = x; \
}} while(false)
#endif
<|endoftext|> |
<commit_before>#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <errno.h>
#include <unistd.h>
#include <algorithm>
#include <regex>
#include <string>
#include <vector>
#include "SDL2/SDL.h"
#include "SDL2/SDL_joystick.h"
#include <GL/gl3w.h>
#include "../Libraries/imgui-1.49/imgui.h"
#include "../Libraries/imgui-1.49/examples/sdl_opengl3_example/imgui_impl_sdl_gl3.h"
extern "C" {
#include "snepulator.h"
#include "sms.h"
}
/* Global state */
extern Snepulator snepulator;
void snepulator_render_open_modal (void)
{
if (ImGui::BeginPopupModal ("Open ROM...", NULL, ImGuiWindowFlags_AlwaysAutoResize |
ImGuiWindowFlags_NoMove |
ImGuiWindowFlags_NoScrollbar))
{
int width = (snepulator.host_width / 2 > 512) ? snepulator.host_width / 2 : 512;
int height = (snepulator.host_height / 2 > 384) ? snepulator.host_width / 2 : 384;
/* State */
static bool cwd_cached = false;
static char cwd_path_buf[240]; /* TODO: Can we make this dynamic? */
static const char *cwd_path = NULL;
static std::vector<std::string> file_list;
static int selected_file = 0;
bool open_action = false;
std::regex sms_regex (".*\\.(BIN|bin|SMS|sms)$");
if (!cwd_cached)
{
/* Current working directory string */
cwd_path = getcwd (cwd_path_buf, 240);
if (cwd_path == NULL)
{
cwd_path = "getcwd () -> NULL";
}
/* File listing */
DIR *dir = opendir (".");
struct dirent *entry = NULL;
std::string entry_string;
if (dir != NULL)
{
for (entry = readdir (dir); entry != NULL; entry = readdir (dir))
{
if (!strcmp (".", entry->d_name))
{
continue;
}
entry_string = std::string (entry->d_name);
/* Show directories as ending with '/' */
if (entry->d_type == DT_DIR)
{
entry_string += '/';
}
/* Only list files that have a valid ROM extension */
else if (!std::regex_match (entry_string, sms_regex))
{
continue;
}
file_list.push_back (entry_string);
}
std::sort (file_list.begin (), file_list.end ());
}
cwd_cached = true;
}
ImGui::Text ("%s", cwd_path);
#if 0
/* Placeholder - Configured ROM Directories */
ImGui::BeginChild ("Directories", ImVec2 (150, 400), true);
ImGui::Button ("Master System", ImVec2 (ImGui::GetContentRegionAvailWidth (), 24));
ImGui::Button ("SG-1000", ImVec2 (ImGui::GetContentRegionAvailWidth (), 24));
ImGui::EndChild ();
ImGui::SameLine ();
#endif
/* Current directory contents */
ImGui::BeginChild ("Files", ImVec2 (width, height - 64), true);
for (int i = 0; i < file_list.size (); i++)
{
/* TODO: Can we get the text height rather than hard-coding it? */
ImVec2 draw_cursor = ImGui::GetCursorScreenPos ();
bool hovering = ImGui::IsMouseHoveringRect (draw_cursor, ImVec2 (draw_cursor.x + 350, draw_cursor.y + 16));
/* Click to select */
if (hovering && ImGui::IsMouseClicked (0))
{
selected_file = i;
}
/* Double-click to open */
if (hovering && ImGui::IsMouseDoubleClicked (0))
{
open_action = true;
}
/* Render the selected file in green, hovered file in yellow, and others with the text default */
if (i == selected_file)
{
ImGui::TextColored (ImVec4 (0.5f, 1.0f, 0.5f, 1.0f), "%s", file_list[i].c_str ());
}
else if (hovering)
{
ImGui::TextColored (ImVec4 (1.0f, 1.0f, 0.5f, 1.0f), "%s", file_list[i].c_str ());
}
else
{
ImGui::Text ("%s", file_list[i].c_str ());
}
}
ImGui::EndChild ();
/* Buttons */
if (ImGui::Button ("Cancel", ImVec2 (120,0))) {
snepulator.running = true;
ImGui::CloseCurrentPopup ();
}
ImGui::SameLine ();
if (ImGui::Button ("Open", ImVec2 (120,0))) { /* TODO: Do we want an "Open BIOS"? */
open_action = true;
}
/* Open action */
if (open_action)
{
/* Directory */
if (file_list[selected_file].back () == '/')
{
chdir (file_list[selected_file].c_str ());
}
/* ROM */
else
{
free (snepulator.cart_filename);
snepulator.cart_filename = strdup (file_list[selected_file].c_str ());
sms_init (snepulator.bios_filename, snepulator.cart_filename);
snepulator.running = true;
ImGui::CloseCurrentPopup ();
}
cwd_cached = false;
file_list.clear ();
}
ImGui::EndPopup ();
}
}
<commit_msg>config: Store the most recently used rom directory to the config<commit_after>#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <errno.h>
#include <unistd.h>
#include <algorithm>
#include <regex>
#include <string>
#include <vector>
#include "SDL2/SDL.h"
#include "SDL2/SDL_joystick.h"
#include <GL/gl3w.h>
#include "../Libraries/imgui-1.49/imgui.h"
#include "../Libraries/imgui-1.49/examples/sdl_opengl3_example/imgui_impl_sdl_gl3.h"
extern "C" {
#include "snepulator.h"
#include "config.h"
#include "sms.h"
}
/* Global state */
extern Snepulator snepulator;
static char rom_path[160] = { '\0' }; /* TODO: Make the size dynamic */
void snepulator_render_open_modal (void)
{
if (ImGui::BeginPopupModal ("Open ROM...", NULL, ImGuiWindowFlags_AlwaysAutoResize |
ImGuiWindowFlags_NoMove |
ImGuiWindowFlags_NoScrollbar))
{
int width = (snepulator.host_width / 2 > 512) ? snepulator.host_width / 2 : 512;
int height = (snepulator.host_height / 2 > 384) ? snepulator.host_width / 2 : 384;
/* State */
static bool rom_path_cached = false;
static std::vector<std::string> file_list;
static int selected_file = 0;
bool open_action = false;
std::regex sms_regex (".*\\.(BIN|bin|SMS|sms)$");
if (!rom_path_cached)
{
/* Retrieve initial path from config */
if (rom_path [0] == '\0')
{
char *path = NULL;
if (config_string_get ("paths", "sms_roms", &path) == 0)
{
strncpy (rom_path, path, 179);
}
}
/* Fallback to home directory */
if (rom_path [0] == '\0')
{
char *path = getenv ("HOME");
if (path != NULL)
{
sprintf (rom_path, "%s/", path);
}
else
{
fprintf (stderr, "Error: ${HOME} not defined.");
return;
}
}
/* File listing */
DIR *dir = opendir (rom_path);
struct dirent *entry = NULL;
std::string entry_string;
if (dir != NULL)
{
for (entry = readdir (dir); entry != NULL; entry = readdir (dir))
{
/* Ignore "." directory */
if (strcmp (entry->d_name, ".") == 0)
{
continue;
}
/* Hide ".." directory if we're already at the root */
if ((strcmp (rom_path, "/") == 0) && (strcmp (entry->d_name, "..") == 0))
{
continue;
}
entry_string = std::string (entry->d_name);
/* Show directories as ending with '/' */
if (entry->d_type == DT_DIR)
{
entry_string += '/';
}
/* Only list files that have a valid ROM extension */
else if (!std::regex_match (entry_string, sms_regex))
{
continue;
}
file_list.push_back (entry_string);
}
std::sort (file_list.begin (), file_list.end ());
}
rom_path_cached = true;
}
ImGui::Text ("%s", rom_path);
/* Current directory contents */
ImGui::BeginChild ("Files", ImVec2 (width, height - 64), true);
for (int i = 0; i < file_list.size (); i++)
{
/* TODO: Can we get the text height rather than hard-coding it? */
ImVec2 draw_cursor = ImGui::GetCursorScreenPos ();
bool hovering = ImGui::IsMouseHoveringRect (draw_cursor, ImVec2 (draw_cursor.x + 350, draw_cursor.y + 16));
/* Click to select */
if (hovering && ImGui::IsMouseClicked (0))
{
selected_file = i;
}
/* Double-click to open */
if (hovering && ImGui::IsMouseDoubleClicked (0))
{
open_action = true;
}
/* Render the selected file in green, hovered file in yellow, and others with the text default */
if (i == selected_file)
{
ImGui::TextColored (ImVec4 (0.5f, 1.0f, 0.5f, 1.0f), "%s", file_list[i].c_str ());
}
else if (hovering)
{
ImGui::TextColored (ImVec4 (1.0f, 1.0f, 0.5f, 1.0f), "%s", file_list[i].c_str ());
}
else
{
ImGui::Text ("%s", file_list[i].c_str ());
}
}
ImGui::EndChild ();
/* Buttons */
if (ImGui::Button ("Cancel", ImVec2 (120,0))) {
snepulator.running = true;
ImGui::CloseCurrentPopup ();
}
ImGui::SameLine ();
if (ImGui::Button ("Open", ImVec2 (120,0))) { /* TODO: Do we want an "Open BIOS"? */
open_action = true;
}
/* Open action */
if (open_action)
{
/* Directory */
if (file_list[selected_file].back () == '/')
{
char new_rom_path[160] = { '\0' };
if (strcmp (file_list [selected_file].c_str (), "../") == 0)
{
/* Go up to the parent directory */
/* First, remove the final slash from the path */
char *end_slash = strrchr (rom_path, '/');
if (end_slash == NULL)
{
fprintf (stderr, "Error: Failed to change directory.");
return;
}
end_slash [0] = '\0';
/* Now, zero the path name after the new final slash */
end_slash = strrchr (rom_path, '/');
if (end_slash == NULL)
{
fprintf (stderr, "Error: Failed to change directory.");
return;
}
memset (&end_slash [1], 0, strlen (&end_slash [1]));
}
else
{
/* Enter new directory */
sprintf (new_rom_path, "%s%s", rom_path, file_list [selected_file].c_str ());
strcpy (rom_path, new_rom_path);
}
config_string_set ("paths", "sms_roms", rom_path);
config_write ();
}
/* ROM */
else
{
char new_rom_path[160] = { '\0' };
sprintf (new_rom_path, "%s%s", rom_path, file_list [selected_file].c_str ());
free (snepulator.cart_filename);
snepulator.cart_filename = strdup (new_rom_path);
sms_init (snepulator.bios_filename, snepulator.cart_filename);
snepulator.running = true;
ImGui::CloseCurrentPopup ();
}
rom_path_cached = false;
file_list.clear ();
}
ImGui::EndPopup ();
}
}
<|endoftext|> |
<commit_before>#ifndef ORM_SQLOBJECT_HPP
#define ORM_SQLOBJECT_HPP
#include "Bdd.hpp"
#include "Query.hpp"
#include <list>
namespace orm
{
class Query;
template<typename T>
class SQLObject
{
public:
SQLObject() : pk(-1)
{
};
bool loadFromBdd(Query& query)
{
//TODO Loop on this->attrs
return true;
};
static T* createFromBdd(Query& query)
{
T* res = new T;
query.getObj(*res);
return res;
};
static T* get(unsigned int id)
{
Query* q = bdd_used->query("SELECT * FROM "+
table+
" WHERE (id "+
(*bdd_used)["exact"]+std::to_string(id)+
") ");
return createFromBdd(*q);
};
static std::list<T*> filter();
static std::list<T*> all()
{
/* Query* q = bdd_used->query("SELECT * FROM "+table+" ");
q->execute();*/
};
static Bdd* bdd_used;
protected:
int pk;
const static std::string table;
};
};
#define REGISTER_TABLE(T,tab) \
template<>\
const std::string orm::SQLObject<T>::table = tab;\
template<>\
orm::Bdd* orm::SQLObject<T>::bdd_used = &orm::Bdd::Default;
#define REGISTER_BDD(T,bdd) \
orm::SQLObject<T>::bdd_used = bdd;
#endif
<commit_msg>remove non portable code<commit_after>#ifndef ORM_SQLOBJECT_HPP
#define ORM_SQLOBJECT_HPP
#include "Bdd.hpp"
#include "Query.hpp"
#include <list>
namespace orm
{
class Query;
template<typename T>
class SQLObject
{
public:
SQLObject() : pk(-1)
{
};
bool loadFromBdd(Query& query)
{
//TODO Loop on this->attrs
return true;
};
static T* createFromBdd(Query& query)
{
//TODO Loop on this->attrs
T* res = new T;
return res;
};
static T* get(unsigned int id)
{
Query* q = bdd_used->query("SELECT * FROM "+
table+
" WHERE (id "+
(*bdd_used)["exact"]+std::to_string(id)+
") ");
return createFromBdd(*q);
};
static std::list<T*> filter();
static std::list<T*> all()
{
/* Query* q = bdd_used->query("SELECT * FROM "+table+" ");
q->execute();*/
};
static Bdd* bdd_used;
protected:
int pk;
const static std::string table;
};
};
#define REGISTER_TABLE(T,tab) \
template<>\
const std::string orm::SQLObject<T>::table = tab;\
template<>\
orm::Bdd* orm::SQLObject<T>::bdd_used = &orm::Bdd::Default;
#define REGISTER_BDD(T,bdd) \
orm::SQLObject<T>::bdd_used = bdd;
#endif
<|endoftext|> |
<commit_before>// Filename: textMonitor.cxx
// Created by: drose (12Jul00)
//
////////////////////////////////////////////////////////////////////
#include "textMonitor.h"
#include <indent.h>
////////////////////////////////////////////////////////////////////
// Function: TextMonitor::Constructor
// Access: Public
// Description:
////////////////////////////////////////////////////////////////////
TextMonitor::
TextMonitor() {
}
////////////////////////////////////////////////////////////////////
// Function: TextMonitor::get_monitor_name
// Access: Public, Virtual
// Description: Should be redefined to return a descriptive name for
// the type of PStatsMonitor this is.
////////////////////////////////////////////////////////////////////
string TextMonitor::
get_monitor_name() {
return "Text Stats";
}
////////////////////////////////////////////////////////////////////
// Function: TextMonitor::got_hello
// Access: Public, Virtual
// Description: Called when the "hello" message has been received
// from the client. At this time, the client's hostname
// and program name will be known.
////////////////////////////////////////////////////////////////////
void TextMonitor::
got_hello() {
nout << "Now connected to " << get_client_progname() << " on host "
<< get_client_hostname() << "\n";
}
////////////////////////////////////////////////////////////////////
// Function: TextMonitor::new_data
// Access: Public, Virtual
// Description: Called as each frame's data is made available. There
// is no gurantee the frames will arrive in order, or
// that all of them will arrive at all. The monitor
// should be prepared to accept frames received
// out-of-order or missing.
////////////////////////////////////////////////////////////////////
void TextMonitor::
new_data(int thread_index, int frame_number) {
PStatView &view = get_view(thread_index);
const PStatThreadData *thread_data = view.get_thread_data();
if (frame_number = thread_data->get_latest_frame_number()) {
view.set_to_frame(frame_number);
if (view.all_collectors_known()) {
nout << "\rThread "
<< get_client_data()->get_thread_name(thread_index)
<< " frame " << frame_number << ", "
<< view.get_net_time() * 1000.0 << " ms ("
<< thread_data->get_frame_rate() << " Hz):\n";
const PStatViewLevel *level = view.get_top_level();
int num_children = level->get_num_children();
for (int i = 0; i < num_children; i++) {
show_level(level->get_child(i), 2);
}
}
}
}
////////////////////////////////////////////////////////////////////
// Function: TextMonitor::lost_connection
// Access: Public, Virtual
// Description: Called whenever the connection to the client has been
// lost. This is a permanent state change. The monitor
// should update its display to represent this, and may
// choose to close down automatically.
////////////////////////////////////////////////////////////////////
void TextMonitor::
lost_connection() {
nout << "Lost connection.\n";
}
////////////////////////////////////////////////////////////////////
// Function: TextMonitor::is_thread_safe
// Access: Public, Virtual
// Description: Should be redefined to return true if this monitor
// class can handle running in a sub-thread.
//
// This is not related to the question of whether it can
// handle multiple different PStatThreadDatas; this is
// strictly a question of whether or not the monitor
// itself wants to run in a sub-thread.
////////////////////////////////////////////////////////////////////
bool TextMonitor::
is_thread_safe() {
return true;
}
////////////////////////////////////////////////////////////////////
// Function: TextMonitor::show_level
// Access: Public
// Description:
////////////////////////////////////////////////////////////////////
void TextMonitor::
show_level(const PStatViewLevel *level, int indent_level) {
int collector_index = level->get_collector();
indent(nout, indent_level)
<< get_client_data()->get_collector_name(collector_index)
<< " = " << level->get_net_time() * 1000.0 << " ms\n";
int num_children = level->get_num_children();
for (int i = 0; i < num_children; i++) {
show_level(level->get_child(i), indent_level + 2);
}
}
<commit_msg>*** empty log message ***<commit_after>// Filename: textMonitor.cxx
// Created by: drose (12Jul00)
//
////////////////////////////////////////////////////////////////////
#include "textMonitor.h"
#include <indent.h>
////////////////////////////////////////////////////////////////////
// Function: TextMonitor::Constructor
// Access: Public
// Description:
////////////////////////////////////////////////////////////////////
TextMonitor::
TextMonitor() {
}
////////////////////////////////////////////////////////////////////
// Function: TextMonitor::get_monitor_name
// Access: Public, Virtual
// Description: Should be redefined to return a descriptive name for
// the type of PStatsMonitor this is.
////////////////////////////////////////////////////////////////////
string TextMonitor::
get_monitor_name() {
return "Text Stats";
}
////////////////////////////////////////////////////////////////////
// Function: TextMonitor::got_hello
// Access: Public, Virtual
// Description: Called when the "hello" message has been received
// from the client. At this time, the client's hostname
// and program name will be known.
////////////////////////////////////////////////////////////////////
void TextMonitor::
got_hello() {
nout << "Now connected to " << get_client_progname() << " on host "
<< get_client_hostname() << "\n";
}
////////////////////////////////////////////////////////////////////
// Function: TextMonitor::new_data
// Access: Public, Virtual
// Description: Called as each frame's data is made available. There
// is no gurantee the frames will arrive in order, or
// that all of them will arrive at all. The monitor
// should be prepared to accept frames received
// out-of-order or missing.
////////////////////////////////////////////////////////////////////
void TextMonitor::
new_data(int thread_index, int frame_number) {
PStatView &view = get_view(thread_index);
const PStatThreadData *thread_data = view.get_thread_data();
if (frame_number == thread_data->get_latest_frame_number()) {
view.set_to_frame(frame_number);
if (view.all_collectors_known()) {
nout << "\rThread "
<< get_client_data()->get_thread_name(thread_index)
<< " frame " << frame_number << ", "
<< view.get_net_time() * 1000.0 << " ms ("
<< thread_data->get_frame_rate() << " Hz):\n";
const PStatViewLevel *level = view.get_top_level();
int num_children = level->get_num_children();
for (int i = 0; i < num_children; i++) {
show_level(level->get_child(i), 2);
}
}
}
}
////////////////////////////////////////////////////////////////////
// Function: TextMonitor::lost_connection
// Access: Public, Virtual
// Description: Called whenever the connection to the client has been
// lost. This is a permanent state change. The monitor
// should update its display to represent this, and may
// choose to close down automatically.
////////////////////////////////////////////////////////////////////
void TextMonitor::
lost_connection() {
nout << "Lost connection.\n";
}
////////////////////////////////////////////////////////////////////
// Function: TextMonitor::is_thread_safe
// Access: Public, Virtual
// Description: Should be redefined to return true if this monitor
// class can handle running in a sub-thread.
//
// This is not related to the question of whether it can
// handle multiple different PStatThreadDatas; this is
// strictly a question of whether or not the monitor
// itself wants to run in a sub-thread.
////////////////////////////////////////////////////////////////////
bool TextMonitor::
is_thread_safe() {
return true;
}
////////////////////////////////////////////////////////////////////
// Function: TextMonitor::show_level
// Access: Public
// Description:
////////////////////////////////////////////////////////////////////
void TextMonitor::
show_level(const PStatViewLevel *level, int indent_level) {
int collector_index = level->get_collector();
indent(nout, indent_level)
<< get_client_data()->get_collector_name(collector_index)
<< " = " << level->get_net_time() * 1000.0 << " ms\n";
int num_children = level->get_num_children();
for (int i = 0; i < num_children; i++) {
show_level(level->get_child(i), indent_level + 2);
}
}
<|endoftext|> |
<commit_before>// Copyright Verizon Media. 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/eval/tensor_function.h>
#include <vespa/eval/eval/simple_tensor.h>
#include <vespa/eval/eval/simple_tensor_engine.h>
#include <vespa/eval/tensor/default_tensor_engine.h>
#include <vespa/eval/tensor/dense/dense_replace_type_function.h>
#include <vespa/eval/tensor/dense/dense_cell_range_function.h>
#include <vespa/eval/tensor/dense/dense_lambda_peek_function.h>
#include <vespa/eval/tensor/dense/dense_lambda_function.h>
#include <vespa/eval/tensor/dense/dense_fast_rename_optimizer.h>
#include <vespa/eval/tensor/dense/dense_tensor.h>
#include <vespa/eval/eval/test/tensor_model.hpp>
#include <vespa/eval/eval/test/eval_fixture.h>
#include <vespa/eval/eval/tensor_nodes.h>
#include <vespa/vespalib/util/stringfmt.h>
#include <vespa/vespalib/util/stash.h>
using namespace vespalib;
using namespace vespalib::eval;
using namespace vespalib::eval::test;
using namespace vespalib::tensor;
using namespace vespalib::eval::tensor_function;
using EvalMode = DenseLambdaFunction::EvalMode;
namespace vespalib::tensor {
std::ostream &operator<<(std::ostream &os, EvalMode eval_mode)
{
switch(eval_mode) {
case EvalMode::COMPILED: return os << "COMPILED";
case EvalMode::INTERPRETED: return os << "INTERPRETED";
}
abort();
}
}
const TensorEngine &prod_engine = DefaultTensorEngine::ref();
EvalFixture::ParamRepo make_params() {
return EvalFixture::ParamRepo()
.add("a", spec(1))
.add("b", spec(2))
.add("x3", spec({x(3)}, N()))
.add("x3f", spec(float_cells({x(3)}), N()))
.add("x3m", spec({x({"0", "1", "2"})}, N()))
.add("x3y5", spec({x(3), y(5)}, N()))
.add("x3y5f", spec(float_cells({x(3), y(5)}), N()))
.add("x15", spec({x(15)}, N()))
.add("x15f", spec(float_cells({x(15)}), N()));
}
EvalFixture::ParamRepo param_repo = make_params();
template <typename T, typename F>
void verify_impl(const vespalib::string &expr, const vespalib::string &expect, F &&inspect) {
EvalFixture fixture(prod_engine, expr, param_repo, true);
EvalFixture slow_fixture(prod_engine, expr, param_repo, false);
EXPECT_EQUAL(fixture.result(), slow_fixture.result());
EXPECT_EQUAL(fixture.result(), EvalFixture::ref(expr, param_repo));
EXPECT_EQUAL(fixture.result(), EvalFixture::ref(expect, param_repo));
auto info = fixture.find_all<T>();
if (EXPECT_EQUAL(info.size(), 1u)) {
inspect(info[0]);
}
}
template <typename T>
void verify_impl(const vespalib::string &expr, const vespalib::string &expect) {
verify_impl<T>(expr, expect, [](const T*){});
}
void verify_generic(const vespalib::string &expr, const vespalib::string &expect,
EvalMode expect_eval_mode)
{
verify_impl<DenseLambdaFunction>(expr, expect,
[&](const DenseLambdaFunction *info)
{
EXPECT_EQUAL(info->eval_mode(), expect_eval_mode);
});
}
void verify_reshape(const vespalib::string &expr, const vespalib::string &expect) {
verify_impl<DenseReplaceTypeFunction>(expr, expect);
}
void verify_range(const vespalib::string &expr, const vespalib::string &expect) {
verify_impl<DenseCellRangeFunction>(expr, expect);
}
void verify_idx_fun(const vespalib::string &expr, const vespalib::string &expect,
const vespalib::string &expect_idx_fun)
{
verify_impl<DenseLambdaPeekFunction>(expr, expect,
[&](const DenseLambdaPeekFunction *info)
{
EXPECT_EQUAL(info->idx_fun_dump(), expect_idx_fun);
});
}
void verify_const(const vespalib::string &expr, const vespalib::string &expect) {
verify_impl<ConstValue>(expr, expect);
}
//-----------------------------------------------------------------------------
TEST("require that simple constant tensor lambda works") {
TEST_DO(verify_const("tensor(x[3])(x+1)", "tensor(x[3]):[1,2,3]"));
}
TEST("require that simple dynamic tensor lambda works") {
TEST_DO(verify_generic("tensor(x[3])(x+a)", "tensor(x[3]):[1,2,3]", EvalMode::COMPILED));
}
TEST("require that compiled multi-dimensional multi-param dynamic tensor lambda works") {
TEST_DO(verify_generic("tensor(x[3],y[2])((b-a)+x+y)", "tensor(x[3],y[2]):[[1,2],[2,3],[3,4]]", EvalMode::COMPILED));
TEST_DO(verify_generic("tensor<float>(x[3],y[2])((b-a)+x+y)", "tensor<float>(x[3],y[2]):[[1,2],[2,3],[3,4]]", EvalMode::COMPILED));
}
TEST("require that interpreted multi-dimensional multi-param dynamic tensor lambda works") {
TEST_DO(verify_generic("tensor(x[3],y[2])((x3{x:(a)}-a)+x+y)", "tensor(x[3],y[2]):[[1,2],[2,3],[3,4]]", EvalMode::INTERPRETED));
TEST_DO(verify_generic("tensor<float>(x[3],y[2])((x3{x:(a)}-a)+x+y)", "tensor<float>(x[3],y[2]):[[1,2],[2,3],[3,4]]", EvalMode::INTERPRETED));
}
TEST("require that tensor lambda can be used for tensor slicing") {
TEST_DO(verify_generic("tensor(x[2])(x3{x:(x+a)})", "tensor(x[2]):[2,3]", EvalMode::INTERPRETED));
TEST_DO(verify_generic("tensor(x[2])(a+x3{x:(x)})", "tensor(x[2]):[2,3]", EvalMode::INTERPRETED));
}
TEST("require that tensor lambda can be used for cell type casting") {
TEST_DO(verify_idx_fun("tensor(x[3])(x3f{x:(x)})", "tensor(x[3]):[1,2,3]", "f(x)(x)"));
TEST_DO(verify_idx_fun("tensor<float>(x[3])(x3{x:(x)})", "tensor<float>(x[3]):[1,2,3]", "f(x)(x)"));
}
TEST("require that tensor lambda can be used to convert from sparse to dense tensors") {
TEST_DO(verify_generic("tensor(x[3])(x3m{x:(x)})", "tensor(x[3]):[1,2,3]", EvalMode::INTERPRETED));
TEST_DO(verify_generic("tensor(x[2])(x3m{x:(x)})", "tensor(x[2]):[1,2]", EvalMode::INTERPRETED));
}
TEST("require that constant nested tensor lambda using tensor peek works") {
TEST_DO(verify_const("tensor(x[2])(tensor(y[2])((x+y)+1){y:(x)})", "tensor(x[2]):[1,3]"));
}
TEST("require that dynamic nested tensor lambda using tensor peek works") {
TEST_DO(verify_generic("tensor(x[2])(tensor(y[2])((x+y)+a){y:(x)})", "tensor(x[2]):[1,3]", EvalMode::INTERPRETED));
}
TEST("require that tensor reshape is optimized") {
TEST_DO(verify_reshape("tensor(x[15])(x3y5{x:(x/5),y:(x%5)})", "x15"));
TEST_DO(verify_reshape("tensor(x[3],y[5])(x15{x:(x*5+y)})", "x3y5"));
TEST_DO(verify_reshape("tensor<float>(x[15])(x3y5f{x:(x/5),y:(x%5)})", "x15f"));
}
TEST("require that tensor reshape with non-matching cell type requires cell copy") {
TEST_DO(verify_idx_fun("tensor(x[15])(x3y5f{x:(x/5),y:(x%5)})", "x15", "f(x)((floor((x/5))*5)+(x%5))"));
TEST_DO(verify_idx_fun("tensor<float>(x[15])(x3y5{x:(x/5),y:(x%5)})", "x15f", "f(x)((floor((x/5))*5)+(x%5))"));
TEST_DO(verify_idx_fun("tensor(x[3],y[5])(x15f{x:(x*5+y)})", "x3y5", "f(x,y)((x*5)+y)"));
TEST_DO(verify_idx_fun("tensor<float>(x[3],y[5])(x15{x:(x*5+y)})", "x3y5f", "f(x,y)((x*5)+y)"));
}
TEST("require that tensor cell subrange view is optimized") {
TEST_DO(verify_range("tensor(y[5])(x3y5{x:1,y:(y)})", "x3y5{x:1}"));
TEST_DO(verify_range("tensor(x[3])(x15{x:(x+5)})", "tensor(x[3]):[6,7,8]"));
TEST_DO(verify_range("tensor<float>(y[5])(x3y5f{x:1,y:(y)})", "x3y5f{x:1}"));
TEST_DO(verify_range("tensor<float>(x[3])(x15f{x:(x+5)})", "tensor<float>(x[3]):[6,7,8]"));
}
TEST("require that tensor cell subrange with non-matching cell type requires cell copy") {
TEST_DO(verify_idx_fun("tensor(x[3])(x15f{x:(x+5)})", "tensor(x[3]):[6,7,8]", "f(x)(x+5)"));
TEST_DO(verify_idx_fun("tensor<float>(x[3])(x15{x:(x+5)})", "tensor<float>(x[3]):[6,7,8]", "f(x)(x+5)"));
}
TEST("require that non-continuous cell extraction is optimized") {
TEST_DO(verify_idx_fun("tensor(x[3])(x3y5{x:(x),y:2})", "x3y5{y:2}", "f(x)((floor(x)*5)+2)"));
TEST_DO(verify_idx_fun("tensor(x[3])(x3y5f{x:(x),y:2})", "x3y5{y:2}", "f(x)((floor(x)*5)+2)"));
TEST_DO(verify_idx_fun("tensor<float>(x[3])(x3y5{x:(x),y:2})", "x3y5f{y:2}", "f(x)((floor(x)*5)+2)"));
TEST_DO(verify_idx_fun("tensor<float>(x[3])(x3y5f{x:(x),y:2})", "x3y5f{y:2}", "f(x)((floor(x)*5)+2)"));
}
TEST("require that out-of-bounds cell extraction is not optimized") {
TEST_DO(verify_generic("tensor(x[3])(x3y5{x:1,y:(x+3)})", "tensor(x[3]):[9,10,0]", EvalMode::INTERPRETED));
TEST_DO(verify_generic("tensor(x[3])(x3y5{x:1,y:(x-1)})", "tensor(x[3]):[0,6,7]", EvalMode::INTERPRETED));
TEST_DO(verify_generic("tensor(x[3])(x3y5{x:(x+1),y:(x)})", "tensor(x[3]):[6,12,0]", EvalMode::INTERPRETED));
TEST_DO(verify_generic("tensor(x[3])(x3y5{x:(x-1),y:(x)})", "tensor(x[3]):[0,2,8]", EvalMode::INTERPRETED));
}
TEST("require that non-double result from inner tensor lambda function fails type resolving") {
auto fun_a = Function::parse("tensor(x[2])(a)");
auto fun_b = Function::parse("tensor(x[2])(a{y:(x)})");
NodeTypes types_ad(*fun_a, {ValueType::from_spec("double")});
NodeTypes types_at(*fun_a, {ValueType::from_spec("tensor(y[2])")});
NodeTypes types_bd(*fun_b, {ValueType::from_spec("double")});
NodeTypes types_bt(*fun_b, {ValueType::from_spec("tensor(y[2])")});
EXPECT_EQUAL(types_ad.get_type(fun_a->root()).to_spec(), "tensor(x[2])");
EXPECT_EQUAL(types_at.get_type(fun_a->root()).to_spec(), "error");
EXPECT_EQUAL(types_bd.get_type(fun_b->root()).to_spec(), "error");
EXPECT_EQUAL(types_bt.get_type(fun_b->root()).to_spec(), "tensor(x[2])");
}
TEST("require that type resolving also include nodes in the inner tensor lambda function") {
auto fun = Function::parse("tensor(x[2])(a)");
NodeTypes types(*fun, {ValueType::from_spec("double")});
auto lambda = nodes::as<nodes::TensorLambda>(fun->root());
ASSERT_TRUE(lambda != nullptr);
EXPECT_EQUAL(types.get_type(*lambda).to_spec(), "tensor(x[2])");
auto symbol = nodes::as<nodes::Symbol>(lambda->lambda().root());
ASSERT_TRUE(symbol != nullptr);
EXPECT_EQUAL(types.get_type(*symbol).to_spec(), "double");
}
TEST_MAIN() { TEST_RUN_ALL(); }
<commit_msg>test with simple factory also<commit_after>// Copyright Verizon Media. 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/eval/tensor_function.h>
#include <vespa/eval/eval/simple_tensor.h>
#include <vespa/eval/eval/simple_tensor_engine.h>
#include <vespa/eval/eval/simple_value.h>
#include <vespa/eval/eval/fast_value.h>
#include <vespa/eval/tensor/default_tensor_engine.h>
#include <vespa/eval/tensor/dense/dense_replace_type_function.h>
#include <vespa/eval/tensor/dense/dense_cell_range_function.h>
#include <vespa/eval/tensor/dense/dense_lambda_peek_function.h>
#include <vespa/eval/tensor/dense/dense_lambda_function.h>
#include <vespa/eval/tensor/dense/dense_fast_rename_optimizer.h>
#include <vespa/eval/tensor/dense/dense_tensor.h>
#include <vespa/eval/eval/test/tensor_model.hpp>
#include <vespa/eval/eval/test/eval_fixture.h>
#include <vespa/eval/eval/tensor_nodes.h>
#include <vespa/vespalib/util/stringfmt.h>
#include <vespa/vespalib/util/stash.h>
using namespace vespalib;
using namespace vespalib::eval;
using namespace vespalib::eval::test;
using namespace vespalib::tensor;
using namespace vespalib::eval::tensor_function;
using EvalMode = DenseLambdaFunction::EvalMode;
namespace vespalib::tensor {
std::ostream &operator<<(std::ostream &os, EvalMode eval_mode)
{
switch(eval_mode) {
case EvalMode::COMPILED: return os << "COMPILED";
case EvalMode::INTERPRETED: return os << "INTERPRETED";
}
abort();
}
}
const TensorEngine &prod_engine = DefaultTensorEngine::ref();
const ValueBuilderFactory &simple_factory = SimpleValueBuilderFactory::get();
EvalFixture::ParamRepo make_params() {
return EvalFixture::ParamRepo()
.add("a", spec(1))
.add("b", spec(2))
.add("x3", spec({x(3)}, N()))
.add("x3f", spec(float_cells({x(3)}), N()))
.add("x3m", spec({x({"0", "1", "2"})}, N()))
.add("x3y5", spec({x(3), y(5)}, N()))
.add("x3y5f", spec(float_cells({x(3), y(5)}), N()))
.add("x15", spec({x(15)}, N()))
.add("x15f", spec(float_cells({x(15)}), N()));
}
EvalFixture::ParamRepo param_repo = make_params();
template <typename T, typename F>
void verify_impl(const vespalib::string &expr, const vespalib::string &expect, F &&inspect) {
EvalFixture fixture(prod_engine, expr, param_repo, true);
EvalFixture slow_fixture(prod_engine, expr, param_repo, false);
EvalFixture simple_factory_fixture(simple_factory, expr, param_repo, false);
EXPECT_EQUAL(fixture.result(), slow_fixture.result());
EXPECT_EQUAL(fixture.result(), simple_factory_fixture.result());
EXPECT_EQUAL(fixture.result(), EvalFixture::ref(expr, param_repo));
EXPECT_EQUAL(fixture.result(), EvalFixture::ref(expect, param_repo));
auto info = fixture.find_all<T>();
if (EXPECT_EQUAL(info.size(), 1u)) {
inspect(info[0]);
}
}
template <typename T>
void verify_impl(const vespalib::string &expr, const vespalib::string &expect) {
verify_impl<T>(expr, expect, [](const T*){});
}
void verify_generic(const vespalib::string &expr, const vespalib::string &expect,
EvalMode expect_eval_mode)
{
verify_impl<DenseLambdaFunction>(expr, expect,
[&](const DenseLambdaFunction *info)
{
EXPECT_EQUAL(info->eval_mode(), expect_eval_mode);
});
}
void verify_reshape(const vespalib::string &expr, const vespalib::string &expect) {
verify_impl<DenseReplaceTypeFunction>(expr, expect);
}
void verify_range(const vespalib::string &expr, const vespalib::string &expect) {
verify_impl<DenseCellRangeFunction>(expr, expect);
}
void verify_idx_fun(const vespalib::string &expr, const vespalib::string &expect,
const vespalib::string &expect_idx_fun)
{
verify_impl<DenseLambdaPeekFunction>(expr, expect,
[&](const DenseLambdaPeekFunction *info)
{
EXPECT_EQUAL(info->idx_fun_dump(), expect_idx_fun);
});
}
void verify_const(const vespalib::string &expr, const vespalib::string &expect) {
verify_impl<ConstValue>(expr, expect);
}
//-----------------------------------------------------------------------------
TEST("require that simple constant tensor lambda works") {
TEST_DO(verify_const("tensor(x[3])(x+1)", "tensor(x[3]):[1,2,3]"));
}
TEST("require that simple dynamic tensor lambda works") {
TEST_DO(verify_generic("tensor(x[3])(x+a)", "tensor(x[3]):[1,2,3]", EvalMode::COMPILED));
}
TEST("require that compiled multi-dimensional multi-param dynamic tensor lambda works") {
TEST_DO(verify_generic("tensor(x[3],y[2])((b-a)+x+y)", "tensor(x[3],y[2]):[[1,2],[2,3],[3,4]]", EvalMode::COMPILED));
TEST_DO(verify_generic("tensor<float>(x[3],y[2])((b-a)+x+y)", "tensor<float>(x[3],y[2]):[[1,2],[2,3],[3,4]]", EvalMode::COMPILED));
}
TEST("require that interpreted multi-dimensional multi-param dynamic tensor lambda works") {
TEST_DO(verify_generic("tensor(x[3],y[2])((x3{x:(a)}-a)+x+y)", "tensor(x[3],y[2]):[[1,2],[2,3],[3,4]]", EvalMode::INTERPRETED));
TEST_DO(verify_generic("tensor<float>(x[3],y[2])((x3{x:(a)}-a)+x+y)", "tensor<float>(x[3],y[2]):[[1,2],[2,3],[3,4]]", EvalMode::INTERPRETED));
}
TEST("require that tensor lambda can be used for tensor slicing") {
TEST_DO(verify_generic("tensor(x[2])(x3{x:(x+a)})", "tensor(x[2]):[2,3]", EvalMode::INTERPRETED));
TEST_DO(verify_generic("tensor(x[2])(a+x3{x:(x)})", "tensor(x[2]):[2,3]", EvalMode::INTERPRETED));
}
TEST("require that tensor lambda can be used for cell type casting") {
TEST_DO(verify_idx_fun("tensor(x[3])(x3f{x:(x)})", "tensor(x[3]):[1,2,3]", "f(x)(x)"));
TEST_DO(verify_idx_fun("tensor<float>(x[3])(x3{x:(x)})", "tensor<float>(x[3]):[1,2,3]", "f(x)(x)"));
}
TEST("require that tensor lambda can be used to convert from sparse to dense tensors") {
TEST_DO(verify_generic("tensor(x[3])(x3m{x:(x)})", "tensor(x[3]):[1,2,3]", EvalMode::INTERPRETED));
TEST_DO(verify_generic("tensor(x[2])(x3m{x:(x)})", "tensor(x[2]):[1,2]", EvalMode::INTERPRETED));
}
TEST("require that constant nested tensor lambda using tensor peek works") {
TEST_DO(verify_const("tensor(x[2])(tensor(y[2])((x+y)+1){y:(x)})", "tensor(x[2]):[1,3]"));
}
TEST("require that dynamic nested tensor lambda using tensor peek works") {
TEST_DO(verify_generic("tensor(x[2])(tensor(y[2])((x+y)+a){y:(x)})", "tensor(x[2]):[1,3]", EvalMode::INTERPRETED));
}
TEST("require that tensor reshape is optimized") {
TEST_DO(verify_reshape("tensor(x[15])(x3y5{x:(x/5),y:(x%5)})", "x15"));
TEST_DO(verify_reshape("tensor(x[3],y[5])(x15{x:(x*5+y)})", "x3y5"));
TEST_DO(verify_reshape("tensor<float>(x[15])(x3y5f{x:(x/5),y:(x%5)})", "x15f"));
}
TEST("require that tensor reshape with non-matching cell type requires cell copy") {
TEST_DO(verify_idx_fun("tensor(x[15])(x3y5f{x:(x/5),y:(x%5)})", "x15", "f(x)((floor((x/5))*5)+(x%5))"));
TEST_DO(verify_idx_fun("tensor<float>(x[15])(x3y5{x:(x/5),y:(x%5)})", "x15f", "f(x)((floor((x/5))*5)+(x%5))"));
TEST_DO(verify_idx_fun("tensor(x[3],y[5])(x15f{x:(x*5+y)})", "x3y5", "f(x,y)((x*5)+y)"));
TEST_DO(verify_idx_fun("tensor<float>(x[3],y[5])(x15{x:(x*5+y)})", "x3y5f", "f(x,y)((x*5)+y)"));
}
TEST("require that tensor cell subrange view is optimized") {
TEST_DO(verify_range("tensor(y[5])(x3y5{x:1,y:(y)})", "x3y5{x:1}"));
TEST_DO(verify_range("tensor(x[3])(x15{x:(x+5)})", "tensor(x[3]):[6,7,8]"));
TEST_DO(verify_range("tensor<float>(y[5])(x3y5f{x:1,y:(y)})", "x3y5f{x:1}"));
TEST_DO(verify_range("tensor<float>(x[3])(x15f{x:(x+5)})", "tensor<float>(x[3]):[6,7,8]"));
}
TEST("require that tensor cell subrange with non-matching cell type requires cell copy") {
TEST_DO(verify_idx_fun("tensor(x[3])(x15f{x:(x+5)})", "tensor(x[3]):[6,7,8]", "f(x)(x+5)"));
TEST_DO(verify_idx_fun("tensor<float>(x[3])(x15{x:(x+5)})", "tensor<float>(x[3]):[6,7,8]", "f(x)(x+5)"));
}
TEST("require that non-continuous cell extraction is optimized") {
TEST_DO(verify_idx_fun("tensor(x[3])(x3y5{x:(x),y:2})", "x3y5{y:2}", "f(x)((floor(x)*5)+2)"));
TEST_DO(verify_idx_fun("tensor(x[3])(x3y5f{x:(x),y:2})", "x3y5{y:2}", "f(x)((floor(x)*5)+2)"));
TEST_DO(verify_idx_fun("tensor<float>(x[3])(x3y5{x:(x),y:2})", "x3y5f{y:2}", "f(x)((floor(x)*5)+2)"));
TEST_DO(verify_idx_fun("tensor<float>(x[3])(x3y5f{x:(x),y:2})", "x3y5f{y:2}", "f(x)((floor(x)*5)+2)"));
}
TEST("require that out-of-bounds cell extraction is not optimized") {
TEST_DO(verify_generic("tensor(x[3])(x3y5{x:1,y:(x+3)})", "tensor(x[3]):[9,10,0]", EvalMode::INTERPRETED));
TEST_DO(verify_generic("tensor(x[3])(x3y5{x:1,y:(x-1)})", "tensor(x[3]):[0,6,7]", EvalMode::INTERPRETED));
TEST_DO(verify_generic("tensor(x[3])(x3y5{x:(x+1),y:(x)})", "tensor(x[3]):[6,12,0]", EvalMode::INTERPRETED));
TEST_DO(verify_generic("tensor(x[3])(x3y5{x:(x-1),y:(x)})", "tensor(x[3]):[0,2,8]", EvalMode::INTERPRETED));
}
TEST("require that non-double result from inner tensor lambda function fails type resolving") {
auto fun_a = Function::parse("tensor(x[2])(a)");
auto fun_b = Function::parse("tensor(x[2])(a{y:(x)})");
NodeTypes types_ad(*fun_a, {ValueType::from_spec("double")});
NodeTypes types_at(*fun_a, {ValueType::from_spec("tensor(y[2])")});
NodeTypes types_bd(*fun_b, {ValueType::from_spec("double")});
NodeTypes types_bt(*fun_b, {ValueType::from_spec("tensor(y[2])")});
EXPECT_EQUAL(types_ad.get_type(fun_a->root()).to_spec(), "tensor(x[2])");
EXPECT_EQUAL(types_at.get_type(fun_a->root()).to_spec(), "error");
EXPECT_EQUAL(types_bd.get_type(fun_b->root()).to_spec(), "error");
EXPECT_EQUAL(types_bt.get_type(fun_b->root()).to_spec(), "tensor(x[2])");
}
TEST("require that type resolving also include nodes in the inner tensor lambda function") {
auto fun = Function::parse("tensor(x[2])(a)");
NodeTypes types(*fun, {ValueType::from_spec("double")});
auto lambda = nodes::as<nodes::TensorLambda>(fun->root());
ASSERT_TRUE(lambda != nullptr);
EXPECT_EQUAL(types.get_type(*lambda).to_spec(), "tensor(x[2])");
auto symbol = nodes::as<nodes::Symbol>(lambda->lambda().root());
ASSERT_TRUE(symbol != nullptr);
EXPECT_EQUAL(types.get_type(*symbol).to_spec(), "double");
}
TEST_MAIN() { TEST_RUN_ALL(); }
<|endoftext|> |
<commit_before>// $Id$
/***********************************************************************
Moses - factored phrase-based, hierarchical and syntactic language decoder
Copyright (C) 2009 Hieu Hoang
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 <algorithm>
#include <iostream>
#include <string>
#include <vector>
#include <iterator>
#include <cassert>
#include "../moses/src/InputFileStream.h"
#include "../moses/src/Util.h"
#include "../moses/src/UserMessage.h"
#include "../OnDiskPt/OnDiskWrapper.h"
#include "../OnDiskPt/SourcePhrase.h"
#include "../OnDiskPt/TargetPhrase.h"
#include "../OnDiskPt/TargetPhraseCollection.h"
#include "../OnDiskPt/Word.h"
#include "../OnDiskPt/Vocab.h"
#include "Main.h"
using namespace std;
using namespace OnDiskPt;
int main (int argc, char * const argv[])
{
// insert code here...
Moses::ResetUserTime();
Moses::PrintUserTime("Starting");
if (argc != 8) {
std::cerr << "Usage: " << argv[0] << " numSourceFactors numTargetFactors numScores tableLimit inputPath outputPath" << std::endl;
return 1;
}
int numSourceFactors = Moses::Scan<int>(argv[1])
, numTargetFactors = Moses::Scan<int>(argv[2])
, numScores = Moses::Scan<int>(argv[3])
, tableLimit = Moses::Scan<int>(argv[4]);
TargetPhraseCollection::s_sortScoreInd = Moses::Scan<int>(argv[5]);
assert(TargetPhraseCollection::s_sortScoreInd < numScores);
const string filePath = argv[6]
,destPath = argv[7];
Moses::InputFileStream inStream(filePath);
OnDiskWrapper onDiskWrapper;
bool retDb = onDiskWrapper.BeginSave(destPath, numSourceFactors, numTargetFactors, numScores);
assert(retDb);
PhraseNode &rootNode = onDiskWrapper.GetRootSourceNode();
size_t lineNum = 0;
char line[100000];
//while(getline(inStream, line))
while(inStream.getline(line, 100000)) {
lineNum++;
if (lineNum%1000 == 0) cerr << "." << flush;
if (lineNum%10000 == 0) cerr << ":" << flush;
if (lineNum%100000 == 0) cerr << lineNum << flush;
//cerr << lineNum << " " << line << endl;
std::vector<float> misc(1);
SourcePhrase sourcePhrase;
TargetPhrase *targetPhrase = new TargetPhrase(numScores);
OnDiskPt::PhrasePtr spShort = Tokenize(sourcePhrase, *targetPhrase, line, onDiskWrapper, numScores, misc);
assert(misc.size() == onDiskWrapper.GetNumCounts());
rootNode.AddTargetPhrase(sourcePhrase, targetPhrase, onDiskWrapper, tableLimit, misc, spShort);
}
rootNode.Save(onDiskWrapper, 0, tableLimit);
onDiskWrapper.EndSave();
Moses::PrintUserTime("Finished");
//pause();
return 0;
} // main()
bool Flush(const OnDiskPt::SourcePhrase *prevSourcePhrase, const OnDiskPt::SourcePhrase *currSourcePhrase)
{
if (prevSourcePhrase == NULL)
return false;
assert(currSourcePhrase);
bool ret = (*currSourcePhrase > *prevSourcePhrase);
//cerr << *prevSourcePhrase << endl << *currSourcePhrase << " " << ret << endl << endl;
return ret;
}
OnDiskPt::PhrasePtr Tokenize(SourcePhrase &sourcePhrase, TargetPhrase &targetPhrase, char *line, OnDiskWrapper &onDiskWrapper, int numScores, vector<float> &misc)
{
size_t scoreInd = 0;
// MAIN LOOP
size_t stage = 0;
/* 0 = source phrase
1 = target phrase
2 = scores
3 = align
4 = count
*/
char *tok = strtok (line," ");
OnDiskPt::PhrasePtr out(new Phrase());
while (tok != NULL) {
if (0 == strcmp(tok, "|||")) {
++stage;
} else {
switch (stage) {
case 0: {
WordPtr w = Tokenize(sourcePhrase, tok, true, true, onDiskWrapper);
if (w != NULL)
out->AddWord(w);
break;
}
case 1: {
Tokenize(targetPhrase, tok, false, true, onDiskWrapper);
break;
}
case 2: {
float score = Moses::Scan<float>(tok);
targetPhrase.SetScore(score, scoreInd);
++scoreInd;
break;
}
case 3: {
//targetPhrase.Create1AlignFromString(tok);
targetPhrase.CreateAlignFromString(tok);
break;
}
case 4:
++stage;
break;
/* case 5: {
// count info. Only store the 2nd one
float val = Moses::Scan<float>(tok);
misc[0] = val;
++stage;
break;
}*/
case 5: {
// count info. Only store the 2nd one
//float val = Moses::Scan<float>(tok);
//misc[0] = val;
++stage;
break;
}
case 6: {
// store only the 3rd one (rule count)
float val = Moses::Scan<float>(tok);
misc[0] = val;
++stage;
break;
}
default:
assert(false);
break;
}
}
tok = strtok (NULL, " ");
} // while (tok != NULL)
assert(scoreInd == numScores);
targetPhrase.SortAlign();
return out;
} // Tokenize()
OnDiskPt::WordPtr Tokenize(OnDiskPt::Phrase &phrase
, const std::string &token, bool addSourceNonTerm, bool addTargetNonTerm
, OnDiskPt::OnDiskWrapper &onDiskWrapper)
{
bool nonTerm = false;
size_t tokSize = token.size();
int comStr =token.compare(0, 1, "[");
if (comStr == 0) {
comStr = token.compare(tokSize - 1, 1, "]");
nonTerm = comStr == 0;
}
OnDiskPt::WordPtr out;
if (nonTerm) {
// non-term
size_t splitPos = token.find_first_of("[", 2);
string wordStr = token.substr(0, splitPos);
if (splitPos == string::npos) {
// lhs - only 1 word
WordPtr word(new Word());
word->CreateFromString(wordStr, onDiskWrapper.GetVocab());
phrase.AddWord(word);
} else {
// source & target non-terms
if (addSourceNonTerm) {
WordPtr word(new Word());
word->CreateFromString(wordStr, onDiskWrapper.GetVocab());
phrase.AddWord(word);
}
wordStr = token.substr(splitPos, tokSize - splitPos);
if (addTargetNonTerm) {
WordPtr word(new Word());
word->CreateFromString(wordStr, onDiskWrapper.GetVocab());
phrase.AddWord(word);
out = word;
}
}
} else {
// term
WordPtr word(new Word());
word->CreateFromString(token, onDiskWrapper.GetVocab());
phrase.AddWord(word);
out = word;
}
return out;
}
void InsertTargetNonTerminals(std::vector<std::string> &sourceToks, const std::vector<std::string> &targetToks, const ::AlignType &alignments)
{
for (int ind = alignments.size() - 1; ind >= 0; --ind) {
const ::AlignPair &alignPair = alignments[ind];
size_t sourcePos = alignPair.first
,targetPos = alignPair.second;
const string &target = targetToks[targetPos];
sourceToks.insert(sourceToks.begin() + sourcePos + 1, target);
}
}
class AlignOrderer
{
public:
bool operator()(const ::AlignPair &a, const ::AlignPair &b) const {
return a.first < b.first;
}
};
void SortAlign(::AlignType &alignments)
{
std::sort(alignments.begin(), alignments.end(), AlignOrderer());
}
<commit_msg>D'oh missed an argument in usage<commit_after>// $Id$
/***********************************************************************
Moses - factored phrase-based, hierarchical and syntactic language decoder
Copyright (C) 2009 Hieu Hoang
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 <algorithm>
#include <iostream>
#include <string>
#include <vector>
#include <iterator>
#include <cassert>
#include "../moses/src/InputFileStream.h"
#include "../moses/src/Util.h"
#include "../moses/src/UserMessage.h"
#include "../OnDiskPt/OnDiskWrapper.h"
#include "../OnDiskPt/SourcePhrase.h"
#include "../OnDiskPt/TargetPhrase.h"
#include "../OnDiskPt/TargetPhraseCollection.h"
#include "../OnDiskPt/Word.h"
#include "../OnDiskPt/Vocab.h"
#include "Main.h"
using namespace std;
using namespace OnDiskPt;
int main (int argc, char * const argv[])
{
// insert code here...
Moses::ResetUserTime();
Moses::PrintUserTime("Starting");
if (argc != 8) {
std::cerr << "Usage: " << argv[0] << " numSourceFactors numTargetFactors numScores tableLimit sortScoreIndex inputPath outputPath" << std::endl;
return 1;
}
int numSourceFactors = Moses::Scan<int>(argv[1])
, numTargetFactors = Moses::Scan<int>(argv[2])
, numScores = Moses::Scan<int>(argv[3])
, tableLimit = Moses::Scan<int>(argv[4]);
TargetPhraseCollection::s_sortScoreInd = Moses::Scan<int>(argv[5]);
assert(TargetPhraseCollection::s_sortScoreInd < numScores);
const string filePath = argv[6]
,destPath = argv[7];
Moses::InputFileStream inStream(filePath);
OnDiskWrapper onDiskWrapper;
bool retDb = onDiskWrapper.BeginSave(destPath, numSourceFactors, numTargetFactors, numScores);
assert(retDb);
PhraseNode &rootNode = onDiskWrapper.GetRootSourceNode();
size_t lineNum = 0;
char line[100000];
//while(getline(inStream, line))
while(inStream.getline(line, 100000)) {
lineNum++;
if (lineNum%1000 == 0) cerr << "." << flush;
if (lineNum%10000 == 0) cerr << ":" << flush;
if (lineNum%100000 == 0) cerr << lineNum << flush;
//cerr << lineNum << " " << line << endl;
std::vector<float> misc(1);
SourcePhrase sourcePhrase;
TargetPhrase *targetPhrase = new TargetPhrase(numScores);
OnDiskPt::PhrasePtr spShort = Tokenize(sourcePhrase, *targetPhrase, line, onDiskWrapper, numScores, misc);
assert(misc.size() == onDiskWrapper.GetNumCounts());
rootNode.AddTargetPhrase(sourcePhrase, targetPhrase, onDiskWrapper, tableLimit, misc, spShort);
}
rootNode.Save(onDiskWrapper, 0, tableLimit);
onDiskWrapper.EndSave();
Moses::PrintUserTime("Finished");
//pause();
return 0;
} // main()
bool Flush(const OnDiskPt::SourcePhrase *prevSourcePhrase, const OnDiskPt::SourcePhrase *currSourcePhrase)
{
if (prevSourcePhrase == NULL)
return false;
assert(currSourcePhrase);
bool ret = (*currSourcePhrase > *prevSourcePhrase);
//cerr << *prevSourcePhrase << endl << *currSourcePhrase << " " << ret << endl << endl;
return ret;
}
OnDiskPt::PhrasePtr Tokenize(SourcePhrase &sourcePhrase, TargetPhrase &targetPhrase, char *line, OnDiskWrapper &onDiskWrapper, int numScores, vector<float> &misc)
{
size_t scoreInd = 0;
// MAIN LOOP
size_t stage = 0;
/* 0 = source phrase
1 = target phrase
2 = scores
3 = align
4 = count
*/
char *tok = strtok (line," ");
OnDiskPt::PhrasePtr out(new Phrase());
while (tok != NULL) {
if (0 == strcmp(tok, "|||")) {
++stage;
} else {
switch (stage) {
case 0: {
WordPtr w = Tokenize(sourcePhrase, tok, true, true, onDiskWrapper);
if (w != NULL)
out->AddWord(w);
break;
}
case 1: {
Tokenize(targetPhrase, tok, false, true, onDiskWrapper);
break;
}
case 2: {
float score = Moses::Scan<float>(tok);
targetPhrase.SetScore(score, scoreInd);
++scoreInd;
break;
}
case 3: {
//targetPhrase.Create1AlignFromString(tok);
targetPhrase.CreateAlignFromString(tok);
break;
}
case 4:
++stage;
break;
/* case 5: {
// count info. Only store the 2nd one
float val = Moses::Scan<float>(tok);
misc[0] = val;
++stage;
break;
}*/
case 5: {
// count info. Only store the 2nd one
//float val = Moses::Scan<float>(tok);
//misc[0] = val;
++stage;
break;
}
case 6: {
// store only the 3rd one (rule count)
float val = Moses::Scan<float>(tok);
misc[0] = val;
++stage;
break;
}
default:
assert(false);
break;
}
}
tok = strtok (NULL, " ");
} // while (tok != NULL)
assert(scoreInd == numScores);
targetPhrase.SortAlign();
return out;
} // Tokenize()
OnDiskPt::WordPtr Tokenize(OnDiskPt::Phrase &phrase
, const std::string &token, bool addSourceNonTerm, bool addTargetNonTerm
, OnDiskPt::OnDiskWrapper &onDiskWrapper)
{
bool nonTerm = false;
size_t tokSize = token.size();
int comStr =token.compare(0, 1, "[");
if (comStr == 0) {
comStr = token.compare(tokSize - 1, 1, "]");
nonTerm = comStr == 0;
}
OnDiskPt::WordPtr out;
if (nonTerm) {
// non-term
size_t splitPos = token.find_first_of("[", 2);
string wordStr = token.substr(0, splitPos);
if (splitPos == string::npos) {
// lhs - only 1 word
WordPtr word(new Word());
word->CreateFromString(wordStr, onDiskWrapper.GetVocab());
phrase.AddWord(word);
} else {
// source & target non-terms
if (addSourceNonTerm) {
WordPtr word(new Word());
word->CreateFromString(wordStr, onDiskWrapper.GetVocab());
phrase.AddWord(word);
}
wordStr = token.substr(splitPos, tokSize - splitPos);
if (addTargetNonTerm) {
WordPtr word(new Word());
word->CreateFromString(wordStr, onDiskWrapper.GetVocab());
phrase.AddWord(word);
out = word;
}
}
} else {
// term
WordPtr word(new Word());
word->CreateFromString(token, onDiskWrapper.GetVocab());
phrase.AddWord(word);
out = word;
}
return out;
}
void InsertTargetNonTerminals(std::vector<std::string> &sourceToks, const std::vector<std::string> &targetToks, const ::AlignType &alignments)
{
for (int ind = alignments.size() - 1; ind >= 0; --ind) {
const ::AlignPair &alignPair = alignments[ind];
size_t sourcePos = alignPair.first
,targetPos = alignPair.second;
const string &target = targetToks[targetPos];
sourceToks.insert(sourceToks.begin() + sourcePos + 1, target);
}
}
class AlignOrderer
{
public:
bool operator()(const ::AlignPair &a, const ::AlignPair &b) const {
return a.first < b.first;
}
};
void SortAlign(::AlignType &alignments)
{
std::sort(alignments.begin(), alignments.end(), AlignOrderer());
}
<|endoftext|> |
<commit_before>/***************************************************************************
* tests/mng/test_aligned.cpp
*
* Part of the STXXL. See http://stxxl.sourceforge.net
*
* Copyright (C) 2009 Andreas Beckmann <[email protected]>
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
**************************************************************************/
#define STXXL_VERBOSE_LEVEL 0
#define STXXL_VERBOSE_ALIGNED_ALLOC STXXL_VERBOSE0
#define STXXL_VERBOSE_TYPED_BLOCK STXXL_VERBOSE0
#include <iostream>
#include <vector>
#include <stxxl/mng>
#define BLOCK_SIZE (1024 * 1024)
struct type
{
int i;
~type() { }
};
typedef stxxl::typed_block<BLOCK_SIZE, type> block_type;
template class stxxl::typed_block<BLOCK_SIZE, type>; // forced instantiation
void test_typed_block()
{
block_type* a = new block_type;
block_type* b = new block_type;
block_type* A = new block_type[4];
block_type* B = new block_type[1];
block_type* C = NULL;
C = new block_type[0];
delete a;
a = b;
b = 0;
//-tb delete of NULL is a noop
//delete b;
delete a;
delete[] A;
delete[] B;
delete[] C;
}
void test_aligned_alloc()
{
void* p = stxxl::aligned_alloc<1024>(4096);
void* q = NULL;
void* r = stxxl::aligned_alloc<1024>(4096, 42);
stxxl::aligned_dealloc<1024>(p);
stxxl::aligned_dealloc<1024>(q);
stxxl::aligned_dealloc<1024>(r);
}
void test_typed_block_vector()
{
std::vector<block_type> v1(2);
std::vector<block_type, stxxl::new_alloc<block_type> > v2(2);
}
int main()
{
test_typed_block();
test_aligned_alloc();
test_typed_block_vector();
return 0;
}
// vim: et:ts=4:sw=4
<commit_msg>Reduce block size in test_aligned due to segfaults.<commit_after>/***************************************************************************
* tests/mng/test_aligned.cpp
*
* Part of the STXXL. See http://stxxl.sourceforge.net
*
* Copyright (C) 2009 Andreas Beckmann <[email protected]>
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
**************************************************************************/
#define STXXL_VERBOSE_LEVEL 0
#define STXXL_VERBOSE_ALIGNED_ALLOC STXXL_VERBOSE0
#define STXXL_VERBOSE_TYPED_BLOCK STXXL_VERBOSE0
#include <iostream>
#include <vector>
#include <stxxl/mng>
#define BLOCK_SIZE (512 * 1024)
struct type
{
int i;
~type() { }
};
typedef stxxl::typed_block<BLOCK_SIZE, type> block_type;
template class stxxl::typed_block<BLOCK_SIZE, type>; // forced instantiation
void test_typed_block()
{
block_type* a = new block_type;
block_type* b = new block_type;
block_type* A = new block_type[4];
block_type* B = new block_type[1];
block_type* C = NULL;
C = new block_type[0];
delete a;
a = b;
b = 0;
//-tb delete of NULL is a noop
//delete b;
delete a;
delete[] A;
delete[] B;
delete[] C;
}
void test_aligned_alloc()
{
void* p = stxxl::aligned_alloc<1024>(4096);
void* q = NULL;
void* r = stxxl::aligned_alloc<1024>(4096, 42);
stxxl::aligned_dealloc<1024>(p);
stxxl::aligned_dealloc<1024>(q);
stxxl::aligned_dealloc<1024>(r);
}
void test_typed_block_vector()
{
std::vector<block_type> v1(2);
std::vector<block_type, stxxl::new_alloc<block_type> > v2(2);
}
int main()
{
test_typed_block();
test_aligned_alloc();
test_typed_block_vector();
return 0;
}
// vim: et:ts=4:sw=4
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright RTK Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "rtkCudaForwardProjectionImageFilter.h"
#include "rtkCudaUtilities.hcu"
#include "rtkCudaForwardProjectionImageFilter.hcu"
#include <itkImageRegionConstIterator.h>
#include <itkImageRegionIteratorWithIndex.h>
#include <itkLinearInterpolateImageFunction.h>
#include <itkMacro.h>
#include "rtkMacro.h"
namespace rtk
{
CudaForwardProjectionImageFilter
::CudaForwardProjectionImageFilter()
{
m_DeviceVolume = NULL;
m_DeviceProjection = NULL;
m_DeviceMatrix = NULL;
}
void
CudaForwardProjectionImageFilter
::InitDevice()
{
// Dimension arguments in CUDA format for volume
m_VolumeDimension[0] = this->GetInput(1)->GetRequestedRegion().GetSize()[0];
m_VolumeDimension[1] = this->GetInput(1)->GetRequestedRegion().GetSize()[1];
m_VolumeDimension[2] = this->GetInput(1)->GetRequestedRegion().GetSize()[2];
// Dimension arguments in CUDA format for projections
m_ProjectionDimension[0] = this->GetInput(0)->GetRequestedRegion().GetSize()[0];
m_ProjectionDimension[1] = this->GetInput(0)->GetRequestedRegion().GetSize()[1];
// Cuda initialization
std::vector<int> devices = GetListOfCudaDevices();
if(devices.size()>1)
{
cudaThreadExit();
cudaSetDevice(devices[0]);
}
const float *host_volume = this->GetInput(1)->GetBufferPointer();
CUDA_forward_project_init (m_ProjectionDimension, m_VolumeDimension,
m_DeviceVolume, m_DeviceProjection, m_DeviceMatrix, host_volume);
}
void
CudaForwardProjectionImageFilter
::CleanUpDevice()
{
if(this->GetOutput()->GetRequestedRegion() != this->GetOutput()->GetBufferedRegion() )
itkExceptionMacro(<< "Can't handle different requested and buffered regions "
<< this->GetOutput()->GetRequestedRegion()
<< this->GetOutput()->GetBufferedRegion() );
CUDA_forward_project_cleanup (m_ProjectionDimension,
m_DeviceVolume,
m_DeviceProjection,
m_DeviceMatrix);
m_DeviceVolume = NULL;
m_DeviceProjection = NULL;
m_DeviceMatrix = NULL;
}
void
CudaForwardProjectionImageFilter
::GenerateData()
{
this->AllocateOutputs();
this->InitDevice();
const Superclass::GeometryType::Pointer geometry = this->GetGeometry();
const unsigned int Dimension = ImageType::ImageDimension;
const unsigned int iFirstProj = this->GetInput(0)->GetRequestedRegion().GetIndex(Dimension-1);
const unsigned int nProj = this->GetInput(0)->GetRequestedRegion().GetSize(Dimension-1);
const unsigned int nPixelsPerProj = this->GetOutput()->GetBufferedRegion().GetSize(0) *
this->GetOutput()->GetBufferedRegion().GetSize(1);
float t_step = 1; // Step in mm
int blockSize[3] = {16,16,1};
itk::Vector<double, 4> source_position;
// Setting BoxMin and BoxMax
// SR: we are using cuda textures where the pixel definition is not center but corner.
// Therefore, we set the box limits from index to index+size instead of, for ITK,
// index-0.5 to index+size-0.5.
float boxMin[3];
float boxMax[3];
for(unsigned int i=0; i<3; i++)
{
boxMin[i] = this->GetInput(1)->GetBufferedRegion().GetIndex()[i];
boxMax[i] = boxMin[i] + this->GetInput(1)->GetBufferedRegion().GetSize()[i];
}
// Getting Spacing
float spacing[3];
for(unsigned int i=0; i<3; i++)
spacing[i] = this->GetInput(1)->GetSpacing()[i];
// Go over each projection
for(unsigned int iProj=iFirstProj; iProj<iFirstProj+nProj; iProj++)
{
// Account for system rotations
Superclass::GeometryType::ThreeDHomogeneousMatrixType volPPToIndex;
volPPToIndex = GetPhysicalPointToIndexMatrix( this->GetInput(1) );
// Adding 0.5 offset to change from the centered pixel convention (ITK)
// to the corner pixel convention (CUDA).
for(unsigned int i=0; i<3; i++)
volPPToIndex[i][3] += 0.5;
// Compute matrix to transform projection index to volume index
Superclass::GeometryType::ThreeDHomogeneousMatrixType d_matrix;
d_matrix = volPPToIndex.GetVnlMatrix() *
geometry->GetProjectionCoordinatesToFixedSystemMatrix(iProj).GetVnlMatrix() *
GetIndexToPhysicalPointMatrix( this->GetInput() ).GetVnlMatrix();
float matrix[4][4];
for (int j=0; j<4; j++)
for (int k=0; k<4; k++)
matrix[j][k] = (float)d_matrix[j][k];
// Set source position in volume indices
source_position = volPPToIndex * geometry->GetSourcePosition(iProj);
CUDA_forward_project(blockSize,
this->GetOutput()->GetBufferPointer() + (iProj -
this->GetOutput()->GetBufferedRegion().GetIndex()[2]) *
nPixelsPerProj,
m_DeviceProjection,
(double*)&(source_position[0]),
m_ProjectionDimension,
t_step,
m_DeviceMatrix,
(float*)&(matrix[0][0]),
boxMin,
boxMax,
spacing);
}
this->CleanUpDevice();
}
} // end namespace rtk
<commit_msg>Account for memory management flag<commit_after>/*=========================================================================
*
* Copyright RTK Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "rtkCudaForwardProjectionImageFilter.h"
#include "rtkCudaUtilities.hcu"
#include "rtkCudaForwardProjectionImageFilter.hcu"
#include <itkImageRegionConstIterator.h>
#include <itkImageRegionIteratorWithIndex.h>
#include <itkLinearInterpolateImageFunction.h>
#include <itkMacro.h>
#include "rtkMacro.h"
namespace rtk
{
CudaForwardProjectionImageFilter
::CudaForwardProjectionImageFilter()
{
m_DeviceVolume = NULL;
m_DeviceProjection = NULL;
m_DeviceMatrix = NULL;
m_ExplicitGPUMemoryManagementFlag = false;
}
void
CudaForwardProjectionImageFilter
::InitDevice()
{
// Dimension arguments in CUDA format for volume
m_VolumeDimension[0] = this->GetInput(1)->GetRequestedRegion().GetSize()[0];
m_VolumeDimension[1] = this->GetInput(1)->GetRequestedRegion().GetSize()[1];
m_VolumeDimension[2] = this->GetInput(1)->GetRequestedRegion().GetSize()[2];
// Dimension arguments in CUDA format for projections
m_ProjectionDimension[0] = this->GetInput(0)->GetRequestedRegion().GetSize()[0];
m_ProjectionDimension[1] = this->GetInput(0)->GetRequestedRegion().GetSize()[1];
// Cuda initialization
std::vector<int> devices = GetListOfCudaDevices();
if(devices.size()>1)
{
cudaThreadExit();
cudaSetDevice(devices[0]);
}
const float *host_volume = this->GetInput(1)->GetBufferPointer();
CUDA_forward_project_init (m_ProjectionDimension, m_VolumeDimension,
m_DeviceVolume, m_DeviceProjection, m_DeviceMatrix, host_volume);
}
void
CudaForwardProjectionImageFilter
::CleanUpDevice()
{
if(this->GetOutput()->GetRequestedRegion() != this->GetOutput()->GetBufferedRegion() )
itkExceptionMacro(<< "Can't handle different requested and buffered regions "
<< this->GetOutput()->GetRequestedRegion()
<< this->GetOutput()->GetBufferedRegion() );
CUDA_forward_project_cleanup (m_ProjectionDimension,
m_DeviceVolume,
m_DeviceProjection,
m_DeviceMatrix);
m_DeviceVolume = NULL;
m_DeviceProjection = NULL;
m_DeviceMatrix = NULL;
}
void
CudaForwardProjectionImageFilter
::GenerateData()
{
this->AllocateOutputs();
if(!m_ExplicitGPUMemoryManagementFlag)
this->InitDevice();
const Superclass::GeometryType::Pointer geometry = this->GetGeometry();
const unsigned int Dimension = ImageType::ImageDimension;
const unsigned int iFirstProj = this->GetInput(0)->GetRequestedRegion().GetIndex(Dimension-1);
const unsigned int nProj = this->GetInput(0)->GetRequestedRegion().GetSize(Dimension-1);
const unsigned int nPixelsPerProj = this->GetOutput()->GetBufferedRegion().GetSize(0) *
this->GetOutput()->GetBufferedRegion().GetSize(1);
float t_step = 1; // Step in mm
int blockSize[3] = {16,16,1};
itk::Vector<double, 4> source_position;
// Setting BoxMin and BoxMax
// SR: we are using cuda textures where the pixel definition is not center but corner.
// Therefore, we set the box limits from index to index+size instead of, for ITK,
// index-0.5 to index+size-0.5.
float boxMin[3];
float boxMax[3];
for(unsigned int i=0; i<3; i++)
{
boxMin[i] = this->GetInput(1)->GetBufferedRegion().GetIndex()[i];
boxMax[i] = boxMin[i] + this->GetInput(1)->GetBufferedRegion().GetSize()[i];
}
// Getting Spacing
float spacing[3];
for(unsigned int i=0; i<3; i++)
spacing[i] = this->GetInput(1)->GetSpacing()[i];
// Go over each projection
for(unsigned int iProj=iFirstProj; iProj<iFirstProj+nProj; iProj++)
{
// Account for system rotations
Superclass::GeometryType::ThreeDHomogeneousMatrixType volPPToIndex;
volPPToIndex = GetPhysicalPointToIndexMatrix( this->GetInput(1) );
// Adding 0.5 offset to change from the centered pixel convention (ITK)
// to the corner pixel convention (CUDA).
for(unsigned int i=0; i<3; i++)
volPPToIndex[i][3] += 0.5;
// Compute matrix to transform projection index to volume index
Superclass::GeometryType::ThreeDHomogeneousMatrixType d_matrix;
d_matrix = volPPToIndex.GetVnlMatrix() *
geometry->GetProjectionCoordinatesToFixedSystemMatrix(iProj).GetVnlMatrix() *
GetIndexToPhysicalPointMatrix( this->GetInput() ).GetVnlMatrix();
float matrix[4][4];
for (int j=0; j<4; j++)
for (int k=0; k<4; k++)
matrix[j][k] = (float)d_matrix[j][k];
// Set source position in volume indices
source_position = volPPToIndex * geometry->GetSourcePosition(iProj);
CUDA_forward_project(blockSize,
this->GetOutput()->GetBufferPointer() + (iProj -
this->GetOutput()->GetBufferedRegion().GetIndex()[2]) *
nPixelsPerProj,
m_DeviceProjection,
(double*)&(source_position[0]),
m_ProjectionDimension,
t_step,
m_DeviceMatrix,
(float*)&(matrix[0][0]),
boxMin,
boxMax,
spacing);
}
if(!m_ExplicitGPUMemoryManagementFlag)
this->CleanUpDevice();
}
} // end namespace rtk
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: AccessibleViewForwarder.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: ihi $ $Date: 2006-11-14 14:24: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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#ifndef _SVX_ACCESSIBILITY_ACCESSIBLE_VIEW_FORWARDER_HXX
#include "AccessibleViewForwarder.hxx"
#endif
#ifndef _SVDPNTV_HXX
#include <svx/svdpntv.hxx>
#endif
#ifndef _SV_OUTDEV_HXX
#include <vcl/outdev.hxx>
#endif
#ifndef _SDRPAINTWINDOW_HXX
#include <svx/sdrpaintwindow.hxx>
#endif
namespace accessibility {
/** For the time beeing, the implementation of this class will not use the
member mrDevice. Instead the device is retrieved from the view
everytime it is used. This is necessary because the device has to stay
up-to-date with the current view and the class has to stay compatible.
May change in the future.
*/
AccessibleViewForwarder::AccessibleViewForwarder (SdrPaintView* pView, USHORT nWindowId)
: mpView (pView),
mnWindowId (nWindowId),
mrDevice (pView->GetPaintWindow((sal_uInt32)nWindowId)->GetOutputDevice())
{
OSL_ASSERT (mpView != NULL);
// empty
}
AccessibleViewForwarder::AccessibleViewForwarder (SdrPaintView* pView, OutputDevice& rDevice)
: mpView (pView),
mnWindowId (0),
mrDevice (rDevice)
{
// Search the output device to determine its id.
for(sal_uInt32 a(0L); a < mpView->PaintWindowCount(); a++)
{
SdrPaintWindow* pPaintWindow = mpView->GetPaintWindow(a);
OutputDevice& rOutDev = pPaintWindow->GetOutputDevice();
if(&rOutDev == &rDevice)
{
mnWindowId = (sal_uInt16)a;
break;
}
}
}
AccessibleViewForwarder::~AccessibleViewForwarder (void)
{
// empty
}
void AccessibleViewForwarder::SetView (SdrPaintView* pView)
{
mpView = pView;
OSL_ASSERT (mpView != NULL);
}
sal_Bool AccessibleViewForwarder::IsValid (void) const
{
return sal_True;
}
Rectangle AccessibleViewForwarder::GetVisibleArea (void) const
{
Rectangle aVisibleArea;
if((sal_uInt32)mnWindowId < mpView->PaintWindowCount())
{
SdrPaintWindow* pPaintWindow = mpView->GetPaintWindow((sal_uInt32)mnWindowId);
aVisibleArea = pPaintWindow->GetVisibleArea();
}
return aVisibleArea;
}
/** Tansform the given point into pixel coordiantes. After the the pixel
coordiantes of the window origin are added to make the point coordinates
absolute.
*/
Point AccessibleViewForwarder::LogicToPixel (const Point& rPoint) const
{
OSL_ASSERT (mpView != NULL);
if((sal_uInt32)mnWindowId < mpView->PaintWindowCount())
{
SdrPaintWindow* pPaintWindow = mpView->GetPaintWindow((sal_uInt32)mnWindowId);
OutputDevice& rOutDev = pPaintWindow->GetOutputDevice();
Rectangle aBBox(static_cast<Window&>(rOutDev).GetWindowExtentsRelative(0L));
return rOutDev.LogicToPixel (rPoint) + aBBox.TopLeft();
}
else
return Point();
}
Size AccessibleViewForwarder::LogicToPixel (const Size& rSize) const
{
OSL_ASSERT (mpView != NULL);
if((sal_uInt32)mnWindowId < mpView->PaintWindowCount())
{
SdrPaintWindow* pPaintWindow = mpView->GetPaintWindow((sal_uInt32)mnWindowId);
OutputDevice& rOutDev = pPaintWindow->GetOutputDevice();
return rOutDev.LogicToPixel (rSize);
}
else
return Size();
}
/** First subtract the window origin to make the point coordinates relative
to the window and then transform them into internal coordinates.
*/
Point AccessibleViewForwarder::PixelToLogic (const Point& rPoint) const
{
OSL_ASSERT (mpView != NULL);
if((sal_uInt32)mnWindowId < mpView->PaintWindowCount())
{
SdrPaintWindow* pPaintWindow = mpView->GetPaintWindow((sal_uInt32)mnWindowId);
OutputDevice& rOutDev = pPaintWindow->GetOutputDevice();
Rectangle aBBox (static_cast<Window&>(rOutDev).GetWindowExtentsRelative(0L));
return rOutDev.PixelToLogic (rPoint - aBBox.TopLeft());
}
else
return Point();
}
Size AccessibleViewForwarder::PixelToLogic (const Size& rSize) const
{
OSL_ASSERT (mpView != NULL);
if((sal_uInt32)mnWindowId < mpView->PaintWindowCount())
{
SdrPaintWindow* pPaintWindow = mpView->GetPaintWindow((sal_uInt32)mnWindowId);
OutputDevice& rOutDev = pPaintWindow->GetOutputDevice();
return rOutDev.PixelToLogic (rSize);
}
else
return Size();
}
} // end of namespace accessibility
<commit_msg>INTEGRATION: CWS changefileheader (1.8.314); FILE MERGED 2008/04/01 15:34:08 thb 1.8.314.2: #i85898# Stripping all external header guards 2008/03/31 13:56:54 rt 1.8.314.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: AccessibleViewForwarder.cxx,v $
* $Revision: 1.9 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#ifndef _SVX_ACCESSIBILITY_ACCESSIBLE_VIEW_FORWARDER_HXX
#include "AccessibleViewForwarder.hxx"
#endif
#include <svx/svdpntv.hxx>
#include <vcl/outdev.hxx>
#include <svx/sdrpaintwindow.hxx>
namespace accessibility {
/** For the time beeing, the implementation of this class will not use the
member mrDevice. Instead the device is retrieved from the view
everytime it is used. This is necessary because the device has to stay
up-to-date with the current view and the class has to stay compatible.
May change in the future.
*/
AccessibleViewForwarder::AccessibleViewForwarder (SdrPaintView* pView, USHORT nWindowId)
: mpView (pView),
mnWindowId (nWindowId),
mrDevice (pView->GetPaintWindow((sal_uInt32)nWindowId)->GetOutputDevice())
{
OSL_ASSERT (mpView != NULL);
// empty
}
AccessibleViewForwarder::AccessibleViewForwarder (SdrPaintView* pView, OutputDevice& rDevice)
: mpView (pView),
mnWindowId (0),
mrDevice (rDevice)
{
// Search the output device to determine its id.
for(sal_uInt32 a(0L); a < mpView->PaintWindowCount(); a++)
{
SdrPaintWindow* pPaintWindow = mpView->GetPaintWindow(a);
OutputDevice& rOutDev = pPaintWindow->GetOutputDevice();
if(&rOutDev == &rDevice)
{
mnWindowId = (sal_uInt16)a;
break;
}
}
}
AccessibleViewForwarder::~AccessibleViewForwarder (void)
{
// empty
}
void AccessibleViewForwarder::SetView (SdrPaintView* pView)
{
mpView = pView;
OSL_ASSERT (mpView != NULL);
}
sal_Bool AccessibleViewForwarder::IsValid (void) const
{
return sal_True;
}
Rectangle AccessibleViewForwarder::GetVisibleArea (void) const
{
Rectangle aVisibleArea;
if((sal_uInt32)mnWindowId < mpView->PaintWindowCount())
{
SdrPaintWindow* pPaintWindow = mpView->GetPaintWindow((sal_uInt32)mnWindowId);
aVisibleArea = pPaintWindow->GetVisibleArea();
}
return aVisibleArea;
}
/** Tansform the given point into pixel coordiantes. After the the pixel
coordiantes of the window origin are added to make the point coordinates
absolute.
*/
Point AccessibleViewForwarder::LogicToPixel (const Point& rPoint) const
{
OSL_ASSERT (mpView != NULL);
if((sal_uInt32)mnWindowId < mpView->PaintWindowCount())
{
SdrPaintWindow* pPaintWindow = mpView->GetPaintWindow((sal_uInt32)mnWindowId);
OutputDevice& rOutDev = pPaintWindow->GetOutputDevice();
Rectangle aBBox(static_cast<Window&>(rOutDev).GetWindowExtentsRelative(0L));
return rOutDev.LogicToPixel (rPoint) + aBBox.TopLeft();
}
else
return Point();
}
Size AccessibleViewForwarder::LogicToPixel (const Size& rSize) const
{
OSL_ASSERT (mpView != NULL);
if((sal_uInt32)mnWindowId < mpView->PaintWindowCount())
{
SdrPaintWindow* pPaintWindow = mpView->GetPaintWindow((sal_uInt32)mnWindowId);
OutputDevice& rOutDev = pPaintWindow->GetOutputDevice();
return rOutDev.LogicToPixel (rSize);
}
else
return Size();
}
/** First subtract the window origin to make the point coordinates relative
to the window and then transform them into internal coordinates.
*/
Point AccessibleViewForwarder::PixelToLogic (const Point& rPoint) const
{
OSL_ASSERT (mpView != NULL);
if((sal_uInt32)mnWindowId < mpView->PaintWindowCount())
{
SdrPaintWindow* pPaintWindow = mpView->GetPaintWindow((sal_uInt32)mnWindowId);
OutputDevice& rOutDev = pPaintWindow->GetOutputDevice();
Rectangle aBBox (static_cast<Window&>(rOutDev).GetWindowExtentsRelative(0L));
return rOutDev.PixelToLogic (rPoint - aBBox.TopLeft());
}
else
return Point();
}
Size AccessibleViewForwarder::PixelToLogic (const Size& rSize) const
{
OSL_ASSERT (mpView != NULL);
if((sal_uInt32)mnWindowId < mpView->PaintWindowCount())
{
SdrPaintWindow* pPaintWindow = mpView->GetPaintWindow((sal_uInt32)mnWindowId);
OutputDevice& rOutDev = pPaintWindow->GetOutputDevice();
return rOutDev.PixelToLogic (rSize);
}
else
return Size();
}
} // end of namespace accessibility
<|endoftext|> |
<commit_before>#include "precompiled.h"
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// VertexDeclarationCache.cpp: Implements a helper class to construct and cache vertex declarations.
#include "libGLESv2/ProgramBinary.h"
#include "libGLESv2/VertexAttribute.h"
#include "libGLESv2/renderer/d3d/d3d9/VertexBuffer9.h"
#include "libGLESv2/renderer/d3d/d3d9/VertexDeclarationCache.h"
#include "libGLESv2/renderer/d3d/d3d9/formatutils9.h"
namespace rx
{
VertexDeclarationCache::VertexDeclarationCache() : mMaxLru(0)
{
for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
{
mVertexDeclCache[i].vertexDeclaration = NULL;
mVertexDeclCache[i].lruCount = 0;
}
for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
mAppliedVBs[i].serial = 0;
}
mLastSetVDecl = NULL;
mInstancingEnabled = true;
}
VertexDeclarationCache::~VertexDeclarationCache()
{
for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
{
SafeRelease(mVertexDeclCache[i].vertexDeclaration);
}
}
GLenum VertexDeclarationCache::applyDeclaration(IDirect3DDevice9 *device, TranslatedAttribute attributes[], gl::ProgramBinary *programBinary, GLsizei instances, GLsizei *repeatDraw)
{
*repeatDraw = 1;
int indexedAttribute = gl::MAX_VERTEX_ATTRIBS;
int instancedAttribute = gl::MAX_VERTEX_ATTRIBS;
if (instances > 0)
{
// Find an indexed attribute to be mapped to D3D stream 0
for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
if (attributes[i].active)
{
if (indexedAttribute == gl::MAX_VERTEX_ATTRIBS && attributes[i].divisor == 0)
{
indexedAttribute = i;
}
else if (instancedAttribute == gl::MAX_VERTEX_ATTRIBS && attributes[i].divisor != 0)
{
instancedAttribute = i;
}
if (indexedAttribute != gl::MAX_VERTEX_ATTRIBS && instancedAttribute != gl::MAX_VERTEX_ATTRIBS)
break; // Found both an indexed and instanced attribute
}
}
if (indexedAttribute == gl::MAX_VERTEX_ATTRIBS)
{
return GL_INVALID_OPERATION;
}
}
D3DCAPS9 caps;
device->GetDeviceCaps(&caps);
D3DVERTEXELEMENT9 elements[gl::MAX_VERTEX_ATTRIBS + 1];
D3DVERTEXELEMENT9 *element = &elements[0];
for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
if (attributes[i].active)
{
// Directly binding the storage buffer is not supported for d3d9
ASSERT(attributes[i].storage == NULL);
int stream = i;
if (instances > 0)
{
// Due to a bug on ATI cards we can't enable instancing when none of the attributes are instanced.
if (instancedAttribute == gl::MAX_VERTEX_ATTRIBS)
{
*repeatDraw = instances;
}
else
{
if (i == indexedAttribute)
{
stream = 0;
}
else if (i == 0)
{
stream = indexedAttribute;
}
UINT frequency = 1;
if (attributes[i].divisor == 0)
{
frequency = D3DSTREAMSOURCE_INDEXEDDATA | instances;
}
else
{
frequency = D3DSTREAMSOURCE_INSTANCEDATA | attributes[i].divisor;
}
device->SetStreamSourceFreq(stream, frequency);
mInstancingEnabled = true;
}
}
VertexBuffer9 *vertexBuffer = VertexBuffer9::makeVertexBuffer9(attributes[i].vertexBuffer);
if (mAppliedVBs[stream].serial != attributes[i].serial ||
mAppliedVBs[stream].stride != attributes[i].stride ||
mAppliedVBs[stream].offset != attributes[i].offset)
{
device->SetStreamSource(stream, vertexBuffer->getBuffer(), attributes[i].offset, attributes[i].stride);
mAppliedVBs[stream].serial = attributes[i].serial;
mAppliedVBs[stream].stride = attributes[i].stride;
mAppliedVBs[stream].offset = attributes[i].offset;
}
gl::VertexFormat vertexFormat(*attributes[i].attribute, GL_FLOAT);
const d3d9::VertexFormat &d3d9VertexInfo = d3d9::GetVertexFormatInfo(caps.DeclTypes, vertexFormat);
element->Stream = stream;
element->Offset = 0;
element->Type = d3d9VertexInfo.nativeFormat;
element->Method = D3DDECLMETHOD_DEFAULT;
element->Usage = D3DDECLUSAGE_TEXCOORD;
element->UsageIndex = programBinary->getSemanticIndex(i);
element++;
}
}
if (instances == 0 || instancedAttribute == gl::MAX_VERTEX_ATTRIBS)
{
if (mInstancingEnabled)
{
for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
device->SetStreamSourceFreq(i, 1);
}
mInstancingEnabled = false;
}
}
static const D3DVERTEXELEMENT9 end = D3DDECL_END();
*(element++) = end;
for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
{
VertexDeclCacheEntry *entry = &mVertexDeclCache[i];
if (memcmp(entry->cachedElements, elements, (element - elements) * sizeof(D3DVERTEXELEMENT9)) == 0 && entry->vertexDeclaration)
{
entry->lruCount = ++mMaxLru;
if(entry->vertexDeclaration != mLastSetVDecl)
{
device->SetVertexDeclaration(entry->vertexDeclaration);
mLastSetVDecl = entry->vertexDeclaration;
}
return GL_NO_ERROR;
}
}
VertexDeclCacheEntry *lastCache = mVertexDeclCache;
for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
{
if (mVertexDeclCache[i].lruCount < lastCache->lruCount)
{
lastCache = &mVertexDeclCache[i];
}
}
if (lastCache->vertexDeclaration != NULL)
{
SafeRelease(lastCache->vertexDeclaration);
// mLastSetVDecl is set to the replacement, so we don't have to worry
// about it.
}
memcpy(lastCache->cachedElements, elements, (element - elements) * sizeof(D3DVERTEXELEMENT9));
device->CreateVertexDeclaration(elements, &lastCache->vertexDeclaration);
device->SetVertexDeclaration(lastCache->vertexDeclaration);
mLastSetVDecl = lastCache->vertexDeclaration;
lastCache->lruCount = ++mMaxLru;
return GL_NO_ERROR;
}
void VertexDeclarationCache::markStateDirty()
{
for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
mAppliedVBs[i].serial = 0;
}
mLastSetVDecl = NULL;
mInstancingEnabled = true; // Forces it to be disabled when not used
}
}
<commit_msg>Fix application of vertex divisor for non-instanced draws in D3D9<commit_after>#include "precompiled.h"
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// VertexDeclarationCache.cpp: Implements a helper class to construct and cache vertex declarations.
#include "libGLESv2/ProgramBinary.h"
#include "libGLESv2/VertexAttribute.h"
#include "libGLESv2/renderer/d3d/d3d9/VertexBuffer9.h"
#include "libGLESv2/renderer/d3d/d3d9/VertexDeclarationCache.h"
#include "libGLESv2/renderer/d3d/d3d9/formatutils9.h"
namespace rx
{
VertexDeclarationCache::VertexDeclarationCache() : mMaxLru(0)
{
for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
{
mVertexDeclCache[i].vertexDeclaration = NULL;
mVertexDeclCache[i].lruCount = 0;
}
for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
mAppliedVBs[i].serial = 0;
}
mLastSetVDecl = NULL;
mInstancingEnabled = true;
}
VertexDeclarationCache::~VertexDeclarationCache()
{
for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
{
SafeRelease(mVertexDeclCache[i].vertexDeclaration);
}
}
GLenum VertexDeclarationCache::applyDeclaration(IDirect3DDevice9 *device, TranslatedAttribute attributes[], gl::ProgramBinary *programBinary, GLsizei instances, GLsizei *repeatDraw)
{
*repeatDraw = 1;
int indexedAttribute = gl::MAX_VERTEX_ATTRIBS;
int instancedAttribute = gl::MAX_VERTEX_ATTRIBS;
if (instances == 0)
{
for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; ++i)
{
if (attributes[i].divisor != 0)
{
// If a divisor is set, it still applies even if an instanced draw was not used, so treat
// as a single-instance draw.
instances = 1;
break;
}
}
}
if (instances > 0)
{
// Find an indexed attribute to be mapped to D3D stream 0
for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
if (attributes[i].active)
{
if (indexedAttribute == gl::MAX_VERTEX_ATTRIBS && attributes[i].divisor == 0)
{
indexedAttribute = i;
}
else if (instancedAttribute == gl::MAX_VERTEX_ATTRIBS && attributes[i].divisor != 0)
{
instancedAttribute = i;
}
if (indexedAttribute != gl::MAX_VERTEX_ATTRIBS && instancedAttribute != gl::MAX_VERTEX_ATTRIBS)
break; // Found both an indexed and instanced attribute
}
}
if (indexedAttribute == gl::MAX_VERTEX_ATTRIBS)
{
return GL_INVALID_OPERATION;
}
}
D3DCAPS9 caps;
device->GetDeviceCaps(&caps);
D3DVERTEXELEMENT9 elements[gl::MAX_VERTEX_ATTRIBS + 1];
D3DVERTEXELEMENT9 *element = &elements[0];
for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
if (attributes[i].active)
{
// Directly binding the storage buffer is not supported for d3d9
ASSERT(attributes[i].storage == NULL);
int stream = i;
if (instances > 0)
{
// Due to a bug on ATI cards we can't enable instancing when none of the attributes are instanced.
if (instancedAttribute == gl::MAX_VERTEX_ATTRIBS)
{
*repeatDraw = instances;
}
else
{
if (i == indexedAttribute)
{
stream = 0;
}
else if (i == 0)
{
stream = indexedAttribute;
}
UINT frequency = 1;
if (attributes[i].divisor == 0)
{
frequency = D3DSTREAMSOURCE_INDEXEDDATA | instances;
}
else
{
frequency = D3DSTREAMSOURCE_INSTANCEDATA | attributes[i].divisor;
}
device->SetStreamSourceFreq(stream, frequency);
mInstancingEnabled = true;
}
}
VertexBuffer9 *vertexBuffer = VertexBuffer9::makeVertexBuffer9(attributes[i].vertexBuffer);
if (mAppliedVBs[stream].serial != attributes[i].serial ||
mAppliedVBs[stream].stride != attributes[i].stride ||
mAppliedVBs[stream].offset != attributes[i].offset)
{
device->SetStreamSource(stream, vertexBuffer->getBuffer(), attributes[i].offset, attributes[i].stride);
mAppliedVBs[stream].serial = attributes[i].serial;
mAppliedVBs[stream].stride = attributes[i].stride;
mAppliedVBs[stream].offset = attributes[i].offset;
}
gl::VertexFormat vertexFormat(*attributes[i].attribute, GL_FLOAT);
const d3d9::VertexFormat &d3d9VertexInfo = d3d9::GetVertexFormatInfo(caps.DeclTypes, vertexFormat);
element->Stream = stream;
element->Offset = 0;
element->Type = d3d9VertexInfo.nativeFormat;
element->Method = D3DDECLMETHOD_DEFAULT;
element->Usage = D3DDECLUSAGE_TEXCOORD;
element->UsageIndex = programBinary->getSemanticIndex(i);
element++;
}
}
if (instances == 0 || instancedAttribute == gl::MAX_VERTEX_ATTRIBS)
{
if (mInstancingEnabled)
{
for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
device->SetStreamSourceFreq(i, 1);
}
mInstancingEnabled = false;
}
}
static const D3DVERTEXELEMENT9 end = D3DDECL_END();
*(element++) = end;
for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
{
VertexDeclCacheEntry *entry = &mVertexDeclCache[i];
if (memcmp(entry->cachedElements, elements, (element - elements) * sizeof(D3DVERTEXELEMENT9)) == 0 && entry->vertexDeclaration)
{
entry->lruCount = ++mMaxLru;
if(entry->vertexDeclaration != mLastSetVDecl)
{
device->SetVertexDeclaration(entry->vertexDeclaration);
mLastSetVDecl = entry->vertexDeclaration;
}
return GL_NO_ERROR;
}
}
VertexDeclCacheEntry *lastCache = mVertexDeclCache;
for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
{
if (mVertexDeclCache[i].lruCount < lastCache->lruCount)
{
lastCache = &mVertexDeclCache[i];
}
}
if (lastCache->vertexDeclaration != NULL)
{
SafeRelease(lastCache->vertexDeclaration);
// mLastSetVDecl is set to the replacement, so we don't have to worry
// about it.
}
memcpy(lastCache->cachedElements, elements, (element - elements) * sizeof(D3DVERTEXELEMENT9));
device->CreateVertexDeclaration(elements, &lastCache->vertexDeclaration);
device->SetVertexDeclaration(lastCache->vertexDeclaration);
mLastSetVDecl = lastCache->vertexDeclaration;
lastCache->lruCount = ++mMaxLru;
return GL_NO_ERROR;
}
void VertexDeclarationCache::markStateDirty()
{
for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
mAppliedVBs[i].serial = 0;
}
mLastSetVDecl = NULL;
mInstancingEnabled = true; // Forces it to be disabled when not used
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <memory>
template <typename T>
class propagate_const
{
typedef decltype(*std::declval<T>()) reference_type;
public:
using value_type = typename std::enable_if<
std::is_lvalue_reference<reference_type>::value,
typename std::remove_reference<reference_type>::type>::type;
propagate_const() = default;
template <typename U, typename V = typename std::enable_if<std::is_convertible<U,T>::value>::type>
propagate_const(U&& u) : t{std::forward<U>(u)} {}
template <typename U>
propagate_const(const propagate_const<U>& pu) : t(pu.t) {}
template <typename U>
propagate_const(propagate_const<U>&& pu) : t(std::move(pu.t)) {}
template <typename U, typename V = typename std::enable_if<std::is_convertible<U,T>::value>::type>
propagate_const<T>& operator=(U&& u)
{
t = std::forward<U>(u);
return *this;
}
template <typename U>
propagate_const<T>& operator=(const propagate_const<U>& pt)
{
t = pt.t;
return *this;
}
template <typename U>
propagate_const<T>& operator=(propagate_const<U>&& pt)
{
t = std::move(pt.t);
return *this;
}
value_type* operator->() { return underlying_pointer(t); }
const value_type* operator->() const { return underlying_pointer(t); }
value_type* get() { return underlying_pointer(t); }
const value_type* get() const { return underlying_pointer(t); }
operator value_type*() { return underlying_pointer(t); }
operator const value_type*() const { return underlying_pointer(t); }
value_type& operator*() { return *t; }
const value_type& operator*() const { return *t; }
explicit operator bool() const { return static_cast<bool>(t); }
private:
T t;
template <typename U>
static value_type* underlying_pointer(U* p)
{
return p;
}
template <typename U>
static value_type* underlying_pointer(U& p)
{
return p.get();
}
template <typename U>
static const value_type* underlying_pointer(const U* p)
{
return p;
}
template <typename U>
static const value_type* underlying_pointer(const U& p)
{
return p.get();
}
};
struct A
{
void bar() const { std::cout << "bar (const)" << std::endl; }
void bar() { std::cout << "bar (non-const)" << std::endl; }
};
struct B
{
B() : m_ptrA(std::make_unique<A>()) {}
void operator()() { m_ptrA->bar(); }
void operator()() const { m_ptrA->bar(); }
propagate_const<std::unique_ptr<A>> m_ptrA;
};
int main(int argc, char* argv[])
{
const B b;
b();
A a;
propagate_const<A*> pcA(&a);
static_assert(std::is_trivially_destructible<decltype(pcA)>::value, "Not trivially destructible");
static_assert(std::is_trivially_move_constructible<decltype(pcA)>::value, "Not trivially move constructible");
propagate_const<A*> pcA2(pcA);
auto shptrA = std::make_shared<A>();
propagate_const<std::shared_ptr<A>> pcsptrA(shptrA);
propagate_const<std::shared_ptr<A>> pcsptrA2(pcsptrA);
propagate_const<std::shared_ptr<A>> pcsptrA3(std::move(pcsptrA));
propagate_const<std::unique_ptr<A>> pcuptrA(std::make_unique<A>());
propagate_const<std::unique_ptr<A>> pcuptrA2(std::move(pcuptrA));
}
<commit_msg>restrict operator value*<commit_after>#include <iostream>
#include <memory>
template <typename T>
class propagate_const
{
typedef decltype(*std::declval<T>()) reference_type;
public:
using value_type = typename std::enable_if<
std::is_lvalue_reference<reference_type>::value,
typename std::remove_reference<reference_type>::type>::type;
propagate_const() = default;
template <typename U, typename V = typename std::enable_if<std::is_convertible<U,T>::value>::type>
propagate_const(U&& u) : t{std::forward<U>(u)} {}
template <typename U>
propagate_const(const propagate_const<U>& pu) : t(pu.t) {}
template <typename U>
propagate_const(propagate_const<U>&& pu) : t(std::move(pu.t)) {}
template <typename U, typename V = typename std::enable_if<std::is_convertible<U,T>::value>::type>
propagate_const<T>& operator=(U&& u)
{
t = std::forward<U>(u);
return *this;
}
template <typename U>
propagate_const<T>& operator=(const propagate_const<U>& pt)
{
t = pt.t;
return *this;
}
template <typename U>
propagate_const<T>& operator=(propagate_const<U>&& pt)
{
t = std::move(pt.t);
return *this;
}
value_type* operator->() { return underlying_pointer(t); }
const value_type* operator->() const { return underlying_pointer(t); }
value_type* get() { return underlying_pointer(t); }
const value_type* get() const { return underlying_pointer(t); }
operator value_type*()
{
static_assert(std::is_pointer<T>::value,"");
return underlying_pointer(t);
}
operator const value_type*() const
{
static_assert(std::is_pointer<T>::value,"");
return underlying_pointer(t);
}
value_type& operator*() { return *t; }
const value_type& operator*() const { return *t; }
explicit operator bool() const { return static_cast<bool>(t); }
private:
T t;
template <typename U>
static value_type* underlying_pointer(U* p)
{
return p;
}
template <typename U>
static value_type* underlying_pointer(U& p)
{
return p.get();
}
template <typename U>
static const value_type* underlying_pointer(const U* p)
{
return p;
}
template <typename U>
static const value_type* underlying_pointer(const U& p)
{
return p.get();
}
};
struct A
{
void bar() const { std::cout << "bar (const)" << std::endl; }
void bar() { std::cout << "bar (non-const)" << std::endl; }
};
struct B
{
B() : m_ptrA(std::make_unique<A>()) {}
void operator()() { m_ptrA->bar(); }
void operator()() const { m_ptrA->bar(); }
propagate_const<std::unique_ptr<A>> m_ptrA;
};
int main(int argc, char* argv[])
{
const B b;
b();
A a;
propagate_const<A*> pcA(&a);
static_assert(std::is_trivially_destructible<decltype(pcA)>::value, "Not trivially destructible");
static_assert(std::is_trivially_move_constructible<decltype(pcA)>::value, "Not trivially move constructible");
propagate_const<A*> pcA2(pcA);
auto shptrA = std::make_shared<A>();
propagate_const<std::shared_ptr<A>> pcsptrA(shptrA);
propagate_const<std::shared_ptr<A>> pcsptrA2(pcsptrA);
propagate_const<std::shared_ptr<A>> pcsptrA3(std::move(pcsptrA));
propagate_const<std::unique_ptr<A>> pcuptrA(std::make_unique<A>());
propagate_const<std::unique_ptr<A>> pcuptrA2(std::move(pcuptrA));
}
<|endoftext|> |
<commit_before>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Written (W) 2007-2010 Christian Widmer
* Copyright (C) 2007-2010 Max-Planck-Society
*/
#include "lib/config.h"
#include "classifier/svm/DomainAdaptationSVMLinear.h"
#include "lib/io.h"
#include <iostream>
#include <vector>
#ifdef HAVE_BOOST_SERIALIZATION
#include <boost/serialization/export.hpp>
BOOST_CLASS_EXPORT(shogun::CDomainAdaptationSVMLinear);
#endif //HAVE_BOOST_SERIALIZATION
using namespace shogun;
CDomainAdaptationSVMLinear::CDomainAdaptationSVMLinear() : CLibLinear(L2R_L2LOSS_SVC_DUAL)
{
init(NULL, 0.0);
}
CDomainAdaptationSVMLinear::CDomainAdaptationSVMLinear(float64_t C, CDotFeatures* f, CLabels* lab, CLinearClassifier* pre_svm, float64_t B_param) : CLibLinear(C, f, lab)
{
init(pre_svm, B_param);
}
CDomainAdaptationSVMLinear::~CDomainAdaptationSVMLinear()
{
SG_UNREF(presvm);
SG_DEBUG("deleting DomainAdaptationSVMLinear\n");
}
void CDomainAdaptationSVMLinear::init(CLinearClassifier* pre_svm, float64_t B_param)
{
if (pre_svm)
{
// increase reference counts
SG_REF(pre_svm);
// set bias of parent svm to zero
pre_svm->set_bias(0.0);
}
this->presvm=pre_svm;
this->B=B_param;
this->train_factor=1.0;
set_liblinear_solver_type(L2R_L2LOSS_SVC_DUAL);
// invoke sanity check
is_presvm_sane();
}
bool CDomainAdaptationSVMLinear::is_presvm_sane()
{
if (!presvm) {
SG_WARNING("presvm is null");
} else {
if (presvm->get_bias() != 0) {
SG_ERROR("presvm bias not set to zero");
}
if (presvm->get_features()->get_feature_type() != this->get_features()->get_feature_type()) {
SG_ERROR("feature types do not agree");
}
}
return true;
}
bool CDomainAdaptationSVMLinear::train(CDotFeatures* train_data)
{
CDotFeatures* tmp_data;
if (train_data)
{
if (labels->get_num_labels() != train_data->get_num_vectors())
SG_ERROR("Number of training vectors does not match number of labels\n");
tmp_data = train_data;
} else {
tmp_data = features;
}
int32_t num_training_points = get_labels()->get_num_labels();
std::vector<float64_t> lin_term = std::vector<float64_t>(num_training_points);
if (presvm)
{
// bias of parent SVM was set to zero in constructor, already contains B
CLabels* parent_svm_out = presvm->classify(tmp_data);
SG_DEBUG("pre-computing linear term from presvm\n");
// pre-compute linear term
for (int32_t i=0; i!=num_training_points; i++)
{
lin_term[i] = (- B*(get_label(i) * parent_svm_out->get_label(i)))*train_factor - 1.0;
}
//set linear term for QP
this->set_linear_term(lin_term);
}
//presvm w stored in presvm
float64_t* tmp_w;
presvm->get_w(tmp_w, w_dim);
//copy vector
float64_t* tmp_w_copy = new float64_t[w_dim];
std::copy(tmp_w, tmp_w + w_dim, tmp_w_copy);
for (int32_t i=0; i!=w_dim; i++)
{
tmp_w_copy[i] = B * tmp_w_copy[i];
}
//set w (copied in setter)
set_w(tmp_w_copy, w_dim);
delete[] tmp_w_copy;
bool success = false;
//train SVM
if (train_data)
{
success = CLibLinear::train(train_data);
} else {
success = CLibLinear::train();
}
//ASSERT(presvm)
return success;
}
CLinearClassifier* CDomainAdaptationSVMLinear::get_presvm()
{
return presvm;
}
float64_t CDomainAdaptationSVMLinear::get_B()
{
return B;
}
float64_t CDomainAdaptationSVMLinear::get_train_factor()
{
return train_factor;
}
void CDomainAdaptationSVMLinear::set_train_factor(float64_t factor)
{
train_factor = factor;
}
CLabels* CDomainAdaptationSVMLinear::classify(CDotFeatures* data)
{
ASSERT(presvm->get_bias()==0.0);
int32_t num_examples = data->get_num_vectors();
CLabels* out_current = CLibLinear::classify(data);
if (presvm)
{
// recursive call if used on DomainAdaptationSVM object
CLabels* out_presvm = presvm->classify(data);
// combine outputs
for (int32_t i=0; i!=num_examples; i++)
{
float64_t out_combined = out_current->get_label(i) + B*out_presvm->get_label(i);
out_current->set_label(i, out_combined);
}
}
return out_current;
}
<commit_msg>adapted solver type<commit_after>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Written (W) 2007-2010 Christian Widmer
* Copyright (C) 2007-2010 Max-Planck-Society
*/
#include "lib/config.h"
#include "classifier/svm/DomainAdaptationSVMLinear.h"
#include "lib/io.h"
#include <iostream>
#include <vector>
#ifdef HAVE_BOOST_SERIALIZATION
#include <boost/serialization/export.hpp>
BOOST_CLASS_EXPORT(shogun::CDomainAdaptationSVMLinear);
#endif //HAVE_BOOST_SERIALIZATION
using namespace shogun;
CDomainAdaptationSVMLinear::CDomainAdaptationSVMLinear() : CLibLinear(L2R_L1LOSS_SVC_DUAL)
{
init(NULL, 0.0);
}
CDomainAdaptationSVMLinear::CDomainAdaptationSVMLinear(float64_t C, CDotFeatures* f, CLabels* lab, CLinearClassifier* pre_svm, float64_t B_param) : CLibLinear(C, f, lab)
{
init(pre_svm, B_param);
}
CDomainAdaptationSVMLinear::~CDomainAdaptationSVMLinear()
{
SG_UNREF(presvm);
SG_DEBUG("deleting DomainAdaptationSVMLinear\n");
}
void CDomainAdaptationSVMLinear::init(CLinearClassifier* pre_svm, float64_t B_param)
{
if (pre_svm)
{
// increase reference counts
SG_REF(pre_svm);
// set bias of parent svm to zero
pre_svm->set_bias(0.0);
}
this->presvm=pre_svm;
this->B=B_param;
this->train_factor=1.0;
set_liblinear_solver_type(L2R_L1LOSS_SVC_DUAL);
// invoke sanity check
is_presvm_sane();
}
bool CDomainAdaptationSVMLinear::is_presvm_sane()
{
if (!presvm) {
SG_WARNING("presvm is null");
} else {
if (presvm->get_bias() != 0) {
SG_ERROR("presvm bias not set to zero");
}
if (presvm->get_features()->get_feature_type() != this->get_features()->get_feature_type()) {
SG_ERROR("feature types do not agree");
}
}
return true;
}
bool CDomainAdaptationSVMLinear::train(CDotFeatures* train_data)
{
CDotFeatures* tmp_data;
if (train_data)
{
if (labels->get_num_labels() != train_data->get_num_vectors())
SG_ERROR("Number of training vectors does not match number of labels\n");
tmp_data = train_data;
} else {
tmp_data = features;
}
int32_t num_training_points = get_labels()->get_num_labels();
std::vector<float64_t> lin_term = std::vector<float64_t>(num_training_points);
if (presvm)
{
// bias of parent SVM was set to zero in constructor, already contains B
CLabels* parent_svm_out = presvm->classify(tmp_data);
SG_DEBUG("pre-computing linear term from presvm\n");
// pre-compute linear term
for (int32_t i=0; i!=num_training_points; i++)
{
lin_term[i] = (- B*(get_label(i) * parent_svm_out->get_label(i)))*train_factor - 1.0;
}
//set linear term for QP
this->set_linear_term(lin_term);
}
//presvm w stored in presvm
float64_t* tmp_w;
presvm->get_w(tmp_w, w_dim);
//copy vector
float64_t* tmp_w_copy = new float64_t[w_dim];
std::copy(tmp_w, tmp_w + w_dim, tmp_w_copy);
for (int32_t i=0; i!=w_dim; i++)
{
tmp_w_copy[i] = B * tmp_w_copy[i];
}
//set w (copied in setter)
set_w(tmp_w_copy, w_dim);
delete[] tmp_w_copy;
bool success = false;
//train SVM
if (train_data)
{
success = CLibLinear::train(train_data);
} else {
success = CLibLinear::train();
}
//ASSERT(presvm)
return success;
}
CLinearClassifier* CDomainAdaptationSVMLinear::get_presvm()
{
return presvm;
}
float64_t CDomainAdaptationSVMLinear::get_B()
{
return B;
}
float64_t CDomainAdaptationSVMLinear::get_train_factor()
{
return train_factor;
}
void CDomainAdaptationSVMLinear::set_train_factor(float64_t factor)
{
train_factor = factor;
}
CLabels* CDomainAdaptationSVMLinear::classify(CDotFeatures* data)
{
ASSERT(presvm->get_bias()==0.0);
int32_t num_examples = data->get_num_vectors();
CLabels* out_current = CLibLinear::classify(data);
if (presvm)
{
// recursive call if used on DomainAdaptationSVM object
CLabels* out_presvm = presvm->classify(data);
// combine outputs
for (int32_t i=0; i!=num_examples; i++)
{
float64_t out_combined = out_current->get_label(i) + B*out_presvm->get_label(i);
out_current->set_label(i, out_combined);
}
}
return out_current;
}
<|endoftext|> |
<commit_before>/*
* Copyright © 2012, 2013, 2014 Intel Corporation
*
* 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 (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND 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 "brw_vec4.h"
#include "brw_cfg.h"
using namespace brw;
/** @file brw_vec4_cse.cpp
*
* Support for local common subexpression elimination.
*
* See Muchnick's Advanced Compiler Design and Implementation, section
* 13.1 (p378).
*/
namespace {
struct aeb_entry : public exec_node {
/** The instruction that generates the expression value. */
vec4_instruction *generator;
/** The temporary where the value is stored. */
src_reg tmp;
};
}
static bool
is_expression(const vec4_instruction *const inst)
{
switch (inst->opcode) {
case BRW_OPCODE_SEL:
case BRW_OPCODE_NOT:
case BRW_OPCODE_AND:
case BRW_OPCODE_OR:
case BRW_OPCODE_XOR:
case BRW_OPCODE_SHR:
case BRW_OPCODE_SHL:
case BRW_OPCODE_ASR:
case BRW_OPCODE_ADD:
case BRW_OPCODE_MUL:
case BRW_OPCODE_FRC:
case BRW_OPCODE_RNDU:
case BRW_OPCODE_RNDD:
case BRW_OPCODE_RNDE:
case BRW_OPCODE_RNDZ:
case BRW_OPCODE_LINE:
case BRW_OPCODE_PLN:
case BRW_OPCODE_MAD:
case BRW_OPCODE_LRP:
return true;
case SHADER_OPCODE_RCP:
case SHADER_OPCODE_RSQ:
case SHADER_OPCODE_SQRT:
case SHADER_OPCODE_EXP2:
case SHADER_OPCODE_LOG2:
case SHADER_OPCODE_POW:
case SHADER_OPCODE_INT_QUOTIENT:
case SHADER_OPCODE_INT_REMAINDER:
case SHADER_OPCODE_SIN:
case SHADER_OPCODE_COS:
return inst->mlen == 0;
default:
return false;
}
}
static bool
is_expression_commutative(enum opcode op)
{
switch (op) {
case BRW_OPCODE_AND:
case BRW_OPCODE_OR:
case BRW_OPCODE_XOR:
case BRW_OPCODE_ADD:
case BRW_OPCODE_MUL:
return true;
default:
return false;
}
}
static bool
operands_match(enum opcode op, src_reg *xs, src_reg *ys)
{
if (!is_expression_commutative(op)) {
return xs[0].equals(ys[0]) && xs[1].equals(ys[1]) && xs[2].equals(ys[2]);
} else {
return (xs[0].equals(ys[0]) && xs[1].equals(ys[1])) ||
(xs[1].equals(ys[0]) && xs[0].equals(ys[1]));
}
}
static bool
instructions_match(vec4_instruction *a, vec4_instruction *b)
{
return a->opcode == b->opcode &&
a->saturate == b->saturate &&
a->conditional_mod == b->conditional_mod &&
a->dst.type == b->dst.type &&
a->dst.writemask == b->dst.writemask &&
operands_match(a->opcode, a->src, b->src);
}
bool
vec4_visitor::opt_cse_local(bblock_t *block, exec_list *aeb)
{
bool progress = false;
void *cse_ctx = ralloc_context(NULL);
int ip = block->start_ip;
for (vec4_instruction *inst = (vec4_instruction *)block->start;
inst != block->end->next;
inst = (vec4_instruction *) inst->next) {
/* Skip some cases. */
if (is_expression(inst) && !inst->predicate && inst->mlen == 0 &&
!inst->conditional_mod)
{
bool found = false;
foreach_in_list_use_after(aeb_entry, entry, aeb) {
/* Match current instruction's expression against those in AEB. */
if (instructions_match(inst, entry->generator)) {
found = true;
progress = true;
break;
}
}
if (!found) {
/* Our first sighting of this expression. Create an entry. */
aeb_entry *entry = ralloc(cse_ctx, aeb_entry);
entry->tmp = src_reg(); /* file will be BAD_FILE */
entry->generator = inst;
aeb->push_tail(entry);
} else {
/* This is at least our second sighting of this expression.
* If we don't have a temporary already, make one.
*/
bool no_existing_temp = entry->tmp.file == BAD_FILE;
if (no_existing_temp) {
entry->tmp = src_reg(this, glsl_type::float_type);
entry->tmp.type = inst->dst.type;
entry->tmp.swizzle = BRW_SWIZZLE_XYZW;
vec4_instruction *copy = MOV(entry->generator->dst, entry->tmp);
entry->generator->insert_after(copy);
entry->generator->dst = dst_reg(entry->tmp);
}
/* dest <- temp */
assert(inst->dst.type == entry->tmp.type);
vec4_instruction *copy = MOV(inst->dst, entry->tmp);
copy->force_writemask_all = inst->force_writemask_all;
inst->insert_before(copy);
/* Set our iterator so that next time through the loop inst->next
* will get the instruction in the basic block after the one we've
* removed.
*/
vec4_instruction *prev = (vec4_instruction *)inst->prev;
inst->remove();
/* Appending an instruction may have changed our bblock end. */
if (inst == block->end) {
block->end = prev;
}
inst = prev;
}
}
foreach_in_list_safe(aeb_entry, entry, aeb) {
for (int i = 0; i < 3; i++) {
src_reg *src = &entry->generator->src[i];
/* Kill all AEB entries that use the destination we just
* overwrote.
*/
if (inst->dst.file == entry->generator->src[i].file &&
inst->dst.reg == entry->generator->src[i].reg) {
entry->remove();
ralloc_free(entry);
break;
}
/* Kill any AEB entries using registers that don't get reused any
* more -- a sure sign they'll fail operands_match().
*/
int last_reg_use = MAX2(MAX2(virtual_grf_end[src->reg * 4 + 0],
virtual_grf_end[src->reg * 4 + 1]),
MAX2(virtual_grf_end[src->reg * 4 + 2],
virtual_grf_end[src->reg * 4 + 3]));
if (src->file == GRF && last_reg_use < ip) {
entry->remove();
ralloc_free(entry);
break;
}
}
}
ip++;
}
ralloc_free(cse_ctx);
if (progress)
invalidate_live_intervals();
return progress;
}
bool
vec4_visitor::opt_cse()
{
bool progress = false;
calculate_live_intervals();
cfg_t cfg(&instructions);
for (int b = 0; b < cfg.num_blocks; b++) {
bblock_t *block = cfg.blocks[b];
exec_list aeb;
progress = opt_cse_local(block, &aeb) || progress;
}
return progress;
}
<commit_msg>i965/vec4: Don't emit null MOVs in CSE.<commit_after>/*
* Copyright © 2012, 2013, 2014 Intel Corporation
*
* 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 (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND 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 "brw_vec4.h"
#include "brw_cfg.h"
using namespace brw;
/** @file brw_vec4_cse.cpp
*
* Support for local common subexpression elimination.
*
* See Muchnick's Advanced Compiler Design and Implementation, section
* 13.1 (p378).
*/
namespace {
struct aeb_entry : public exec_node {
/** The instruction that generates the expression value. */
vec4_instruction *generator;
/** The temporary where the value is stored. */
src_reg tmp;
};
}
static bool
is_expression(const vec4_instruction *const inst)
{
switch (inst->opcode) {
case BRW_OPCODE_SEL:
case BRW_OPCODE_NOT:
case BRW_OPCODE_AND:
case BRW_OPCODE_OR:
case BRW_OPCODE_XOR:
case BRW_OPCODE_SHR:
case BRW_OPCODE_SHL:
case BRW_OPCODE_ASR:
case BRW_OPCODE_ADD:
case BRW_OPCODE_MUL:
case BRW_OPCODE_FRC:
case BRW_OPCODE_RNDU:
case BRW_OPCODE_RNDD:
case BRW_OPCODE_RNDE:
case BRW_OPCODE_RNDZ:
case BRW_OPCODE_LINE:
case BRW_OPCODE_PLN:
case BRW_OPCODE_MAD:
case BRW_OPCODE_LRP:
return true;
case SHADER_OPCODE_RCP:
case SHADER_OPCODE_RSQ:
case SHADER_OPCODE_SQRT:
case SHADER_OPCODE_EXP2:
case SHADER_OPCODE_LOG2:
case SHADER_OPCODE_POW:
case SHADER_OPCODE_INT_QUOTIENT:
case SHADER_OPCODE_INT_REMAINDER:
case SHADER_OPCODE_SIN:
case SHADER_OPCODE_COS:
return inst->mlen == 0;
default:
return false;
}
}
static bool
is_expression_commutative(enum opcode op)
{
switch (op) {
case BRW_OPCODE_AND:
case BRW_OPCODE_OR:
case BRW_OPCODE_XOR:
case BRW_OPCODE_ADD:
case BRW_OPCODE_MUL:
return true;
default:
return false;
}
}
static bool
operands_match(enum opcode op, src_reg *xs, src_reg *ys)
{
if (!is_expression_commutative(op)) {
return xs[0].equals(ys[0]) && xs[1].equals(ys[1]) && xs[2].equals(ys[2]);
} else {
return (xs[0].equals(ys[0]) && xs[1].equals(ys[1])) ||
(xs[1].equals(ys[0]) && xs[0].equals(ys[1]));
}
}
static bool
instructions_match(vec4_instruction *a, vec4_instruction *b)
{
return a->opcode == b->opcode &&
a->saturate == b->saturate &&
a->conditional_mod == b->conditional_mod &&
a->dst.type == b->dst.type &&
a->dst.writemask == b->dst.writemask &&
operands_match(a->opcode, a->src, b->src);
}
bool
vec4_visitor::opt_cse_local(bblock_t *block, exec_list *aeb)
{
bool progress = false;
void *cse_ctx = ralloc_context(NULL);
int ip = block->start_ip;
for (vec4_instruction *inst = (vec4_instruction *)block->start;
inst != block->end->next;
inst = (vec4_instruction *) inst->next) {
/* Skip some cases. */
if (is_expression(inst) && !inst->predicate && inst->mlen == 0 &&
!inst->conditional_mod)
{
bool found = false;
foreach_in_list_use_after(aeb_entry, entry, aeb) {
/* Match current instruction's expression against those in AEB. */
if (instructions_match(inst, entry->generator)) {
found = true;
progress = true;
break;
}
}
if (!found) {
/* Our first sighting of this expression. Create an entry. */
aeb_entry *entry = ralloc(cse_ctx, aeb_entry);
entry->tmp = src_reg(); /* file will be BAD_FILE */
entry->generator = inst;
aeb->push_tail(entry);
} else {
/* This is at least our second sighting of this expression.
* If we don't have a temporary already, make one.
*/
bool no_existing_temp = entry->tmp.file == BAD_FILE;
if (no_existing_temp && !entry->generator->dst.is_null()) {
entry->tmp = src_reg(this, glsl_type::float_type);
entry->tmp.type = inst->dst.type;
entry->tmp.swizzle = BRW_SWIZZLE_XYZW;
vec4_instruction *copy = MOV(entry->generator->dst, entry->tmp);
entry->generator->insert_after(copy);
entry->generator->dst = dst_reg(entry->tmp);
}
/* dest <- temp */
if (!inst->dst.is_null()) {
assert(inst->dst.type == entry->tmp.type);
vec4_instruction *copy = MOV(inst->dst, entry->tmp);
copy->force_writemask_all = inst->force_writemask_all;
inst->insert_before(copy);
}
/* Set our iterator so that next time through the loop inst->next
* will get the instruction in the basic block after the one we've
* removed.
*/
vec4_instruction *prev = (vec4_instruction *)inst->prev;
inst->remove();
/* Appending an instruction may have changed our bblock end. */
if (inst == block->end) {
block->end = prev;
}
inst = prev;
}
}
foreach_in_list_safe(aeb_entry, entry, aeb) {
for (int i = 0; i < 3; i++) {
src_reg *src = &entry->generator->src[i];
/* Kill all AEB entries that use the destination we just
* overwrote.
*/
if (inst->dst.file == entry->generator->src[i].file &&
inst->dst.reg == entry->generator->src[i].reg) {
entry->remove();
ralloc_free(entry);
break;
}
/* Kill any AEB entries using registers that don't get reused any
* more -- a sure sign they'll fail operands_match().
*/
int last_reg_use = MAX2(MAX2(virtual_grf_end[src->reg * 4 + 0],
virtual_grf_end[src->reg * 4 + 1]),
MAX2(virtual_grf_end[src->reg * 4 + 2],
virtual_grf_end[src->reg * 4 + 3]));
if (src->file == GRF && last_reg_use < ip) {
entry->remove();
ralloc_free(entry);
break;
}
}
}
ip++;
}
ralloc_free(cse_ctx);
if (progress)
invalidate_live_intervals();
return progress;
}
bool
vec4_visitor::opt_cse()
{
bool progress = false;
calculate_live_intervals();
cfg_t cfg(&instructions);
for (int b = 0; b < cfg.num_blocks; b++) {
bblock_t *block = cfg.blocks[b];
exec_list aeb;
progress = opt_cse_local(block, &aeb) || progress;
}
return progress;
}
<|endoftext|> |
<commit_before>/*********************************************************************
* node-dvbtee for Node.js
*
* Copyright (c) 2017 Michael Ira Krufky <https://github.com/mkrufky>
*
* MIT License <https://github.com/mkrufky/node-dvbtee/blob/master/LICENSE>
*
* See https://github.com/mkrufky/node-dvbtee for more information
********************************************************************/
#include <nan.h>
#include <native-json.h>
#include "dvbtee-parser.h"
TableData::TableData(const uint8_t &tableId,
const std::string &decoderName,
const std::string &json)
: tableId(tableId)
, decoderName(decoderName)
, json(json)
{}
////////////////////////////////////////
TableReceiver::TableReceiver(dvbteeParser *dvbteeParser)
: m_dvbteeParser(dvbteeParser) {
uv_mutex_init(&m_ev_mutex);
uv_async_init(uv_default_loop(), &m_async, completeCb);
m_async.data = this;
}
TableReceiver::~TableReceiver() {
unregisterInterface();
m_cb.Reset();
uv_mutex_lock(&m_ev_mutex);
while (!m_eq.empty()) {
TableData *data = m_eq.front();
delete data;
m_eq.pop();
}
uv_mutex_unlock(&m_ev_mutex);
uv_mutex_destroy(&m_ev_mutex);
}
void TableReceiver::subscribe(const v8::Local<v8::Function> &fn) {
m_cb.SetFunction(fn);
registerInterface();
}
void TableReceiver::registerInterface() {
m_dvbteeParser->m_parser.subscribeTables(this);
}
void TableReceiver::unregisterInterface() {
m_dvbteeParser->m_parser.subscribeTables(NULL);
}
void TableReceiver::updateTable(uint8_t tId, dvbtee::decode::Table *table) {
uv_mutex_lock(&m_ev_mutex);
m_eq.push(
new TableData(table->getTableid(),
table->getDecoderName(),
table->toJson())
);
uv_mutex_unlock(&m_ev_mutex);
uv_async_send(&m_async);
}
void TableReceiver::notify() {
Nan::HandleScope scope;
uv_mutex_lock(&m_ev_mutex);
while (!m_eq.empty()) {
TableData *data = m_eq.front();
uv_mutex_unlock(&m_ev_mutex);
if (!m_cb.IsEmpty()) {
v8::MaybeLocal<v8::String> jsonStr = Nan::New(data->json);
if (!jsonStr.IsEmpty()) {
v8::MaybeLocal<v8::Value> jsonVal =
Native::JSON::Parse(jsonStr.ToLocalChecked());
if (!jsonVal.IsEmpty()) {
v8::MaybeLocal<v8::String> decoderName = Nan::New(data->decoderName);
v8::Local<v8::Value> decoderNameArg;
if (decoderName.IsEmpty())
decoderNameArg = Nan::Null();
else
decoderNameArg = decoderName.ToLocalChecked();
v8::Local<v8::Value> argv[] = {
Nan::New(data->tableId),
decoderNameArg,
jsonVal.ToLocalChecked()
};
m_cb.Call(3, argv);
}
}
}
delete data;
uv_mutex_lock(&m_ev_mutex);
m_eq.pop();
}
uv_mutex_unlock(&m_ev_mutex);
}
void TableReceiver::completeCb(uv_async_t *handle
#if NODE_MODULE_VERSION <= 11
, int status /*UNUSED*/
#endif
) {
TableReceiver* rcvr = static_cast<TableReceiver*>(handle->data);
rcvr->notify();
}
////////////////////////////////////////
Nan::Persistent<v8::Function> dvbteeParser::constructor;
dvbteeParser::dvbteeParser()
: m_tableReceiver(this) {
}
dvbteeParser::~dvbteeParser() {
}
void dvbteeParser::Init(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE exports) {
Nan::HandleScope scope;
v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
tpl->SetClassName(Nan::New("Parser").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
Nan::SetPrototypeMethod(tpl, "reset", reset);
Nan::SetPrototypeMethod(tpl, "feed", feed);
Nan::SetPrototypeMethod(tpl, "push", feed); // deprecated
Nan::SetPrototypeMethod(tpl, "parse", feed); // deprecated
Nan::SetPrototypeMethod(tpl, "listenTables", listenTables);
constructor.Reset(tpl->GetFunction());
exports->Set(Nan::New("Parser").ToLocalChecked(), tpl->GetFunction());
}
void dvbteeParser::New(const Nan::FunctionCallbackInfo<v8::Value>& info) {
if (info.IsConstructCall()) {
// Invoked as constructor: `new dvbteeParser(...)`
dvbteeParser* obj = new dvbteeParser();
obj->Wrap(info.This());
info.GetReturnValue().Set(info.This());
} else {
// Invoked as plain function `dvbteeParser(...)`, turn into construct call.
const int argc = 0;
v8::Local<v8::Value> argv[argc] = { };
v8::Local<v8::Function> cons = Nan::New<v8::Function>(constructor);
info.GetReturnValue().Set(cons->NewInstance(argc, argv));
}
}
void dvbteeParser::listenTables(const Nan::FunctionCallbackInfo<v8::Value>& info) {
dvbteeParser* obj = ObjectWrap::Unwrap<dvbteeParser>(info.Holder());
int lastArg = info.Length() - 1;
if ((lastArg >= 0) && (info[lastArg]->IsFunction())) {
obj->m_tableReceiver.subscribe(info[lastArg].As<v8::Function>());
}
info.GetReturnValue().Set(info.Holder());
}
////////////////////////////////////////
class ResetWorker : public Nan::AsyncWorker {
public:
ResetWorker(Nan::Callback *callback,
const Nan::FunctionCallbackInfo<v8::Value>& info)
: Nan::AsyncWorker(callback) {
m_obj = Nan::ObjectWrap::Unwrap<dvbteeParser>(info.Holder());
}
~ResetWorker() {
}
void Execute () {
m_obj->m_parser.cleanup();
m_obj->m_parser.reset();
}
void HandleOKCallback () {
Nan::HandleScope scope;
v8::Local<v8::Value> argv[] = {
Nan::Null()
, Nan::New<v8::Number>(0)
};
callback->Call(2, argv);
}
private:
dvbteeParser* m_obj;
};
void dvbteeParser::reset(const Nan::FunctionCallbackInfo<v8::Value>& info) {
// If a callback function is supplied, this method will run async
// otherwise, it will run synchronous
int lastArg = info.Length() - 1;
if ((lastArg >= 0) && (info[lastArg]->IsFunction())) {
Nan::Callback *callback = new Nan::Callback(
info[lastArg].As<v8::Function>()
);
Nan::AsyncQueueWorker(new ResetWorker(callback, info));
} else {
dvbteeParser* obj = ObjectWrap::Unwrap<dvbteeParser>(info.Holder());
obj->m_parser.cleanup();
obj->m_parser.reset();
info.GetReturnValue().Set(info.Holder());
}
}
////////////////////////////////////////
class FeedWorker : public Nan::AsyncWorker {
public:
FeedWorker(Nan::Callback *callback,
const Nan::FunctionCallbackInfo<v8::Value>& info)
: Nan::AsyncWorker(callback)
, m_buf(NULL)
, m_buf_len(0)
, m_ret(-1) {
m_obj = Nan::ObjectWrap::Unwrap<dvbteeParser>(info.Holder());
if ((info[0]->IsObject()) && (info[1]->IsNumber())) {
const char *key = "buf";
SaveToPersistent(key, info[0]);
Nan::MaybeLocal<v8::Object> mbBuf =
Nan::To<v8::Object>(GetFromPersistent(key));
if (!mbBuf.IsEmpty()) {
m_buf = node::Buffer::Data(mbBuf.ToLocalChecked());
m_buf_len = info[1]->Uint32Value();
}
}
}
~FeedWorker() {
}
void Execute () {
if ((m_buf) && (m_buf_len)) {
m_ret = m_obj->m_parser.feed(
m_buf_len, reinterpret_cast<uint8_t*>(m_buf)
);
}
if (m_ret < 0) {
SetErrorMessage("invalid buffer / length");
}
}
void HandleOKCallback () {
Nan::HandleScope scope;
v8::Local<v8::Value> argv[] = {
Nan::Null()
, Nan::New<v8::Number>(m_ret)
};
callback->Call(2, argv);
}
private:
dvbteeParser* m_obj;
char* m_buf;
unsigned int m_buf_len;
int m_ret;
};
void dvbteeParser::feed(const Nan::FunctionCallbackInfo<v8::Value>& info) {
// If a callback function is supplied, this method will run async
// otherwise, it will run synchronous
//
// Note: when packets are pushed to the parser, the parser will start
// generating async events containing PSIP table data regardless of
// whether this function was called synchronously or not
int lastArg = info.Length() - 1;
if ((lastArg >= 0) && (info[lastArg]->IsFunction())) {
Nan::Callback *callback = new Nan::Callback(
info[lastArg].As<v8::Function>()
);
Nan::AsyncQueueWorker(new FeedWorker(callback, info));
} else {
dvbteeParser* obj = ObjectWrap::Unwrap<dvbteeParser>(info.Holder());
int ret = -1;
if ((info[0]->IsObject()) && (info[1]->IsNumber())) {
Nan::MaybeLocal<v8::Object> bufferObj = Nan::To<v8::Object>(info[0]);
if (!bufferObj.IsEmpty()) {
unsigned int len = info[1]->Uint32Value();
char* buf = node::Buffer::Data(bufferObj.ToLocalChecked());
ret = obj->m_parser.feed(len, reinterpret_cast<uint8_t*>(buf));
}
}
info.GetReturnValue().Set(Nan::New(ret));
}
}
<commit_msg>dvbtee-parser: fix error: ‘MaybeLocal’ is not a member of ‘v8’<commit_after>/*********************************************************************
* node-dvbtee for Node.js
*
* Copyright (c) 2017 Michael Ira Krufky <https://github.com/mkrufky>
*
* MIT License <https://github.com/mkrufky/node-dvbtee/blob/master/LICENSE>
*
* See https://github.com/mkrufky/node-dvbtee for more information
********************************************************************/
#include <nan.h>
#include <native-json.h>
#include "dvbtee-parser.h"
TableData::TableData(const uint8_t &tableId,
const std::string &decoderName,
const std::string &json)
: tableId(tableId)
, decoderName(decoderName)
, json(json)
{}
////////////////////////////////////////
TableReceiver::TableReceiver(dvbteeParser *dvbteeParser)
: m_dvbteeParser(dvbteeParser) {
uv_mutex_init(&m_ev_mutex);
uv_async_init(uv_default_loop(), &m_async, completeCb);
m_async.data = this;
}
TableReceiver::~TableReceiver() {
unregisterInterface();
m_cb.Reset();
uv_mutex_lock(&m_ev_mutex);
while (!m_eq.empty()) {
TableData *data = m_eq.front();
delete data;
m_eq.pop();
}
uv_mutex_unlock(&m_ev_mutex);
uv_mutex_destroy(&m_ev_mutex);
}
void TableReceiver::subscribe(const v8::Local<v8::Function> &fn) {
m_cb.SetFunction(fn);
registerInterface();
}
void TableReceiver::registerInterface() {
m_dvbteeParser->m_parser.subscribeTables(this);
}
void TableReceiver::unregisterInterface() {
m_dvbteeParser->m_parser.subscribeTables(NULL);
}
void TableReceiver::updateTable(uint8_t tId, dvbtee::decode::Table *table) {
uv_mutex_lock(&m_ev_mutex);
m_eq.push(
new TableData(table->getTableid(),
table->getDecoderName(),
table->toJson())
);
uv_mutex_unlock(&m_ev_mutex);
uv_async_send(&m_async);
}
void TableReceiver::notify() {
Nan::HandleScope scope;
uv_mutex_lock(&m_ev_mutex);
while (!m_eq.empty()) {
TableData *data = m_eq.front();
uv_mutex_unlock(&m_ev_mutex);
if (!m_cb.IsEmpty()) {
Nan::MaybeLocal<v8::String> jsonStr = Nan::New(data->json);
if (!jsonStr.IsEmpty()) {
Nan::MaybeLocal<v8::Value> jsonVal =
Native::JSON::Parse(jsonStr.ToLocalChecked());
if (!jsonVal.IsEmpty()) {
Nan::MaybeLocal<v8::String> decoderName = Nan::New(data->decoderName);
v8::Local<v8::Value> decoderNameArg;
if (decoderName.IsEmpty())
decoderNameArg = Nan::Null();
else
decoderNameArg = decoderName.ToLocalChecked();
v8::Local<v8::Value> argv[] = {
Nan::New(data->tableId),
decoderNameArg,
jsonVal.ToLocalChecked()
};
m_cb.Call(3, argv);
}
}
}
delete data;
uv_mutex_lock(&m_ev_mutex);
m_eq.pop();
}
uv_mutex_unlock(&m_ev_mutex);
}
void TableReceiver::completeCb(uv_async_t *handle
#if NODE_MODULE_VERSION <= 11
, int status /*UNUSED*/
#endif
) {
TableReceiver* rcvr = static_cast<TableReceiver*>(handle->data);
rcvr->notify();
}
////////////////////////////////////////
Nan::Persistent<v8::Function> dvbteeParser::constructor;
dvbteeParser::dvbteeParser()
: m_tableReceiver(this) {
}
dvbteeParser::~dvbteeParser() {
}
void dvbteeParser::Init(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE exports) {
Nan::HandleScope scope;
v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
tpl->SetClassName(Nan::New("Parser").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
Nan::SetPrototypeMethod(tpl, "reset", reset);
Nan::SetPrototypeMethod(tpl, "feed", feed);
Nan::SetPrototypeMethod(tpl, "push", feed); // deprecated
Nan::SetPrototypeMethod(tpl, "parse", feed); // deprecated
Nan::SetPrototypeMethod(tpl, "listenTables", listenTables);
constructor.Reset(tpl->GetFunction());
exports->Set(Nan::New("Parser").ToLocalChecked(), tpl->GetFunction());
}
void dvbteeParser::New(const Nan::FunctionCallbackInfo<v8::Value>& info) {
if (info.IsConstructCall()) {
// Invoked as constructor: `new dvbteeParser(...)`
dvbteeParser* obj = new dvbteeParser();
obj->Wrap(info.This());
info.GetReturnValue().Set(info.This());
} else {
// Invoked as plain function `dvbteeParser(...)`, turn into construct call.
const int argc = 0;
v8::Local<v8::Value> argv[argc] = { };
v8::Local<v8::Function> cons = Nan::New<v8::Function>(constructor);
info.GetReturnValue().Set(cons->NewInstance(argc, argv));
}
}
void dvbteeParser::listenTables(const Nan::FunctionCallbackInfo<v8::Value>& info) {
dvbteeParser* obj = ObjectWrap::Unwrap<dvbteeParser>(info.Holder());
int lastArg = info.Length() - 1;
if ((lastArg >= 0) && (info[lastArg]->IsFunction())) {
obj->m_tableReceiver.subscribe(info[lastArg].As<v8::Function>());
}
info.GetReturnValue().Set(info.Holder());
}
////////////////////////////////////////
class ResetWorker : public Nan::AsyncWorker {
public:
ResetWorker(Nan::Callback *callback,
const Nan::FunctionCallbackInfo<v8::Value>& info)
: Nan::AsyncWorker(callback) {
m_obj = Nan::ObjectWrap::Unwrap<dvbteeParser>(info.Holder());
}
~ResetWorker() {
}
void Execute () {
m_obj->m_parser.cleanup();
m_obj->m_parser.reset();
}
void HandleOKCallback () {
Nan::HandleScope scope;
v8::Local<v8::Value> argv[] = {
Nan::Null()
, Nan::New<v8::Number>(0)
};
callback->Call(2, argv);
}
private:
dvbteeParser* m_obj;
};
void dvbteeParser::reset(const Nan::FunctionCallbackInfo<v8::Value>& info) {
// If a callback function is supplied, this method will run async
// otherwise, it will run synchronous
int lastArg = info.Length() - 1;
if ((lastArg >= 0) && (info[lastArg]->IsFunction())) {
Nan::Callback *callback = new Nan::Callback(
info[lastArg].As<v8::Function>()
);
Nan::AsyncQueueWorker(new ResetWorker(callback, info));
} else {
dvbteeParser* obj = ObjectWrap::Unwrap<dvbteeParser>(info.Holder());
obj->m_parser.cleanup();
obj->m_parser.reset();
info.GetReturnValue().Set(info.Holder());
}
}
////////////////////////////////////////
class FeedWorker : public Nan::AsyncWorker {
public:
FeedWorker(Nan::Callback *callback,
const Nan::FunctionCallbackInfo<v8::Value>& info)
: Nan::AsyncWorker(callback)
, m_buf(NULL)
, m_buf_len(0)
, m_ret(-1) {
m_obj = Nan::ObjectWrap::Unwrap<dvbteeParser>(info.Holder());
if ((info[0]->IsObject()) && (info[1]->IsNumber())) {
const char *key = "buf";
SaveToPersistent(key, info[0]);
Nan::MaybeLocal<v8::Object> mbBuf =
Nan::To<v8::Object>(GetFromPersistent(key));
if (!mbBuf.IsEmpty()) {
m_buf = node::Buffer::Data(mbBuf.ToLocalChecked());
m_buf_len = info[1]->Uint32Value();
}
}
}
~FeedWorker() {
}
void Execute () {
if ((m_buf) && (m_buf_len)) {
m_ret = m_obj->m_parser.feed(
m_buf_len, reinterpret_cast<uint8_t*>(m_buf)
);
}
if (m_ret < 0) {
SetErrorMessage("invalid buffer / length");
}
}
void HandleOKCallback () {
Nan::HandleScope scope;
v8::Local<v8::Value> argv[] = {
Nan::Null()
, Nan::New<v8::Number>(m_ret)
};
callback->Call(2, argv);
}
private:
dvbteeParser* m_obj;
char* m_buf;
unsigned int m_buf_len;
int m_ret;
};
void dvbteeParser::feed(const Nan::FunctionCallbackInfo<v8::Value>& info) {
// If a callback function is supplied, this method will run async
// otherwise, it will run synchronous
//
// Note: when packets are pushed to the parser, the parser will start
// generating async events containing PSIP table data regardless of
// whether this function was called synchronously or not
int lastArg = info.Length() - 1;
if ((lastArg >= 0) && (info[lastArg]->IsFunction())) {
Nan::Callback *callback = new Nan::Callback(
info[lastArg].As<v8::Function>()
);
Nan::AsyncQueueWorker(new FeedWorker(callback, info));
} else {
dvbteeParser* obj = ObjectWrap::Unwrap<dvbteeParser>(info.Holder());
int ret = -1;
if ((info[0]->IsObject()) && (info[1]->IsNumber())) {
Nan::MaybeLocal<v8::Object> bufferObj = Nan::To<v8::Object>(info[0]);
if (!bufferObj.IsEmpty()) {
unsigned int len = info[1]->Uint32Value();
char* buf = node::Buffer::Data(bufferObj.ToLocalChecked());
ret = obj->m_parser.feed(len, reinterpret_cast<uint8_t*>(buf));
}
}
info.GetReturnValue().Set(Nan::New(ret));
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: exceptiontree.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2004-03-30 16:51: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): _______________________________________
*
*
************************************************************************/
#include "codemaker/exceptiontree.hxx"
#include "codemaker/typemanager.hxx"
#include "osl/diagnose.h"
#include "registry/reader.hxx"
#include "registry/types.h"
#include "rtl/string.hxx"
#include "rtl/textenc.h"
#include "rtl/ustring.hxx"
#include <memory>
#include <vector>
using codemaker::ExceptionTree;
using codemaker::ExceptionTreeNode;
ExceptionTreeNode * ExceptionTreeNode::add(rtl::OString const & name) {
std::auto_ptr< ExceptionTreeNode > node(new ExceptionTreeNode(name));
children.push_back(node.get());
return node.release();
}
void ExceptionTreeNode::clearChildren() {
for (Children::iterator i(children.begin()); i != children.end(); ++i) {
delete *i;
}
children.clear();
}
void ExceptionTree::add(rtl::OString const & name, TypeManager & manager)
{
typedef std::vector< rtl::OString > List;
List list;
bool runtimeException = false;
for (rtl::OString n(name); n != "com/sun/star/uno/Exception";) {
if (n == "com/sun/star/uno/RuntimeException") {
runtimeException = true;
break;
}
list.push_back(n);
typereg::Reader reader(manager.getTypeReader(n));
OSL_ASSERT(
reader.getTypeClass() == RT_TYPE_EXCEPTION
&& reader.getSuperTypeCount() == 1);
n = rtl::OUStringToOString(
reader.getSuperTypeName(0), RTL_TEXTENCODING_UTF8);
}
if (!runtimeException) {
ExceptionTreeNode * node = &m_root;
for (List::reverse_iterator i(list.rbegin()); !node->present; ++i) {
if (i == list.rend()) {
node->setPresent();
break;
}
for (ExceptionTreeNode::Children::iterator j(
node->children.begin());;
++j)
{
if (j == node->children.end()) {
node = node->add(*i);
break;
}
if ((*j)->name == *i) {
node = *j;
break;
}
}
}
}
}
<commit_msg>INTEGRATION: CWS sb18 (1.2.4); FILE MERGED 2004/04/28 08:59:02 sb 1.2.4.1: #i21150# Constness improvements.<commit_after>/*************************************************************************
*
* $RCSfile: exceptiontree.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: obo $ $Date: 2004-06-04 03:10:27 $
*
* 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 "codemaker/exceptiontree.hxx"
#include "codemaker/typemanager.hxx"
#include "osl/diagnose.h"
#include "registry/reader.hxx"
#include "registry/types.h"
#include "rtl/string.hxx"
#include "rtl/textenc.h"
#include "rtl/ustring.hxx"
#include <memory>
#include <vector>
using codemaker::ExceptionTree;
using codemaker::ExceptionTreeNode;
ExceptionTreeNode * ExceptionTreeNode::add(rtl::OString const & name) {
std::auto_ptr< ExceptionTreeNode > node(new ExceptionTreeNode(name));
children.push_back(node.get());
return node.release();
}
void ExceptionTreeNode::clearChildren() {
for (Children::iterator i(children.begin()); i != children.end(); ++i) {
delete *i;
}
children.clear();
}
void ExceptionTree::add(rtl::OString const & name, TypeManager const & manager)
{
typedef std::vector< rtl::OString > List;
List list;
bool runtimeException = false;
for (rtl::OString n(name); n != "com/sun/star/uno/Exception";) {
if (n == "com/sun/star/uno/RuntimeException") {
runtimeException = true;
break;
}
list.push_back(n);
typereg::Reader reader(manager.getTypeReader(n));
OSL_ASSERT(
reader.getTypeClass() == RT_TYPE_EXCEPTION
&& reader.getSuperTypeCount() == 1);
n = rtl::OUStringToOString(
reader.getSuperTypeName(0), RTL_TEXTENCODING_UTF8);
}
if (!runtimeException) {
ExceptionTreeNode * node = &m_root;
for (List::reverse_iterator i(list.rbegin()); !node->present; ++i) {
if (i == list.rend()) {
node->setPresent();
break;
}
for (ExceptionTreeNode::Children::iterator j(
node->children.begin());;
++j)
{
if (j == node->children.end()) {
node = node->add(*i);
break;
}
if ((*j)->name == *i) {
node = *j;
break;
}
}
}
}
}
<|endoftext|> |
<commit_before>#ifndef _INCLUDED_LZW_BIT_CODER_HPP_
#define _INCLUDED_LZW_BIT_CODER_HPP_
#include <tudocomp/Coder.hpp>
#include <tudocomp/lz78/trie.h>
#include <tudocomp/lz78/Lz78DecodeBuffer.hpp>
#include <tudocomp/lzw/factor.h>
#include <tudocomp/lzw/decode.hpp>
namespace tudocomp {
namespace lzw {
using ::lzw::LzwEntry;
using lz78_dictionary::CodeType;
/**
* Encodes factors as simple strings.
*/
class LzwBitCoder {
private:
// TODO: Change encode_* methods to not take Output& since that inital setup
// rather, have a single init location
tudocomp::io::OutputStreamGuard m_out_guard;
tudocomp::BitOStream m_out;
uint64_t m_factor_counter = 0;
public:
inline LzwBitCoder(Env& env, Output& out)
: m_out_guard(out.as_stream()), m_out(*m_out_guard)
{
}
inline ~LzwBitCoder() {
m_out.flush();
(*m_out_guard).flush();
}
inline void encode_fact(const LzwEntry& entry) {
// output format: variable_number_backref_bits 8bit_char
// slowly grow the number of bits needed together with the output
size_t back_ref_idx_bits = bitsFor(m_factor_counter + 256);
DCHECK(bitsFor(entry) <= back_ref_idx_bits);
m_out.write(entry, back_ref_idx_bits);
m_factor_counter++;
}
inline void dictionary_reset() {
m_factor_counter = 0;
}
inline static void decode(Input& _inp, Output& _out,
CodeType dms,
CodeType reserve_dms) {
auto iguard = _inp.as_stream();
auto oguard = _out.as_stream();
auto& inp = *iguard;
auto& out = *oguard;
bool done = false;
BitIStream is(inp, done);
uint64_t counter = 0;
decode_step([&](CodeType& entry, bool reset, bool &file_corrupted) -> LzwEntry {
// Try to read next factor
LzwEntry factor(is.readBits<uint64_t>(bitsFor(counter + 256)));
if (done) {
// Could not read all bits -> done
// (this works because the encoded factors are always > 8 bit)
return false;
}
counter++;
entry = factor;
return true;
}, out, dms, reserve_dms);
}
};
}
}
#endif
<commit_msg>Fixed new template based bit decoder to reset dictionary<commit_after>#ifndef _INCLUDED_LZW_BIT_CODER_HPP_
#define _INCLUDED_LZW_BIT_CODER_HPP_
#include <tudocomp/Coder.hpp>
#include <tudocomp/lz78/trie.h>
#include <tudocomp/lz78/Lz78DecodeBuffer.hpp>
#include <tudocomp/lzw/factor.h>
#include <tudocomp/lzw/decode.hpp>
namespace tudocomp {
namespace lzw {
using ::lzw::LzwEntry;
using lz78_dictionary::CodeType;
/**
* Encodes factors as simple strings.
*/
class LzwBitCoder {
private:
// TODO: Change encode_* methods to not take Output& since that inital setup
// rather, have a single init location
tudocomp::io::OutputStreamGuard m_out_guard;
tudocomp::BitOStream m_out;
uint64_t m_factor_counter = 0;
public:
inline LzwBitCoder(Env& env, Output& out)
: m_out_guard(out.as_stream()), m_out(*m_out_guard)
{
}
inline ~LzwBitCoder() {
m_out.flush();
(*m_out_guard).flush();
}
inline void encode_fact(const LzwEntry& entry) {
// output format: variable_number_backref_bits 8bit_char
// slowly grow the number of bits needed together with the output
size_t back_ref_idx_bits = bitsFor(m_factor_counter + 256);
DCHECK(bitsFor(entry) <= back_ref_idx_bits);
m_out.write(entry, back_ref_idx_bits);
m_factor_counter++;
}
inline void dictionary_reset() {
m_factor_counter = 0;
}
inline static void decode(Input& _inp, Output& _out,
CodeType dms,
CodeType reserve_dms) {
auto iguard = _inp.as_stream();
auto oguard = _out.as_stream();
auto& inp = *iguard;
auto& out = *oguard;
bool done = false;
BitIStream is(inp, done);
uint64_t counter = 0;
decode_step([&](CodeType& entry, bool reset, bool &file_corrupted) -> LzwEntry {
if (reset) {
counter = 0;
}
// Try to read next factor
LzwEntry factor(is.readBits<uint64_t>(bitsFor(counter + 256)));
if (done) {
// Could not read all bits -> done
// (this works because the encoded factors are always > 8 bit)
return false;
}
counter++;
entry = factor;
return true;
}, out, dms, reserve_dms);
}
};
}
}
#endif
<|endoftext|> |
<commit_before>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright (C) 2011 - 2015 *
* Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#ifndef CAF_SCHEDULER_PROFILED_COORDINATOR_HPP
#define CAF_SCHEDULER_PROFILED_COORDINATOR_HPP
#include "caf/config.hpp"
#if defined(CAF_MACOS) || defined(CAF_IOS)
#include <mach/mach.h>
#else
#include <sys/resource.h>
#endif // CAF_MACOS
#include <cmath>
#include <mutex>
#include <chrono>
#include <vector>
#include <fstream>
#include <iomanip>
#include <unordered_map>
#include "caf/policy/profiled.hpp"
#include "caf/policy/work_stealing.hpp"
#include "caf/detail/logging.hpp"
namespace caf {
namespace scheduler {
/// A coordinator which keeps fine-grained profiling state about its workers
/// and their jobs.
template <class Policy = policy::profiled<policy::work_stealing>>
class profiled_coordinator : public coordinator<Policy> {
public:
using super = coordinator<Policy>;
using clock_type = std::chrono::high_resolution_clock;
using usec = std::chrono::microseconds;
using msec = std::chrono::milliseconds;
class measurement {
public:
# if defined(CAF_MACOS) || defined(CAF_IOS)
static usec to_usec(const ::time_value_t& tv) {
return std::chrono::seconds(tv.seconds) + usec(tv.microseconds);
}
# else
static usec to_usec(const ::timeval& tv) {
return std::chrono::seconds(tv.tv_sec) + usec(tv.tv_usec);
}
# endif // CAF_MACOS
static measurement take() {
auto now = clock_type::now().time_since_epoch();
measurement m;
m.time = std::chrono::duration_cast<usec>(now);
# if defined(CAF_MACOS) || defined(CAF_IOS)
auto tself = ::mach_thread_self();
::thread_basic_info info;
auto count = THREAD_BASIC_INFO_COUNT;
auto result = ::thread_info(tself, THREAD_BASIC_INFO,
reinterpret_cast<thread_info_t>(&info),
&count);
if (result == KERN_SUCCESS && (info.flags & TH_FLAGS_IDLE) == 0) {
m.usr = to_usec(info.user_time);
m.sys = to_usec(info.system_time);
}
::mach_port_deallocate(mach_task_self(), tself);
# else
::rusage ru;
::getrusage(RUSAGE_THREAD, &ru);
m.usr = to_usec(ru.ru_utime);
m.sys = to_usec(ru.ru_stime);
m.mem = ru.ru_maxrss;
# endif // CAF_MACOS
return m;
}
measurement& operator+=(const measurement& other) {
time += other.time;
usr += other.usr;
sys += other.sys;
mem += other.mem;
return *this;
}
measurement& operator-=(const measurement& other) {
time -= other.time;
usr -= other.usr;
sys -= other.sys;
mem -= other.mem;
return *this;
}
friend measurement operator+(const measurement& x, const measurement& y) {
measurement tmp(x);
tmp += y;
return tmp;
}
friend measurement operator-(const measurement& x, const measurement& y) {
measurement tmp(x);
tmp -= y;
return tmp;
}
friend std::ostream& operator<<(std::ostream& out, const measurement& m) {
using std::setw;
out << setw(15) << m.time.count()
<< setw(15) << m.usr.count()
<< setw(15) << m.sys.count()
<< m.mem;
return out;
}
usec time = usec::zero();
usec usr = usec::zero();
usec sys = usec::zero();
long mem = 0;
};
struct worker_state {
actor_id current;
measurement job;
measurement worker;
clock_type::duration last_flush;
};
profiled_coordinator(const std::string& filename,
msec res = msec{1000},
size_t nw = std::max(std::thread::hardware_concurrency(),
4u),
size_t mt = std::numeric_limits<size_t>::max())
: super{nw, mt},
file_{filename},
resolution_{res},
system_start_{std::chrono::system_clock::now()},
clock_start_{clock_type::now().time_since_epoch()} {
if (! file_) {
throw std::runtime_error{"failed to open CAF profiler file"};
}
}
void initialize() override {
super::initialize();
worker_states_.resize(this->num_workers());
using std::setw;
file_.flags(std::ios::left);
file_ << setw(21) << "clock" // UNIX timestamp in microseconds
<< setw(10) << "type" // "actor" or "worker"
<< setw(10) << "id" // ID of the above
<< setw(15) << "time" // duration of this sample (cumulative)
<< setw(15) << "usr" // time spent in user mode (cumulative)
<< setw(15) << "sys" // time spent in kernel model (cumulative)
<< "mem" // used memory (cumulative)
<< std::endl;
}
void stop() override {
CAF_LOG_TRACE("");
super::stop();
auto now = clock_type::now().time_since_epoch();
auto wallclock = system_start_ + (now - clock_start_);
for (size_t i = 0; i < worker_states_.size(); ++i) {
record(wallclock, "worker", i, worker_states_[i].worker);
}
}
void start_measuring(size_t worker, actor_id job) {
auto& w = worker_states_[worker];
w.current = job;
w.job = measurement::take();
}
void stop_measuring(size_t worker, actor_id job) {
auto m = measurement::take();
auto& w = worker_states_[worker];
CAF_ASSERT(job == w.current);
auto delta = m - w.job;
// It's not possible that the wallclock timer is less than actual CPU time
// spent. Due to resolution mismatches of the C++ high-resolution clock and
// the system timers, this may appear to be the case sometimes. We "fix"
// this by adjusting the wallclock to the sum of user and system time, so
// that utilization never exceeds 100%.
if (delta.time < delta.usr + delta.sys) {
delta.time = delta.usr + delta.sys;
}
w.worker += delta;
report(job, delta);
if (m.time - w.last_flush >= resolution_) {
w.last_flush = m.time;
auto wallclock = system_start_ + (m.time - clock_start_);
std::lock_guard<std::mutex> file_guard{file_mtx_};
record(wallclock, "worker", worker, w.worker);
w.worker = {};
}
}
void remove_job(actor_id job) {
std::lock_guard<std::mutex> job_guard{job_mtx_};
auto j = jobs_.find(job);
if (j != jobs_.end()) {
if (job != 0) {
auto now = clock_type::now().time_since_epoch();
auto wallclock = system_start_ + (now - clock_start_);
std::lock_guard<std::mutex> file_guard{file_mtx_};
record(wallclock, "actor", job, j->second);
}
jobs_.erase(j);
}
}
template <class Time, class Label>
void record(Time t, Label label, size_t id, const measurement& m) {
using std::setw;
file_ << setw(21) << t.time_since_epoch().count()
<< setw(10) << label
<< setw(10) << id
<< m
<< std::endl;
}
void report(const actor_id& job, const measurement& m) {
std::lock_guard<std::mutex> job_guard{job_mtx_};
jobs_[job] += m;
if (m.time - last_flush_ >= resolution_) {
last_flush_ = m.time;
auto now = clock_type::now().time_since_epoch();
auto wallclock = system_start_ + (now - clock_start_);
std::lock_guard<std::mutex> file_guard{file_mtx_};
for (auto& j : jobs_) {
record(wallclock, "actor", j.first, j.second);
j.second = {};
}
}
}
std::mutex job_mtx_;
std::mutex file_mtx_;
std::ofstream file_;
msec resolution_;
std::chrono::system_clock::time_point system_start_;
clock_type::duration clock_start_;
std::vector<worker_state> worker_states_;
std::unordered_map<actor_id, measurement> jobs_;
clock_type::duration last_flush_;
};
} // namespace scheduler
} // namespace caf
#endif // CAF_SCHEDULER_PROFILED_COORDINATOR_HPP
<commit_msg>Add missing initialization and improve naming<commit_after>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright (C) 2011 - 2015 *
* Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#ifndef CAF_SCHEDULER_PROFILED_COORDINATOR_HPP
#define CAF_SCHEDULER_PROFILED_COORDINATOR_HPP
#include "caf/config.hpp"
#if defined(CAF_MACOS) || defined(CAF_IOS)
#include <mach/mach.h>
#else
#include <sys/resource.h>
#endif // CAF_MACOS
#include <cmath>
#include <mutex>
#include <chrono>
#include <vector>
#include <fstream>
#include <iomanip>
#include <unordered_map>
#include "caf/policy/profiled.hpp"
#include "caf/policy/work_stealing.hpp"
#include "caf/detail/logging.hpp"
namespace caf {
namespace scheduler {
/// A coordinator which keeps fine-grained profiling state about its workers
/// and their jobs.
template <class Policy = policy::profiled<policy::work_stealing>>
class profiled_coordinator : public coordinator<Policy> {
public:
using super = coordinator<Policy>;
using clock_type = std::chrono::high_resolution_clock;
using usec = std::chrono::microseconds;
using msec = std::chrono::milliseconds;
class measurement {
public:
# if defined(CAF_MACOS) || defined(CAF_IOS)
static usec to_usec(const ::time_value_t& tv) {
return std::chrono::seconds(tv.seconds) + usec(tv.microseconds);
}
# else
static usec to_usec(const ::timeval& tv) {
return std::chrono::seconds(tv.tv_sec) + usec(tv.tv_usec);
}
# endif // CAF_MACOS
static measurement take() {
auto now = clock_type::now().time_since_epoch();
measurement m;
m.runtime = std::chrono::duration_cast<usec>(now);
# if defined(CAF_MACOS) || defined(CAF_IOS)
auto tself = ::mach_thread_self();
::thread_basic_info info;
auto count = THREAD_BASIC_INFO_COUNT;
auto result = ::thread_info(tself, THREAD_BASIC_INFO,
reinterpret_cast<thread_info_t>(&info),
&count);
if (result == KERN_SUCCESS && (info.flags & TH_FLAGS_IDLE) == 0) {
m.usr = to_usec(info.user_time);
m.sys = to_usec(info.system_time);
}
::mach_port_deallocate(mach_task_self(), tself);
# else
::rusage ru;
::getrusage(RUSAGE_THREAD, &ru);
m.usr = to_usec(ru.ru_utime);
m.sys = to_usec(ru.ru_stime);
m.mem = ru.ru_maxrss;
# endif // CAF_MACOS
return m;
}
measurement& operator+=(const measurement& other) {
runtime += other.runtime;
usr += other.usr;
sys += other.sys;
mem += other.mem;
return *this;
}
measurement& operator-=(const measurement& other) {
runtime -= other.runtime;
usr -= other.usr;
sys -= other.sys;
mem -= other.mem;
return *this;
}
friend measurement operator+(const measurement& x, const measurement& y) {
measurement tmp(x);
tmp += y;
return tmp;
}
friend measurement operator-(const measurement& x, const measurement& y) {
measurement tmp(x);
tmp -= y;
return tmp;
}
friend std::ostream& operator<<(std::ostream& out, const measurement& m) {
using std::setw;
out << setw(15) << m.runtime.count()
<< setw(15) << m.usr.count()
<< setw(15) << m.sys.count()
<< m.mem;
return out;
}
usec runtime = usec::zero();
usec usr = usec::zero();
usec sys = usec::zero();
long mem = 0;
};
struct worker_state {
actor_id current;
measurement job;
measurement worker;
clock_type::duration last_flush = clock_type::duration::zero();
};
profiled_coordinator(const std::string& filename,
msec res = msec{1000},
size_t nw = std::max(std::thread::hardware_concurrency(),
4u),
size_t mt = std::numeric_limits<size_t>::max())
: super{nw, mt},
file_{filename},
resolution_{res},
system_start_{std::chrono::system_clock::now()},
clock_start_{clock_type::now().time_since_epoch()} {
if (! file_) {
throw std::runtime_error{"failed to open CAF profiler file"};
}
}
void initialize() override {
super::initialize();
worker_states_.resize(this->num_workers());
using std::setw;
file_.flags(std::ios::left);
file_ << setw(21) << "clock" // UNIX timestamp in microseconds
<< setw(10) << "type" // "actor" or "worker"
<< setw(10) << "id" // ID of the above
<< setw(15) << "time" // duration of this sample (cumulative)
<< setw(15) << "usr" // time spent in user mode (cumulative)
<< setw(15) << "sys" // time spent in kernel model (cumulative)
<< "mem" // used memory (cumulative)
<< std::endl;
}
void stop() override {
CAF_LOG_TRACE("");
super::stop();
auto now = clock_type::now().time_since_epoch();
auto wallclock = system_start_ + (now - clock_start_);
for (size_t i = 0; i < worker_states_.size(); ++i) {
record(wallclock, "worker", i, worker_states_[i].worker);
}
}
void start_measuring(size_t worker, actor_id job) {
auto& w = worker_states_[worker];
w.current = job;
w.job = measurement::take();
}
void stop_measuring(size_t worker, actor_id job) {
auto m = measurement::take();
auto& w = worker_states_[worker];
CAF_ASSERT(job == w.current);
auto delta = m - w.job;
// It's not possible that the wallclock timer is less than actual CPU time
// spent. Due to resolution mismatches of the C++ high-resolution clock and
// the system timers, this may appear to be the case sometimes. We "fix"
// this by adjusting the wallclock to the sum of user and system time, so
// that utilization never exceeds 100%.
if (delta.runtime < delta.usr + delta.sys) {
delta.runtime = delta.usr + delta.sys;
}
w.worker += delta;
report(job, delta);
if (m.runtime - w.last_flush >= resolution_) {
w.last_flush = m.runtime;
auto wallclock = system_start_ + (m.runtime - clock_start_);
std::lock_guard<std::mutex> file_guard{file_mtx_};
record(wallclock, "worker", worker, w.worker);
w.worker = {};
}
}
void remove_job(actor_id job) {
std::lock_guard<std::mutex> job_guard{job_mtx_};
auto j = jobs_.find(job);
if (j != jobs_.end()) {
if (job != 0) {
auto now = clock_type::now().time_since_epoch();
auto wallclock = system_start_ + (now - clock_start_);
std::lock_guard<std::mutex> file_guard{file_mtx_};
record(wallclock, "actor", job, j->second);
}
jobs_.erase(j);
}
}
template <class Time, class Label>
void record(Time t, Label label, size_t id, const measurement& m) {
using std::setw;
file_ << setw(21) << t.time_since_epoch().count()
<< setw(10) << label
<< setw(10) << id
<< m
<< std::endl;
}
void report(const actor_id& job, const measurement& m) {
std::lock_guard<std::mutex> job_guard{job_mtx_};
jobs_[job] += m;
if (m.runtime - last_flush_ >= resolution_) {
last_flush_ = m.runtime;
auto now = clock_type::now().time_since_epoch();
auto wallclock = system_start_ + (now - clock_start_);
std::lock_guard<std::mutex> file_guard{file_mtx_};
for (auto& j : jobs_) {
record(wallclock, "actor", j.first, j.second);
j.second = {};
}
}
}
std::mutex job_mtx_;
std::mutex file_mtx_;
std::ofstream file_;
msec resolution_;
std::chrono::system_clock::time_point system_start_;
clock_type::duration clock_start_;
std::vector<worker_state> worker_states_;
std::unordered_map<actor_id, measurement> jobs_;
clock_type::duration last_flush_ = clock_type::duration::zero();
};
} // namespace scheduler
} // namespace caf
#endif // CAF_SCHEDULER_PROFILED_COORDINATOR_HPP
<|endoftext|> |
<commit_before>#include <QtTest/QtTest>
#include "../qtest-platform.h"
#include "setupdialog.h"
#define VISUAL_INIT \
IF_VISUAL \
{ \
setupWizard->show(); \
VISUAL_WAIT; \
}
class TestSetupWizard : public QObject
{
Q_OBJECT
public:
TestSetupWizard();
~TestSetupWizard();
private slots:
void normal_install();
void cli();
private:
};
TestSetupWizard::TestSetupWizard()
{
QCoreApplication::setOrganizationName(TEST_NAME);
}
TestSetupWizard::~TestSetupWizard()
{
}
void TestSetupWizard::normal_install()
{
SetupDialog * setupWizard = new SetupDialog();
Ui::SetupDialog ui = setupWizard->_ui;
QSignalSpy sig_cli(setupWizard, SIGNAL(getTarsnapVersion(QString)));
QSignalSpy sig_register(setupWizard,
SIGNAL(requestRegisterMachine(QString, QString,
QString, QString,
QString, QString)));
VISUAL_INIT;
// Page 1
QVERIFY(ui.titleLabel->text() == "Setup wizard");
QTest::mouseClick(ui.nextButton, Qt::LeftButton);
VISUAL_WAIT;
// Page 2
QVERIFY(ui.titleLabel->text() == "Command-line utilities");
QVERIFY(sig_cli.count() == 1);
// Fake the CLI detection and checking
setupWizard->setTarsnapVersion("X.Y.Z");
QVERIFY(ui.advancedValidationLabel->text().contains("Tarsnap CLI version"));
QTest::mouseClick(ui.nextButton, Qt::LeftButton);
VISUAL_WAIT;
// Page 3
QVERIFY(ui.titleLabel->text() == "Register with server");
// Pretend that we already have a key
setupWizard->restoreYes();
ui.restoreYesButton->setChecked(true);
ui.machineKeyCombo->setCurrentText("pretend.key");
ui.nextButton->setEnabled(true);
QTest::mouseClick(ui.nextButton, Qt::LeftButton);
// Check results of registration
QVERIFY(sig_register.count() == 1);
QVERIFY(sig_register.takeFirst().at(3).toString()
== QString("pretend.key"));
setupWizard->registerMachineStatus(TaskStatus::Completed, "");
VISUAL_WAIT;
// Page 4
QVERIFY(ui.titleLabel->text() == "Setup complete!");
QTest::mouseClick(ui.nextButton, Qt::LeftButton);
VISUAL_WAIT;
delete setupWizard;
}
void TestSetupWizard::cli()
{
SetupDialog * setupWizard = new SetupDialog();
Ui::SetupDialog ui = setupWizard->_ui;
QSignalSpy sig_cli(setupWizard, SIGNAL(getTarsnapVersion(QString)));
VISUAL_INIT;
// Advanced to CLI page and expand advanced options
QTest::mouseClick(ui.nextButton, Qt::LeftButton);
QVERIFY(ui.titleLabel->text() == "Command-line utilities");
ui.advancedCLIButton->click();
VISUAL_WAIT;
// App data directory
ui.appDataPathLineEdit->setText("fake-dir");
QVERIFY(ui.advancedValidationLabel->text()
== "Invalid App data directory set.");
VISUAL_WAIT;
ui.appDataPathLineEdit->setText("/tmp");
// Cache directory
ui.tarsnapCacheLineEdit->setText("fake-dir");
QVERIFY(ui.advancedValidationLabel->text()
== "Invalid Tarsnap cache directory set.");
VISUAL_WAIT;
ui.tarsnapCacheLineEdit->setText("/tmp");
// Tarsnap CLI directory
ui.tarsnapPathLineEdit->setText("fake-dir");
QVERIFY(ui.advancedValidationLabel->text().contains(
"Tarsnap utilities not found."));
VISUAL_WAIT;
ui.tarsnapPathLineEdit->setText("/tmp");
// Fake detecting the binaries
setupWizard->setTarsnapVersion("X.Y.Z.");
QVERIFY(ui.advancedValidationLabel->text().contains("Tarsnap CLI version"));
VISUAL_WAIT;
delete setupWizard;
}
QTEST_MAIN(TestSetupWizard)
#include "main.moc"
<commit_msg>tests/setupwizard: filter out bad "offscreen" warnings<commit_after>#include <QtTest/QtTest>
#include "../qtest-platform.h"
#include "setupdialog.h"
#define VISUAL_INIT \
IF_VISUAL \
{ \
setupWizard->show(); \
VISUAL_WAIT; \
}
class TestSetupWizard : public QObject
{
Q_OBJECT
public:
TestSetupWizard();
~TestSetupWizard();
private slots:
void initTestCase();
void normal_install();
void cli();
private:
};
TestSetupWizard::TestSetupWizard()
{
QCoreApplication::setOrganizationName(TEST_NAME);
}
TestSetupWizard::~TestSetupWizard()
{
}
void TestSetupWizard::initTestCase()
{
IF_NOT_VISUAL
{
// Use a custom message handler to filter out unwanted messages
orig_message_handler = qInstallMessageHandler(offscreenMessageOutput);
}
}
void TestSetupWizard::normal_install()
{
SetupDialog * setupWizard = new SetupDialog();
Ui::SetupDialog ui = setupWizard->_ui;
QSignalSpy sig_cli(setupWizard, SIGNAL(getTarsnapVersion(QString)));
QSignalSpy sig_register(setupWizard,
SIGNAL(requestRegisterMachine(QString, QString,
QString, QString,
QString, QString)));
VISUAL_INIT;
// Page 1
QVERIFY(ui.titleLabel->text() == "Setup wizard");
QTest::mouseClick(ui.nextButton, Qt::LeftButton);
VISUAL_WAIT;
// Page 2
QVERIFY(ui.titleLabel->text() == "Command-line utilities");
QVERIFY(sig_cli.count() == 1);
// Fake the CLI detection and checking
setupWizard->setTarsnapVersion("X.Y.Z");
QVERIFY(ui.advancedValidationLabel->text().contains("Tarsnap CLI version"));
QTest::mouseClick(ui.nextButton, Qt::LeftButton);
VISUAL_WAIT;
// Page 3
QVERIFY(ui.titleLabel->text() == "Register with server");
// Pretend that we already have a key
setupWizard->restoreYes();
ui.restoreYesButton->setChecked(true);
ui.machineKeyCombo->setCurrentText("pretend.key");
ui.nextButton->setEnabled(true);
QTest::mouseClick(ui.nextButton, Qt::LeftButton);
// Check results of registration
QVERIFY(sig_register.count() == 1);
QVERIFY(sig_register.takeFirst().at(3).toString()
== QString("pretend.key"));
setupWizard->registerMachineStatus(TaskStatus::Completed, "");
VISUAL_WAIT;
// Page 4
QVERIFY(ui.titleLabel->text() == "Setup complete!");
QTest::mouseClick(ui.nextButton, Qt::LeftButton);
VISUAL_WAIT;
delete setupWizard;
}
void TestSetupWizard::cli()
{
SetupDialog * setupWizard = new SetupDialog();
Ui::SetupDialog ui = setupWizard->_ui;
QSignalSpy sig_cli(setupWizard, SIGNAL(getTarsnapVersion(QString)));
VISUAL_INIT;
// Advanced to CLI page and expand advanced options
QTest::mouseClick(ui.nextButton, Qt::LeftButton);
QVERIFY(ui.titleLabel->text() == "Command-line utilities");
ui.advancedCLIButton->click();
VISUAL_WAIT;
// App data directory
ui.appDataPathLineEdit->setText("fake-dir");
QVERIFY(ui.advancedValidationLabel->text()
== "Invalid App data directory set.");
VISUAL_WAIT;
ui.appDataPathLineEdit->setText("/tmp");
// Cache directory
ui.tarsnapCacheLineEdit->setText("fake-dir");
QVERIFY(ui.advancedValidationLabel->text()
== "Invalid Tarsnap cache directory set.");
VISUAL_WAIT;
ui.tarsnapCacheLineEdit->setText("/tmp");
// Tarsnap CLI directory
ui.tarsnapPathLineEdit->setText("fake-dir");
QVERIFY(ui.advancedValidationLabel->text().contains(
"Tarsnap utilities not found."));
VISUAL_WAIT;
ui.tarsnapPathLineEdit->setText("/tmp");
// Fake detecting the binaries
setupWizard->setTarsnapVersion("X.Y.Z.");
QVERIFY(ui.advancedValidationLabel->text().contains("Tarsnap CLI version"));
VISUAL_WAIT;
delete setupWizard;
}
QTEST_MAIN(TestSetupWizard)
#include "main.moc"
<|endoftext|> |
<commit_before>
#include <iostream>
#include <assert.h>
#include "semantican.h"
SemanticAn::SemanticAn( std::vector<Token *> tokens)
{
this->tokens = tokens;
}
std::vector<SemanticUnit *> SemanticAn::run()
{
std::vector<SemanticUnit *> res;
for ( tok = tokens.begin(); tok != tokens.end(); )
{
if ( tok[0]->type() == TOKEN_EOS)
{
tok ++;
}
else if ( tok[0]->type() == TOKEN_ID &&
tok[1]->type() == TOKEN_COLON) // label
{
res.push_back( SemanticUnit::createLabel( tok[0]->str()));
tok += 2;
}
else if ( tok[0]->type() == TOKEN_ID && isOpcode( tok[0]->str()))
{
std::string opcode = tok[0]->str();
tok ++;
std::vector<Operand *> operands = parseOperandList();
res.push_back( SemanticUnit::createOperation( opcode, operands));
}
else
{
std::cerr << "token type = " << tok[0]->type() << std::endl;
throw;
}
}
return res;
}
bool SemanticAn::isOpcode( std::string s)
{
return s == "brm" || s == "brr" || s == "ld" ||
s == "nop" || s == "add" || s == "sub" ||
s == "jmp" || s == "jgt";
}
std::vector<Operand *> SemanticAn::parseOperandList()
{
std::vector<Operand *> res;
while ( tok[0]->type() != TOKEN_EOS)
{
res.push_back( parseOperand());
if ( tok[0]->type() == TOKEN_COMMA)
{
tok ++;
}
else if ( tok[0]->type() != TOKEN_EOS)
{
std::cerr << "token type = " << tok[0]->type() << std::endl;
throw;
}
}
return res;
}
Operand *SemanticAn::parseOperand()
{
Operand *res = NULL;
if ( tok[0]->type() == TOKEN_ID)
{
res = Operand::createId( tok[0]->str());
tok ++;
}
else if ( tok[0]->type() == TOKEN_LBRACKET &&
tok[1]->type() == TOKEN_ID &&
tok[2]->type() == TOKEN_RBRACKET)
{
res = Operand::createIdInd( tok[1]->str()); // indirect via id
tok += 3;
}
else if ( tok[0]->type() == TOKEN_CONST_INT)
{
res = Operand::createConstInt( tok[0]->integer());
tok ++;
}
else
{
std::cerr << "token type = " << tok[0]->type() << std::endl;
throw;
}
return res;
}
Operand *Operand::createId( std::string id_string)
{
Operand *res = new Operand;
if ( id_string[0] == '%')
{
res->type = OPERAND_GPR;
res->sVal = id_string;
}
else
{
res->type = OPERAND_CUSTOM_ID;
res->sVal = id_string;
}
return res;
}
Operand *Operand::createIdInd(
std::string id_string)
{
Operand *res = createId( id_string);
res->indirect = true;
return res;
}
Operand *Operand::createConstInt( int iVal)
{
Operand *res = new Operand;
res->type = OPERAND_CONST_INT;
res->iVal = iVal;
return res;
}
Operand::Operand()
{
indirect = false;
}
bool Operand::isIndirectGpr() const
{
return indirect && type == OPERAND_GPR;
}
bool Operand::isDirectGpr() const
{
return !indirect && type == OPERAND_GPR;
}
bool Operand::isConstInt() const
{
return type == OPERAND_CONST_INT;
}
SemanticUnit *SemanticUnit::createOperation(
std::string opcode, std::vector<Operand *> operands)
{
SemanticUnit *res = new SemanticUnit;
res->unitType = UNIT_OPERATION;
res->sVal = opcode;
res->operands = operands;
return res;
}
SemanticUnit *SemanticUnit::createLabel( std::string id)
{
SemanticUnit *res = new SemanticUnit;
res->unitType = UNIT_LABEL;
res->sVal = id;
return res;
}
UNIT_TYPE SemanticUnit::type()
{
return unitType;
}
std::string SemanticUnit::str() const
{
assert( unitType == UNIT_LABEL || unitType == UNIT_OPERATION);
return sVal;
}
bool SemanticUnit::operator== ( const std::string &str)
{
assert( unitType == UNIT_LABEL || unitType == UNIT_OPERATION);
return sVal == str;
}
int SemanticUnit::nOperands()
{
assert( unitType == UNIT_OPERATION);
return (int)operands.size();
}
const Operand *SemanticUnit::operator[] ( int index)
{
assert( unitType == UNIT_OPERATION);
assert( index >= 0 && index < nOperands());
return operands[index];
}
void SemanticUnit::dump()
{
switch ( unitType)
{
case UNIT_LABEL:
std::cout << "(label) " << sVal << ":";
break;
case UNIT_OPERATION:
std::cout << "(op ) " << sVal << " ";
for ( int i = 0; i < (int)operands.size(); i ++)
{
if ( i > 0)
{
std::cout << ", ";
}
operands[i]->dump();
}
break;
default: throw;
}
}
std::string Operand::str() const
{
return sVal;
}
int Operand::integer() const
{
return iVal;
}
void Operand::dump()
{
if ( indirect)
{
std::cout << "m(";
}
switch ( type)
{
case OPERAND_GPR: std::cout << sVal; break;
case OPERAND_CONST_INT: std::cout << "$" << iVal; break;
case OPERAND_CUSTOM_ID: std::cout << sVal; break;
default: throw;
}
if ( indirect)
{
std::cout << ")";
}
}
<commit_msg>Complete making methods const (fix build)<commit_after>
#include <iostream>
#include <assert.h>
#include "semantican.h"
SemanticAn::SemanticAn( std::vector<Token *> tokens)
{
this->tokens = tokens;
}
std::vector<SemanticUnit *> SemanticAn::run()
{
std::vector<SemanticUnit *> res;
for ( tok = tokens.begin(); tok != tokens.end(); )
{
if ( tok[0]->type() == TOKEN_EOS)
{
tok ++;
}
else if ( tok[0]->type() == TOKEN_ID &&
tok[1]->type() == TOKEN_COLON) // label
{
res.push_back( SemanticUnit::createLabel( tok[0]->str()));
tok += 2;
}
else if ( tok[0]->type() == TOKEN_ID && isOpcode( tok[0]->str()))
{
std::string opcode = tok[0]->str();
tok ++;
std::vector<Operand *> operands = parseOperandList();
res.push_back( SemanticUnit::createOperation( opcode, operands));
}
else
{
std::cerr << "token type = " << tok[0]->type() << std::endl;
throw;
}
}
return res;
}
bool SemanticAn::isOpcode( std::string s)
{
return s == "brm" || s == "brr" || s == "ld" ||
s == "nop" || s == "add" || s == "sub" ||
s == "jmp" || s == "jgt";
}
std::vector<Operand *> SemanticAn::parseOperandList()
{
std::vector<Operand *> res;
while ( tok[0]->type() != TOKEN_EOS)
{
res.push_back( parseOperand());
if ( tok[0]->type() == TOKEN_COMMA)
{
tok ++;
}
else if ( tok[0]->type() != TOKEN_EOS)
{
std::cerr << "token type = " << tok[0]->type() << std::endl;
throw;
}
}
return res;
}
Operand *SemanticAn::parseOperand()
{
Operand *res = NULL;
if ( tok[0]->type() == TOKEN_ID)
{
res = Operand::createId( tok[0]->str());
tok ++;
}
else if ( tok[0]->type() == TOKEN_LBRACKET &&
tok[1]->type() == TOKEN_ID &&
tok[2]->type() == TOKEN_RBRACKET)
{
res = Operand::createIdInd( tok[1]->str()); // indirect via id
tok += 3;
}
else if ( tok[0]->type() == TOKEN_CONST_INT)
{
res = Operand::createConstInt( tok[0]->integer());
tok ++;
}
else
{
std::cerr << "token type = " << tok[0]->type() << std::endl;
throw;
}
return res;
}
Operand *Operand::createId( std::string id_string)
{
Operand *res = new Operand;
if ( id_string[0] == '%')
{
res->type = OPERAND_GPR;
res->sVal = id_string;
}
else
{
res->type = OPERAND_CUSTOM_ID;
res->sVal = id_string;
}
return res;
}
Operand *Operand::createIdInd(
std::string id_string)
{
Operand *res = createId( id_string);
res->indirect = true;
return res;
}
Operand *Operand::createConstInt( int iVal)
{
Operand *res = new Operand;
res->type = OPERAND_CONST_INT;
res->iVal = iVal;
return res;
}
Operand::Operand()
{
indirect = false;
}
bool Operand::isIndirectGpr() const
{
return indirect && type == OPERAND_GPR;
}
bool Operand::isDirectGpr() const
{
return !indirect && type == OPERAND_GPR;
}
bool Operand::isConstInt() const
{
return type == OPERAND_CONST_INT;
}
SemanticUnit *SemanticUnit::createOperation(
std::string opcode, std::vector<Operand *> operands)
{
SemanticUnit *res = new SemanticUnit;
res->unitType = UNIT_OPERATION;
res->sVal = opcode;
res->operands = operands;
return res;
}
SemanticUnit *SemanticUnit::createLabel( std::string id)
{
SemanticUnit *res = new SemanticUnit;
res->unitType = UNIT_LABEL;
res->sVal = id;
return res;
}
UNIT_TYPE SemanticUnit::type() const
{
return unitType;
}
std::string SemanticUnit::str() const
{
assert( unitType == UNIT_LABEL || unitType == UNIT_OPERATION);
return sVal;
}
bool SemanticUnit::operator== ( const std::string &str) const
{
assert( unitType == UNIT_LABEL || unitType == UNIT_OPERATION);
return sVal == str;
}
int SemanticUnit::nOperands() const
{
assert( unitType == UNIT_OPERATION);
return (int)operands.size();
}
const Operand *SemanticUnit::operator[] ( int index) const
{
assert( unitType == UNIT_OPERATION);
assert( index >= 0 && index < nOperands());
return operands[index];
}
void SemanticUnit::dump() const
{
switch ( unitType)
{
case UNIT_LABEL:
std::cout << "(label) " << sVal << ":";
break;
case UNIT_OPERATION:
std::cout << "(op ) " << sVal << " ";
for ( int i = 0; i < (int)operands.size(); i ++)
{
if ( i > 0)
{
std::cout << ", ";
}
operands[i]->dump();
}
break;
default: throw;
}
}
std::string Operand::str() const
{
return sVal;
}
int Operand::integer() const
{
return iVal;
}
void Operand::dump() const
{
if ( indirect)
{
std::cout << "m(";
}
switch ( type)
{
case OPERAND_GPR: std::cout << sVal; break;
case OPERAND_CONST_INT: std::cout << "$" << iVal; break;
case OPERAND_CUSTOM_ID: std::cout << sVal; break;
default: throw;
}
if ( indirect)
{
std::cout << ")";
}
}
<|endoftext|> |
<commit_before>#include "StringUtils.h"
namespace ccons {
void vstring_printf(std::string *dst, const char *fmt, va_list ap)
{
char *s;
if (vasprintf(&s, fmt, ap) > 0) {
dst->assign(s);
free(s);
}
}
void string_printf(std::string *dst, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vstring_printf(dst, fmt, ap);
va_end(ap);
}
void oprintf(std::ostream& out, const char *fmt, ...)
{
std::string str;
va_list ap;
va_start(ap, fmt);
vstring_printf(&str, fmt, ap);
va_end(ap);
out << str;
}
} // namespace ccons
<commit_msg>add missing header files<commit_after>#include "StringUtils.h"
#include <stdlib.h>
#include <stdarg.h>
namespace ccons {
void vstring_printf(std::string *dst, const char *fmt, va_list ap)
{
char *s;
if (vasprintf(&s, fmt, ap) > 0) {
dst->assign(s);
free(s);
}
}
void string_printf(std::string *dst, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vstring_printf(dst, fmt, ap);
va_end(ap);
}
void oprintf(std::ostream& out, const char *fmt, ...)
{
std::string str;
va_list ap;
va_start(ap, fmt);
vstring_printf(&str, fmt, ap);
va_end(ap);
out << str;
}
} // namespace ccons
<|endoftext|> |
<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2014, University of Toronto
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the University of Toronto 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.
*********************************************************************/
/* Author: Jonathan Gammell*/
// The class's header
#include "ompl/util/ProlateHyperspheroid.h"
// For OMPL exceptions
#include "ompl/util/Exception.h"
// For OMPL information
#include "ompl/util/Console.h"
// For geometric equations like prolateHyperspheroidMeasure
#include "ompl/util/GeometricEquations.h"
// For boost::make_shared
#include <boost/make_shared.hpp>
// Eigen core:
#include <Eigen/Core>
// Inversion and determinants
#include <Eigen/LU>
// SVD decomposition
#include <Eigen/SVD>
struct ompl::ProlateHyperspheroid::PhsData
{
/** \brief The dimension of the prolate hyperspheroid.*/
unsigned int dim_;
/** \brief Whether the transformation is up to date */
bool isTransformUpToDate_;
/** \brief The minimum possible transverse diameter of the PHS. Defined as the distance between the two foci*/
double minTransverseDiameter_;
/** \brief The transverse diameter of the PHS. */
double transverseDiameter_;
/** \brief The measure of the PHS. */
double phsMeasure_;
/** \brief The first focus of the PHS (i.e., the start state of the planning problem). Unlike other parts of Eigen, variably sized matrices do not require special allocators. */
Eigen::VectorXd xFocus1_;
/** \brief The second focus of the PHS (i.e., the goal state of the planning problem). Unlike other parts of Eigen, variably sized matrices do not require special allocators. */
Eigen::VectorXd xFocus2_;
/** \brief The centre of the PHS. Defined as the average of the foci. Unlike other parts of Eigen, variably sized matrices do not require special allocators. */
Eigen::VectorXd xCentre_;
/** \brief The rotation from PHS-frame to world frame. Is only calculated on construction. Unlike other parts of Eigen, variably sized matrices do not require special allocators. */
Eigen::MatrixXd rotationWorldFromEllipse_;
/** \brief The transformation from PHS-frame to world frame. Is calculated every time the transverse diameter changes. Unlike other parts of Eigen, variably sized matrices do not require special allocators. */
Eigen::MatrixXd transformationWorldFromEllipse_;
};
ompl::ProlateHyperspheroid::ProlateHyperspheroid(unsigned int n, const double focus1[], const double focus2[])
: dataPtr_ (boost::make_shared<PhsData>())
{
//Initialize the data:
dataPtr_->dim_ = n;
dataPtr_->transverseDiameter_ = 0.0; // Initialize to something.
dataPtr_->isTransformUpToDate_ = false;
// Copy the arrays into their Eigen containers via the Eigen::Map "view"
dataPtr_->xFocus1_ = Eigen::Map<const Eigen::VectorXd>(focus1, dataPtr_->dim_);
dataPtr_->xFocus2_ = Eigen::Map<const Eigen::VectorXd>(focus2, dataPtr_->dim_);
// Calculate the minimum transverse diameter
dataPtr_->minTransverseDiameter_ = (dataPtr_->xFocus1_ - dataPtr_->xFocus2_).norm();
// Calculate the centre:
dataPtr_->xCentre_ = 0.5 * (dataPtr_->xFocus1_ + dataPtr_->xFocus2_);
// Calculate the rotation
updateRotation();
}
void ompl::ProlateHyperspheroid::setTransverseDiameter(double transverseDiameter)
{
if (transverseDiameter < dataPtr_->minTransverseDiameter_)
{
OMPL_ERROR("%g < %g", transverseDiameter, dataPtr_->minTransverseDiameter_);
throw Exception("Transverse diameter cannot be less than the distance between the foci.");
}
// Store and update if changed
if (dataPtr_->transverseDiameter_ != transverseDiameter)
{
// Mark as out of date
dataPtr_->isTransformUpToDate_ = false;
// Store
dataPtr_->transverseDiameter_ = transverseDiameter;
// Update the transform
updateTransformation();
}
// No else, the diameter didn't change
}
void ompl::ProlateHyperspheroid::transform(const double sphere[], double phs[]) const
{
if (dataPtr_->isTransformUpToDate_ == false)
{
throw Exception("The transformation is not up to date in the PHS class. Has the transverse diameter been set?");
}
// Calculate the tranformation and offset, using Eigen::Map views of the data
Eigen::Map<Eigen::VectorXd>(phs, dataPtr_->dim_) = dataPtr_->transformationWorldFromEllipse_*Eigen::Map<const Eigen::VectorXd>(sphere, dataPtr_->dim_) + dataPtr_->xCentre_;
}
bool ompl::ProlateHyperspheroid::isInPhs(const double point[]) const
{
if (dataPtr_->isTransformUpToDate_ == false)
{
// The transform is not up to date until the transverse diameter has been set
throw Exception ("The transverse diameter has not been set");
}
return (getPathLength(point) <= dataPtr_->transverseDiameter_);
}
unsigned int ompl::ProlateHyperspheroid::getPhsDimension(void) const
{
return dataPtr_->dim_;
}
double ompl::ProlateHyperspheroid::getPhsMeasure(void) const
{
if (dataPtr_->isTransformUpToDate_ == false)
{
// The transform is not up to date until the transverse diameter has been set, therefore we have no transverse diameter and we have infinite measure
return std::numeric_limits<double>::infinity();
}
else
{
// Calculate and return:
return dataPtr_->phsMeasure_;
}
}
double ompl::ProlateHyperspheroid::getPhsMeasure(double tranDiam) const
{
return prolateHyperspheroidMeasure(dataPtr_->dim_, dataPtr_->minTransverseDiameter_, tranDiam);
}
double ompl::ProlateHyperspheroid::getMinTransverseDiameter(void) const
{
return dataPtr_->minTransverseDiameter_;
}
double ompl::ProlateHyperspheroid::getPathLength(const double point[]) const
{
return (dataPtr_->xFocus1_ - Eigen::Map<const Eigen::VectorXd>(point, dataPtr_->dim_)).norm() + (Eigen::Map<const Eigen::VectorXd>(point, dataPtr_->dim_) - dataPtr_->xFocus2_).norm();
}
unsigned int ompl::ProlateHyperspheroid::getDimension() const
{
return dataPtr_->dim_;
}
void ompl::ProlateHyperspheroid::updateRotation(void)
{
// Mark the transform as out of date
dataPtr_->isTransformUpToDate_ = false;
// If the minTransverseDiameter_ is too close to 0, we treat this as a circle.
double circleTol = 1E-9;
if (dataPtr_->minTransverseDiameter_ < circleTol)
{
dataPtr_->rotationWorldFromEllipse_.setIdentity(dataPtr_->dim_, dataPtr_->dim_);
}
else
{
// Variables
// The transverse axis of the PHS expressed in the world frame.
Eigen::VectorXd transverseAxis(dataPtr_->dim_);
// The matrix representation of the Wahba problem
Eigen::MatrixXd wahbaProb(dataPtr_->dim_, dataPtr_->dim_);
// The middle diagonal matrix in the SVD solution to the Wahba problem
Eigen::VectorXd middleM(dataPtr_->dim_);
// Calculate the major axis, storing as the first eigenvector
transverseAxis = (dataPtr_->xFocus2_ - dataPtr_->xFocus1_ )/dataPtr_->minTransverseDiameter_;
// Calculate the rotation that will allow us to generate the remaining eigenvectors
// Formulate as a Wahba problem, first forming the matrix a_j*a_i' where a_j is the transverse axis if the ellipse in the world frame, and a_i is the first basis vector of the world frame (i.e., [1 0 .... 0])
wahbaProb = transverseAxis * Eigen::MatrixXd::Identity(dataPtr_->dim_, dataPtr_->dim_).col(0).transpose();
// Then run it through the SVD solver
Eigen::JacobiSVD<Eigen::MatrixXd, Eigen::NoQRPreconditioner> svd(wahbaProb, Eigen::ComputeFullV | Eigen::ComputeFullU);
// Then calculate the rotation matrix from the U and V components of SVD
// Calculate the middle diagonal matrix
middleM = Eigen::VectorXd::Ones(dataPtr_->dim_);
// Make the last value equal to det(U)*det(V) (zero-based indexing remember)
middleM(dataPtr_->dim_ - 1) = svd.matrixU().determinant() * svd.matrixV().determinant();
// Calculate the rotation
dataPtr_->rotationWorldFromEllipse_ = svd.matrixU() * middleM.asDiagonal() * svd.matrixV().transpose();
}
}
void ompl::ProlateHyperspheroid::updateTransformation(void)
{
// Variables
// The radii of the ellipse
Eigen::VectorXd diagAsVector(dataPtr_->dim_);
// The conjugate diameters:
double conjugateDiamater;
// Calculate the conjugate radius
conjugateDiamater = std::sqrt(dataPtr_->transverseDiameter_*dataPtr_->transverseDiameter_ - dataPtr_->minTransverseDiameter_*dataPtr_->minTransverseDiameter_);
// Store into the diagonal matrix
// All the elements but one are the conjugate radius
diagAsVector.fill(conjugateDiamater/2.0);
// The first element in diagonal is the transverse radius
diagAsVector(0) = 0.5 * dataPtr_->transverseDiameter_;
// Calculate the transformation matrix
dataPtr_->transformationWorldFromEllipse_ = dataPtr_->rotationWorldFromEllipse_ * diagAsVector.asDiagonal();
// Calculate the measure:
dataPtr_->phsMeasure_ = prolateHyperspheroidMeasure(dataPtr_->dim_, dataPtr_->minTransverseDiameter_, dataPtr_->transverseDiameter_);
// Mark as up to date
dataPtr_->isTransformUpToDate_ = true;
}
<commit_msg>xcode static analysis says this is safer<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2014, University of Toronto
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the University of Toronto 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.
*********************************************************************/
/* Author: Jonathan Gammell*/
// The class's header
#include "ompl/util/ProlateHyperspheroid.h"
// For OMPL exceptions
#include "ompl/util/Exception.h"
// For OMPL information
#include "ompl/util/Console.h"
// For geometric equations like prolateHyperspheroidMeasure
#include "ompl/util/GeometricEquations.h"
// For boost::make_shared
#include <boost/make_shared.hpp>
// Eigen core:
#include <Eigen/Core>
// Inversion and determinants
#include <Eigen/LU>
// SVD decomposition
#include <Eigen/SVD>
struct ompl::ProlateHyperspheroid::PhsData
{
/** \brief The dimension of the prolate hyperspheroid.*/
unsigned int dim_;
/** \brief Whether the transformation is up to date */
bool isTransformUpToDate_;
/** \brief The minimum possible transverse diameter of the PHS. Defined as the distance between the two foci*/
double minTransverseDiameter_;
/** \brief The transverse diameter of the PHS. */
double transverseDiameter_;
/** \brief The measure of the PHS. */
double phsMeasure_;
/** \brief The first focus of the PHS (i.e., the start state of the planning problem). Unlike other parts of Eigen, variably sized matrices do not require special allocators. */
Eigen::VectorXd xFocus1_;
/** \brief The second focus of the PHS (i.e., the goal state of the planning problem). Unlike other parts of Eigen, variably sized matrices do not require special allocators. */
Eigen::VectorXd xFocus2_;
/** \brief The centre of the PHS. Defined as the average of the foci. Unlike other parts of Eigen, variably sized matrices do not require special allocators. */
Eigen::VectorXd xCentre_;
/** \brief The rotation from PHS-frame to world frame. Is only calculated on construction. Unlike other parts of Eigen, variably sized matrices do not require special allocators. */
Eigen::MatrixXd rotationWorldFromEllipse_;
/** \brief The transformation from PHS-frame to world frame. Is calculated every time the transverse diameter changes. Unlike other parts of Eigen, variably sized matrices do not require special allocators. */
Eigen::MatrixXd transformationWorldFromEllipse_;
};
ompl::ProlateHyperspheroid::ProlateHyperspheroid(unsigned int n, const double focus1[], const double focus2[])
: dataPtr_ (boost::make_shared<PhsData>())
{
//Initialize the data:
dataPtr_->dim_ = n;
dataPtr_->transverseDiameter_ = 0.0; // Initialize to something.
dataPtr_->isTransformUpToDate_ = false;
// Copy the arrays into their Eigen containers via the Eigen::Map "view"
dataPtr_->xFocus1_ = Eigen::Map<const Eigen::VectorXd>(focus1, dataPtr_->dim_);
dataPtr_->xFocus2_ = Eigen::Map<const Eigen::VectorXd>(focus2, dataPtr_->dim_);
// Calculate the minimum transverse diameter
dataPtr_->minTransverseDiameter_ = (dataPtr_->xFocus1_ - dataPtr_->xFocus2_).norm();
// Calculate the centre:
dataPtr_->xCentre_ = 0.5 * (dataPtr_->xFocus1_ + dataPtr_->xFocus2_);
// Calculate the rotation
updateRotation();
}
void ompl::ProlateHyperspheroid::setTransverseDiameter(double transverseDiameter)
{
if (transverseDiameter < dataPtr_->minTransverseDiameter_)
{
OMPL_ERROR("%g < %g", transverseDiameter, dataPtr_->minTransverseDiameter_);
throw Exception("Transverse diameter cannot be less than the distance between the foci.");
}
// Store and update if changed
if (dataPtr_->transverseDiameter_ != transverseDiameter)
{
// Mark as out of date
dataPtr_->isTransformUpToDate_ = false;
// Store
dataPtr_->transverseDiameter_ = transverseDiameter;
// Update the transform
updateTransformation();
}
// No else, the diameter didn't change
}
void ompl::ProlateHyperspheroid::transform(const double sphere[], double phs[]) const
{
if (dataPtr_->isTransformUpToDate_ == false)
{
throw Exception("The transformation is not up to date in the PHS class. Has the transverse diameter been set?");
}
// Calculate the tranformation and offset, using Eigen::Map views of the data
Eigen::Map<Eigen::VectorXd>(phs, dataPtr_->dim_) = dataPtr_->transformationWorldFromEllipse_*Eigen::Map<const Eigen::VectorXd>(sphere, dataPtr_->dim_);
Eigen::Map<Eigen::VectorXd>(phs, dataPtr_->dim_) += dataPtr_->xCentre_;
}
bool ompl::ProlateHyperspheroid::isInPhs(const double point[]) const
{
if (dataPtr_->isTransformUpToDate_ == false)
{
// The transform is not up to date until the transverse diameter has been set
throw Exception ("The transverse diameter has not been set");
}
return (getPathLength(point) <= dataPtr_->transverseDiameter_);
}
unsigned int ompl::ProlateHyperspheroid::getPhsDimension(void) const
{
return dataPtr_->dim_;
}
double ompl::ProlateHyperspheroid::getPhsMeasure(void) const
{
if (dataPtr_->isTransformUpToDate_ == false)
{
// The transform is not up to date until the transverse diameter has been set, therefore we have no transverse diameter and we have infinite measure
return std::numeric_limits<double>::infinity();
}
else
{
// Calculate and return:
return dataPtr_->phsMeasure_;
}
}
double ompl::ProlateHyperspheroid::getPhsMeasure(double tranDiam) const
{
return prolateHyperspheroidMeasure(dataPtr_->dim_, dataPtr_->minTransverseDiameter_, tranDiam);
}
double ompl::ProlateHyperspheroid::getMinTransverseDiameter(void) const
{
return dataPtr_->minTransverseDiameter_;
}
double ompl::ProlateHyperspheroid::getPathLength(const double point[]) const
{
return (dataPtr_->xFocus1_ - Eigen::Map<const Eigen::VectorXd>(point, dataPtr_->dim_)).norm() + (Eigen::Map<const Eigen::VectorXd>(point, dataPtr_->dim_) - dataPtr_->xFocus2_).norm();
}
unsigned int ompl::ProlateHyperspheroid::getDimension() const
{
return dataPtr_->dim_;
}
void ompl::ProlateHyperspheroid::updateRotation(void)
{
// Mark the transform as out of date
dataPtr_->isTransformUpToDate_ = false;
// If the minTransverseDiameter_ is too close to 0, we treat this as a circle.
double circleTol = 1E-9;
if (dataPtr_->minTransverseDiameter_ < circleTol)
{
dataPtr_->rotationWorldFromEllipse_.setIdentity(dataPtr_->dim_, dataPtr_->dim_);
}
else
{
// Variables
// The transverse axis of the PHS expressed in the world frame.
Eigen::VectorXd transverseAxis(dataPtr_->dim_);
// The matrix representation of the Wahba problem
Eigen::MatrixXd wahbaProb(dataPtr_->dim_, dataPtr_->dim_);
// The middle diagonal matrix in the SVD solution to the Wahba problem
Eigen::VectorXd middleM(dataPtr_->dim_);
// Calculate the major axis, storing as the first eigenvector
transverseAxis = (dataPtr_->xFocus2_ - dataPtr_->xFocus1_ )/dataPtr_->minTransverseDiameter_;
// Calculate the rotation that will allow us to generate the remaining eigenvectors
// Formulate as a Wahba problem, first forming the matrix a_j*a_i' where a_j is the transverse axis if the ellipse in the world frame, and a_i is the first basis vector of the world frame (i.e., [1 0 .... 0])
wahbaProb = transverseAxis * Eigen::MatrixXd::Identity(dataPtr_->dim_, dataPtr_->dim_).col(0).transpose();
// Then run it through the SVD solver
Eigen::JacobiSVD<Eigen::MatrixXd, Eigen::NoQRPreconditioner> svd(wahbaProb, Eigen::ComputeFullV | Eigen::ComputeFullU);
// Then calculate the rotation matrix from the U and V components of SVD
// Calculate the middle diagonal matrix
middleM = Eigen::VectorXd::Ones(dataPtr_->dim_);
// Make the last value equal to det(U)*det(V) (zero-based indexing remember)
middleM(dataPtr_->dim_ - 1) = svd.matrixU().determinant() * svd.matrixV().determinant();
// Calculate the rotation
dataPtr_->rotationWorldFromEllipse_ = svd.matrixU() * middleM.asDiagonal() * svd.matrixV().transpose();
}
}
void ompl::ProlateHyperspheroid::updateTransformation(void)
{
// Variables
// The radii of the ellipse
Eigen::VectorXd diagAsVector(dataPtr_->dim_);
// The conjugate diameters:
double conjugateDiamater;
// Calculate the conjugate radius
conjugateDiamater = std::sqrt(dataPtr_->transverseDiameter_*dataPtr_->transverseDiameter_ - dataPtr_->minTransverseDiameter_*dataPtr_->minTransverseDiameter_);
// Store into the diagonal matrix
// All the elements but one are the conjugate radius
diagAsVector.fill(conjugateDiamater/2.0);
// The first element in diagonal is the transverse radius
diagAsVector(0) = 0.5 * dataPtr_->transverseDiameter_;
// Calculate the transformation matrix
dataPtr_->transformationWorldFromEllipse_ = dataPtr_->rotationWorldFromEllipse_ * diagAsVector.asDiagonal();
// Calculate the measure:
dataPtr_->phsMeasure_ = prolateHyperspheroidMeasure(dataPtr_->dim_, dataPtr_->minTransverseDiameter_, dataPtr_->transverseDiameter_);
// Mark as up to date
dataPtr_->isTransformUpToDate_ = true;
}
<|endoftext|> |
<commit_before>#pragma once
#include <planning/Path.hpp>
#include <Geometry2d/Point.hpp>
#include <Geometry2d/Segment.hpp>
#include <Geometry2d/CompositeShape.hpp>
#include <Configuration.hpp>
namespace Planning
{
/**
* @brief Represents a motion path made up of a series of Paths.
*
* @details The path represents a function of position given time that the robot should follow.
* The path is made up of other Paths and can be made up of CompositePaths.
*/
class CompositePath: public Path
{
private:
//Vector of Paths
std::vector<std::unique_ptr<Path>> paths;
/**
* Append the path to the end of the CompositePath
* The path passed in should not be refenced anywhere else.
*/
void append(Path *path);
//Saving some variables to speed up computation
float duration;
public:
/** default path is empty */
CompositePath() {}
/** constructors with one path */
CompositePath(Path *path);
CompositePath(std::unique_ptr<Path> path);
/**
* Append the path to the end of the CompositePath
*/
void append(std::unique_ptr<Path> path);
virtual bool evaluate(float t, Geometry2d::Point &targetPosOut, Geometry2d::Point &targetVelOut) const override;
virtual bool hit(const Geometry2d::CompositeShape &shape, float startTime = 0) const override;
virtual void draw(SystemState * const state, const QColor &color = Qt::black, const QString &layer = "Motion") const override;
virtual float getDuration() const override;
virtual std::unique_ptr<Path> subPath(float startTime = 0, float endTime = std::numeric_limits<float>::infinity()) const override;
virtual boost::optional<Geometry2d::Point> destination() const override;
virtual std::unique_ptr<Path> clone() const override;
};
}
<commit_msg>explicitly state default value of duration variable in CompositePath<commit_after>#pragma once
#include <planning/Path.hpp>
#include <Geometry2d/Point.hpp>
#include <Geometry2d/Segment.hpp>
#include <Geometry2d/CompositeShape.hpp>
#include <Configuration.hpp>
namespace Planning
{
/**
* @brief Represents a motion path made up of a series of Paths.
*
* @details The path represents a function of position given time that the robot should follow.
* The path is made up of other Paths and can be made up of CompositePaths.
*/
class CompositePath: public Path
{
private:
//Vector of Paths
std::vector<std::unique_ptr<Path>> paths;
//Saving some variables to speed up computation
float duration = 0.0f;
/**
* Append the path to the end of the CompositePath
* The path passed in should not be refenced anywhere else.
*/
void append(Path *path);
public:
/** default path is empty */
CompositePath() {}
/** constructors with one path */
CompositePath(Path *path);
CompositePath(std::unique_ptr<Path> path);
/**
* Append the path to the end of the CompositePath
*/
void append(std::unique_ptr<Path> path);
virtual bool evaluate(float t, Geometry2d::Point &targetPosOut, Geometry2d::Point &targetVelOut) const override;
virtual bool hit(const Geometry2d::CompositeShape &shape, float startTime = 0) const override;
virtual void draw(SystemState * const state, const QColor &color = Qt::black, const QString &layer = "Motion") const override;
virtual float getDuration() const override;
virtual std::unique_ptr<Path> subPath(float startTime = 0, float endTime = std::numeric_limits<float>::infinity()) const override;
virtual boost::optional<Geometry2d::Point> destination() const override;
virtual std::unique_ptr<Path> clone() const override;
};
}
<|endoftext|> |
<commit_before>// $Id: forceField.C,v 1.12 2000/02/02 09:52:09 len Exp $
#include <BALL/MOLMEC/COMMON/forceField.h>
#include <BALL/MOLMEC/COMMON/forceFieldComponent.h>
#include <BALL/MOLMEC/COMMON/periodicBoundary.h>
#include <BALL/KERNEL/bond.h>
#include <BALL/KERNEL/forEach.h>
using namespace std;
namespace BALL
{
// default constructor
ForceField::ForceField()
: periodic_boundary(*this),
system_( 0 ),
valid_(true),
name_("Force Field"),
number_of_movable_atoms_(0),
use_selection_(false)
{
}
// copy constructor
ForceField::ForceField(const ForceField& force_field, bool /* deep */)
{
// Copy the attributes
name_ = force_field.name_;
energy_ = force_field.energy_;
options = force_field.options;
system_ = force_field.system_;
atoms_ = force_field.atoms_;
number_of_movable_atoms_ = force_field.number_of_movable_atoms_;
parameters_ = force_field.parameters_;
periodic_boundary = force_field.periodic_boundary;
use_selection_ = force_field.use_selection_;
valid_ = force_field.valid_;
// Copy the component vector
for (Size i = 0; i < force_field.components_.size(); i++)
{
components_.push_back((ForceFieldComponent*)force_field.components_[i]->create());
}
}
// assignment operator
ForceField& ForceField::operator = (const ForceField& force_field)
{
// guard against self assignment
if (&force_field != this)
{
atoms_.clear();
atoms_ = force_field.atoms_;
number_of_movable_atoms_ = force_field.number_of_movable_atoms_;
name_ = force_field.name_;
energy_ = force_field.energy_;
options = force_field.options;
system_ = force_field.system_;
parameters_ = force_field.parameters_;
periodic_boundary = force_field.periodic_boundary;
use_selection_ = force_field.use_selection_;
valid_ = force_field.valid_;
Size i;
for (i = 0; i < components_.size(); i++)
{
delete components_[i];
}
components_.clear();
for (i = 0; i < force_field.components_.size(); i++)
{
components_.push_back((ForceFieldComponent*)force_field.components_[i]->create());
}
}
return (*this);
}
// Constructor initialized with a system
ForceField::ForceField(System& system)
: periodic_boundary(*this)
{
bool result = setup(system);
if (!result)
{
Log.level(LogStream::ERROR) << "Force Field setup failed! " << endl;
valid_ = false;
}
}
// Constructor intialized with a system and a set of options
ForceField::ForceField(System& system, const Options& new_options)
: periodic_boundary(*this)
{
bool result = setup(system, new_options);
if (!result)
{
Log.level(LogStream::ERROR) << "Force Field setup failed! " << endl;
valid_ = false;
}
}
// destructor
ForceField::~ForceField()
{
// clear pointers
system_ = 0;
// remove all force field components from the list after
// calling their destructors
vector<ForceFieldComponent*>::iterator it;
for (it = components_.begin(); it != components_.end(); ++it)
{
delete (*it);
}
components_.clear();
}
// Is the force field valid
bool ForceField::isValid()
{
return valid_;
}
// setup methods
bool ForceField::setup(System& system)
{
bool success = true;
// store the specified system
system_ = &system;
// Setup periodic boundary
if(!periodic_boundary.setup())
{
Log.error() << "setup of periodic boundary failed" << endl;
return false;
}
// clear existing atoms entries
atoms_.clear();
// check for selected atoms
// if any of the atoms is selected, the atoms_ array holds
// the selected atoms first (0 < i < number_of_movable_atoms_)
use_selection_ = system.containsSelection();
number_of_movable_atoms_ = 0;
AtomIterator atom_it = system.beginAtom();
if (use_selection_ == true)
{
for (; +atom_it; ++atom_it)
{
if (atom_it->isSelected() == true)
{
atoms_.push_back(&(*atom_it));
}
}
} else {
for (; +atom_it; ++atom_it)
{
atoms_.push_back(&(*atom_it));
}
}
number_of_movable_atoms_ = atoms_.size();
// generate the vector of molecules if periodic boundary is enabled
if (periodic_boundary.isEnabled())
{
periodic_boundary.generateMoleculesVector();
}
// force field specific parts
success = specificSetup();
if (!success)
{
Log.error() << "Force Field specificSetup failed!" << endl;
return false;
}
// call the setup method for each force field component
vector<ForceFieldComponent*>::iterator it;
for (it = components_.begin(); (it != components_.end()) && success; ++it)
{
success = (*(*it)).setup();
if (!success)
{
Log.error() << "Force Field Component setup of "
<< (*it)->name_ << " failed!" << endl;
}
}
return success;
}
// Setup with a system and a set of options
bool ForceField::setup(System& system, const Options& new_options)
{
options = new_options;
return setup(system);
}
// Returns the name of the force field
String ForceField::getName() const
{
return name_;
}
// Sets the name of force field to name
void ForceField::setName(const String& name)
{
name_ = name;
}
// Returns the number of atoms stored in the vector atoms_
Size ForceField::getNumberOfAtoms() const
{
return atoms_.size();
}
// Returns the number of movable (non-fixed) atoms stored in the vector atoms_
Size ForceField::getNumberOfMovableAtoms() const
{
return number_of_movable_atoms_;
}
// Returns the reference of the atom vector atoms_
const vector<Atom*>& ForceField::getAtoms() const
{
return atoms_;
}
// Return a pointer to the system
System* ForceField::getSystem()
{
return system_;
}
// Return the parameter use_selection_
bool ForceField::getUseSelection()
{
return use_selection_;
}
// Return the parameter use_selection_
void ForceField::setUseSelection(bool use_selection)
{
use_selection_ = use_selection;
}
// Return a pointer to the parameter file
ForceFieldParameters& ForceField::getParameters()
{
return parameters_;
}
void ForceField::updateForces()
{
// check for validity of the force field
if (!isValid())
{
return;
}
// Set forces to zero
for (vector<Atom*>::iterator it = atoms_.begin(); it != atoms_.end(); ++it)
{
(*it)->setForce(RTTI::getDefault<Vector3>());
}
// call each component - they will add their forces...
vector<ForceFieldComponent*>::iterator component_it = components_.begin();
for (; component_it != components_.end(); ++component_it)
{
(*component_it)->updateForces();
}
}
// Calculate the RMS of the gradient
float ForceField::getRMSGradient() const
{
float sum = 0;
vector<Atom*>::const_iterator it = atoms_.begin();
for (; it != atoms_.end(); ++it)
{
sum += (*it)->getForce().getSquareLength();
}
sum = sqrt(sum/(3 * (float)atoms_.size()));
sum *= Constants::AVOGADRO / 1e13;
return(sum);
}
float ForceField::getEnergy() const
{
return energy_;
}
float ForceField::updateEnergy()
{
// check for validity of the force field
if (!isValid())
{
return 0.0;
}
// clear the total energy
energy_ = 0;
// call each component and add their energies
vector<ForceFieldComponent*>::iterator it;
for (it = components_.begin(); it != components_.end(); ++it)
{
energy_ += (*it)->updateEnergy();
}
// return the resulting energy
return energy_;
}
Size ForceField::getUpdateFrequency() const
{
return 1;
}
void ForceField::update()
{
}
bool ForceField::specificSetup()
{
return true;
}
// Insert a component in the component vector
void ForceField::insertComponent(ForceFieldComponent* force_field_component)
{
components_.push_back(force_field_component);
}
// Remove the component
void ForceField::removeComponent(const ForceFieldComponent* force_field_component)
{
// call each component - test if equal - remove
vector<ForceFieldComponent*>::iterator it;
for (it = components_.begin(); it != components_.end(); ++it)
{
if ((*it) == force_field_component)
{
components_.erase(it);
break ;
}
}
}
// Remove the component
void ForceField::removeComponent(const String& name)
{
// call each component - test if equal - remove
vector<ForceFieldComponent*>::iterator it;
for (it = components_.begin(); it != components_.end(); ++it)
{
if ((*it)->getName() == name)
{
components_.erase(it);
break ;
}
}
}
// Returns the number of components
Size ForceField::countComponents() const
{
return components_.size();
}
// Returns the component with index "index"
ForceFieldComponent* ForceField::getComponent(const Size index) const
{
if (index >= components_.size())
return 0;
return components_[index];
}
ForceFieldComponent* ForceField::getComponent(const String& name) const
{
for (Size i = 0; i < components_.size(); ++i)
{
if (components_[i]->getName() == name)
{
return components_[i];
}
}
return 0;
}
} // namespace BALL
<commit_msg>added: member collectAtoms_ to avoid redundant code. Introduced by CHARMM force field which might remove atoms (to create extended atoms) in specificSetup. SO the atoms_ vector might have to be rebuilt<commit_after>// $Id: forceField.C,v 1.13 2000/02/06 20:08:27 oliver Exp $
#include <BALL/MOLMEC/COMMON/forceField.h>
#include <BALL/MOLMEC/COMMON/forceFieldComponent.h>
#include <BALL/MOLMEC/COMMON/periodicBoundary.h>
#include <BALL/KERNEL/bond.h>
#include <BALL/KERNEL/forEach.h>
using namespace std;
namespace BALL
{
// default constructor
ForceField::ForceField()
: periodic_boundary(*this),
system_( 0 ),
valid_(true),
name_("Force Field"),
number_of_movable_atoms_(0),
use_selection_(false)
{
}
// copy constructor
ForceField::ForceField(const ForceField& force_field, bool /* deep */)
{
// Copy the attributes
name_ = force_field.name_;
energy_ = force_field.energy_;
options = force_field.options;
system_ = force_field.system_;
atoms_ = force_field.atoms_;
number_of_movable_atoms_ = force_field.number_of_movable_atoms_;
parameters_ = force_field.parameters_;
periodic_boundary = force_field.periodic_boundary;
use_selection_ = force_field.use_selection_;
valid_ = force_field.valid_;
// Copy the component vector
for (Size i = 0; i < force_field.components_.size(); i++)
{
components_.push_back((ForceFieldComponent*)force_field.components_[i]->create());
}
}
// assignment operator
ForceField& ForceField::operator = (const ForceField& force_field)
{
// guard against self assignment
if (&force_field != this)
{
atoms_.clear();
atoms_ = force_field.atoms_;
number_of_movable_atoms_ = force_field.number_of_movable_atoms_;
name_ = force_field.name_;
energy_ = force_field.energy_;
options = force_field.options;
system_ = force_field.system_;
parameters_ = force_field.parameters_;
periodic_boundary = force_field.periodic_boundary;
use_selection_ = force_field.use_selection_;
valid_ = force_field.valid_;
Size i;
for (i = 0; i < components_.size(); i++)
{
delete components_[i];
}
components_.clear();
for (i = 0; i < force_field.components_.size(); i++)
{
components_.push_back((ForceFieldComponent*)force_field.components_[i]->create());
}
}
return (*this);
}
// Constructor initialized with a system
ForceField::ForceField(System& system)
: periodic_boundary(*this)
{
bool result = setup(system);
if (!result)
{
Log.level(LogStream::ERROR) << "Force Field setup failed! " << endl;
valid_ = false;
}
}
// Constructor intialized with a system and a set of options
ForceField::ForceField(System& system, const Options& new_options)
: periodic_boundary(*this)
{
bool result = setup(system, new_options);
if (!result)
{
Log.level(LogStream::ERROR) << "Force Field setup failed! " << endl;
valid_ = false;
}
}
// destructor
ForceField::~ForceField()
{
// clear pointers
system_ = 0;
// remove all force field components from the list after
// calling their destructors
vector<ForceFieldComponent*>::iterator it;
for (it = components_.begin(); it != components_.end(); ++it)
{
delete (*it);
}
components_.clear();
}
// Is the force field valid
bool ForceField::isValid()
{
return valid_;
}
// setup methods
bool ForceField::setup(System& system)
{
bool success = true;
// store the specified system
system_ = &system;
// Setup periodic boundary
if(!periodic_boundary.setup())
{
Log.error() << "setup of periodic boundary failed" << endl;
return false;
}
// collect the atoms of the system in the atoms_ vector
collectAtoms_(system);
Size old_size = atoms_.size();
// force field specific parts
success = specificSetup();
if (!success)
{
Log.error() << "Force Field specificSetup failed!" << endl;
return false;
}
// if specificSetup cleared this array, it wants to tell us
// that it had to change the system a bit (e.g. CHARMM replacing
// hydrogens by united atoms). So, we have to recalculated the vector.
if (atoms_.size() != old_size)
{
collectAtoms_(system);
}
// call the setup method for each force field component
vector<ForceFieldComponent*>::iterator it;
for (it = components_.begin(); (it != components_.end()) && success; ++it)
{
success = (*(*it)).setup();
if (!success)
{
Log.error() << "Force Field Component setup of "
<< (*it)->name_ << " failed!" << endl;
}
}
// if the setup failed, our force field becomes invalid!
valid_ = success;
return success;
}
// collect all atoms
void ForceField::collectAtoms_(const System& system)
{
// clear existing atoms entries
atoms_.clear();
// check for selected atoms
// if any of the atoms is selected, the atoms_ array holds
// the selected atoms first (0 < i < number_of_movable_atoms_)
use_selection_ = system.containsSelection();
number_of_movable_atoms_ = 0;
AtomIterator atom_it = system.beginAtom();
if (use_selection_ == true)
{
for (; +atom_it; ++atom_it)
{
if (atom_it->isSelected() == true)
{
atoms_.push_back(&(*atom_it));
}
}
} else {
for (; +atom_it; ++atom_it)
{
atoms_.push_back(&(*atom_it));
}
}
number_of_movable_atoms_ = atoms_.size();
// generate the vector of molecules if periodic boundary is enabled
if (periodic_boundary.isEnabled())
{
periodic_boundary.generateMoleculesVector();
}
// force field specific parts
success = specificSetup();
if (!success)
{
Log.error() << "Force Field specificSetup failed!" << endl;
return false;
}
// call the setup method for each force field component
vector<ForceFieldComponent*>::iterator it;
for (it = components_.begin(); (it != components_.end()) && success; ++it)
{
success = (*(*it)).setup();
if (!success)
{
Log.error() << "Force Field Component setup of "
<< (*it)->name_ << " failed!" << endl;
}
}
return success;
}
// Setup with a system and a set of options
bool ForceField::setup(System& system, const Options& new_options)
{
options = new_options;
return setup(system);
}
// Returns the name of the force field
String ForceField::getName() const
{
return name_;
}
// Sets the name of force field to name
void ForceField::setName(const String& name)
{
name_ = name;
}
// Returns the number of atoms stored in the vector atoms_
Size ForceField::getNumberOfAtoms() const
{
return atoms_.size();
}
// Returns the number of movable (non-fixed) atoms stored in the vector atoms_
Size ForceField::getNumberOfMovableAtoms() const
{
return number_of_movable_atoms_;
}
// Returns the reference of the atom vector atoms_
const vector<Atom*>& ForceField::getAtoms() const
{
return atoms_;
}
// Return a pointer to the system
System* ForceField::getSystem()
{
return system_;
}
// Return the parameter use_selection_
bool ForceField::getUseSelection()
{
return use_selection_;
}
// Return the parameter use_selection_
void ForceField::setUseSelection(bool use_selection)
{
use_selection_ = use_selection;
}
// Return a pointer to the parameter file
ForceFieldParameters& ForceField::getParameters()
{
return parameters_;
}
void ForceField::updateForces()
{
// check for validity of the force field
if (!isValid())
{
return;
}
// Set forces to zero
for (vector<Atom*>::iterator it = atoms_.begin(); it != atoms_.end(); ++it)
{
(*it)->setForce(RTTI::getDefault<Vector3>());
}
// call each component - they will add their forces...
vector<ForceFieldComponent*>::iterator component_it = components_.begin();
for (; component_it != components_.end(); ++component_it)
{
(*component_it)->updateForces();
}
}
// Calculate the RMS of the gradient
float ForceField::getRMSGradient() const
{
float sum = 0;
vector<Atom*>::const_iterator it = atoms_.begin();
for (; it != atoms_.end(); ++it)
{
sum += (*it)->getForce().getSquareLength();
}
sum = sqrt(sum/(3 * (float)atoms_.size()));
sum *= Constants::AVOGADRO / 1e13;
return(sum);
}
float ForceField::getEnergy() const
{
return energy_;
}
float ForceField::updateEnergy()
{
// check for validity of the force field
if (!isValid())
{
return 0.0;
}
// clear the total energy
energy_ = 0;
// call each component and add their energies
vector<ForceFieldComponent*>::iterator it;
for (it = components_.begin(); it != components_.end(); ++it)
{
energy_ += (*it)->updateEnergy();
}
// return the resulting energy
return energy_;
}
Size ForceField::getUpdateFrequency() const
{
return 1;
}
void ForceField::update()
{
}
bool ForceField::specificSetup()
{
return true;
}
// Insert a component in the component vector
void ForceField::insertComponent(ForceFieldComponent* force_field_component)
{
components_.push_back(force_field_component);
}
// Remove the component
void ForceField::removeComponent(const ForceFieldComponent* force_field_component)
{
// call each component - test if equal - remove
vector<ForceFieldComponent*>::iterator it;
for (it = components_.begin(); it != components_.end(); ++it)
{
if ((*it) == force_field_component)
{
components_.erase(it);
break ;
}
}
}
// Remove the component
void ForceField::removeComponent(const String& name)
{
// call each component - test if equal - remove
vector<ForceFieldComponent*>::iterator it;
for (it = components_.begin(); it != components_.end(); ++it)
{
if ((*it)->getName() == name)
{
components_.erase(it);
break ;
}
}
}
// Returns the number of components
Size ForceField::countComponents() const
{
return components_.size();
}
// Returns the component with index "index"
ForceFieldComponent* ForceField::getComponent(const Size index) const
{
if (index >= components_.size())
return 0;
return components_[index];
}
ForceFieldComponent* ForceField::getComponent(const String& name) const
{
for (Size i = 0; i < components_.size(); ++i)
{
if (components_[i]->getName() == name)
{
return components_[i];
}
}
return 0;
}
} // namespace BALL
<|endoftext|> |
<commit_before>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright (C) 2011 - 2015 *
* Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#ifndef CAF_OPENCL_GLOBAL_HPP
#define CAF_OPENCL_GLOBAL_HPP
#include <string>
#include "caf/config.hpp"
#include "caf/detail/limited_vector.hpp"
#ifdef CAF_MACOS
# include <OpenCL/opencl.h>
#else
# include <CL/opencl.h>
#endif
// needed for OpenCL 1.0 compatibility (works around missing clReleaseDevice)
extern "C" {
cl_int clReleaseDeviceDummy(cl_device_id);
cl_int clRetainDeviceDummy(cl_device_id);
} // extern "C"
namespace caf {
namespace opencl {
/**
* A vector of up to three elements used for OpenCL dimensions.
*/
using dim_vec = detail::limited_vector<size_t, 3>;
std::string get_opencl_error(cl_int err);
} // namespace opencl
} // namespace caf
#endif // CAF_OPENCL_GLOBAL_HPP
<commit_msg>Fix build on iOS<commit_after>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright (C) 2011 - 2015 *
* Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#ifndef CAF_OPENCL_GLOBAL_HPP
#define CAF_OPENCL_GLOBAL_HPP
#include <string>
#include "caf/config.hpp"
#include "caf/detail/limited_vector.hpp"
#if defined(CAF_MACOS) || defined(CAF_IOS)
# include <OpenCL/opencl.h>
#else
# include <CL/opencl.h>
#endif
// needed for OpenCL 1.0 compatibility (works around missing clReleaseDevice)
extern "C" {
cl_int clReleaseDeviceDummy(cl_device_id);
cl_int clRetainDeviceDummy(cl_device_id);
} // extern "C"
namespace caf {
namespace opencl {
/**
* A vector of up to three elements used for OpenCL dimensions.
*/
using dim_vec = detail::limited_vector<size_t, 3>;
std::string get_opencl_error(cl_int err);
} // namespace opencl
} // namespace caf
#endif // CAF_OPENCL_GLOBAL_HPP
<|endoftext|> |
<commit_before><commit_msg>Rmoved logging line<commit_after><|endoftext|> |
<commit_before>
#include <iostream>
#include <fstream>
#include <sstream>
#include <boost/algorithm/string.hpp>
#include "storage/DevicegraphImpl.h"
#include "storage/Environment.h"
#include "storage/Storage.h"
#include "storage/Action.h"
#include "storage/Devices/DeviceImpl.h"
#include "storage/Devices/BlkDevice.h"
#include "storage/Devices/Partitionable.h"
#include "storage/Devices/PartitionTable.h"
#include "storage/Devices/LvmVgImpl.h"
#include "storage/Devices/LvmPvImpl.h"
#include "storage/Devices/BcacheCsetImpl.h"
#include "storage/Filesystems/BlkFilesystem.h"
#include "storage/Filesystems/Btrfs.h"
#include "storage/Filesystems/BtrfsSubvolume.h"
#include "storage/Filesystems/MountPoint.h"
#include "storage/Utils/Mockup.h"
#include "testsuite/helpers/TsCmp.h"
using namespace std;
namespace storage
{
std::ostream&
operator<<(std::ostream& out, const TsCmp& ts_cmp)
{
out << endl;
for (const string& error : ts_cmp.errors)
out << error << endl;
return out;
}
TsCmpDevicegraph::TsCmpDevicegraph(const Devicegraph& lhs, Devicegraph& rhs)
{
adjust_sids(lhs, rhs);
if (lhs != rhs)
{
ostringstream tmp1;
lhs.get_impl().log_diff(tmp1, rhs.get_impl());
string tmp2 = tmp1.str();
boost::split(errors, tmp2, boost::is_any_of("\n"), boost::token_compress_on);
}
}
/**
* This function adjusts the sids which is needed when devices are the
* detected in a differnet order than expected. Block devices use the name
* for identification, most others a uuid or a path. Some types are not
* handled at all, e.g. Nfs.
*
* The function makes assumptions that break in the general case and does
* no error checking. It can even ruin the devicegraph.
*
* Only enable it when you know what you are doing!
*/
void
TsCmpDevicegraph::adjust_sids(const Devicegraph& lhs, Devicegraph& rhs) const
{
#if 0
for (Device* device_rhs : Device::get_all(&rhs))
{
// BlkDevices
if (is_blk_device(device_rhs))
{
BlkDevice* blk_device_rhs = to_blk_device(device_rhs);
const BlkDevice* blk_device_lhs = BlkDevice::find_by_name(&lhs, blk_device_rhs->get_name());
adjust_sid(blk_device_lhs, blk_device_rhs);
// PartitionTables
if (is_partitionable(blk_device_lhs) && is_partitionable(blk_device_rhs))
{
const Partitionable* partitionable_lhs = to_partitionable(blk_device_lhs);
Partitionable* partitionable_rhs = to_partitionable(blk_device_rhs);
if (partitionable_lhs->has_partition_table() && partitionable_rhs->has_partition_table())
adjust_sid(partitionable_lhs->get_partition_table(), partitionable_rhs->get_partition_table());
}
}
// LvmVgs
if (is_lvm_vg(device_rhs))
{
LvmVg* lvm_vg_rhs = to_lvm_vg(device_rhs);
const LvmVg* lvm_vg_lhs = LvmVg::Impl::find_by_uuid(&lhs, lvm_vg_rhs->get_impl().get_uuid());
adjust_sid(lvm_vg_lhs, lvm_vg_rhs);
}
// LvmPvs
if (is_lvm_pv(device_rhs))
{
LvmPv* lvm_pv_rhs = to_lvm_pv(device_rhs);
const LvmPv* lvm_pv_lhs = LvmPv::Impl::find_by_uuid(&lhs, lvm_pv_rhs->get_impl().get_uuid());
adjust_sid(lvm_pv_lhs, lvm_pv_rhs);
}
// BcacheCset
if (is_bcache_cset(device_rhs))
{
BcacheCset* bcache_cset_rhs = to_bcache_cset(device_rhs);
const BcacheCset* bcache_cset_lhs = BcacheCset::Impl::find_by_uuid(&lhs, bcache_cset_rhs->get_uuid());
adjust_sid(bcache_cset_lhs, bcache_cset_rhs);
}
// BlkFilesystems
if (is_blk_filesystem(device_rhs))
{
BlkFilesystem* blk_filesystem_rhs = to_blk_filesystem(device_rhs);
const BlkFilesystem* blk_filesystem_lhs = BlkFilesystem::find_by_uuid(&lhs, blk_filesystem_rhs->get_uuid()).front();
adjust_sid(blk_filesystem_lhs, blk_filesystem_rhs);
// BtrfsSubvolumes
if (is_btrfs(blk_filesystem_lhs) && is_btrfs(blk_filesystem_rhs))
{
const Btrfs* btrfs_lhs = to_btrfs(blk_filesystem_lhs);
Btrfs* btrfs_rhs = to_btrfs(blk_filesystem_rhs);
for (BtrfsSubvolume* btrfs_subvolume_rhs : btrfs_rhs->get_btrfs_subvolumes())
{
const BtrfsSubvolume* btrfs_subvolume_lhs = btrfs_lhs->find_btrfs_subvolume_by_path(btrfs_subvolume_rhs->get_path());
adjust_sid(btrfs_subvolume_lhs, btrfs_subvolume_rhs);
}
}
}
// MountPoints
if (is_mount_point(device_rhs))
{
MountPoint* mount_point_rhs = to_mount_point(device_rhs);
const MountPoint* mount_point_lhs = MountPoint::find_by_path(&lhs, mount_point_rhs->get_path()).front();
adjust_sid(mount_point_lhs, mount_point_rhs);
}
}
#endif
}
void
TsCmpDevicegraph::adjust_sid(const Device* lhs, Device* rhs) const
{
if (lhs->get_sid() != rhs->get_sid())
{
cout << "adjust sid " << rhs->get_impl().get_classname() << " ("
<< rhs->get_displayname() << ") " << rhs->get_sid() << " -> "
<< lhs->get_sid() << endl;
rhs->get_impl().set_sid(lhs->get_sid());
}
}
TsCmpActiongraph::Expected::Expected(const string& filename)
{
std::ifstream fin(filename);
if (!fin)
ST_THROW(Exception("failed to load " + filename));
string line;
while (getline(fin, line))
{
if (!line.empty() && !boost::starts_with(line, "#"))
lines.push_back(line);
}
}
TsCmpActiongraph::TsCmpActiongraph(const string& name, bool commit)
{
Environment environment(true, ProbeMode::READ_DEVICEGRAPH, TargetMode::DIRECT);
environment.set_devicegraph_filename(name + "-probed.xml");
storage = make_unique<Storage>(environment);
storage->probe();
storage->get_staging()->load(name + "-staging.xml");
probed = storage->get_probed();
staging = storage->get_staging();
actiongraph = storage->calculate_actiongraph();
if (access(DOT_BIN, X_OK) == 0)
{
probed->write_graphviz(name + "-probed.gv", get_debug_devicegraph_style_callbacks(), View::ALL);
system((DOT_BIN " -Tsvg < " + name + "-probed.gv > " + name + "-probed.svg").c_str());
staging->write_graphviz(name + "-staging.gv", get_debug_devicegraph_style_callbacks(), View::ALL);
system((DOT_BIN " -Tsvg < " + name + "-staging.gv > " + name + "-staging.svg").c_str());
actiongraph->write_graphviz(name + "-action.gv", get_debug_actiongraph_style_callbacks());
system((DOT_BIN " -Tsvg < " + name + "-action.gv > " + name + "-action.svg").c_str());
}
TsCmpActiongraph::Expected expected(name + "-expected.txt");
const CommitData commit_data(actiongraph->get_impl(), Tense::SIMPLE_PRESENT);
cmp(commit_data, expected);
// smoke test for compound actions
for (const CompoundAction* compound_action : actiongraph->get_compound_actions())
compound_action->sentence();
if (!commit)
return;
Mockup::set_mode(Mockup::Mode::PLAYBACK);
Mockup::load(name + "-mockup.xml");
CommitOptions commit_options(false);
storage->commit(commit_options);
Mockup::occams_razor();
}
void
TsCmpActiongraph::cmp(const CommitData& commit_data, const Expected& expected)
{
for (const string& line : expected.lines)
entries.push_back(Entry(line));
check();
cmp_texts(commit_data);
if (!ok())
return;
cmp_dependencies(commit_data);
}
TsCmpActiongraph::Entry::Entry(const string& line)
{
string::size_type pos1 = line.find('-');
if (pos1 == string::npos)
ST_THROW(Exception("parse error, did not find '-'"));
string::size_type pos2 = line.rfind("->");
if (pos2 == string::npos)
ST_THROW(Exception("parse error, did not find '->'"));
id = boost::trim_copy(line.substr(0, pos1), locale::classic());
text = boost::trim_copy(line.substr(pos1 + 1, pos2 - pos1 - 1), locale::classic());
string tmp = boost::trim_copy(line.substr(pos2 + 2), locale::classic());
if (!tmp.empty())
boost::split(dep_ids, tmp, boost::is_any_of(" "), boost::token_compress_on);
}
void
TsCmpActiongraph::check() const
{
set<string> ids;
set<string> texts;
for (const Entry& entry : entries)
{
if (!ids.insert(entry.id).second)
ST_THROW(Exception("duplicate id"));
if (!texts.insert(entry.text).second)
ST_THROW(Exception("duplicate text"));
}
for (const Entry& entry : entries)
{
for (const string dep_id : entry.dep_ids)
{
if (ids.find(dep_id) == ids.end())
ST_THROW(Exception("unknown dependency-id"));
}
}
}
string
TsCmpActiongraph::text(const CommitData& commit_data, Actiongraph::Impl::vertex_descriptor vertex) const
{
const Action::Base* action = commit_data.actiongraph[vertex];
return action->debug_text(commit_data);
}
void
TsCmpActiongraph::cmp_texts(const CommitData& commit_data)
{
set<string> tmp1;
for (Actiongraph::Impl::vertex_descriptor vertex : commit_data.actiongraph.vertices())
tmp1.insert(text(commit_data, vertex));
set<string> tmp2;
for (const Entry& entry : entries)
tmp2.insert(entry.text);
if (tmp1 != tmp2)
{
errors.push_back("action texts differ");
vector<string> diff1;
set_difference(tmp2.begin(), tmp2.end(), tmp1.begin(), tmp1.end(), back_inserter(diff1));
for (const string& error : diff1)
errors.push_back("- " + error);
vector<string> diff2;
set_difference(tmp1.begin(), tmp1.end(), tmp2.begin(), tmp2.end(), back_inserter(diff2));
for (const string& error : diff2)
errors.push_back("+ " + error);
}
}
void
TsCmpActiongraph::cmp_dependencies(const CommitData& commit_data)
{
map<string, string> text_to_id;
for (const Entry& entry : entries)
text_to_id[entry.text] = entry.id;
map<string, Actiongraph::Impl::vertex_descriptor> text_to_vertex;
for (Actiongraph::Impl::vertex_descriptor vertex : commit_data.actiongraph.vertices())
text_to_vertex[text(commit_data, vertex)] = vertex;
for (const Entry& entry : entries)
{
Actiongraph::Impl::vertex_descriptor vertex = text_to_vertex[entry.text];
set<string> tmp;
for (Actiongraph::Impl::vertex_descriptor child : commit_data.actiongraph.children(vertex))
tmp.insert(text_to_id[text(commit_data, child)]);
if (tmp != entry.dep_ids)
{
errors.push_back("wrong dependencies for '" + entry.text + "'");
errors.push_back("- " + boost::join(tmp, " "));
errors.push_back("+ " + boost::join(entry.dep_ids, " "));
}
}
}
string
required_features(const Devicegraph* devicegraph)
{
return get_used_features_names(devicegraph->used_features(UsedFeaturesDependencyType::REQUIRED));
}
string
suggested_features(const Devicegraph* devicegraph)
{
return get_used_features_names(devicegraph->used_features(UsedFeaturesDependencyType::SUGGESTED));
}
string
features(const Actiongraph* actiongraph)
{
return get_used_features_names(actiongraph->used_features());
}
}
<commit_msg>- fixed typo<commit_after>
#include <iostream>
#include <fstream>
#include <sstream>
#include <boost/algorithm/string.hpp>
#include "storage/DevicegraphImpl.h"
#include "storage/Environment.h"
#include "storage/Storage.h"
#include "storage/Action.h"
#include "storage/Devices/DeviceImpl.h"
#include "storage/Devices/BlkDevice.h"
#include "storage/Devices/Partitionable.h"
#include "storage/Devices/PartitionTable.h"
#include "storage/Devices/LvmVgImpl.h"
#include "storage/Devices/LvmPvImpl.h"
#include "storage/Devices/BcacheCsetImpl.h"
#include "storage/Filesystems/BlkFilesystem.h"
#include "storage/Filesystems/Btrfs.h"
#include "storage/Filesystems/BtrfsSubvolume.h"
#include "storage/Filesystems/MountPoint.h"
#include "storage/Utils/Mockup.h"
#include "testsuite/helpers/TsCmp.h"
using namespace std;
namespace storage
{
std::ostream&
operator<<(std::ostream& out, const TsCmp& ts_cmp)
{
out << endl;
for (const string& error : ts_cmp.errors)
out << error << endl;
return out;
}
TsCmpDevicegraph::TsCmpDevicegraph(const Devicegraph& lhs, Devicegraph& rhs)
{
adjust_sids(lhs, rhs);
if (lhs != rhs)
{
ostringstream tmp1;
lhs.get_impl().log_diff(tmp1, rhs.get_impl());
string tmp2 = tmp1.str();
boost::split(errors, tmp2, boost::is_any_of("\n"), boost::token_compress_on);
}
}
/**
* This function adjusts the sids which is needed when devices are detected in a
* differnet order than expected. Block devices use the name for identification, most
* others a uuid or a path. Some types are not handled at all, e.g. Nfs.
*
* The function makes assumptions that break in the general case and does no error
* checking. It can even ruin the devicegraph.
*
* Only enable it when you know what you are doing!
*/
void
TsCmpDevicegraph::adjust_sids(const Devicegraph& lhs, Devicegraph& rhs) const
{
#if 0
for (Device* device_rhs : Device::get_all(&rhs))
{
// BlkDevices
if (is_blk_device(device_rhs))
{
BlkDevice* blk_device_rhs = to_blk_device(device_rhs);
const BlkDevice* blk_device_lhs = BlkDevice::find_by_name(&lhs, blk_device_rhs->get_name());
adjust_sid(blk_device_lhs, blk_device_rhs);
// PartitionTables
if (is_partitionable(blk_device_lhs) && is_partitionable(blk_device_rhs))
{
const Partitionable* partitionable_lhs = to_partitionable(blk_device_lhs);
Partitionable* partitionable_rhs = to_partitionable(blk_device_rhs);
if (partitionable_lhs->has_partition_table() && partitionable_rhs->has_partition_table())
adjust_sid(partitionable_lhs->get_partition_table(), partitionable_rhs->get_partition_table());
}
}
// LvmVgs
if (is_lvm_vg(device_rhs))
{
LvmVg* lvm_vg_rhs = to_lvm_vg(device_rhs);
const LvmVg* lvm_vg_lhs = LvmVg::Impl::find_by_uuid(&lhs, lvm_vg_rhs->get_impl().get_uuid());
adjust_sid(lvm_vg_lhs, lvm_vg_rhs);
}
// LvmPvs
if (is_lvm_pv(device_rhs))
{
LvmPv* lvm_pv_rhs = to_lvm_pv(device_rhs);
const LvmPv* lvm_pv_lhs = LvmPv::Impl::find_by_uuid(&lhs, lvm_pv_rhs->get_impl().get_uuid());
adjust_sid(lvm_pv_lhs, lvm_pv_rhs);
}
// BcacheCset
if (is_bcache_cset(device_rhs))
{
BcacheCset* bcache_cset_rhs = to_bcache_cset(device_rhs);
const BcacheCset* bcache_cset_lhs = BcacheCset::Impl::find_by_uuid(&lhs, bcache_cset_rhs->get_uuid());
adjust_sid(bcache_cset_lhs, bcache_cset_rhs);
}
// BlkFilesystems
if (is_blk_filesystem(device_rhs))
{
BlkFilesystem* blk_filesystem_rhs = to_blk_filesystem(device_rhs);
const BlkFilesystem* blk_filesystem_lhs = BlkFilesystem::find_by_uuid(&lhs, blk_filesystem_rhs->get_uuid()).front();
adjust_sid(blk_filesystem_lhs, blk_filesystem_rhs);
// BtrfsSubvolumes
if (is_btrfs(blk_filesystem_lhs) && is_btrfs(blk_filesystem_rhs))
{
const Btrfs* btrfs_lhs = to_btrfs(blk_filesystem_lhs);
Btrfs* btrfs_rhs = to_btrfs(blk_filesystem_rhs);
for (BtrfsSubvolume* btrfs_subvolume_rhs : btrfs_rhs->get_btrfs_subvolumes())
{
const BtrfsSubvolume* btrfs_subvolume_lhs = btrfs_lhs->find_btrfs_subvolume_by_path(btrfs_subvolume_rhs->get_path());
adjust_sid(btrfs_subvolume_lhs, btrfs_subvolume_rhs);
}
}
}
// MountPoints
if (is_mount_point(device_rhs))
{
MountPoint* mount_point_rhs = to_mount_point(device_rhs);
const MountPoint* mount_point_lhs = MountPoint::find_by_path(&lhs, mount_point_rhs->get_path()).front();
adjust_sid(mount_point_lhs, mount_point_rhs);
}
}
#endif
}
void
TsCmpDevicegraph::adjust_sid(const Device* lhs, Device* rhs) const
{
if (lhs->get_sid() != rhs->get_sid())
{
cout << "adjust sid " << rhs->get_impl().get_classname() << " ("
<< rhs->get_displayname() << ") " << rhs->get_sid() << " -> "
<< lhs->get_sid() << endl;
rhs->get_impl().set_sid(lhs->get_sid());
}
}
TsCmpActiongraph::Expected::Expected(const string& filename)
{
std::ifstream fin(filename);
if (!fin)
ST_THROW(Exception("failed to load " + filename));
string line;
while (getline(fin, line))
{
if (!line.empty() && !boost::starts_with(line, "#"))
lines.push_back(line);
}
}
TsCmpActiongraph::TsCmpActiongraph(const string& name, bool commit)
{
Environment environment(true, ProbeMode::READ_DEVICEGRAPH, TargetMode::DIRECT);
environment.set_devicegraph_filename(name + "-probed.xml");
storage = make_unique<Storage>(environment);
storage->probe();
storage->get_staging()->load(name + "-staging.xml");
probed = storage->get_probed();
staging = storage->get_staging();
actiongraph = storage->calculate_actiongraph();
if (access(DOT_BIN, X_OK) == 0)
{
probed->write_graphviz(name + "-probed.gv", get_debug_devicegraph_style_callbacks(), View::ALL);
system((DOT_BIN " -Tsvg < " + name + "-probed.gv > " + name + "-probed.svg").c_str());
staging->write_graphviz(name + "-staging.gv", get_debug_devicegraph_style_callbacks(), View::ALL);
system((DOT_BIN " -Tsvg < " + name + "-staging.gv > " + name + "-staging.svg").c_str());
actiongraph->write_graphviz(name + "-action.gv", get_debug_actiongraph_style_callbacks());
system((DOT_BIN " -Tsvg < " + name + "-action.gv > " + name + "-action.svg").c_str());
}
TsCmpActiongraph::Expected expected(name + "-expected.txt");
const CommitData commit_data(actiongraph->get_impl(), Tense::SIMPLE_PRESENT);
cmp(commit_data, expected);
// smoke test for compound actions
for (const CompoundAction* compound_action : actiongraph->get_compound_actions())
compound_action->sentence();
if (!commit)
return;
Mockup::set_mode(Mockup::Mode::PLAYBACK);
Mockup::load(name + "-mockup.xml");
CommitOptions commit_options(false);
storage->commit(commit_options);
Mockup::occams_razor();
}
void
TsCmpActiongraph::cmp(const CommitData& commit_data, const Expected& expected)
{
for (const string& line : expected.lines)
entries.push_back(Entry(line));
check();
cmp_texts(commit_data);
if (!ok())
return;
cmp_dependencies(commit_data);
}
TsCmpActiongraph::Entry::Entry(const string& line)
{
string::size_type pos1 = line.find('-');
if (pos1 == string::npos)
ST_THROW(Exception("parse error, did not find '-'"));
string::size_type pos2 = line.rfind("->");
if (pos2 == string::npos)
ST_THROW(Exception("parse error, did not find '->'"));
id = boost::trim_copy(line.substr(0, pos1), locale::classic());
text = boost::trim_copy(line.substr(pos1 + 1, pos2 - pos1 - 1), locale::classic());
string tmp = boost::trim_copy(line.substr(pos2 + 2), locale::classic());
if (!tmp.empty())
boost::split(dep_ids, tmp, boost::is_any_of(" "), boost::token_compress_on);
}
void
TsCmpActiongraph::check() const
{
set<string> ids;
set<string> texts;
for (const Entry& entry : entries)
{
if (!ids.insert(entry.id).second)
ST_THROW(Exception("duplicate id"));
if (!texts.insert(entry.text).second)
ST_THROW(Exception("duplicate text"));
}
for (const Entry& entry : entries)
{
for (const string dep_id : entry.dep_ids)
{
if (ids.find(dep_id) == ids.end())
ST_THROW(Exception("unknown dependency-id"));
}
}
}
string
TsCmpActiongraph::text(const CommitData& commit_data, Actiongraph::Impl::vertex_descriptor vertex) const
{
const Action::Base* action = commit_data.actiongraph[vertex];
return action->debug_text(commit_data);
}
void
TsCmpActiongraph::cmp_texts(const CommitData& commit_data)
{
set<string> tmp1;
for (Actiongraph::Impl::vertex_descriptor vertex : commit_data.actiongraph.vertices())
tmp1.insert(text(commit_data, vertex));
set<string> tmp2;
for (const Entry& entry : entries)
tmp2.insert(entry.text);
if (tmp1 != tmp2)
{
errors.push_back("action texts differ");
vector<string> diff1;
set_difference(tmp2.begin(), tmp2.end(), tmp1.begin(), tmp1.end(), back_inserter(diff1));
for (const string& error : diff1)
errors.push_back("- " + error);
vector<string> diff2;
set_difference(tmp1.begin(), tmp1.end(), tmp2.begin(), tmp2.end(), back_inserter(diff2));
for (const string& error : diff2)
errors.push_back("+ " + error);
}
}
void
TsCmpActiongraph::cmp_dependencies(const CommitData& commit_data)
{
map<string, string> text_to_id;
for (const Entry& entry : entries)
text_to_id[entry.text] = entry.id;
map<string, Actiongraph::Impl::vertex_descriptor> text_to_vertex;
for (Actiongraph::Impl::vertex_descriptor vertex : commit_data.actiongraph.vertices())
text_to_vertex[text(commit_data, vertex)] = vertex;
for (const Entry& entry : entries)
{
Actiongraph::Impl::vertex_descriptor vertex = text_to_vertex[entry.text];
set<string> tmp;
for (Actiongraph::Impl::vertex_descriptor child : commit_data.actiongraph.children(vertex))
tmp.insert(text_to_id[text(commit_data, child)]);
if (tmp != entry.dep_ids)
{
errors.push_back("wrong dependencies for '" + entry.text + "'");
errors.push_back("- " + boost::join(tmp, " "));
errors.push_back("+ " + boost::join(entry.dep_ids, " "));
}
}
}
string
required_features(const Devicegraph* devicegraph)
{
return get_used_features_names(devicegraph->used_features(UsedFeaturesDependencyType::REQUIRED));
}
string
suggested_features(const Devicegraph* devicegraph)
{
return get_used_features_names(devicegraph->used_features(UsedFeaturesDependencyType::SUGGESTED));
}
string
features(const Actiongraph* actiongraph)
{
return get_used_features_names(actiongraph->used_features());
}
}
<|endoftext|> |
<commit_before><commit_msg>Planning: enlarge BackToSelfLaneTolerance<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: docu_pe2.hxx,v $
*
* $Revision: 1.1.1.1 $
*
* last change: $Author: np $ $Date: 2002-03-08 14:45:35 $
*
* 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 ADC_DSAPI_DOCU_PE2_HXX
#define ADC_DSAPI_DOCU_PE2_HXX
// USED SERVICES
// BASE CLASSES
#include <s2_dsapi/tokintpr.hxx>
// COMPONENTS
// PARAMETERS
namespace ary
{
namespace info
{
class CodeInformation;
class DocuToken;
} // namespace info
} // namespace ary
namespace csi
{
namespace dsapi
{
class Token;
class DT_AtTag;
class SapiDocu_PE : public TokenInterpreter
{
public:
SapiDocu_PE();
~SapiDocu_PE();
void ProcessToken(
DYN csi::dsapi::Token &
let_drToken );
virtual void Process_AtTag(
const Tok_AtTag & i_rToken );
virtual void Process_HtmlTag(
const Tok_HtmlTag & i_rToken );
virtual void Process_XmlConst(
const Tok_XmlConst &
i_rToken );
virtual void Process_XmlLink_BeginTag(
const Tok_XmlLink_BeginTag &
i_rToken );
virtual void Process_XmlLink_EndTag(
const Tok_XmlLink_EndTag &
i_rToken );
virtual void Process_XmlFormat_BeginTag(
const Tok_XmlFormat_BeginTag &
i_rToken );
virtual void Process_XmlFormat_EndTag(
const Tok_XmlFormat_EndTag &
i_rToken );
virtual void Process_Word(
const Tok_Word & i_rToken );
virtual void Process_Comma();
virtual void Process_DocuEnd();
virtual void Process_EOL();
DYN ary::info::CodeInformation *
ReleaseJustParsedDocu();
bool IsComplete() const;
private:
enum E_State
{
e_none = 0,
st_short,
st_description,
st_attags,
st_complete
};
typedef void ( SapiDocu_PE::*F_TokenAdder )( DYN ary::info::DocuToken & let_drNewToken );
void AddDocuToken2Void(
DYN ary::info::DocuToken &
let_drNewToken );
void AddDocuToken2Short(
DYN ary::info::DocuToken &
let_drNewToken );
void AddDocuToken2Description(
DYN ary::info::DocuToken &
let_drNewToken );
void AddDocuToken2CurAtTag(
DYN ary::info::DocuToken &
let_drNewToken );
void SetCurParameterAtTagName(
DYN ary::info::DocuToken &
let_drNewToken );
void SetCurSeeAlsoAtTagLinkText(
DYN ary::info::DocuToken &
let_drNewToken );
// DATA
Dyn<ary::info::CodeInformation>
pDocu;
E_State eState;
F_TokenAdder fCurTokenAddFunction;
Dyn<DT_AtTag> pCurAtTag;
udmstri sCurDimAttribute;
};
} // namespace dsapi
} // namespace csi
// IMPLEMENTATION
#endif
<commit_msg>INTEGRATION: CWS sdk02 (1.1.1.1.46); FILE MERGED 2003/05/26 16:42:19 np 1.1.1.1.46.1: #108925# Enable tag @since and text for tag @deprecated.<commit_after>/*************************************************************************
*
* $RCSfile: docu_pe2.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: vg $ $Date: 2003-06-10 11:35:31 $
*
* 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 ADC_DSAPI_DOCU_PE2_HXX
#define ADC_DSAPI_DOCU_PE2_HXX
// USED SERVICES
// BASE CLASSES
#include <s2_dsapi/tokintpr.hxx>
// COMPONENTS
// PARAMETERS
namespace ary
{
namespace info
{
class CodeInformation;
class DocuToken;
} // namespace info
} // namespace ary
namespace csi
{
namespace dsapi
{
class Token;
class DT_AtTag;
class SapiDocu_PE : public TokenInterpreter
{
public:
SapiDocu_PE();
~SapiDocu_PE();
void ProcessToken(
DYN csi::dsapi::Token &
let_drToken );
virtual void Process_AtTag(
const Tok_AtTag & i_rToken );
virtual void Process_HtmlTag(
const Tok_HtmlTag & i_rToken );
virtual void Process_XmlConst(
const Tok_XmlConst &
i_rToken );
virtual void Process_XmlLink_BeginTag(
const Tok_XmlLink_BeginTag &
i_rToken );
virtual void Process_XmlLink_EndTag(
const Tok_XmlLink_EndTag &
i_rToken );
virtual void Process_XmlFormat_BeginTag(
const Tok_XmlFormat_BeginTag &
i_rToken );
virtual void Process_XmlFormat_EndTag(
const Tok_XmlFormat_EndTag &
i_rToken );
virtual void Process_Word(
const Tok_Word & i_rToken );
virtual void Process_Comma();
virtual void Process_DocuEnd();
virtual void Process_EOL();
DYN ary::info::CodeInformation *
ReleaseJustParsedDocu();
bool IsComplete() const;
private:
enum E_State
{
e_none = 0,
st_short,
st_description,
st_attags,
st_complete
};
typedef void ( SapiDocu_PE::*F_TokenAdder )( DYN ary::info::DocuToken & let_drNewToken );
void AddDocuToken2Void(
DYN ary::info::DocuToken &
let_drNewToken );
void AddDocuToken2Short(
DYN ary::info::DocuToken &
let_drNewToken );
void AddDocuToken2Description(
DYN ary::info::DocuToken &
let_drNewToken );
void AddDocuToken2Deprecated(
DYN ary::info::DocuToken &
let_drNewToken );
void AddDocuToken2CurAtTag(
DYN ary::info::DocuToken &
let_drNewToken );
void SetCurParameterAtTagName(
DYN ary::info::DocuToken &
let_drNewToken );
void SetCurSeeAlsoAtTagLinkText(
DYN ary::info::DocuToken &
let_drNewToken );
void SetCurSinceAtTagVersion(
DYN ary::info::DocuToken &
let_drNewToken );
// DATA
Dyn<ary::info::CodeInformation>
pDocu;
E_State eState;
F_TokenAdder fCurTokenAddFunction;
Dyn<DT_AtTag> pCurAtTag;
udmstri sCurDimAttribute;
};
} // namespace dsapi
} // namespace csi
// IMPLEMENTATION
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2021 Ultimaker B.V.
// CuraEngine is released under the terms of the AGPLv3 or higher.
#include <algorithm>
#include "CenterDeviationBeadingStrategy.h"
namespace cura
{
CenterDeviationBeadingStrategy::CenterDeviationBeadingStrategy(const coord_t pref_bead_width,
const AngleRadians transitioning_angle,
const Ratio wall_split_middle_threshold,
const Ratio wall_add_middle_threshold)
: BeadingStrategy(pref_bead_width, pref_bead_width / 2, transitioning_angle),
minimum_line_width_split(pref_bead_width * wall_split_middle_threshold),
minimum_line_width_add(pref_bead_width * wall_add_middle_threshold)
{
name = "CenterDeviationBeadingStrategy";
}
CenterDeviationBeadingStrategy::Beading CenterDeviationBeadingStrategy::compute(coord_t thickness, coord_t bead_count) const
{
Beading ret;
ret.total_thickness = thickness;
if (bead_count > 0)
{
// Set the bead widths
ret.bead_widths = std::vector<coord_t>(static_cast<size_t>(bead_count), optimal_width);
const coord_t optimal_thickness = getOptimalThickness(bead_count);
const coord_t diff_thickness = (thickness - optimal_thickness) / 2;
const coord_t inner_bead_widths = optimal_width + diff_thickness;
const size_t center_bead_idx = ret.bead_widths.size() / 2;
if (bead_count % 2 == 0) // Even lines
{
if (inner_bead_widths < minimum_line_width_add)
{
return compute(thickness, bead_count + 1);
}
ret.bead_widths[center_bead_idx - 1] = inner_bead_widths;
ret.bead_widths[center_bead_idx] = inner_bead_widths;
}
else // Uneven lines
{
if (inner_bead_widths < minimum_line_width_split)
{
return compute(thickness, bead_count - 1);
}
ret.bead_widths[center_bead_idx] = inner_bead_widths;
}
// Set the center line location of the bead toolpaths.
ret.toolpath_locations.resize(ret.bead_widths.size());
ret.toolpath_locations.front() = ret.bead_widths.front() / 2;
for (size_t bead_idx = 1; bead_idx < ret.bead_widths.size(); ++bead_idx)
{
ret.toolpath_locations[bead_idx] =
ret.toolpath_locations[bead_idx - 1] + (ret.bead_widths[bead_idx] + ret.bead_widths[bead_idx - 1]) / 2;
}
ret.left_over = 0;
}
else
{
ret.left_over = thickness;
}
return ret;
}
coord_t CenterDeviationBeadingStrategy::getOptimalThickness(coord_t bead_count) const
{
return bead_count * optimal_width;
}
coord_t CenterDeviationBeadingStrategy::getTransitionThickness(coord_t lower_bead_count) const
{
return lower_bead_count * optimal_width + (lower_bead_count % 2 == 1 ? minimum_line_width_split : minimum_line_width_add);
}
coord_t CenterDeviationBeadingStrategy::getOptimalBeadCount(coord_t thickness) const
{
const coord_t naive_count = thickness / optimal_width; // How many lines we can fit in for sure.
const coord_t remainder = thickness - naive_count * optimal_width; // Space left after fitting that many lines.
const coord_t minimum_line_width = naive_count % 2 == 1 ? minimum_line_width_split : minimum_line_width_add;
return naive_count + (remainder > minimum_line_width); // If there's enough space, fit an extra one.
}
} // namespace cura
<commit_msg>Spread diff_thickness over middle 2 lines only if there are 2 middle lines<commit_after>// Copyright (c) 2021 Ultimaker B.V.
// CuraEngine is released under the terms of the AGPLv3 or higher.
#include <algorithm>
#include "CenterDeviationBeadingStrategy.h"
namespace cura
{
CenterDeviationBeadingStrategy::CenterDeviationBeadingStrategy(const coord_t pref_bead_width,
const AngleRadians transitioning_angle,
const Ratio wall_split_middle_threshold,
const Ratio wall_add_middle_threshold)
: BeadingStrategy(pref_bead_width, pref_bead_width / 2, transitioning_angle),
minimum_line_width_split(pref_bead_width * wall_split_middle_threshold),
minimum_line_width_add(pref_bead_width * wall_add_middle_threshold)
{
name = "CenterDeviationBeadingStrategy";
}
CenterDeviationBeadingStrategy::Beading CenterDeviationBeadingStrategy::compute(coord_t thickness, coord_t bead_count) const
{
Beading ret;
ret.total_thickness = thickness;
if (bead_count > 0)
{
// Set the bead widths
ret.bead_widths = std::vector<coord_t>(static_cast<size_t>(bead_count), optimal_width);
const coord_t optimal_thickness = getOptimalThickness(bead_count);
const coord_t diff_thickness = thickness - optimal_thickness; //Amount of deviation. Either spread out over the middle 2 lines, or concentrated in the center line.
const size_t center_bead_idx = ret.bead_widths.size() / 2;
if (bead_count % 2 == 0) // Even lines
{
const coord_t inner_bead_widths = optimal_width + diff_thickness / 2;
if (inner_bead_widths < minimum_line_width_add)
{
return compute(thickness, bead_count + 1);
}
ret.bead_widths[center_bead_idx - 1] = inner_bead_widths;
ret.bead_widths[center_bead_idx] = inner_bead_widths;
}
else // Uneven lines
{
const coord_t inner_bead_widths = optimal_width + diff_thickness;
if (inner_bead_widths < minimum_line_width_split)
{
return compute(thickness, bead_count - 1);
}
ret.bead_widths[center_bead_idx] = inner_bead_widths;
}
// Set the center line location of the bead toolpaths.
ret.toolpath_locations.resize(ret.bead_widths.size());
ret.toolpath_locations.front() = ret.bead_widths.front() / 2;
for (size_t bead_idx = 1; bead_idx < ret.bead_widths.size(); ++bead_idx)
{
ret.toolpath_locations[bead_idx] =
ret.toolpath_locations[bead_idx - 1] + (ret.bead_widths[bead_idx] + ret.bead_widths[bead_idx - 1]) / 2;
}
ret.left_over = 0;
}
else
{
ret.left_over = thickness;
}
return ret;
}
coord_t CenterDeviationBeadingStrategy::getOptimalThickness(coord_t bead_count) const
{
return bead_count * optimal_width;
}
coord_t CenterDeviationBeadingStrategy::getTransitionThickness(coord_t lower_bead_count) const
{
return lower_bead_count * optimal_width + (lower_bead_count % 2 == 1 ? minimum_line_width_split : minimum_line_width_add);
}
coord_t CenterDeviationBeadingStrategy::getOptimalBeadCount(coord_t thickness) const
{
const coord_t naive_count = thickness / optimal_width; // How many lines we can fit in for sure.
const coord_t remainder = thickness - naive_count * optimal_width; // Space left after fitting that many lines.
const coord_t minimum_line_width = naive_count % 2 == 1 ? minimum_line_width_split : minimum_line_width_add;
return naive_count + (remainder > minimum_line_width); // If there's enough space, fit an extra one.
}
} // namespace cura
<|endoftext|> |
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2012 Scientific Computing and Imaging Institute,
University of Utah.
License for the specific language governing rights and limitations under
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 <Interface/Modules/Visualization/ShowFieldDialog.h>
#include <Modules/Visualization/ShowField.h>
#include <Dataflow/Network/ModuleStateInterface.h> //TODO: extract into intermediate
#include <Core/Datatypes/Color.h>
#include <QColorDialog>
using namespace SCIRun::Gui;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Modules::Visualization;
using namespace SCIRun::Core::Datatypes;
ShowFieldDialog::ShowFieldDialog(const std::string& name, ModuleStateHandle state,
QWidget* parent /* = 0 */)
: ModuleDialogGeneric(state, parent),
defaultMeshColor_(Qt::gray)
{
setupUi(this);
setWindowTitle(QString::fromStdString(name));
fixSize();
WidgetStyleMixin::tabStyle(this->displayOptionsTabs_);
addCheckBoxManager(showNodesCheckBox_, ShowFieldModule::ShowNodes);
addCheckBoxManager(showEdgesCheckBox_, ShowFieldModule::ShowEdges);
addCheckBoxManager(showFacesCheckBox_, ShowFieldModule::ShowFaces);
addCheckBoxManager(enableTransparencyNodesCheckBox_, ShowFieldModule::NodeTransparency);
addCheckBoxManager(enableTransparencyEdgesCheckBox_, ShowFieldModule::EdgeTransparency);
addCheckBoxManager(enableTransparencyFacesCheckBox_, ShowFieldModule::FaceTransparency);
addCheckBoxManager(invertNormalsCheckBox, ShowFieldModule::FaceInvertNormals);
addDoubleSpinBoxManager(transparencyDoubleSpinBox_, ShowFieldModule::FaceTransparencyValue);
addDoubleSpinBoxManager(edgeTransparencyDoubleSpinBox_, ShowFieldModule::EdgeTransparencyValue);
addDoubleSpinBoxManager(scaleSphereDoubleSpinBox_, ShowFieldModule::SphereScaleValue);
addDoubleSpinBoxManager(cylinder_rad_spin, ShowFieldModule::CylinderRadius);
addSpinBoxManager(cylinder_res_spin, ShowFieldModule::CylinderResolution);
addRadioButtonGroupManager({ edgesAsLinesButton_, edgesAsCylindersButton_ }, ShowFieldModule::EdgesAsCylinders);
addRadioButtonGroupManager({ nodesAsPointsButton_, nodesAsSpheresButton_ }, ShowFieldModule::NodeAsSpheres);
//TODO: make enumerable version of function
connectButtonToExecuteSignal(showNodesCheckBox_);
connectButtonToExecuteSignal(showEdgesCheckBox_);
connectButtonToExecuteSignal(showFacesCheckBox_);
connectButtonToExecuteSignal(enableTransparencyNodesCheckBox_);
connectButtonToExecuteSignal(enableTransparencyEdgesCheckBox_);
connectButtonToExecuteSignal(enableTransparencyFacesCheckBox_);
connectButtonToExecuteSignal(invertNormalsCheckBox);
connectButtonToExecuteSignal(edgesAsLinesButton_);
connectButtonToExecuteSignal(edgesAsCylindersButton_);
connectButtonToExecuteSignal(nodesAsPointsButton_);
connectButtonToExecuteSignal(nodesAsSpheresButton_);
//default values
cylinder_rad_spin->setValue(1.0);
cylinder_res_spin->setValue(5);
connect(defaultMeshColorButton_, SIGNAL(clicked()), this, SLOT(assignDefaultMeshColor()));
/////Set unused widgets to be not visible
//Nodes Tab
label_4->setVisible(false); // Sphere scale lable
scaleSphereDoubleSpinBox_->setVisible(false); // Sphere scale spin box
resolutionSpinBox->setVisible(false); //resolution spin box
label_5->setVisible(false); //resolution label
groupBox_3->setVisible(false); //Node coloring
groupBox_4->setVisible(false); //Node Display Type Group Box
//Edges Tab
groupBox_7->setVisible(false);//Edge Display Type Group Box
label_9->setVisible(false); //resolution label
cylinder_res_spin->setVisible(false); //resolution spinbox
label_8->setVisible(false); //scale label
cylinder_rad_spin->setVisible(false); //cylinder scale spinbox
groupBox_6->setVisible(false); //edge coloring
//Faces Tab
groupBox_5->setVisible(false); //face coloring
checkBox->setVisible(false); //Use Face Normal box
checkBox_2->setVisible(false); //Images as texture box
}
void ShowFieldDialog::push()
{
if (!pulling_)
{
pushColor();
}
}
void ShowFieldDialog::createStartupNote()
{
auto showFieldId = windowTitle().split(':')[1];
setStartupNote("ID: " + showFieldId);
}
void ShowFieldDialog::pull()
{
pull_newVersionToReplaceOld();
Pulling p(this);
ColorRGB color(state_->getValue(ShowFieldModule::DefaultMeshColor).toString());
defaultMeshColor_ = QColor(
static_cast<int>(color.r() * 255.0),
static_cast<int>(color.g() * 255.0),
static_cast<int>(color.b() * 255.0));
}
void ShowFieldDialog::assignDefaultMeshColor()
{
auto newColor = QColorDialog::getColor(defaultMeshColor_, this, "Choose default mesh color");
if (newColor.isValid())
{
defaultMeshColor_ = newColor;
//TODO: set color of button to this color
//defaultMeshColorButton_->set
pushColor();
}
}
void ShowFieldDialog::pushColor()
{
state_->setValue(ShowFieldModule::DefaultMeshColor, ColorRGB(defaultMeshColor_.red(), defaultMeshColor_.green(), defaultMeshColor_.blue()).toString());
}
<commit_msg>Fix color conversion<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2012 Scientific Computing and Imaging Institute,
University of Utah.
License for the specific language governing rights and limitations under
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 <Interface/Modules/Visualization/ShowFieldDialog.h>
#include <Modules/Visualization/ShowField.h>
#include <Dataflow/Network/ModuleStateInterface.h> //TODO: extract into intermediate
#include <Core/Datatypes/Color.h>
#include <QColorDialog>
using namespace SCIRun::Gui;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Modules::Visualization;
using namespace SCIRun::Core::Datatypes;
ShowFieldDialog::ShowFieldDialog(const std::string& name, ModuleStateHandle state,
QWidget* parent /* = 0 */)
: ModuleDialogGeneric(state, parent),
defaultMeshColor_(Qt::gray)
{
setupUi(this);
setWindowTitle(QString::fromStdString(name));
fixSize();
WidgetStyleMixin::tabStyle(this->displayOptionsTabs_);
addCheckBoxManager(showNodesCheckBox_, ShowFieldModule::ShowNodes);
addCheckBoxManager(showEdgesCheckBox_, ShowFieldModule::ShowEdges);
addCheckBoxManager(showFacesCheckBox_, ShowFieldModule::ShowFaces);
addCheckBoxManager(enableTransparencyNodesCheckBox_, ShowFieldModule::NodeTransparency);
addCheckBoxManager(enableTransparencyEdgesCheckBox_, ShowFieldModule::EdgeTransparency);
addCheckBoxManager(enableTransparencyFacesCheckBox_, ShowFieldModule::FaceTransparency);
addCheckBoxManager(invertNormalsCheckBox, ShowFieldModule::FaceInvertNormals);
addDoubleSpinBoxManager(transparencyDoubleSpinBox_, ShowFieldModule::FaceTransparencyValue);
addDoubleSpinBoxManager(edgeTransparencyDoubleSpinBox_, ShowFieldModule::EdgeTransparencyValue);
addDoubleSpinBoxManager(scaleSphereDoubleSpinBox_, ShowFieldModule::SphereScaleValue);
addDoubleSpinBoxManager(cylinder_rad_spin, ShowFieldModule::CylinderRadius);
addSpinBoxManager(cylinder_res_spin, ShowFieldModule::CylinderResolution);
addRadioButtonGroupManager({ edgesAsLinesButton_, edgesAsCylindersButton_ }, ShowFieldModule::EdgesAsCylinders);
addRadioButtonGroupManager({ nodesAsPointsButton_, nodesAsSpheresButton_ }, ShowFieldModule::NodeAsSpheres);
//TODO: make enumerable version of function
connectButtonToExecuteSignal(showNodesCheckBox_);
connectButtonToExecuteSignal(showEdgesCheckBox_);
connectButtonToExecuteSignal(showFacesCheckBox_);
connectButtonToExecuteSignal(enableTransparencyNodesCheckBox_);
connectButtonToExecuteSignal(enableTransparencyEdgesCheckBox_);
connectButtonToExecuteSignal(enableTransparencyFacesCheckBox_);
connectButtonToExecuteSignal(invertNormalsCheckBox);
connectButtonToExecuteSignal(edgesAsLinesButton_);
connectButtonToExecuteSignal(edgesAsCylindersButton_);
connectButtonToExecuteSignal(nodesAsPointsButton_);
connectButtonToExecuteSignal(nodesAsSpheresButton_);
//default values
cylinder_rad_spin->setValue(1.0);
cylinder_res_spin->setValue(5);
connect(defaultMeshColorButton_, SIGNAL(clicked()), this, SLOT(assignDefaultMeshColor()));
/////Set unused widgets to be not visible
//Nodes Tab
label_4->setVisible(false); // Sphere scale lable
scaleSphereDoubleSpinBox_->setVisible(false); // Sphere scale spin box
resolutionSpinBox->setVisible(false); //resolution spin box
label_5->setVisible(false); //resolution label
groupBox_3->setVisible(false); //Node coloring
groupBox_4->setVisible(false); //Node Display Type Group Box
//Edges Tab
groupBox_7->setVisible(false);//Edge Display Type Group Box
label_9->setVisible(false); //resolution label
cylinder_res_spin->setVisible(false); //resolution spinbox
label_8->setVisible(false); //scale label
cylinder_rad_spin->setVisible(false); //cylinder scale spinbox
groupBox_6->setVisible(false); //edge coloring
//Faces Tab
groupBox_5->setVisible(false); //face coloring
checkBox->setVisible(false); //Use Face Normal box
checkBox_2->setVisible(false); //Images as texture box
}
void ShowFieldDialog::push()
{
if (!pulling_)
{
pushColor();
}
}
void ShowFieldDialog::createStartupNote()
{
auto showFieldId = windowTitle().split(':')[1];
setStartupNote("ID: " + showFieldId);
}
void ShowFieldDialog::pull()
{
pull_newVersionToReplaceOld();
Pulling p(this);
ColorRGB color(state_->getValue(ShowFieldModule::DefaultMeshColor).toString());
defaultMeshColor_ = QColor(
static_cast<int>(color.r() * 255.0),
static_cast<int>(color.g() * 255.0),
static_cast<int>(color.b() * 255.0));
}
void ShowFieldDialog::assignDefaultMeshColor()
{
auto newColor = QColorDialog::getColor(defaultMeshColor_, this, "Choose default mesh color");
if (newColor.isValid())
{
defaultMeshColor_ = newColor;
//TODO: set color of button to this color
//defaultMeshColorButton_->set
pushColor();
}
}
void ShowFieldDialog::pushColor()
{
state_->setValue(ShowFieldModule::DefaultMeshColor, ColorRGB(defaultMeshColor_.red() / 255.0, defaultMeshColor_.green() / 255.0, defaultMeshColor_.blue() / 255.0).toString());
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: ODriver.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: vg $ $Date: 2005-03-10 15:32:24 $
*
* 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 _CONNECTIVITY_ODBC_ODRIVER_HXX_
#include "odbc/ODriver.hxx"
#endif
#ifndef _CONNECTIVITY_ODBC_OCONNECTION_HXX_
#include "odbc/OConnection.hxx"
#endif
#ifndef _CONNECTIVITY_ODBC_OFUNCTIONS_HXX_
#include "odbc/OFunctions.hxx"
#endif
#ifndef _CONNECTIVITY_OTOOLS_HXX_
#include "odbc/OTools.hxx"
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include "connectivity/dbexception.hxx"
#endif
using namespace connectivity::odbc;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::sdbc;
// --------------------------------------------------------------------------------
ODBCDriver::ODBCDriver(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory)
: ODriver_BASE(m_aMutex)
,m_pDriverHandle(SQL_NULL_HANDLE)
,m_xORB(_rxFactory)
{
}
// --------------------------------------------------------------------------------
void ODBCDriver::disposing()
{
::osl::MutexGuard aGuard(m_aMutex);
for (OWeakRefArray::iterator i = m_xConnections.begin(); m_xConnections.end() != i; ++i)
{
Reference< XComponent > xComp(i->get(), UNO_QUERY);
if (xComp.is())
xComp->dispose();
}
m_xConnections.clear();
ODriver_BASE::disposing();
}
// static ServiceInfo
//------------------------------------------------------------------------------
rtl::OUString ODBCDriver::getImplementationName_Static( ) throw(RuntimeException)
{
return rtl::OUString::createFromAscii("com.sun.star.comp.sdbc.ODBCDriver");
// this name is referenced in the configuration and in the odbc.xml
// Please take care when changing it.
}
typedef Sequence< ::rtl::OUString > SS;
//------------------------------------------------------------------------------
SS ODBCDriver::getSupportedServiceNames_Static( ) throw (RuntimeException)
{
SS aSNS( 1 );
aSNS[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbc.Driver");
return aSNS;
}
//------------------------------------------------------------------
::rtl::OUString SAL_CALL ODBCDriver::getImplementationName( ) throw(RuntimeException)
{
return getImplementationName_Static();
}
//------------------------------------------------------------------
sal_Bool SAL_CALL ODBCDriver::supportsService( const ::rtl::OUString& _rServiceName ) throw(RuntimeException)
{
SS aSupported(getSupportedServiceNames());
const ::rtl::OUString* pSupported = aSupported.getConstArray();
const ::rtl::OUString* pEnd = pSupported + aSupported.getLength();
for (;pSupported != pEnd && !pSupported->equals(_rServiceName); ++pSupported)
;
return pSupported != pEnd;
}
//------------------------------------------------------------------
SS SAL_CALL ODBCDriver::getSupportedServiceNames( ) throw(RuntimeException)
{
return getSupportedServiceNames_Static();
}
// --------------------------------------------------------------------------------
Reference< XConnection > SAL_CALL ODBCDriver::connect( const ::rtl::OUString& url, const Sequence< PropertyValue >& info ) throw(SQLException, RuntimeException)
{
if ( ! acceptsURL(url) )
return NULL;
if(!m_pDriverHandle)
{
::rtl::OUString aPath;
if(!EnvironmentHandle(aPath))
throw SQLException(aPath,*this,::rtl::OUString(),1000,Any());
}
OConnection* pCon = new OConnection(m_pDriverHandle,this);
Reference< XConnection > xCon = pCon;
pCon->Construct(url,info);
m_xConnections.push_back(WeakReferenceHelper(*pCon));
return xCon;
}
// --------------------------------------------------------------------------------
sal_Bool SAL_CALL ODBCDriver::acceptsURL( const ::rtl::OUString& url )
throw(SQLException, RuntimeException)
{
return (!url.compareTo(::rtl::OUString::createFromAscii("sdbc:odbc:"),10));
}
// --------------------------------------------------------------------------------
Sequence< DriverPropertyInfo > SAL_CALL ODBCDriver::getPropertyInfo( const ::rtl::OUString& url, const Sequence< PropertyValue >& info ) throw(SQLException, RuntimeException)
{
if ( acceptsURL(url) )
{
::std::vector< DriverPropertyInfo > aDriverInfo;
Sequence< ::rtl::OUString > aBoolean(2);
aBoolean[0] = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("0"));
aBoolean[1] = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("1"));
aDriverInfo.push_back(DriverPropertyInfo(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("CharSet"))
,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("CharSet of the database."))
,sal_False
,::rtl::OUString()
,Sequence< ::rtl::OUString >())
);
aDriverInfo.push_back(DriverPropertyInfo(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("UseCatalog"))
,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Use catalog for file-based databases."))
,sal_False
,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("0"))
,aBoolean)
);
aDriverInfo.push_back(DriverPropertyInfo(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("SystemDriverSettings"))
,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Driver settings."))
,sal_False
,::rtl::OUString()
,Sequence< ::rtl::OUString >())
);
aDriverInfo.push_back(DriverPropertyInfo(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ParameterNameSubstitution"))
,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Change named parameters with '?'."))
,sal_False
,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("0"))
,aBoolean)
);
aDriverInfo.push_back(DriverPropertyInfo(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("IgnoreDriverPrivileges"))
,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Ignore the privileges from the database driver."))
,sal_False
,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("0"))
,aBoolean)
);
aDriverInfo.push_back(DriverPropertyInfo(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("IsAutoRetrievingEnabled"))
,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Retrieve generated values."))
,sal_False
,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("0"))
,aBoolean)
);
aDriverInfo.push_back(DriverPropertyInfo(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("AutoRetrievingStatement"))
,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Auto-increment statement."))
,sal_False
,::rtl::OUString()
,Sequence< ::rtl::OUString >())
);
return Sequence< DriverPropertyInfo >(&aDriverInfo[0],aDriverInfo.size());
}
::dbtools::throwGenericSQLException(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Invalid URL!")) ,*this);
return Sequence< DriverPropertyInfo >();
}
// --------------------------------------------------------------------------------
sal_Int32 SAL_CALL ODBCDriver::getMajorVersion( ) throw(RuntimeException)
{
return 1;
}
// --------------------------------------------------------------------------------
sal_Int32 SAL_CALL ODBCDriver::getMinorVersion( ) throw(RuntimeException)
{
return 0;
}
// --------------------------------------------------------------------------------
//-----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS ooo19126 (1.12.74); FILE MERGED 2005/09/05 17:24:42 rt 1.12.74.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ODriver.cxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: rt $ $Date: 2005-09-08 06:34:08 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _CONNECTIVITY_ODBC_ODRIVER_HXX_
#include "odbc/ODriver.hxx"
#endif
#ifndef _CONNECTIVITY_ODBC_OCONNECTION_HXX_
#include "odbc/OConnection.hxx"
#endif
#ifndef _CONNECTIVITY_ODBC_OFUNCTIONS_HXX_
#include "odbc/OFunctions.hxx"
#endif
#ifndef _CONNECTIVITY_OTOOLS_HXX_
#include "odbc/OTools.hxx"
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include "connectivity/dbexception.hxx"
#endif
using namespace connectivity::odbc;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::sdbc;
// --------------------------------------------------------------------------------
ODBCDriver::ODBCDriver(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory)
: ODriver_BASE(m_aMutex)
,m_pDriverHandle(SQL_NULL_HANDLE)
,m_xORB(_rxFactory)
{
}
// --------------------------------------------------------------------------------
void ODBCDriver::disposing()
{
::osl::MutexGuard aGuard(m_aMutex);
for (OWeakRefArray::iterator i = m_xConnections.begin(); m_xConnections.end() != i; ++i)
{
Reference< XComponent > xComp(i->get(), UNO_QUERY);
if (xComp.is())
xComp->dispose();
}
m_xConnections.clear();
ODriver_BASE::disposing();
}
// static ServiceInfo
//------------------------------------------------------------------------------
rtl::OUString ODBCDriver::getImplementationName_Static( ) throw(RuntimeException)
{
return rtl::OUString::createFromAscii("com.sun.star.comp.sdbc.ODBCDriver");
// this name is referenced in the configuration and in the odbc.xml
// Please take care when changing it.
}
typedef Sequence< ::rtl::OUString > SS;
//------------------------------------------------------------------------------
SS ODBCDriver::getSupportedServiceNames_Static( ) throw (RuntimeException)
{
SS aSNS( 1 );
aSNS[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbc.Driver");
return aSNS;
}
//------------------------------------------------------------------
::rtl::OUString SAL_CALL ODBCDriver::getImplementationName( ) throw(RuntimeException)
{
return getImplementationName_Static();
}
//------------------------------------------------------------------
sal_Bool SAL_CALL ODBCDriver::supportsService( const ::rtl::OUString& _rServiceName ) throw(RuntimeException)
{
SS aSupported(getSupportedServiceNames());
const ::rtl::OUString* pSupported = aSupported.getConstArray();
const ::rtl::OUString* pEnd = pSupported + aSupported.getLength();
for (;pSupported != pEnd && !pSupported->equals(_rServiceName); ++pSupported)
;
return pSupported != pEnd;
}
//------------------------------------------------------------------
SS SAL_CALL ODBCDriver::getSupportedServiceNames( ) throw(RuntimeException)
{
return getSupportedServiceNames_Static();
}
// --------------------------------------------------------------------------------
Reference< XConnection > SAL_CALL ODBCDriver::connect( const ::rtl::OUString& url, const Sequence< PropertyValue >& info ) throw(SQLException, RuntimeException)
{
if ( ! acceptsURL(url) )
return NULL;
if(!m_pDriverHandle)
{
::rtl::OUString aPath;
if(!EnvironmentHandle(aPath))
throw SQLException(aPath,*this,::rtl::OUString(),1000,Any());
}
OConnection* pCon = new OConnection(m_pDriverHandle,this);
Reference< XConnection > xCon = pCon;
pCon->Construct(url,info);
m_xConnections.push_back(WeakReferenceHelper(*pCon));
return xCon;
}
// --------------------------------------------------------------------------------
sal_Bool SAL_CALL ODBCDriver::acceptsURL( const ::rtl::OUString& url )
throw(SQLException, RuntimeException)
{
return (!url.compareTo(::rtl::OUString::createFromAscii("sdbc:odbc:"),10));
}
// --------------------------------------------------------------------------------
Sequence< DriverPropertyInfo > SAL_CALL ODBCDriver::getPropertyInfo( const ::rtl::OUString& url, const Sequence< PropertyValue >& info ) throw(SQLException, RuntimeException)
{
if ( acceptsURL(url) )
{
::std::vector< DriverPropertyInfo > aDriverInfo;
Sequence< ::rtl::OUString > aBoolean(2);
aBoolean[0] = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("0"));
aBoolean[1] = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("1"));
aDriverInfo.push_back(DriverPropertyInfo(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("CharSet"))
,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("CharSet of the database."))
,sal_False
,::rtl::OUString()
,Sequence< ::rtl::OUString >())
);
aDriverInfo.push_back(DriverPropertyInfo(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("UseCatalog"))
,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Use catalog for file-based databases."))
,sal_False
,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("0"))
,aBoolean)
);
aDriverInfo.push_back(DriverPropertyInfo(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("SystemDriverSettings"))
,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Driver settings."))
,sal_False
,::rtl::OUString()
,Sequence< ::rtl::OUString >())
);
aDriverInfo.push_back(DriverPropertyInfo(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ParameterNameSubstitution"))
,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Change named parameters with '?'."))
,sal_False
,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("0"))
,aBoolean)
);
aDriverInfo.push_back(DriverPropertyInfo(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("IgnoreDriverPrivileges"))
,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Ignore the privileges from the database driver."))
,sal_False
,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("0"))
,aBoolean)
);
aDriverInfo.push_back(DriverPropertyInfo(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("IsAutoRetrievingEnabled"))
,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Retrieve generated values."))
,sal_False
,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("0"))
,aBoolean)
);
aDriverInfo.push_back(DriverPropertyInfo(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("AutoRetrievingStatement"))
,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Auto-increment statement."))
,sal_False
,::rtl::OUString()
,Sequence< ::rtl::OUString >())
);
return Sequence< DriverPropertyInfo >(&aDriverInfo[0],aDriverInfo.size());
}
::dbtools::throwGenericSQLException(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Invalid URL!")) ,*this);
return Sequence< DriverPropertyInfo >();
}
// --------------------------------------------------------------------------------
sal_Int32 SAL_CALL ODBCDriver::getMajorVersion( ) throw(RuntimeException)
{
return 1;
}
// --------------------------------------------------------------------------------
sal_Int32 SAL_CALL ODBCDriver::getMinorVersion( ) throw(RuntimeException)
{
return 0;
}
// --------------------------------------------------------------------------------
//-----------------------------------------------------------------------------
<|endoftext|> |
<commit_before>#include "PoseEstimation_interface.hpp"
////////////////////////////////////////////////////
////////////////// Main //////////////////////////
////////////////////////////////////////////////////
int
main (int argc, char *argv[])
{
PointCloud<PointXYZRGBA> cloud;
pcl::io::loadPCDFile(argv[1], cloud);
PoseEstimation prova;
prova.setParam("verbosity", 2);
//prova.printParams();
prova.setQueryViewpoint(0,0,1);
/*
prova.setQuery("funnel_20_30", cloud);
prova.setDatabase("../../../Objects/Database");
prova.generateLists();
prova.printCandidates();
prova.refineCandidates();
prova.setParam("progBisection", 0); //try bruteforce now
prova.refineCandidates();
prova.setParam("wrongkey", 3); //check errors on wrong key
prova.setParam("filtering", -0.5); //check errors on wrong value
PoseEstimation prova2;
prova2.setQueryViewpoint(0,0,1);
prova2.estimate("object_0", cloud, "../../../Objects/Database");
prova2.printEstimation();
PoseEstimation prova3("../config/parameters.conf");
PoseDB db;
db.load("../../../Objects/Database");
prova3.setQueryViewpoint(1,1,1);
prova3.estimate("obj_0", cloud, db);
prova3.printEstimation();
*/
//Database tests
PoseDB test;
parameters p;
p["computeViewpointFromName"] = 1;
p["useSOasViewpoint"]= 0;
boost::shared_ptr<parameters> par;
par = boost::make_shared<parameters>(p);
test.create("../../../Acquisitions_old/Round1", par);
test.save("../../../Database_Round1/");
PoseDB test2("../../../Database_Round1/");
prova.setParam("progBisection", 1);
prova.setParam("computeViewpointFromName", 1);
prova.setParam("useSOasViewpoint", 0);
prova.resetViewpoint();
prova.estimate("object_23_50", cloud, test2);
prova.printCandidates();
prova.printEstimation();
prova.saveEstimation("Results/prova.estimation");
return 1;
}
<commit_msg>changes in prova<commit_after>#include "PoseEstimation_interface.hpp"
////////////////////////////////////////////////////
////////////////// Main //////////////////////////
////////////////////////////////////////////////////
int
main (int argc, char *argv[])
{
PointCloud<PointXYZRGBA> cloud;
pcl::io::loadPCDFile(argv[1], cloud);
PoseEstimation prova;
prova.setParam("verbosity", 2);
//prova.printParams();
prova.setQueryViewpoint(0,0,1);
/*
prova.setQuery("funnel_20_30", cloud);
prova.setDatabase("../../../Objects/Database");
prova.generateLists();
prova.printCandidates();
prova.refineCandidates();
prova.setParam("progBisection", 0); //try bruteforce now
prova.refineCandidates();
prova.setParam("wrongkey", 3); //check errors on wrong key
prova.setParam("filtering", -0.5); //check errors on wrong value
PoseEstimation prova2;
prova2.setQueryViewpoint(0,0,1);
prova2.estimate("object_0", cloud, "../../../Objects/Database");
prova2.printEstimation();
PoseEstimation prova3("../config/parameters.conf");
PoseDB db;
db.load("../../../Objects/Database");
prova3.setQueryViewpoint(1,1,1);
prova3.estimate("obj_0", cloud, db);
prova3.printEstimation();
*/
//Database tests
PoseDB test;
parameters p;
p["computeViewpointFromName"] = 1;
p["useSOasViewpoint"]= 0;
boost::shared_ptr<parameters> par;
par = boost::make_shared<parameters>(p);
// test.create("../../../Acquisitions_old/Round1", par);
test.create("../../Acquisitions_old/Round1", par);
// test.save("../../../Database_Round1/");
PoseDB test2("../../../Database_Round1/");
prova.setParam("progBisection", 1);
prova.setParam("computeViewpointFromName", 1);
prova.setParam("useSOasViewpoint", 0);
prova.resetViewpoint();
prova.estimate("object_23_50", cloud, test);
prova.printCandidates();
prova.printEstimation();
prova.saveEstimation("Results/prova.estimation");
return 1;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: CConnection.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-08 06:59: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 _CONNECTIVITY_CALC_CONNECTION_HXX_
#define _CONNECTIVITY_CALC_CONNECTION_HXX_
#ifndef _CONNECTIVITY_FILE_OCONNECTION_HXX_
#include "file/FConnection.hxx"
#endif
namespace com { namespace sun { namespace star { namespace sheet {
class XSpreadsheetDocument;
} } } }
namespace connectivity
{
namespace calc
{
class ODriver;
class OCalcConnection : public file::OConnection
{
// the spreadsheet document:
::com::sun::star::uno::Reference< ::com::sun::star::sheet::XSpreadsheetDocument > m_xDoc;
public:
OCalcConnection(ODriver* _pDriver);
virtual ~OCalcConnection();
virtual void construct(const ::rtl::OUString& _rUrl,
const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rInfo )
throw( ::com::sun::star::sdbc::SQLException);
// XServiceInfo
DECLARE_SERVICE_INFO();
// OComponentHelper
virtual void SAL_CALL disposing(void);
// XConnection
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData > SAL_CALL getMetaData( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XTablesSupplier > createCatalog();
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XStatement > SAL_CALL createStatement( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareStatement( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareCall( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
// no interface methods
::com::sun::star::uno::Reference< ::com::sun::star::sheet::XSpreadsheetDocument> getDoc() const
{ return m_xDoc; }
};
}
}
#endif // _CONNECTIVITY_CALC_CONNECTION_HXX_
<commit_msg>INTEGRATION: CWS dba30a (1.2.352); FILE MERGED 2008/02/14 09:51:47 oj 1.2.352.1: #i9899# refcount of doc inside the connection, will be released when the last table has gone<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: CConnection.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: kz $ $Date: 2008-03-05 16:31:51 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _CONNECTIVITY_CALC_CONNECTION_HXX_
#define _CONNECTIVITY_CALC_CONNECTION_HXX_
#ifndef _CONNECTIVITY_FILE_OCONNECTION_HXX_
#include "file/FConnection.hxx"
#endif
namespace com { namespace sun { namespace star { namespace sheet {
class XSpreadsheetDocument;
} } } }
namespace connectivity
{
namespace calc
{
class ODriver;
class OCalcConnection : public file::OConnection
{
// the spreadsheet document:
::com::sun::star::uno::Reference< ::com::sun::star::sheet::XSpreadsheetDocument > m_xDoc;
::rtl::OUString m_sPassword;
String m_aFileName;
oslInterlockedCount m_nDocCount;
public:
OCalcConnection(ODriver* _pDriver);
virtual ~OCalcConnection();
virtual void construct(const ::rtl::OUString& _rUrl,
const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rInfo )
throw( ::com::sun::star::sdbc::SQLException);
// XServiceInfo
DECLARE_SERVICE_INFO();
// OComponentHelper
virtual void SAL_CALL disposing(void);
// XConnection
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData > SAL_CALL getMetaData( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XTablesSupplier > createCatalog();
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XStatement > SAL_CALL createStatement( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareStatement( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareCall( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
// no interface methods
::com::sun::star::uno::Reference< ::com::sun::star::sheet::XSpreadsheetDocument> acquireDoc();
void releaseDoc();
class ODocHolder
{
OCalcConnection* m_pConnection;
::com::sun::star::uno::Reference< ::com::sun::star::sheet::XSpreadsheetDocument> m_xDoc;
public:
ODocHolder(OCalcConnection* _pConnection) : m_pConnection(_pConnection)
{
m_xDoc = m_pConnection->acquireDoc();
}
~ODocHolder()
{
m_xDoc = NULL;
m_pConnection->releaseDoc();
}
::com::sun::star::uno::Reference< ::com::sun::star::sheet::XSpreadsheetDocument> getDoc() const { return m_xDoc; }
};
};
}
}
#endif // _CONNECTIVITY_CALC_CONNECTION_HXX_
<|endoftext|> |
<commit_before>#include <iostream>
#include <algorithm>
#include <vector>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/lexical_cast.hpp>
using namespace boost;
using namespace posix_time;
template <typename F_t>
class Timer
{
public:
Timer(F_t f_) : f(f_)
{
start = microsec_clock::local_time();
}
~Timer()
{
auto end = microsec_clock::local_time();
f((end-start).total_milliseconds());
}
private:
F_t f;
ptime start;
};
template <typename F_t>
Timer<F_t> make_timer(F_t f)
{
return Timer<F_t>(f);
}
int main(int argc, char* argv[])
{
auto t(make_timer([](long t){std::cout << "Time passed: " << t << std::endl; }));
std::vector<int> v(10000000);
assert(std::find(v.begin(), v.end(), 9) == v.end());
}
<commit_msg>Timer cpp timer is more general, will move to common<commit_after>#include <iostream>
#include <algorithm>
#include <vector>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/lexical_cast.hpp>
using namespace boost;
using namespace posix_time;
template <typename F_t>
class Timer
{
public:
Timer(F_t f_) : f(f_)
{
start = microsec_clock::local_time();
}
~Timer()
{
auto end = microsec_clock::local_time();
f((end-start).total_milliseconds());
}
private:
F_t f;
ptime start;
};
struct TimingReport
{
TimingReport(const std::string& e) : event(e) {}
void operator()(long t) const { std::cout << event << " (ms) " << t <<std::endl; }
private:
std::string event;
};
template <typename F_t>
Timer<F_t> make_timer(F_t f)
{
return Timer<F_t>(f);
}
Timer<TimingReport> make_timer(const char* s) { return make_timer(TimingReport(s)); }
Timer<TimingReport> make_timer(const std::string& s) { return make_timer(TimingReport(s)); }
int main(int argc, char* argv[])
{
auto t(make_timer([](long t){std::cout << "Time passed: " << t << std::endl; }));
auto t2(make_timer("Build vector"));
std::vector<int> v(10000000);
assert(std::find(v.begin(), v.end(), 9) == v.end());
}
<|endoftext|> |
<commit_before>/*
Copyright (C) 2000 by Jorrit Tyberghein and K. Robert Bate.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*----------------------------------------------------------------
Written by K. Robert Bate 2000.
----------------------------------------------------------------*/
#include <InputSprocket.h>
ISpNeed gInputNeeds[] =
{
{
"\pAbort Game",
256,
0, // player number
0, // group number
kISpElementKind_Button,
kISpElementLabel_Btn_PauseResume,
0, // flags
0, // reserved 1
0, // reserved 2
0 // reserved 3
},
{
"\pButton",
257,
0, // player number
0, // group number
kISpElementKind_Button,
kISpElementLabel_Btn_Fire,
0, // flags
0, // reserved 1
0, // reserved 2
0 // reserved 3
},
{
"\pX Axis Movement",
258,
0, // player number
0, // group number
kISpElementKind_Axis,
kISpElementLabel_Axis_XAxis,
0, // flags
0, // reserved 1
0, // reserved 2
0 // reserved 3
},
{
"\pY Axis Movement",
259,
0, // player number
0, // group number
kISpElementKind_Axis,
kISpElementLabel_Axis_YAxis,
0, // flags
0, // reserved 1
0, // reserved 2
0 // reserved 3
}
};
int gNumInputNeeds = ( sizeof( gInputNeeds ) / sizeof( ISpNeed ));
ISpElementReference gInputElements[ sizeof( gInputNeeds ) / sizeof( ISpNeed ) ];
bool gInputUseKeyboard = false;
bool gInputUseMouse = false;
<commit_msg>Adding a define so the file will compile with both CW Pro4 and Pro5<commit_after>/*
Copyright (C) 2000 by Jorrit Tyberghein and K. Robert Bate.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*----------------------------------------------------------------
Written by K. Robert Bate 2000.
----------------------------------------------------------------*/
#define USE_OLD_INPUT_SPROCKET_LABELS 1
#include <InputSprocket.h>
ISpNeed gInputNeeds[] =
{
{
"\pAbort Game",
256,
0, // player number
0, // group number
kISpElementKind_Button,
kISpElementLabel_Btn_PauseResume,
0, // flags
0, // reserved 1
0, // reserved 2
0 // reserved 3
},
{
"\pButton",
257,
0, // player number
0, // group number
kISpElementKind_Button,
kISpElementLabel_Btn_Fire,
0, // flags
0, // reserved 1
0, // reserved 2
0 // reserved 3
},
{
"\pX Axis Movement",
258,
0, // player number
0, // group number
kISpElementKind_Axis,
kISpElementLabel_Axis_XAxis,
0, // flags
0, // reserved 1
0, // reserved 2
0 // reserved 3
},
{
"\pY Axis Movement",
259,
0, // player number
0, // group number
kISpElementKind_Axis,
kISpElementLabel_Axis_YAxis,
0, // flags
0, // reserved 1
0, // reserved 2
0 // reserved 3
}
};
int gNumInputNeeds = ( sizeof( gInputNeeds ) / sizeof( ISpNeed ));
ISpElementReference gInputElements[ sizeof( gInputNeeds ) / sizeof( ISpNeed ) ];
bool gInputUseKeyboard = false;
bool gInputUseMouse = false;
<|endoftext|> |
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2012 Scientific Computing and Imaging Institute,
University of Utah.
License for the specific language governing rights and limitations under
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 <Testing/ModuleTestBase/ModuleTestBase.h>
#include <Modules/Factory/HardCodedModuleFactory.h>
#include <Dataflow/Engine/Controller/NetworkEditorController.h>
#include <Dataflow/Network/ConnectionId.h>
using namespace SCIRun;
using namespace SCIRun::Testing;
using namespace SCIRun::Modules::Factory;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Dataflow::Engine;
using namespace SCIRun::Core::Algorithms;
class ModuleReplaceTests : public ModuleTest
{
};
TEST(HardCodedModuleFactoryTests, ListAllModules)
{
HardCodedModuleFactory factory;
auto descMap = factory.getDirectModuleDescriptionLookupMap();
for (const auto& p : descMap)
{
if (false)
std::cout << p.first << " --> " << p.second << std::endl;
}
EXPECT_EQ(86, descMap.size());
}
TEST_F(ModuleReplaceTests, CanComputeConnectedPortInfoFromModule)
{
ModuleFactoryHandle mf(new HardCodedModuleFactory);
NetworkEditorController controller(mf, ModuleStateFactoryHandle(), ExecutionStrategyFactoryHandle(), AlgorithmFactoryHandle(), ReexecuteStrategyFactoryHandle());
initModuleParameters(false);
auto network = controller.getNetwork();
ModuleHandle send = controller.addModule("SendTestMatrix");
ModuleHandle process = controller.addModule("NeedToExecuteTester");
ModuleHandle receive = controller.addModule("ReceiveTestMatrix");
ASSERT_EQ(3, network->nmodules());
{
auto sendInfo = makeConnectedPortInfo(send);
ConnectedPortInfo expectedSendInfo; // empty maps
EXPECT_EQ(expectedSendInfo, sendInfo);
auto procInfo = makeConnectedPortInfo(process);
ConnectedPortInfo expectedProcInfo; // empty maps
EXPECT_EQ(expectedProcInfo, procInfo);
auto recInfo = makeConnectedPortInfo(receive);
ConnectedPortInfo expectedRecInfo; // empty maps
EXPECT_EQ(expectedRecInfo, recInfo);
}
auto cid1 = network->connect(ConnectionOutputPort(send, 0), ConnectionInputPort(process, 0));
auto cid2 = network->connect(ConnectionOutputPort(process, 0), ConnectionInputPort(receive, 0));
ASSERT_EQ(2, network->nconnections());
//clang on mac doesn't like "{}" for empty std::map initialization in a struct.
const ConnectedPortTypesWithCount empty;
{
auto sendInfo = makeConnectedPortInfo(send);
ConnectedPortInfo expectedSendInfo { empty, { { "Matrix", 1 } } };
EXPECT_EQ(expectedSendInfo, sendInfo);
auto procInfo = makeConnectedPortInfo(process);
ConnectedPortInfo expectedProcInfo { { { "Matrix", 1 } }, { { "Matrix", 1 } } };
EXPECT_EQ(expectedProcInfo, procInfo);
auto recInfo = makeConnectedPortInfo(receive);
ConnectedPortInfo expectedRecInfo { { { "Matrix", 1 } }, empty };
EXPECT_EQ(expectedRecInfo, recInfo);
}
network->disconnect(cid1);
ASSERT_EQ(1, network->nconnections());
{
auto sendInfo = makeConnectedPortInfo(send);
ConnectedPortInfo expectedSendInfo; // empty maps
EXPECT_EQ(expectedSendInfo, sendInfo);
auto procInfo = makeConnectedPortInfo(process);
ConnectedPortInfo expectedProcInfo { empty, { { "Matrix", 1 } } };
EXPECT_EQ(expectedProcInfo, procInfo);
auto recInfo = makeConnectedPortInfo(receive);
ConnectedPortInfo expectedRecInfo { { { "Matrix", 1 } }, empty };
EXPECT_EQ(expectedRecInfo, recInfo);
}
network->disconnect(cid2);
ASSERT_EQ(0, network->nconnections());
{
auto sendInfo = makeConnectedPortInfo(send);
ConnectedPortInfo expectedSendInfo; // empty maps
EXPECT_EQ(expectedSendInfo, sendInfo);
auto procInfo = makeConnectedPortInfo(process);
ConnectedPortInfo expectedProcInfo; // empty maps
EXPECT_EQ(expectedProcInfo, procInfo);
auto recInfo = makeConnectedPortInfo(receive);
ConnectedPortInfo expectedRecInfo; // empty maps
EXPECT_EQ(expectedRecInfo, recInfo);
}
ModuleHandle create = controller.addModule("CreateLatVol");
ModuleHandle setFD = controller.addModule("SetFieldData");
ModuleHandle report = controller.addModule("ReportFieldInfo");
cid1 = network->connect(ConnectionOutputPort(create, 0), ConnectionInputPort(setFD, 0));
cid2 = network->connect(ConnectionOutputPort(process, 0), ConnectionInputPort(setFD, 1));
auto cid3 = network->connect(ConnectionOutputPort(setFD, 0), ConnectionInputPort(report, 0));
ASSERT_EQ(3, network->nconnections());
{
auto createInfo = makeConnectedPortInfo(create);
ConnectedPortInfo expectedCreateInfo { empty, { { "Field", 1 } } };
EXPECT_EQ(expectedCreateInfo, createInfo);
auto setInfo = makeConnectedPortInfo(setFD);
ConnectedPortInfo expectedSetInfo { { { "Matrix", 1 }, { "Field", 1 } }, { { "Field", 1 } } };
EXPECT_EQ(expectedSetInfo, setInfo);
auto reportInfo = makeConnectedPortInfo(report);
ConnectedPortInfo expectedReportInfo { { { "Field", 1 } }, empty };
EXPECT_EQ(expectedReportInfo, reportInfo);
}
}
TEST_F(ModuleReplaceTests, DISABLED_NoConnectedPortsCanBeReplacedWithAnything)
{
FAIL() << "todo";
}
<commit_msg>Closes #891<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2012 Scientific Computing and Imaging Institute,
University of Utah.
License for the specific language governing rights and limitations under
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 <Testing/ModuleTestBase/ModuleTestBase.h>
#include <Modules/Factory/HardCodedModuleFactory.h>
#include <Dataflow/Engine/Controller/NetworkEditorController.h>
#include <Dataflow/Network/ConnectionId.h>
using namespace SCIRun;
using namespace SCIRun::Testing;
using namespace SCIRun::Modules::Factory;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Dataflow::Engine;
using namespace SCIRun::Core::Algorithms;
class ModuleReplaceTests : public ModuleTest
{
};
TEST(HardCodedModuleFactoryTests, ListAllModules)
{
HardCodedModuleFactory factory;
auto descMap = factory.getDirectModuleDescriptionLookupMap();
for (const auto& p : descMap)
{
if (false)
std::cout << p.first << " --> " << p.second << std::endl;
}
EXPECT_TRUE(descMap.size() >= 86);
}
TEST_F(ModuleReplaceTests, CanComputeConnectedPortInfoFromModule)
{
ModuleFactoryHandle mf(new HardCodedModuleFactory);
NetworkEditorController controller(mf, ModuleStateFactoryHandle(), ExecutionStrategyFactoryHandle(), AlgorithmFactoryHandle(), ReexecuteStrategyFactoryHandle());
initModuleParameters(false);
auto network = controller.getNetwork();
ModuleHandle send = controller.addModule("SendTestMatrix");
ModuleHandle process = controller.addModule("NeedToExecuteTester");
ModuleHandle receive = controller.addModule("ReceiveTestMatrix");
ASSERT_EQ(3, network->nmodules());
{
auto sendInfo = makeConnectedPortInfo(send);
ConnectedPortInfo expectedSendInfo; // empty maps
EXPECT_EQ(expectedSendInfo, sendInfo);
auto procInfo = makeConnectedPortInfo(process);
ConnectedPortInfo expectedProcInfo; // empty maps
EXPECT_EQ(expectedProcInfo, procInfo);
auto recInfo = makeConnectedPortInfo(receive);
ConnectedPortInfo expectedRecInfo; // empty maps
EXPECT_EQ(expectedRecInfo, recInfo);
}
auto cid1 = network->connect(ConnectionOutputPort(send, 0), ConnectionInputPort(process, 0));
auto cid2 = network->connect(ConnectionOutputPort(process, 0), ConnectionInputPort(receive, 0));
ASSERT_EQ(2, network->nconnections());
//clang on mac doesn't like "{}" for empty std::map initialization in a struct.
const ConnectedPortTypesWithCount empty;
{
auto sendInfo = makeConnectedPortInfo(send);
ConnectedPortInfo expectedSendInfo { empty, { { "Matrix", 1 } } };
EXPECT_EQ(expectedSendInfo, sendInfo);
auto procInfo = makeConnectedPortInfo(process);
ConnectedPortInfo expectedProcInfo { { { "Matrix", 1 } }, { { "Matrix", 1 } } };
EXPECT_EQ(expectedProcInfo, procInfo);
auto recInfo = makeConnectedPortInfo(receive);
ConnectedPortInfo expectedRecInfo { { { "Matrix", 1 } }, empty };
EXPECT_EQ(expectedRecInfo, recInfo);
}
network->disconnect(cid1);
ASSERT_EQ(1, network->nconnections());
{
auto sendInfo = makeConnectedPortInfo(send);
ConnectedPortInfo expectedSendInfo; // empty maps
EXPECT_EQ(expectedSendInfo, sendInfo);
auto procInfo = makeConnectedPortInfo(process);
ConnectedPortInfo expectedProcInfo { empty, { { "Matrix", 1 } } };
EXPECT_EQ(expectedProcInfo, procInfo);
auto recInfo = makeConnectedPortInfo(receive);
ConnectedPortInfo expectedRecInfo { { { "Matrix", 1 } }, empty };
EXPECT_EQ(expectedRecInfo, recInfo);
}
network->disconnect(cid2);
ASSERT_EQ(0, network->nconnections());
{
auto sendInfo = makeConnectedPortInfo(send);
ConnectedPortInfo expectedSendInfo; // empty maps
EXPECT_EQ(expectedSendInfo, sendInfo);
auto procInfo = makeConnectedPortInfo(process);
ConnectedPortInfo expectedProcInfo; // empty maps
EXPECT_EQ(expectedProcInfo, procInfo);
auto recInfo = makeConnectedPortInfo(receive);
ConnectedPortInfo expectedRecInfo; // empty maps
EXPECT_EQ(expectedRecInfo, recInfo);
}
ModuleHandle create = controller.addModule("CreateLatVol");
ModuleHandle setFD = controller.addModule("SetFieldData");
ModuleHandle report = controller.addModule("ReportFieldInfo");
cid1 = network->connect(ConnectionOutputPort(create, 0), ConnectionInputPort(setFD, 0));
cid2 = network->connect(ConnectionOutputPort(process, 0), ConnectionInputPort(setFD, 1));
auto cid3 = network->connect(ConnectionOutputPort(setFD, 0), ConnectionInputPort(report, 0));
ASSERT_EQ(3, network->nconnections());
{
auto createInfo = makeConnectedPortInfo(create);
ConnectedPortInfo expectedCreateInfo { empty, { { "Field", 1 } } };
EXPECT_EQ(expectedCreateInfo, createInfo);
auto setInfo = makeConnectedPortInfo(setFD);
ConnectedPortInfo expectedSetInfo { { { "Matrix", 1 }, { "Field", 1 } }, { { "Field", 1 } } };
EXPECT_EQ(expectedSetInfo, setInfo);
auto reportInfo = makeConnectedPortInfo(report);
ConnectedPortInfo expectedReportInfo { { { "Field", 1 } }, empty };
EXPECT_EQ(expectedReportInfo, reportInfo);
}
}
TEST_F(ModuleReplaceTests, DISABLED_NoConnectedPortsCanBeReplacedWithAnything)
{
FAIL() << "todo";
}
<|endoftext|> |
<commit_before>#include <crossbow/infinio/EventProcessor.hpp>
#include <crossbow/infinio/Fiber.hpp>
#include <crossbow/logger.hpp>
#include <algorithm>
#include <cerrno>
#include <sys/epoll.h>
#include <sys/eventfd.h>
namespace crossbow {
namespace infinio {
EventProcessor::EventProcessor(uint64_t pollCycles)
: mPollCycles(pollCycles) {
LOG_TRACE("Creating epoll file descriptor");
mEpoll = epoll_create1(EPOLL_CLOEXEC);
if (mEpoll == -1) {
throw std::system_error(errno, std::system_category());
}
}
EventProcessor::~EventProcessor() {
// TODO We have to join the poll thread
// We are not allowed to call join in the same thread as the poll loop is
LOG_TRACE("Destroying epoll file descriptor");
if (close(mEpoll)) {
std::error_code ec(errno, std::system_category());
LOG_ERROR("Failed to close the epoll descriptor [error = %1% %2%]", ec, ec.message());
}
}
void EventProcessor::registerPoll(int fd, EventPoll* poll) {
LOG_TRACE("Register event poller");
struct epoll_event event;
event.data.ptr = poll;
event.events = EPOLLIN | EPOLLET;
if (epoll_ctl(mEpoll, EPOLL_CTL_ADD, fd, &event)) {
throw std::system_error(errno, std::system_category());
}
mPoller.emplace_back(poll);
}
void EventProcessor::deregisterPoll(int fd, EventPoll* poll) {
LOG_TRACE("Deregister event poller");
auto i = std::find(mPoller.begin(), mPoller.end(), poll);
if (i == mPoller.end()) {
return;
}
mPoller.erase(i);
if (epoll_ctl(mEpoll, EPOLL_CTL_DEL, fd, nullptr)) {
throw std::system_error(errno, std::system_category());
}
}
void EventProcessor::start() {
LOG_TRACE("Starting event processor");
mPollThread = std::thread([this] () {
while (true) {
doPoll();
}
});
}
void EventProcessor::executeFiber(std::function<void(Fiber&)> fun) {
auto fiber = Fiber::create(*this, std::move(fun));
fiber->resume();
}
void EventProcessor::doPoll() {
for (uint32_t i = 0; i < mPollCycles; ++i) {
for (auto poller : mPoller) {
if (poller->poll()) {
i = 0;
}
}
while (!mTaskQueue.empty()) {
mTaskQueue.front()();
mTaskQueue.pop();
i = 0;
}
}
for (auto poller : mPoller) {
poller->prepareSleep();
}
LOG_TRACE("Going to epoll sleep");
struct epoll_event events[mPoller.size()];
auto num = epoll_wait(mEpoll, events, 10, -1);
LOG_TRACE("Wake up from epoll sleep with %1% events", num);
for (int i = 0; i < num; ++i) {
if ((events[i].events & EPOLLERR) || (events[i].events & EPOLLHUP) || (!(events[i].events & EPOLLIN))) {
LOG_ERROR("Error has occured on fd");
continue;
}
auto poller = reinterpret_cast<EventPoll*>(events[i].data.ptr);
poller->wakeup();
}
}
TaskQueue::TaskQueue(EventProcessor& processor)
: mProcessor(processor),
mSleeping(false) {
mInterrupt = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
if (mInterrupt == -1) {
throw std::system_error(errno, std::system_category());
}
mProcessor.registerPoll(mInterrupt, this);
}
TaskQueue::~TaskQueue() {
try {
mProcessor.deregisterPoll(mInterrupt, this);
} catch (std::system_error& e) {
LOG_ERROR("Failed to deregister from EventProcessor [error = %1% %2%]", e.code(), e.what());
}
if (close(mInterrupt)) {
std::error_code ec(errno, std::system_category());
LOG_ERROR("Failed to close the event descriptor [error = %1% %2%]", ec, ec.message());
}
}
void TaskQueue::execute(std::function<void()> fun) {
mTaskQueue.write(std::move(fun));
if (mSleeping.load()) {
uint64_t counter = 0x1u;
write(mInterrupt, &counter, sizeof(uint64_t));
}
}
bool TaskQueue::poll() {
bool result = false;
// Process all task from the task queue
std::function<void()> fun;
while (mTaskQueue.read(fun)) {
result = true;
fun();
}
return result;
}
void TaskQueue::prepareSleep() {
auto wasSleeping = mSleeping.exchange(true);
if (wasSleeping) {
return;
}
// Poll once more for tasks enqueud in the meantime
poll();
}
void TaskQueue::wakeup() {
mSleeping.store(false);
uint64_t counter = 0;
read(mInterrupt, &counter, sizeof(uint64_t));
}
} // namespace infinio
} // namespace crossbow
<commit_msg>Swap the task queue before processing it<commit_after>#include <crossbow/infinio/EventProcessor.hpp>
#include <crossbow/infinio/Fiber.hpp>
#include <crossbow/logger.hpp>
#include <algorithm>
#include <cerrno>
#include <sys/epoll.h>
#include <sys/eventfd.h>
namespace crossbow {
namespace infinio {
EventProcessor::EventProcessor(uint64_t pollCycles)
: mPollCycles(pollCycles) {
LOG_TRACE("Creating epoll file descriptor");
mEpoll = epoll_create1(EPOLL_CLOEXEC);
if (mEpoll == -1) {
throw std::system_error(errno, std::system_category());
}
}
EventProcessor::~EventProcessor() {
// TODO We have to join the poll thread
// We are not allowed to call join in the same thread as the poll loop is
LOG_TRACE("Destroying epoll file descriptor");
if (close(mEpoll)) {
std::error_code ec(errno, std::system_category());
LOG_ERROR("Failed to close the epoll descriptor [error = %1% %2%]", ec, ec.message());
}
}
void EventProcessor::registerPoll(int fd, EventPoll* poll) {
LOG_TRACE("Register event poller");
struct epoll_event event;
event.data.ptr = poll;
event.events = EPOLLIN | EPOLLET;
if (epoll_ctl(mEpoll, EPOLL_CTL_ADD, fd, &event)) {
throw std::system_error(errno, std::system_category());
}
mPoller.emplace_back(poll);
}
void EventProcessor::deregisterPoll(int fd, EventPoll* poll) {
LOG_TRACE("Deregister event poller");
auto i = std::find(mPoller.begin(), mPoller.end(), poll);
if (i == mPoller.end()) {
return;
}
mPoller.erase(i);
if (epoll_ctl(mEpoll, EPOLL_CTL_DEL, fd, nullptr)) {
throw std::system_error(errno, std::system_category());
}
}
void EventProcessor::start() {
LOG_TRACE("Starting event processor");
mPollThread = std::thread([this] () {
while (true) {
doPoll();
}
});
}
void EventProcessor::executeFiber(std::function<void(Fiber&)> fun) {
auto fiber = Fiber::create(*this, std::move(fun));
fiber->resume();
}
void EventProcessor::doPoll() {
for (uint32_t i = 0; i < mPollCycles; ++i) {
for (auto poller : mPoller) {
if (poller->poll()) {
i = 0;
}
}
if (!mTaskQueue.empty()) {
decltype(mTaskQueue) taskQueue;
taskQueue.swap(mTaskQueue);
do {
taskQueue.front()();
taskQueue.pop();
i = 0;
} while (!taskQueue.empty());
}
}
for (auto poller : mPoller) {
poller->prepareSleep();
}
LOG_TRACE("Going to epoll sleep");
struct epoll_event events[mPoller.size()];
auto num = epoll_wait(mEpoll, events, 10, -1);
LOG_TRACE("Wake up from epoll sleep with %1% events", num);
for (int i = 0; i < num; ++i) {
if ((events[i].events & EPOLLERR) || (events[i].events & EPOLLHUP) || (!(events[i].events & EPOLLIN))) {
LOG_ERROR("Error has occured on fd");
continue;
}
auto poller = reinterpret_cast<EventPoll*>(events[i].data.ptr);
poller->wakeup();
}
}
TaskQueue::TaskQueue(EventProcessor& processor)
: mProcessor(processor),
mSleeping(false) {
mInterrupt = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
if (mInterrupt == -1) {
throw std::system_error(errno, std::system_category());
}
mProcessor.registerPoll(mInterrupt, this);
}
TaskQueue::~TaskQueue() {
try {
mProcessor.deregisterPoll(mInterrupt, this);
} catch (std::system_error& e) {
LOG_ERROR("Failed to deregister from EventProcessor [error = %1% %2%]", e.code(), e.what());
}
if (close(mInterrupt)) {
std::error_code ec(errno, std::system_category());
LOG_ERROR("Failed to close the event descriptor [error = %1% %2%]", ec, ec.message());
}
}
void TaskQueue::execute(std::function<void()> fun) {
mTaskQueue.write(std::move(fun));
if (mSleeping.load()) {
uint64_t counter = 0x1u;
write(mInterrupt, &counter, sizeof(uint64_t));
}
}
bool TaskQueue::poll() {
bool result = false;
// Process all task from the task queue
std::function<void()> fun;
while (mTaskQueue.read(fun)) {
result = true;
fun();
}
return result;
}
void TaskQueue::prepareSleep() {
auto wasSleeping = mSleeping.exchange(true);
if (wasSleeping) {
return;
}
// Poll once more for tasks enqueud in the meantime
poll();
}
void TaskQueue::wakeup() {
mSleeping.store(false);
uint64_t counter = 0;
read(mInterrupt, &counter, sizeof(uint64_t));
}
} // namespace infinio
} // namespace crossbow
<|endoftext|> |
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2015 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <gtest/gtest.h>
#include <gmock/gmock.h>
//
/// @todo
<commit_msg>Start on unit test<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2015 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <Modules/Python/PythonInterfaceParser.h>
using namespace SCIRun::Core::Algorithms::Python;
using namespace SCIRun::Dataflow::Networks;
TEST(PythonInterfaceParserTests, Basic)
{
std::string moduleId = "InterfaceWithPython:0";
ModuleStateHandle state;
std::vector<std::string> portIds = {"InputString:0"};
PythonInterfaceParser parser(moduleId, state, portIds);
FAIL() << "todo";
}
<|endoftext|> |
<commit_before>/*
This file is part of solidity.
solidity 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.
solidity 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 solidity. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Christian <[email protected]>
* @date 2016
* Solidity inline assembly parser.
*/
#include <libsolidity/inlineasm/AsmParser.h>
#include <ctype.h>
#include <algorithm>
#include <libsolidity/parsing/Scanner.h>
using namespace std;
using namespace dev;
using namespace dev::solidity;
using namespace dev::solidity::assembly;
shared_ptr<assembly::Block> Parser::parse(std::shared_ptr<Scanner> const& _scanner)
{
try
{
m_scanner = _scanner;
return make_shared<Block>(parseBlock());
}
catch (FatalError const&)
{
if (m_errors.empty())
throw; // Something is weird here, rather throw again.
}
return nullptr;
}
assembly::Block Parser::parseBlock()
{
assembly::Block block = createWithLocation<Block>();
expectToken(Token::LBrace);
while (m_scanner->currentToken() != Token::RBrace)
block.statements.emplace_back(parseStatement());
block.location.end = endPosition();
m_scanner->next();
return block;
}
assembly::Statement Parser::parseStatement()
{
switch (m_scanner->currentToken())
{
case Token::Let:
return parseVariableDeclaration();
case Token::Function:
return parseFunctionDefinition();
case Token::LBrace:
return parseBlock();
case Token::Assign:
{
assembly::Assignment assignment = createWithLocation<assembly::Assignment>();
m_scanner->next();
expectToken(Token::Colon);
assignment.variableName.location = location();
assignment.variableName.name = m_scanner->currentLiteral();
if (instructions().count(assignment.variableName.name))
fatalParserError("Identifier expected, got instruction name.");
assignment.location.end = endPosition();
expectToken(Token::Identifier);
return assignment;
}
case Token::Return: // opcode
case Token::Byte: // opcode
default:
break;
}
// Options left:
// Simple instruction (might turn into functional),
// literal,
// identifier (might turn into label or functional assignment)
Statement statement(parseElementaryOperation());
switch (m_scanner->currentToken())
{
case Token::LParen:
return parseFunctionalInstruction(std::move(statement));
case Token::Colon:
{
if (statement.type() != typeid(assembly::Identifier))
fatalParserError("Label name / variable name must precede \":\".");
assembly::Identifier const& identifier = boost::get<assembly::Identifier>(statement);
m_scanner->next();
// identifier:=: should be parsed as identifier: =: (i.e. a label),
// while identifier:= (being followed by a non-colon) as identifier := (assignment).
if (m_scanner->currentToken() == Token::Assign && m_scanner->peekNextToken() != Token::Colon)
{
// functional assignment
FunctionalAssignment funAss = createWithLocation<FunctionalAssignment>(identifier.location);
if (instructions().count(identifier.name))
fatalParserError("Cannot use instruction names for identifier names.");
m_scanner->next();
funAss.variableName = identifier;
funAss.value.reset(new Statement(parseExpression()));
funAss.location.end = locationOf(*funAss.value).end;
return funAss;
}
else
{
// label
Label label = createWithLocation<Label>(identifier.location);
label.name = identifier.name;
return label;
}
}
default:
break;
}
return statement;
}
assembly::Statement Parser::parseExpression()
{
Statement operation = parseElementaryOperation(true);
if (m_scanner->currentToken() == Token::LParen)
return parseFunctionalInstruction(std::move(operation));
else
return operation;
}
std::map<string, dev::solidity::Instruction> const& Parser::instructions()
{
// Allowed instructions, lowercase names.
static map<string, dev::solidity::Instruction> s_instructions;
if (s_instructions.empty())
{
for (auto const& instruction: solidity::c_instructions)
{
if (
instruction.second == solidity::Instruction::JUMPDEST ||
(solidity::Instruction::PUSH1 <= instruction.second && instruction.second <= solidity::Instruction::PUSH32)
)
continue;
string name = instruction.first;
transform(name.begin(), name.end(), name.begin(), [](unsigned char _c) { return tolower(_c); });
s_instructions[name] = instruction.second;
}
// add alias for suicide
s_instructions["suicide"] = solidity::Instruction::SELFDESTRUCT;
}
return s_instructions;
}
assembly::Statement Parser::parseElementaryOperation(bool _onlySinglePusher)
{
Statement ret;
switch (m_scanner->currentToken())
{
case Token::Identifier:
case Token::Return:
case Token::Byte:
case Token::Address:
{
string literal;
if (m_scanner->currentToken() == Token::Return)
literal = "return";
else if (m_scanner->currentToken() == Token::Byte)
literal = "byte";
else if (m_scanner->currentToken() == Token::Address)
literal = "address";
else
literal = m_scanner->currentLiteral();
// first search the set of instructions.
if (instructions().count(literal))
{
dev::solidity::Instruction const& instr = instructions().at(literal);
if (_onlySinglePusher)
{
InstructionInfo info = dev::solidity::instructionInfo(instr);
if (info.ret != 1)
fatalParserError("Instruction " + info.name + " not allowed in this context.");
}
ret = Instruction{location(), instr};
}
else
ret = Identifier{location(), literal};
break;
}
case Token::StringLiteral:
case Token::Number:
{
ret = Literal{
location(),
m_scanner->currentToken() == Token::Number,
m_scanner->currentLiteral()
};
break;
}
default:
fatalParserError("Expected elementary inline assembly operation.");
}
m_scanner->next();
return ret;
}
assembly::VariableDeclaration Parser::parseVariableDeclaration()
{
VariableDeclaration varDecl = createWithLocation<VariableDeclaration>();
expectToken(Token::Let);
varDecl.name = expectAsmIdentifier();
expectToken(Token::Colon);
expectToken(Token::Assign);
varDecl.value.reset(new Statement(parseExpression()));
varDecl.location.end = locationOf(*varDecl.value).end;
return varDecl;
}
assembly::FunctionDefinition Parser::parseFunctionDefinition()
{
FunctionDefinition funDef = createWithLocation<FunctionDefinition>();
expectToken(Token::Function);
funDef.name = expectAsmIdentifier();
expectToken(Token::LParen);
while (m_scanner->currentToken() != Token::RParen)
{
funDef.arguments.push_back(expectAsmIdentifier());
if (m_scanner->currentToken() == Token::RParen)
break;
expectToken(Token::Comma);
}
expectToken(Token::RParen);
if (m_scanner->currentToken() == Token::Sub)
{
expectToken(Token::Sub);
expectToken(Token::GreaterThan);
while (true)
{
funDef.returns.push_back(expectAsmIdentifier());
if (m_scanner->currentToken() == Token::LBrace)
break;
expectToken(Token::Comma);
}
}
funDef.body = parseBlock();
funDef.location.end = funDef.body.location.end;
return funDef;
}
assembly::Statement Parser::parseFunctionalInstruction(assembly::Statement&& _instruction)
{
if (_instruction.type() == typeid(Instruction))
{
FunctionalInstruction ret;
ret.instruction = std::move(boost::get<Instruction>(_instruction));
ret.location = ret.instruction.location;
solidity::Instruction instr = ret.instruction.instruction;
InstructionInfo instrInfo = instructionInfo(instr);
if (solidity::Instruction::DUP1 <= instr && instr <= solidity::Instruction::DUP16)
fatalParserError("DUPi instructions not allowed for functional notation");
if (solidity::Instruction::SWAP1 <= instr && instr <= solidity::Instruction::SWAP16)
fatalParserError("SWAPi instructions not allowed for functional notation");
expectToken(Token::LParen);
unsigned args = unsigned(instrInfo.args);
for (unsigned i = 0; i < args; ++i)
{
ret.arguments.emplace_back(parseExpression());
if (i != args - 1)
{
if (m_scanner->currentToken() != Token::Comma)
fatalParserError(string(
"Expected comma (" +
instrInfo.name +
" expects " +
boost::lexical_cast<string>(args) +
" arguments)"
));
else
m_scanner->next();
}
}
ret.location.end = endPosition();
if (m_scanner->currentToken() == Token::Comma)
fatalParserError(
string("Expected ')' (" + instrInfo.name + " expects " + boost::lexical_cast<string>(args) + " arguments)")
);
expectToken(Token::RParen);
return ret;
}
else if (_instruction.type() == typeid(Identifier))
{
FunctionCall ret;
ret.functionName = std::move(boost::get<Identifier>(_instruction));
ret.location = ret.functionName.location;
expectToken(Token::LParen);
while (m_scanner->currentToken() != Token::RParen)
{
ret.arguments.emplace_back(parseExpression());
if (m_scanner->currentToken() == Token::RParen)
break;
expectToken(Token::Comma);
}
ret.location.end = endPosition();
expectToken(Token::RParen);
return ret;
}
else
fatalParserError("Assembly instruction or function name required in front of \"(\")");
return {};
}
string Parser::expectAsmIdentifier()
{
string name = m_scanner->currentLiteral();
if (instructions().count(name))
fatalParserError("Cannot use instruction names for identifier names.");
expectToken(Token::Identifier);
return name;
}
<commit_msg>Do not validate identifiers against EVM instructions in JULIA<commit_after>/*
This file is part of solidity.
solidity 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.
solidity 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 solidity. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Christian <[email protected]>
* @date 2016
* Solidity inline assembly parser.
*/
#include <libsolidity/inlineasm/AsmParser.h>
#include <ctype.h>
#include <algorithm>
#include <libsolidity/parsing/Scanner.h>
#include <libsolidity/interface/Exceptions.h>
using namespace std;
using namespace dev;
using namespace dev::solidity;
using namespace dev::solidity::assembly;
shared_ptr<assembly::Block> Parser::parse(std::shared_ptr<Scanner> const& _scanner)
{
try
{
m_scanner = _scanner;
return make_shared<Block>(parseBlock());
}
catch (FatalError const&)
{
if (m_errors.empty())
throw; // Something is weird here, rather throw again.
}
return nullptr;
}
assembly::Block Parser::parseBlock()
{
assembly::Block block = createWithLocation<Block>();
expectToken(Token::LBrace);
while (m_scanner->currentToken() != Token::RBrace)
block.statements.emplace_back(parseStatement());
block.location.end = endPosition();
m_scanner->next();
return block;
}
assembly::Statement Parser::parseStatement()
{
switch (m_scanner->currentToken())
{
case Token::Let:
return parseVariableDeclaration();
case Token::Function:
return parseFunctionDefinition();
case Token::LBrace:
return parseBlock();
case Token::Assign:
{
assembly::Assignment assignment = createWithLocation<assembly::Assignment>();
m_scanner->next();
expectToken(Token::Colon);
assignment.variableName.location = location();
assignment.variableName.name = m_scanner->currentLiteral();
if (!m_julia && instructions().count(assignment.variableName.name))
fatalParserError("Identifier expected, got instruction name.");
assignment.location.end = endPosition();
expectToken(Token::Identifier);
return assignment;
}
case Token::Return: // opcode
case Token::Byte: // opcode
default:
break;
}
// Options left:
// Simple instruction (might turn into functional),
// literal,
// identifier (might turn into label or functional assignment)
Statement statement(parseElementaryOperation());
switch (m_scanner->currentToken())
{
case Token::LParen:
return parseFunctionalInstruction(std::move(statement));
case Token::Colon:
{
if (statement.type() != typeid(assembly::Identifier))
fatalParserError("Label name / variable name must precede \":\".");
assembly::Identifier const& identifier = boost::get<assembly::Identifier>(statement);
m_scanner->next();
// identifier:=: should be parsed as identifier: =: (i.e. a label),
// while identifier:= (being followed by a non-colon) as identifier := (assignment).
if (m_scanner->currentToken() == Token::Assign && m_scanner->peekNextToken() != Token::Colon)
{
// functional assignment
FunctionalAssignment funAss = createWithLocation<FunctionalAssignment>(identifier.location);
if (!m_julia && instructions().count(identifier.name))
fatalParserError("Cannot use instruction names for identifier names.");
m_scanner->next();
funAss.variableName = identifier;
funAss.value.reset(new Statement(parseExpression()));
funAss.location.end = locationOf(*funAss.value).end;
return funAss;
}
else
{
// label
Label label = createWithLocation<Label>(identifier.location);
label.name = identifier.name;
return label;
}
}
default:
break;
}
return statement;
}
assembly::Statement Parser::parseExpression()
{
Statement operation = parseElementaryOperation(true);
if (m_scanner->currentToken() == Token::LParen)
return parseFunctionalInstruction(std::move(operation));
else
return operation;
}
std::map<string, dev::solidity::Instruction> const& Parser::instructions()
{
// Allowed instructions, lowercase names.
static map<string, dev::solidity::Instruction> s_instructions;
if (s_instructions.empty())
{
for (auto const& instruction: solidity::c_instructions)
{
if (
instruction.second == solidity::Instruction::JUMPDEST ||
(solidity::Instruction::PUSH1 <= instruction.second && instruction.second <= solidity::Instruction::PUSH32)
)
continue;
string name = instruction.first;
transform(name.begin(), name.end(), name.begin(), [](unsigned char _c) { return tolower(_c); });
s_instructions[name] = instruction.second;
}
// add alias for suicide
s_instructions["suicide"] = solidity::Instruction::SELFDESTRUCT;
}
return s_instructions;
}
assembly::Statement Parser::parseElementaryOperation(bool _onlySinglePusher)
{
Statement ret;
switch (m_scanner->currentToken())
{
case Token::Identifier:
case Token::Return:
case Token::Byte:
case Token::Address:
{
string literal;
if (m_scanner->currentToken() == Token::Return)
literal = "return";
else if (m_scanner->currentToken() == Token::Byte)
literal = "byte";
else if (m_scanner->currentToken() == Token::Address)
literal = "address";
else
literal = m_scanner->currentLiteral();
// first search the set of instructions.
if (!m_julia && instructions().count(literal))
{
dev::solidity::Instruction const& instr = instructions().at(literal);
if (_onlySinglePusher)
{
InstructionInfo info = dev::solidity::instructionInfo(instr);
if (info.ret != 1)
fatalParserError("Instruction " + info.name + " not allowed in this context.");
}
ret = Instruction{location(), instr};
}
else
ret = Identifier{location(), literal};
break;
}
case Token::StringLiteral:
case Token::Number:
{
ret = Literal{
location(),
m_scanner->currentToken() == Token::Number,
m_scanner->currentLiteral()
};
break;
}
default:
fatalParserError("Expected elementary inline assembly operation.");
}
m_scanner->next();
return ret;
}
assembly::VariableDeclaration Parser::parseVariableDeclaration()
{
VariableDeclaration varDecl = createWithLocation<VariableDeclaration>();
expectToken(Token::Let);
varDecl.name = expectAsmIdentifier();
expectToken(Token::Colon);
expectToken(Token::Assign);
varDecl.value.reset(new Statement(parseExpression()));
varDecl.location.end = locationOf(*varDecl.value).end;
return varDecl;
}
assembly::FunctionDefinition Parser::parseFunctionDefinition()
{
FunctionDefinition funDef = createWithLocation<FunctionDefinition>();
expectToken(Token::Function);
funDef.name = expectAsmIdentifier();
expectToken(Token::LParen);
while (m_scanner->currentToken() != Token::RParen)
{
funDef.arguments.push_back(expectAsmIdentifier());
if (m_scanner->currentToken() == Token::RParen)
break;
expectToken(Token::Comma);
}
expectToken(Token::RParen);
if (m_scanner->currentToken() == Token::Sub)
{
expectToken(Token::Sub);
expectToken(Token::GreaterThan);
while (true)
{
funDef.returns.push_back(expectAsmIdentifier());
if (m_scanner->currentToken() == Token::LBrace)
break;
expectToken(Token::Comma);
}
}
funDef.body = parseBlock();
funDef.location.end = funDef.body.location.end;
return funDef;
}
assembly::Statement Parser::parseFunctionalInstruction(assembly::Statement&& _instruction)
{
if (_instruction.type() == typeid(Instruction))
{
solAssert(!m_julia, "Instructions are invalid in JULIA");
FunctionalInstruction ret;
ret.instruction = std::move(boost::get<Instruction>(_instruction));
ret.location = ret.instruction.location;
solidity::Instruction instr = ret.instruction.instruction;
InstructionInfo instrInfo = instructionInfo(instr);
if (solidity::Instruction::DUP1 <= instr && instr <= solidity::Instruction::DUP16)
fatalParserError("DUPi instructions not allowed for functional notation");
if (solidity::Instruction::SWAP1 <= instr && instr <= solidity::Instruction::SWAP16)
fatalParserError("SWAPi instructions not allowed for functional notation");
expectToken(Token::LParen);
unsigned args = unsigned(instrInfo.args);
for (unsigned i = 0; i < args; ++i)
{
ret.arguments.emplace_back(parseExpression());
if (i != args - 1)
{
if (m_scanner->currentToken() != Token::Comma)
fatalParserError(string(
"Expected comma (" +
instrInfo.name +
" expects " +
boost::lexical_cast<string>(args) +
" arguments)"
));
else
m_scanner->next();
}
}
ret.location.end = endPosition();
if (m_scanner->currentToken() == Token::Comma)
fatalParserError(
string("Expected ')' (" + instrInfo.name + " expects " + boost::lexical_cast<string>(args) + " arguments)")
);
expectToken(Token::RParen);
return ret;
}
else if (_instruction.type() == typeid(Identifier))
{
FunctionCall ret;
ret.functionName = std::move(boost::get<Identifier>(_instruction));
ret.location = ret.functionName.location;
expectToken(Token::LParen);
while (m_scanner->currentToken() != Token::RParen)
{
ret.arguments.emplace_back(parseExpression());
if (m_scanner->currentToken() == Token::RParen)
break;
expectToken(Token::Comma);
}
ret.location.end = endPosition();
expectToken(Token::RParen);
return ret;
}
else
fatalParserError("Assembly instruction or function name required in front of \"(\")");
return {};
}
string Parser::expectAsmIdentifier()
{
string name = m_scanner->currentLiteral();
if (!m_julia && instructions().count(name))
fatalParserError("Cannot use instruction names for identifier names.");
expectToken(Token::Identifier);
return name;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/renderer/android/content_detector.h"
#include "base/logging.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebPoint.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebHitTestResult.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebSurroundingText.h"
using WebKit::WebRange;
using WebKit::WebSurroundingText;
namespace content {
ContentDetector::Result::Result() : valid(false) {}
ContentDetector::Result::Result(const WebKit::WebRange& content_boundaries,
const std::string& text,
const GURL& intent_url)
: valid(true),
content_boundaries(content_boundaries),
text(text),
intent_url(intent_url) {
}
ContentDetector::Result::~Result() {}
ContentDetector::Result ContentDetector::FindTappedContent(
const WebKit::WebHitTestResult& hit_test) {
if (hit_test.isNull())
return Result();
std::string content_text;
WebKit::WebRange range = FindContentRange(hit_test, &content_text);
if (range.isNull())
return Result();
GURL intent_url = GetIntentURL(content_text);
return Result(range, content_text, intent_url);
}
WebRange ContentDetector::FindContentRange(
const WebKit::WebHitTestResult& hit_test,
std::string* content_text) {
// As the surrounding text extractor looks at maxLength/2 characters on
// either side of the hit point, we need to double max content length here.
WebSurroundingText surrounding_text;
surrounding_text.initialize(hit_test.node(), hit_test.localPoint(),
GetMaximumContentLength() * 2);
if (surrounding_text.isNull())
return WebRange();
string16 content = surrounding_text.textContent();
if (content.empty())
return WebRange();
size_t selected_offset = surrounding_text.hitOffsetInTextContent();
for (size_t start_offset = 0; start_offset < content.length();) {
size_t relative_start, relative_end;
if (!FindContent(content.begin() + start_offset,
content.end(), &relative_start, &relative_end, content_text)) {
break;
} else {
size_t content_start = start_offset + relative_start;
size_t content_end = start_offset + relative_end;
DCHECK(content_end <= content.length());
if (selected_offset >= content_start && selected_offset < content_end) {
WebRange range = surrounding_text.rangeFromContentOffsets(
content_start, content_end);
DCHECK(!range.isNull());
return range;
} else {
start_offset += relative_end;
}
}
}
return WebRange();
}
} // namespace content
<commit_msg>Update some #includes in content/renderer/android for headers in the new Platform directory<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/renderer/android/content_detector.h"
#include "base/logging.h"
#include "third_party/WebKit/Source/Platform/chromium/public/WebPoint.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebHitTestResult.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebSurroundingText.h"
using WebKit::WebRange;
using WebKit::WebSurroundingText;
namespace content {
ContentDetector::Result::Result() : valid(false) {}
ContentDetector::Result::Result(const WebKit::WebRange& content_boundaries,
const std::string& text,
const GURL& intent_url)
: valid(true),
content_boundaries(content_boundaries),
text(text),
intent_url(intent_url) {
}
ContentDetector::Result::~Result() {}
ContentDetector::Result ContentDetector::FindTappedContent(
const WebKit::WebHitTestResult& hit_test) {
if (hit_test.isNull())
return Result();
std::string content_text;
WebKit::WebRange range = FindContentRange(hit_test, &content_text);
if (range.isNull())
return Result();
GURL intent_url = GetIntentURL(content_text);
return Result(range, content_text, intent_url);
}
WebRange ContentDetector::FindContentRange(
const WebKit::WebHitTestResult& hit_test,
std::string* content_text) {
// As the surrounding text extractor looks at maxLength/2 characters on
// either side of the hit point, we need to double max content length here.
WebSurroundingText surrounding_text;
surrounding_text.initialize(hit_test.node(), hit_test.localPoint(),
GetMaximumContentLength() * 2);
if (surrounding_text.isNull())
return WebRange();
string16 content = surrounding_text.textContent();
if (content.empty())
return WebRange();
size_t selected_offset = surrounding_text.hitOffsetInTextContent();
for (size_t start_offset = 0; start_offset < content.length();) {
size_t relative_start, relative_end;
if (!FindContent(content.begin() + start_offset,
content.end(), &relative_start, &relative_end, content_text)) {
break;
} else {
size_t content_start = start_offset + relative_start;
size_t content_end = start_offset + relative_end;
DCHECK(content_end <= content.length());
if (selected_offset >= content_start && selected_offset < content_end) {
WebRange range = surrounding_text.rangeFromContentOffsets(
content_start, content_end);
DCHECK(!range.isNull());
return range;
} else {
start_offset += relative_end;
}
}
}
return WebRange();
}
} // namespace content
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "variablechooser.h"
#include "ui_variablechooser.h"
#include "variablemanager.h"
#include "coreconstants.h"
#include <utils/fancylineedit.h> // IconButton
#include <utils/qtcassert.h>
#include <QTimer>
#include <QLineEdit>
#include <QTextEdit>
#include <QPlainTextEdit>
#include <QListWidgetItem>
using namespace Core;
/*!
* \class Core::VariableChooser
* \brief The VariableChooser class is used to add a tool window for selecting \QC variables
* to line edits, text edits or plain text edits.
*
* If you allow users to add \QC variables to strings that are specified in your UI, for example
* when users can provide a string through a text control, you should add a variable chooser to it.
* The variable chooser allows users to open a tool window that contains the list of
* all available variables together with a description. Double-clicking a variable inserts the
* corresponding string into the corresponding text control like a line edit.
*
* \image variablechooser.png "External Tools Preferences with Variable Chooser"
*
* The variable chooser monitors focus changes of all children of its parent widget.
* When a text control gets focus, the variable chooser checks if it has variable support set,
* either through the addVariableSupport() function or by manually setting the
* custom kVariableSupportProperty on the control. If the control supports variables,
* a tool button which opens the variable chooser is shown in it while it has focus.
*
* Supported text controls are QLineEdit, QTextEdit and QPlainTextEdit.
*
* The variable chooser is deleted when its parent widget is deleted.
*
* Example:
* \code
* QWidget *myOptionsContainerWidget = new QWidget;
* new Core::VariableChooser(myOptionsContainerWidget)
* QLineEdit *myLineEditOption = new QLineEdit(myOptionsContainerWidget);
* myOptionsContainerWidget->layout()->addWidget(myLineEditOption);
* Core::VariableChooser::addVariableSupport(myLineEditOption);
* \endcode
*/
/*!
* \variable VariableChooser::kVariableSupportProperty
* Property name that is checked for deciding if a widget supports \QC variables.
* Can be manually set with
* \c{textcontrol->setProperty(VariableChooser::kVariableSupportProperty, true)}
* \sa addVariableSupport()
*/
const char VariableChooser::kVariableSupportProperty[] = "QtCreator.VariableSupport";
/*!
* Creates a variable chooser that tracks all children of \a parent for variable support.
* Ownership is also transferred to \a parent.
* \sa addVariableSupport()
*/
VariableChooser::VariableChooser(QWidget *parent) :
QWidget(parent),
ui(new Internal::Ui::VariableChooser),
m_lineEdit(0),
m_textEdit(0),
m_plainTextEdit(0)
{
ui->setupUi(this);
m_defaultDescription = ui->variableDescription->text();
ui->variableList->setAttribute(Qt::WA_MacSmallSize);
ui->variableList->setAttribute(Qt::WA_MacShowFocusRect, false);
ui->variableDescription->setAttribute(Qt::WA_MacSmallSize);
setWindowFlags(Qt::Tool | Qt::WindowStaysOnTopHint);
setFocusPolicy(Qt::StrongFocus);
setFocusProxy(ui->variableList);
foreach (const QByteArray &variable, VariableManager::variables())
ui->variableList->addItem(QString::fromLatin1(variable));
connect(ui->variableList, SIGNAL(currentTextChanged(QString)),
this, SLOT(updateDescription(QString)));
connect(ui->variableList, SIGNAL(itemActivated(QListWidgetItem*)),
this, SLOT(handleItemActivated(QListWidgetItem*)));
connect(qApp, SIGNAL(focusChanged(QWidget*,QWidget*)),
this, SLOT(updateCurrentEditor(QWidget*,QWidget*)));
updateCurrentEditor(0, qApp->focusWidget());
}
/*!
* \internal
*/
VariableChooser::~VariableChooser()
{
delete m_iconButton;
delete ui;
}
/*!
* Marks the control as supporting variables.
* \sa kVariableSupportProperty
*/
void VariableChooser::addVariableSupport(QWidget *textcontrol)
{
QTC_ASSERT(textcontrol, return);
textcontrol->setProperty(kVariableSupportProperty, true);
}
/*!
* \internal
*/
void VariableChooser::updateDescription(const QString &variable)
{
if (variable.isNull())
ui->variableDescription->setText(m_defaultDescription);
else
ui->variableDescription->setText(VariableManager::variableDescription(variable.toUtf8()));
}
/*!
* \internal
*/
void VariableChooser::updateCurrentEditor(QWidget *old, QWidget *widget)
{
if (old)
old->removeEventFilter(this);
if (!widget) // we might loose focus, but then keep the previous state
return;
// prevent children of the chooser itself, and limit to children of chooser's parent
bool handle = false;
QWidget *parent = widget;
while (parent) {
if (parent == this)
return;
if (parent == this->parentWidget()) {
handle = true;
break;
}
parent = parent->parentWidget();
}
if (!handle)
return;
widget->installEventFilter(this); // for intercepting escape key presses
QLineEdit *previousLineEdit = m_lineEdit;
QWidget *previousWidget = currentWidget();
m_lineEdit = 0;
m_textEdit = 0;
m_plainTextEdit = 0;
QVariant variablesSupportProperty = widget->property(kVariableSupportProperty);
bool supportsVariables = (variablesSupportProperty.isValid()
? variablesSupportProperty.toBool() : false);
if (QLineEdit *lineEdit = qobject_cast<QLineEdit *>(widget))
m_lineEdit = (supportsVariables ? lineEdit : 0);
else if (QTextEdit *textEdit = qobject_cast<QTextEdit *>(widget))
m_textEdit = (supportsVariables ? textEdit : 0);
else if (QPlainTextEdit *plainTextEdit = qobject_cast<QPlainTextEdit *>(widget))
m_plainTextEdit = (supportsVariables ? plainTextEdit : 0);
if (!(m_lineEdit || m_textEdit || m_plainTextEdit))
hide();
QWidget *current = currentWidget();
if (current != previousWidget) {
if (previousLineEdit)
previousLineEdit->setTextMargins(0, 0, 0, 0);
if (m_iconButton) {
m_iconButton->hide();
m_iconButton->setParent(0);
}
if (current) {
if (!m_iconButton)
createIconButton();
int margin = m_iconButton->pixmap().width() + 8;
if (style()->inherits("OxygenStyle"))
margin = qMax(24, margin);
if (m_lineEdit)
m_lineEdit->setTextMargins(0, 0, margin, 0);
m_iconButton->setParent(current);
m_iconButton->setGeometry(current->rect().adjusted(
current->width() - (margin + 4), 0,
0, -qMax(0, current->height() - (margin + 4))));
m_iconButton->show();
}
}
}
/*!
* \internal
*/
void VariableChooser::createIconButton()
{
m_iconButton = new Utils::IconButton;
m_iconButton->setPixmap(QPixmap(QLatin1String(":/core/images/replace.png")));
m_iconButton->setToolTip(tr("Insert variable"));
m_iconButton->hide();
connect(m_iconButton, SIGNAL(clicked()), this, SLOT(updatePositionAndShow()));
}
/*!
* \internal
*/
void VariableChooser::updatePositionAndShow()
{
if (parentWidget()) {
QPoint parentCenter = parentWidget()->mapToGlobal(parentWidget()->geometry().center());
move(parentCenter.x() - width()/2, parentCenter.y() - height()/2);
}
show();
raise();
activateWindow();
}
/*!
* \internal
*/
QWidget *VariableChooser::currentWidget()
{
if (m_lineEdit)
return m_lineEdit;
if (m_textEdit)
return m_textEdit;
return m_plainTextEdit;
}
/*!
* \internal
*/
void VariableChooser::handleItemActivated(QListWidgetItem *item)
{
if (item)
insertVariable(item->text());
}
/*!
* \internal
*/
void VariableChooser::insertVariable(const QString &variable)
{
const QString &text = QLatin1String("%{") + variable + QLatin1String("}");
if (m_lineEdit) {
m_lineEdit->insert(text);
m_lineEdit->activateWindow();
} else if (m_textEdit) {
m_textEdit->insertPlainText(text);
m_textEdit->activateWindow();
} else if (m_plainTextEdit) {
m_plainTextEdit->insertPlainText(text);
m_plainTextEdit->activateWindow();
}
}
/*!
* \internal
*/
static bool handleEscapePressed(QKeyEvent *ke, QWidget *widget)
{
if (ke->key() == Qt::Key_Escape && !ke->modifiers()) {
ke->accept();
QTimer::singleShot(0, widget, SLOT(close()));
return true;
}
return false;
}
/*!
* \internal
*/
void VariableChooser::keyPressEvent(QKeyEvent *ke)
{
handleEscapePressed(ke, this);
}
/*!
* \internal
*/
bool VariableChooser::eventFilter(QObject *, QEvent *event)
{
if (event->type() == QEvent::KeyPress && isVisible()) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
return handleEscapePressed(ke, this);
}
return false;
}
<commit_msg>Variables: Show current value of variable in chooser dialog<commit_after>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "variablechooser.h"
#include "ui_variablechooser.h"
#include "variablemanager.h"
#include "coreconstants.h"
#include <utils/fancylineedit.h> // IconButton
#include <utils/qtcassert.h>
#include <QTimer>
#include <QLineEdit>
#include <QTextEdit>
#include <QPlainTextEdit>
#include <QListWidgetItem>
using namespace Core;
/*!
* \class Core::VariableChooser
* \brief The VariableChooser class is used to add a tool window for selecting \QC variables
* to line edits, text edits or plain text edits.
*
* If you allow users to add \QC variables to strings that are specified in your UI, for example
* when users can provide a string through a text control, you should add a variable chooser to it.
* The variable chooser allows users to open a tool window that contains the list of
* all available variables together with a description. Double-clicking a variable inserts the
* corresponding string into the corresponding text control like a line edit.
*
* \image variablechooser.png "External Tools Preferences with Variable Chooser"
*
* The variable chooser monitors focus changes of all children of its parent widget.
* When a text control gets focus, the variable chooser checks if it has variable support set,
* either through the addVariableSupport() function or by manually setting the
* custom kVariableSupportProperty on the control. If the control supports variables,
* a tool button which opens the variable chooser is shown in it while it has focus.
*
* Supported text controls are QLineEdit, QTextEdit and QPlainTextEdit.
*
* The variable chooser is deleted when its parent widget is deleted.
*
* Example:
* \code
* QWidget *myOptionsContainerWidget = new QWidget;
* new Core::VariableChooser(myOptionsContainerWidget)
* QLineEdit *myLineEditOption = new QLineEdit(myOptionsContainerWidget);
* myOptionsContainerWidget->layout()->addWidget(myLineEditOption);
* Core::VariableChooser::addVariableSupport(myLineEditOption);
* \endcode
*/
/*!
* \variable VariableChooser::kVariableSupportProperty
* Property name that is checked for deciding if a widget supports \QC variables.
* Can be manually set with
* \c{textcontrol->setProperty(VariableChooser::kVariableSupportProperty, true)}
* \sa addVariableSupport()
*/
const char VariableChooser::kVariableSupportProperty[] = "QtCreator.VariableSupport";
/*!
* Creates a variable chooser that tracks all children of \a parent for variable support.
* Ownership is also transferred to \a parent.
* \sa addVariableSupport()
*/
VariableChooser::VariableChooser(QWidget *parent) :
QWidget(parent),
ui(new Internal::Ui::VariableChooser),
m_lineEdit(0),
m_textEdit(0),
m_plainTextEdit(0)
{
ui->setupUi(this);
m_defaultDescription = ui->variableDescription->text();
ui->variableList->setAttribute(Qt::WA_MacSmallSize);
ui->variableList->setAttribute(Qt::WA_MacShowFocusRect, false);
ui->variableDescription->setAttribute(Qt::WA_MacSmallSize);
setWindowFlags(Qt::Tool | Qt::WindowStaysOnTopHint);
setFocusPolicy(Qt::StrongFocus);
setFocusProxy(ui->variableList);
foreach (const QByteArray &variable, VariableManager::variables())
ui->variableList->addItem(QString::fromLatin1(variable));
connect(ui->variableList, SIGNAL(currentTextChanged(QString)),
this, SLOT(updateDescription(QString)));
connect(ui->variableList, SIGNAL(itemActivated(QListWidgetItem*)),
this, SLOT(handleItemActivated(QListWidgetItem*)));
connect(qApp, SIGNAL(focusChanged(QWidget*,QWidget*)),
this, SLOT(updateCurrentEditor(QWidget*,QWidget*)));
updateCurrentEditor(0, qApp->focusWidget());
}
/*!
* \internal
*/
VariableChooser::~VariableChooser()
{
delete m_iconButton;
delete ui;
}
/*!
* Marks the control as supporting variables.
* \sa kVariableSupportProperty
*/
void VariableChooser::addVariableSupport(QWidget *textcontrol)
{
QTC_ASSERT(textcontrol, return);
textcontrol->setProperty(kVariableSupportProperty, true);
}
/*!
* \internal
*/
void VariableChooser::updateDescription(const QString &variable)
{
if (variable.isNull())
ui->variableDescription->setText(m_defaultDescription);
else
ui->variableDescription->setText(VariableManager::variableDescription(variable.toUtf8())
+ QLatin1String("<p>") + tr("Current Value: %1").arg(VariableManager::value(variable.toUtf8())));
}
/*!
* \internal
*/
void VariableChooser::updateCurrentEditor(QWidget *old, QWidget *widget)
{
if (old)
old->removeEventFilter(this);
if (!widget) // we might loose focus, but then keep the previous state
return;
// prevent children of the chooser itself, and limit to children of chooser's parent
bool handle = false;
QWidget *parent = widget;
while (parent) {
if (parent == this)
return;
if (parent == this->parentWidget()) {
handle = true;
break;
}
parent = parent->parentWidget();
}
if (!handle)
return;
widget->installEventFilter(this); // for intercepting escape key presses
QLineEdit *previousLineEdit = m_lineEdit;
QWidget *previousWidget = currentWidget();
m_lineEdit = 0;
m_textEdit = 0;
m_plainTextEdit = 0;
QVariant variablesSupportProperty = widget->property(kVariableSupportProperty);
bool supportsVariables = (variablesSupportProperty.isValid()
? variablesSupportProperty.toBool() : false);
if (QLineEdit *lineEdit = qobject_cast<QLineEdit *>(widget))
m_lineEdit = (supportsVariables ? lineEdit : 0);
else if (QTextEdit *textEdit = qobject_cast<QTextEdit *>(widget))
m_textEdit = (supportsVariables ? textEdit : 0);
else if (QPlainTextEdit *plainTextEdit = qobject_cast<QPlainTextEdit *>(widget))
m_plainTextEdit = (supportsVariables ? plainTextEdit : 0);
if (!(m_lineEdit || m_textEdit || m_plainTextEdit))
hide();
QWidget *current = currentWidget();
if (current != previousWidget) {
if (previousLineEdit)
previousLineEdit->setTextMargins(0, 0, 0, 0);
if (m_iconButton) {
m_iconButton->hide();
m_iconButton->setParent(0);
}
if (current) {
if (!m_iconButton)
createIconButton();
int margin = m_iconButton->pixmap().width() + 8;
if (style()->inherits("OxygenStyle"))
margin = qMax(24, margin);
if (m_lineEdit)
m_lineEdit->setTextMargins(0, 0, margin, 0);
m_iconButton->setParent(current);
m_iconButton->setGeometry(current->rect().adjusted(
current->width() - (margin + 4), 0,
0, -qMax(0, current->height() - (margin + 4))));
m_iconButton->show();
}
}
}
/*!
* \internal
*/
void VariableChooser::createIconButton()
{
m_iconButton = new Utils::IconButton;
m_iconButton->setPixmap(QPixmap(QLatin1String(":/core/images/replace.png")));
m_iconButton->setToolTip(tr("Insert variable"));
m_iconButton->hide();
connect(m_iconButton, SIGNAL(clicked()), this, SLOT(updatePositionAndShow()));
}
/*!
* \internal
*/
void VariableChooser::updatePositionAndShow()
{
if (parentWidget()) {
QPoint parentCenter = parentWidget()->mapToGlobal(parentWidget()->geometry().center());
move(parentCenter.x() - width()/2, parentCenter.y() - height()/2);
}
show();
raise();
activateWindow();
}
/*!
* \internal
*/
QWidget *VariableChooser::currentWidget()
{
if (m_lineEdit)
return m_lineEdit;
if (m_textEdit)
return m_textEdit;
return m_plainTextEdit;
}
/*!
* \internal
*/
void VariableChooser::handleItemActivated(QListWidgetItem *item)
{
if (item)
insertVariable(item->text());
}
/*!
* \internal
*/
void VariableChooser::insertVariable(const QString &variable)
{
const QString &text = QLatin1String("%{") + variable + QLatin1String("}");
if (m_lineEdit) {
m_lineEdit->insert(text);
m_lineEdit->activateWindow();
} else if (m_textEdit) {
m_textEdit->insertPlainText(text);
m_textEdit->activateWindow();
} else if (m_plainTextEdit) {
m_plainTextEdit->insertPlainText(text);
m_plainTextEdit->activateWindow();
}
}
/*!
* \internal
*/
static bool handleEscapePressed(QKeyEvent *ke, QWidget *widget)
{
if (ke->key() == Qt::Key_Escape && !ke->modifiers()) {
ke->accept();
QTimer::singleShot(0, widget, SLOT(close()));
return true;
}
return false;
}
/*!
* \internal
*/
void VariableChooser::keyPressEvent(QKeyEvent *ke)
{
handleEscapePressed(ke, this);
}
/*!
* \internal
*/
bool VariableChooser::eventFilter(QObject *, QEvent *event)
{
if (event->type() == QEvent::KeyPress && isVisible()) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
return handleEscapePressed(ke, this);
}
return false;
}
<|endoftext|> |
<commit_before>#include "QtViewerMapping.h"
#include <widgetzeug/make_unique.hpp>
#include <glbinding/gl/enum.h>
#include <gloperate/base/RenderTargetType.h>
#include <gloperate/painter/Camera.h>
#include <gloperate/painter/AbstractCameraCapability.h>
#include <gloperate/painter/AbstractProjectionCapability.h>
#include <gloperate/painter/AbstractViewportCapability.h>
#include <gloperate/painter/TypedRenderTargetCapability.h>
#include <gloperate/painter/AbstractTargetFramebufferCapability.h>
#include <gloperate/painter/Painter.h>
#include <gloperate/input/AbstractEvent.h>
#include <gloperate/input/KeyboardEvent.h>
#include <gloperate/input/MouseEvent.h>
#include <gloperate/input/WheelEvent.h>
#include <gloperate/navigation/WorldInHandNavigation.h>
#include <gloperate/tools/CoordinateProvider.h>
#include <gloperate-qt/QtOpenGLWindow.h>
using namespace gloperate;
using namespace gloperate_qt;
using widgetzeug::make_unique;
QtViewerMapping::QtViewerMapping(QtOpenGLWindow * window)
: AbstractQtMapping(window)
{
}
QtViewerMapping::~QtViewerMapping()
{
}
void QtViewerMapping::initializeTools()
{
m_renderTarget = nullptr;
if (m_painter &&
m_painter->supports<AbstractCameraCapability>() &&
m_painter->supports<AbstractViewportCapability>() &&
m_painter->supports<AbstractProjectionCapability>() &&
(m_painter->supports<AbstractTypedRenderTargetCapability>() ||
m_painter->supports<AbstractTargetFramebufferCapability>()))
{
auto cameraCapability = m_painter->getCapability<AbstractCameraCapability>();
auto projectionCapability = m_painter->getCapability<AbstractProjectionCapability>();
auto viewportCapability = m_painter->getCapability<AbstractViewportCapability>();
auto renderTargetCapability = m_painter->getCapability<AbstractTypedRenderTargetCapability>();
if (!renderTargetCapability)
{
m_renderTarget = make_unique<TypedRenderTargetCapability>();
renderTargetCapability = m_renderTarget.get();
auto fboCapability = m_painter->getCapability<AbstractTargetFramebufferCapability>();
fboCapability->changed.connect([this] () { this->onTargetFramebufferChanged(); });
}
m_coordProvider = make_unique<CoordinateProvider>(
cameraCapability, projectionCapability, viewportCapability, renderTargetCapability);
m_navigation = make_unique<WorldInHandNavigation>(
*cameraCapability, *viewportCapability, *m_coordProvider);
}
}
void QtViewerMapping::mapEvent(AbstractEvent * event)
{
if (m_renderTarget && !m_renderTarget->hasRenderTarget(RenderTargetType::Depth))
onTargetFramebufferChanged();
switch (event->sourceType())
{
case gloperate::SourceType::Keyboard:
mapKeyboardEvent(static_cast<KeyboardEvent *>(event));
break;
case gloperate::SourceType::Mouse:
mapMouseEvent(static_cast<MouseEvent *>(event));
break;
case gloperate::SourceType::Wheel:
mapWheelEvent(static_cast<WheelEvent *>(event));
break;
default:
break;
}
}
void QtViewerMapping::mapKeyboardEvent(KeyboardEvent * event)
{
if (event && event->type() == KeyboardEvent::Type::Press)
{
switch (event->key())
{
// WASD move camera
case KeyW:
m_navigation->pan(glm::vec3(0, 0, 1));
break;
case KeyA:
m_navigation->pan(glm::vec3(1, 0, 0));
break;
case KeyS:
m_navigation->pan(glm::vec3(0, 0, -1));
break;
case KeyD:
m_navigation->pan(glm::vec3(-1, 0, 0));
break;
// Reset camera position
case KeyR:
m_navigation->reset();
break;
// Arrows rotate camera
case KeyUp:
m_navigation->rotate(0.0f, glm::radians(-10.0f));
break;
case KeyLeft:
m_navigation->rotate(glm::radians(10.0f), 0.0f);
break;
case KeyDown:
m_navigation->rotate(0.0f, glm::radians(10.0f));
break;
case KeyRight:
m_navigation->rotate(glm::radians(-10.0f), 0.0f);
break;
default:
break;
}
}
}
void QtViewerMapping::mapMouseEvent(MouseEvent * mouseEvent)
{
if (mouseEvent && mouseEvent->type() == MouseEvent::Type::Press)
{
const auto pos = mouseEvent->pos() * static_cast<int>(m_window->devicePixelRatio());
switch (mouseEvent->button())
{
case MouseButtonMiddle:
m_navigation->reset();
break;
case MouseButtonLeft:
m_navigation->panBegin(pos);
break;
case MouseButtonRight:
m_navigation->rotateBegin(pos);
break;
default:
break;
}
}
else if (mouseEvent && mouseEvent->type() == MouseEvent::Type::Move)
{
const auto pos = mouseEvent->pos() * static_cast<int>(m_window->devicePixelRatio());
switch (m_navigation->mode())
{
case WorldInHandNavigation::InteractionMode::PanInteraction:
m_navigation->panProcess(pos);
break;
case WorldInHandNavigation::InteractionMode::RotateInteraction:
m_navigation->rotateProcess(pos);
break;
default:
break;
}
}
else if (mouseEvent && mouseEvent->type() == MouseEvent::Type::Release)
{
switch (mouseEvent->button())
{
case MouseButtonLeft:
m_navigation->panEnd();
break;
case MouseButtonRight:
m_navigation->rotateEnd();
break;
default:
break;
}
}
}
void QtViewerMapping::mapWheelEvent(WheelEvent * wheelEvent)
{
auto scale = wheelEvent->angleDelta().y;
scale /= WheelEvent::defaultMouseAngleDelta();
scale *= 0.1f; // smoother (slower) scaling
m_navigation->scaleAtMouse(wheelEvent->pos(), scale);
}
void QtViewerMapping::onTargetFramebufferChanged()
{
auto fbo = m_painter->getCapability<AbstractTargetFramebufferCapability>()->framebuffer();
if (!fbo)
fbo = globjects::Framebuffer::defaultFBO();
m_renderTarget->setRenderTarget(gloperate::RenderTargetType::Depth, fbo,
gl::GL_DEPTH_ATTACHMENT, gl::GL_DEPTH_COMPONENT);
}
<commit_msg>Add shader reloading via F5<commit_after>#include "QtViewerMapping.h"
#include <widgetzeug/make_unique.hpp>
#include <glbinding/gl/enum.h>
#include <globjects/base/File.h>
#include <gloperate/base/RenderTargetType.h>
#include <gloperate/painter/Camera.h>
#include <gloperate/painter/AbstractCameraCapability.h>
#include <gloperate/painter/AbstractProjectionCapability.h>
#include <gloperate/painter/AbstractViewportCapability.h>
#include <gloperate/painter/TypedRenderTargetCapability.h>
#include <gloperate/painter/AbstractTargetFramebufferCapability.h>
#include <gloperate/painter/Painter.h>
#include <gloperate/input/AbstractEvent.h>
#include <gloperate/input/KeyboardEvent.h>
#include <gloperate/input/MouseEvent.h>
#include <gloperate/input/WheelEvent.h>
#include <gloperate/navigation/WorldInHandNavigation.h>
#include <gloperate/tools/CoordinateProvider.h>
#include <gloperate-qt/QtOpenGLWindow.h>
using namespace globjects;
using namespace gloperate;
using namespace gloperate_qt;
using widgetzeug::make_unique;
QtViewerMapping::QtViewerMapping(QtOpenGLWindow * window)
: AbstractQtMapping(window)
{
}
QtViewerMapping::~QtViewerMapping()
{
}
void QtViewerMapping::initializeTools()
{
m_renderTarget = nullptr;
if (m_painter &&
m_painter->supports<AbstractCameraCapability>() &&
m_painter->supports<AbstractViewportCapability>() &&
m_painter->supports<AbstractProjectionCapability>() &&
(m_painter->supports<AbstractTypedRenderTargetCapability>() ||
m_painter->supports<AbstractTargetFramebufferCapability>()))
{
auto cameraCapability = m_painter->getCapability<AbstractCameraCapability>();
auto projectionCapability = m_painter->getCapability<AbstractProjectionCapability>();
auto viewportCapability = m_painter->getCapability<AbstractViewportCapability>();
auto renderTargetCapability = m_painter->getCapability<AbstractTypedRenderTargetCapability>();
if (!renderTargetCapability)
{
m_renderTarget = make_unique<TypedRenderTargetCapability>();
renderTargetCapability = m_renderTarget.get();
auto fboCapability = m_painter->getCapability<AbstractTargetFramebufferCapability>();
fboCapability->changed.connect([this] () { this->onTargetFramebufferChanged(); });
}
m_coordProvider = make_unique<CoordinateProvider>(
cameraCapability, projectionCapability, viewportCapability, renderTargetCapability);
m_navigation = make_unique<WorldInHandNavigation>(
*cameraCapability, *viewportCapability, *m_coordProvider);
}
}
void QtViewerMapping::mapEvent(AbstractEvent * event)
{
if (m_renderTarget && !m_renderTarget->hasRenderTarget(RenderTargetType::Depth))
onTargetFramebufferChanged();
switch (event->sourceType())
{
case gloperate::SourceType::Keyboard:
mapKeyboardEvent(static_cast<KeyboardEvent *>(event));
break;
case gloperate::SourceType::Mouse:
mapMouseEvent(static_cast<MouseEvent *>(event));
break;
case gloperate::SourceType::Wheel:
mapWheelEvent(static_cast<WheelEvent *>(event));
break;
default:
break;
}
}
void QtViewerMapping::mapKeyboardEvent(KeyboardEvent * event)
{
if (event && event->type() == KeyboardEvent::Type::Press)
{
switch (event->key())
{
// WASD move camera
case KeyW:
m_navigation->pan(glm::vec3(0, 0, 1));
break;
case KeyA:
m_navigation->pan(glm::vec3(1, 0, 0));
break;
case KeyS:
m_navigation->pan(glm::vec3(0, 0, -1));
break;
case KeyD:
m_navigation->pan(glm::vec3(-1, 0, 0));
break;
// Reset camera position
case KeyR:
m_navigation->reset();
break;
// Arrows rotate camera
case KeyUp:
m_navigation->rotate(0.0f, glm::radians(-10.0f));
break;
case KeyLeft:
m_navigation->rotate(glm::radians(10.0f), 0.0f);
break;
case KeyDown:
m_navigation->rotate(0.0f, glm::radians(10.0f));
break;
case KeyRight:
m_navigation->rotate(glm::radians(-10.0f), 0.0f);
break;
// Shader reloading
case KeyF5:
File::reloadAll();
break;
default:
break;
}
}
}
void QtViewerMapping::mapMouseEvent(MouseEvent * mouseEvent)
{
if (mouseEvent && mouseEvent->type() == MouseEvent::Type::Press)
{
const auto pos = mouseEvent->pos() * static_cast<int>(m_window->devicePixelRatio());
switch (mouseEvent->button())
{
case MouseButtonMiddle:
m_navigation->reset();
break;
case MouseButtonLeft:
m_navigation->panBegin(pos);
break;
case MouseButtonRight:
m_navigation->rotateBegin(pos);
break;
default:
break;
}
}
else if (mouseEvent && mouseEvent->type() == MouseEvent::Type::Move)
{
const auto pos = mouseEvent->pos() * static_cast<int>(m_window->devicePixelRatio());
switch (m_navigation->mode())
{
case WorldInHandNavigation::InteractionMode::PanInteraction:
m_navigation->panProcess(pos);
break;
case WorldInHandNavigation::InteractionMode::RotateInteraction:
m_navigation->rotateProcess(pos);
break;
default:
break;
}
}
else if (mouseEvent && mouseEvent->type() == MouseEvent::Type::Release)
{
switch (mouseEvent->button())
{
case MouseButtonLeft:
m_navigation->panEnd();
break;
case MouseButtonRight:
m_navigation->rotateEnd();
break;
default:
break;
}
}
}
void QtViewerMapping::mapWheelEvent(WheelEvent * wheelEvent)
{
auto scale = wheelEvent->angleDelta().y;
scale /= WheelEvent::defaultMouseAngleDelta();
scale *= 0.1f; // smoother (slower) scaling
m_navigation->scaleAtMouse(wheelEvent->pos(), scale);
}
void QtViewerMapping::onTargetFramebufferChanged()
{
auto fbo = m_painter->getCapability<AbstractTargetFramebufferCapability>()->framebuffer();
if (!fbo)
fbo = globjects::Framebuffer::defaultFBO();
m_renderTarget->setRenderTarget(gloperate::RenderTargetType::Depth, fbo,
gl::GL_DEPTH_ATTACHMENT, gl::GL_DEPTH_COMPONENT);
}
<|endoftext|> |
<commit_before>#include <QtGui>
#include <QtGlobal>
#include "editorviewscene.h"
#include "uml_edgeelement.h"
#include "uml_nodeelement.h"
#include "realreporoles.h"
#include <math.h>
using namespace UML;
static const double Pi = 3.14159265358979323846264338327950288419717;
static double TwoPi = 2.0 * Pi;
static bool moving = false;
EdgeElement::EdgeElement()
: src(0), dst(0), portFrom(0), portTo(0), dragState(-1), longPart(0)
{
setZValue(100);
setFlag(ItemIsMovable, true);
// FIXME: draws strangely...
setFlag(ItemClipsToShape, false);
m_penStyle = Qt::SolidLine;
m_line << QPointF(0,0) << QPointF(200,60);
m_endArrowStyle = NO_ARROW;
}
EdgeElement::~EdgeElement()
{
if (src)
src->delEdge(this);
if (dst)
dst->delEdge(this);
}
QRectF EdgeElement::boundingRect() const
{
// return m_line.boundingRect().adjusted(-kvadratik,-kvadratik,kvadratik,kvadratik);
return m_line.boundingRect().adjusted(-20,-20,20,20);
}
static double lineAngle(const QLineF &line)
{
double angle = ::acos(line.dx() / line.length());
if (line.dy() >= 0)
angle = TwoPi - angle;
return angle*180/Pi;
}
void EdgeElement::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget*)
{
painter->save();
QPen pen = painter->pen();
pen.setColor(m_color);
pen.setStyle(m_penStyle);
pen.setWidth(1);
painter->setPen(pen);
painter->drawPolyline(m_line);
painter->restore();
painter->save();
painter->translate(m_line[0]);
painter->rotate(90-lineAngle(QLineF(m_line[1],m_line[0])));
drawStartArrow(painter);
painter->restore();
painter->save();
painter->translate(m_line[m_line.size()-1]);
painter->rotate(90-lineAngle(QLineF(m_line[m_line.size()-2],m_line[m_line.size()-1])));
drawEndArrow(painter);
painter->restore();
if (option->state & QStyle::State_Selected) {
painter->setBrush(Qt::SolidPattern);
foreach( QPointF point, m_line) {
painter->drawRect(QRectF(point-QPointF(kvadratik,kvadratik),QSizeF(kvadratik*2,kvadratik*2)));
}
}
if ( ! m_text.isEmpty() ) {
painter->save();
QLineF longest(m_line[longPart],m_line[longPart+1]);
painter->translate(m_line[longPart]);
painter->rotate(-lineAngle(longest));
// painter->drawText(0,-15,longest.length(),15,
// Qt::TextSingleLine | Qt::AlignCenter, m_text);
QTextDocument d;
d.setHtml(m_text);
d.setTextWidth(longest.length());
// painter->drawRect(QRectF(0,0,longest.length(),20));
d.drawContents(painter);
painter->restore();
}
}
bool canBeConnected( int linkID, int from, int to );
/*
void EdgeElement::checkConnection()
{
// int type = this->type();
int from = -1;
int to = -1;
if ( src != 0 )
from = src->type();
if ( dst != 0 )
to = dst->type();
m_color = Qt::black;
}
*/
QPainterPath EdgeElement::shape() const
{
QPainterPath path;
path.setFillRule(Qt::WindingFill);
QPainterPathStroker ps;
ps.setWidth(kvadratik);
path.addPolygon(m_line);
path = ps.createStroke(path);
foreach( QPointF point, m_line) {
path.addRect(QRectF(point-QPointF(kvadratik,kvadratik),QSizeF(kvadratik*2,kvadratik*2)));
}
return path;
}
int EdgeElement::getPoint( const QPointF &location )
{
for ( int i = 0 ; i < m_line.size() ; i++ )
if ( QRectF(m_line[i]-QPointF(kvadratik,kvadratik),QSizeF(kvadratik*2,kvadratik*2)).contains( location ) )
return i;
return -1;
}
void EdgeElement::updateLongestPart()
{
qreal maxLen = 0.0;
int maxIdx = 0;
for ( int i = 0; i < m_line.size() - 1 ; i++ ) {
qreal newLen = QLineF(m_line[i],m_line[i+1]).length();
if ( newLen > maxLen ) {
maxLen = newLen;
maxIdx = i;
}
}
longPart = maxIdx;
}
void EdgeElement::mousePressEvent ( QGraphicsSceneMouseEvent * event )
{
dragState = -1;
if ( isSelected() )
dragState = getPoint( event->pos() );
if ( dragState == -1 )
Element::mousePressEvent(event);
}
void EdgeElement::mouseMoveEvent ( QGraphicsSceneMouseEvent * event )
{
if ( dragState == -1 ) {
Element::mouseMoveEvent(event);
} else {
prepareGeometryChange();
m_line[dragState] = event->pos();
updateLongestPart();
}
}
void EdgeElement::mouseReleaseEvent ( QGraphicsSceneMouseEvent * event )
{
QAbstractItemModel *im = const_cast<QAbstractItemModel *>(dataIndex.model());
setPos(pos()+m_line[0]);
m_line.translate(-m_line[0]);
if ( dragState == -1 )
Element::mouseReleaseEvent(event);
else
dragState = -1;
moving = true;
// Now we check whether start or end have been connected
NodeElement *new_src = getNodeAt(m_line[0]);
if ( new_src )
portFrom = new_src->getPortId( mapToItem(new_src, m_line[0]) );
else
portFrom = -1.0;
if ( src ) {
src->delEdge(this);
src = 0;
}
if ( portFrom >= 0.0 ) {
src = new_src;
src->addEdge(this);
}
if ( src )
im->setData(dataIndex, src->uuid(), Unreal::krneRelationship::fromRole);
else
im->setData(dataIndex, 0, Unreal::krneRelationship::fromRole);
im->setData(dataIndex, portFrom, Unreal::krneRelationship::fromPortRole);
NodeElement *new_dst = getNodeAt(m_line[m_line.size()-1]);
if ( new_dst )
portTo = new_dst->getPortId( mapToItem(new_dst, m_line[m_line.size()-1]) );
else
portTo = -1.0;
if ( dst ) {
dst->delEdge(this);
dst = 0;
}
if ( portTo >= 0.0 ) {
dst = new_dst;
dst->addEdge(this);
}
if ( dst )
im->setData(dataIndex, dst->uuid(), Unreal::krneRelationship::toRole);
else
im->setData(dataIndex, 0, Unreal::krneRelationship::toRole);
im->setData(dataIndex, portTo, Unreal::krneRelationship::toPortRole);
setFlag(ItemIsMovable, !(dst||src) );
im->setData(dataIndex, pos(), Unreal::PositionRole);
im->setData(dataIndex, m_line.toPolygon(), Unreal::ConfigurationRole);
moving = false;
updateLongestPart();
}
NodeElement *EdgeElement::getNodeAt( const QPointF &position )
{
foreach( QGraphicsItem *item, scene()->items(mapToScene(position)) ) {
NodeElement *e = dynamic_cast<NodeElement *>(item);
if ( e )
return e;
}
return 0;
}
void EdgeElement::contextMenuEvent ( QGraphicsSceneContextMenuEvent * event )
{
QMenu menu;
QAction *addPointAction = menu.addAction("Add point");
QAction *delPointAction = menu.addAction("Remove point");
QAction *squarizeAction = menu.addAction("Squarize :)");
if ( QAction *selectedAction = menu.exec(event->screenPos()) ) {
if ( selectedAction == delPointAction ) {
int i = getPoint( event->pos() );
if ( i != -1 ) {
prepareGeometryChange();
m_line.remove(i);
longPart = 0;
update();
}
} else if ( selectedAction == addPointAction ) {
for ( int i = 0; i < m_line.size()-1; i++ ) {
QPainterPath path;
QPainterPathStroker ps;
ps.setWidth(kvadratik);
path.moveTo(m_line[i]);
path.lineTo(m_line[i+1]);
if ( ps.createStroke(path).contains(event->pos()) ) {
m_line.insert(i+1,event->pos());
update();
break;
}
}
} else if ( selectedAction == squarizeAction ) {
prepareGeometryChange();
for ( int i = 0; i < m_line.size()-1; i++ ) {
QLineF line(m_line[i],m_line[i+1]);
if ( qAbs(line.dx()) < qAbs(line.dy()) ) {
m_line[i+1].setX(m_line[i].x());
} else {
m_line[i+1].setY(m_line[i].y());
}
}
adjustLink();
update();
}
}
}
void EdgeElement::adjustLink()
{
prepareGeometryChange();
if ( src )
m_line[0] = mapFromItem(src, src->getPortPos(portFrom) );
if ( dst )
m_line[m_line.size()-1] = mapFromItem(dst, dst->getPortPos(portTo) );
updateLongestPart();
}
void EdgeElement::updateData()
{
if ( moving )
return;
Element::updateData();
setPos(dataIndex.data(Unreal::PositionRole).toPointF());
QPolygonF newLine = dataIndex.data(Unreal::ConfigurationRole).value<QPolygon>();
if ( !newLine.isEmpty() )
m_line = newLine;
qDebug() << "from role: " << Unreal::krneRelationship::fromRole
<< "to role: " << Unreal::krneRelationship::toRole;
int uuidFrom = dataIndex.data(Unreal::krneRelationship::fromRole).toInt();
int uuidTo = dataIndex.data(Unreal::krneRelationship::toRole).toInt();
qDebug() << "from: " << uuidFrom << ", to: " << uuidTo;
if ( src )
src->delEdge(this);
if ( dst )
dst->delEdge(this);
src = dynamic_cast<NodeElement *>( static_cast<EditorViewScene *>(scene())->getElem(uuidFrom) );
dst = dynamic_cast<NodeElement *>( static_cast<EditorViewScene *>(scene())->getElem(uuidTo) );
if ( src )
src->addEdge(this);
if ( dst )
dst->addEdge(this);
setFlag(ItemIsMovable, !(dst||src) );
portFrom = dataIndex.data(Unreal::krneRelationship::fromPortRole).toDouble();
portTo = dataIndex.data(Unreal::krneRelationship::toPortRole).toDouble();
adjustLink();
}
<commit_msg>Use standard macros M_PI and M_1_PI<commit_after>#include <QtGui>
#include <QtGlobal>
#include "editorviewscene.h"
#include "uml_edgeelement.h"
#include "uml_nodeelement.h"
#include "realreporoles.h"
#include <math.h>
using namespace UML;
static bool moving = false;
EdgeElement::EdgeElement()
: src(0), dst(0), portFrom(0), portTo(0), dragState(-1), longPart(0)
{
setZValue(100);
setFlag(ItemIsMovable, true);
// FIXME: draws strangely...
setFlag(ItemClipsToShape, false);
m_penStyle = Qt::SolidLine;
m_line << QPointF(0,0) << QPointF(200,60);
m_endArrowStyle = NO_ARROW;
}
EdgeElement::~EdgeElement()
{
if (src)
src->delEdge(this);
if (dst)
dst->delEdge(this);
}
QRectF EdgeElement::boundingRect() const
{
// return m_line.boundingRect().adjusted(-kvadratik,-kvadratik,kvadratik,kvadratik);
return m_line.boundingRect().adjusted(-20,-20,20,20);
}
static double lineAngle(const QLineF &line)
{
double angle = ::acos(line.dx() / line.length());
if (line.dy() >= 0)
angle = 2*M_PI - angle;
return angle*180*M_1_PI;
}
void EdgeElement::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget*)
{
painter->save();
QPen pen = painter->pen();
pen.setColor(m_color);
pen.setStyle(m_penStyle);
pen.setWidth(1);
painter->setPen(pen);
painter->drawPolyline(m_line);
painter->restore();
painter->save();
painter->translate(m_line[0]);
painter->rotate(90-lineAngle(QLineF(m_line[1],m_line[0])));
drawStartArrow(painter);
painter->restore();
painter->save();
painter->translate(m_line[m_line.size()-1]);
painter->rotate(90-lineAngle(QLineF(m_line[m_line.size()-2],m_line[m_line.size()-1])));
drawEndArrow(painter);
painter->restore();
if (option->state & QStyle::State_Selected) {
painter->setBrush(Qt::SolidPattern);
foreach( QPointF point, m_line) {
painter->drawRect(QRectF(point-QPointF(kvadratik,kvadratik),QSizeF(kvadratik*2,kvadratik*2)));
}
}
if ( ! m_text.isEmpty() ) {
painter->save();
QLineF longest(m_line[longPart],m_line[longPart+1]);
painter->translate(m_line[longPart]);
painter->rotate(-lineAngle(longest));
// painter->drawText(0,-15,longest.length(),15,
// Qt::TextSingleLine | Qt::AlignCenter, m_text);
QTextDocument d;
d.setHtml(m_text);
d.setTextWidth(longest.length());
// painter->drawRect(QRectF(0,0,longest.length(),20));
d.drawContents(painter);
painter->restore();
}
}
bool canBeConnected( int linkID, int from, int to );
/*
void EdgeElement::checkConnection()
{
// int type = this->type();
int from = -1;
int to = -1;
if ( src != 0 )
from = src->type();
if ( dst != 0 )
to = dst->type();
m_color = Qt::black;
}
*/
QPainterPath EdgeElement::shape() const
{
QPainterPath path;
path.setFillRule(Qt::WindingFill);
QPainterPathStroker ps;
ps.setWidth(kvadratik);
path.addPolygon(m_line);
path = ps.createStroke(path);
foreach( QPointF point, m_line) {
path.addRect(QRectF(point-QPointF(kvadratik,kvadratik),QSizeF(kvadratik*2,kvadratik*2)));
}
return path;
}
int EdgeElement::getPoint( const QPointF &location )
{
for ( int i = 0 ; i < m_line.size() ; i++ )
if ( QRectF(m_line[i]-QPointF(kvadratik,kvadratik),QSizeF(kvadratik*2,kvadratik*2)).contains( location ) )
return i;
return -1;
}
void EdgeElement::updateLongestPart()
{
qreal maxLen = 0.0;
int maxIdx = 0;
for ( int i = 0; i < m_line.size() - 1 ; i++ ) {
qreal newLen = QLineF(m_line[i],m_line[i+1]).length();
if ( newLen > maxLen ) {
maxLen = newLen;
maxIdx = i;
}
}
longPart = maxIdx;
}
void EdgeElement::mousePressEvent ( QGraphicsSceneMouseEvent * event )
{
dragState = -1;
if ( isSelected() )
dragState = getPoint( event->pos() );
if ( dragState == -1 )
Element::mousePressEvent(event);
}
void EdgeElement::mouseMoveEvent ( QGraphicsSceneMouseEvent * event )
{
if ( dragState == -1 ) {
Element::mouseMoveEvent(event);
} else {
prepareGeometryChange();
m_line[dragState] = event->pos();
updateLongestPart();
}
}
void EdgeElement::mouseReleaseEvent ( QGraphicsSceneMouseEvent * event )
{
QAbstractItemModel *im = const_cast<QAbstractItemModel *>(dataIndex.model());
setPos(pos()+m_line[0]);
m_line.translate(-m_line[0]);
if ( dragState == -1 )
Element::mouseReleaseEvent(event);
else
dragState = -1;
moving = true;
// Now we check whether start or end have been connected
NodeElement *new_src = getNodeAt(m_line[0]);
if ( new_src )
portFrom = new_src->getPortId( mapToItem(new_src, m_line[0]) );
else
portFrom = -1.0;
if ( src ) {
src->delEdge(this);
src = 0;
}
if ( portFrom >= 0.0 ) {
src = new_src;
src->addEdge(this);
}
if ( src )
im->setData(dataIndex, src->uuid(), Unreal::krneRelationship::fromRole);
else
im->setData(dataIndex, 0, Unreal::krneRelationship::fromRole);
im->setData(dataIndex, portFrom, Unreal::krneRelationship::fromPortRole);
NodeElement *new_dst = getNodeAt(m_line[m_line.size()-1]);
if ( new_dst )
portTo = new_dst->getPortId( mapToItem(new_dst, m_line[m_line.size()-1]) );
else
portTo = -1.0;
if ( dst ) {
dst->delEdge(this);
dst = 0;
}
if ( portTo >= 0.0 ) {
dst = new_dst;
dst->addEdge(this);
}
if ( dst )
im->setData(dataIndex, dst->uuid(), Unreal::krneRelationship::toRole);
else
im->setData(dataIndex, 0, Unreal::krneRelationship::toRole);
im->setData(dataIndex, portTo, Unreal::krneRelationship::toPortRole);
setFlag(ItemIsMovable, !(dst||src) );
im->setData(dataIndex, pos(), Unreal::PositionRole);
im->setData(dataIndex, m_line.toPolygon(), Unreal::ConfigurationRole);
moving = false;
updateLongestPart();
}
NodeElement *EdgeElement::getNodeAt( const QPointF &position )
{
foreach( QGraphicsItem *item, scene()->items(mapToScene(position)) ) {
NodeElement *e = dynamic_cast<NodeElement *>(item);
if ( e )
return e;
}
return 0;
}
void EdgeElement::contextMenuEvent ( QGraphicsSceneContextMenuEvent * event )
{
QMenu menu;
QAction *addPointAction = menu.addAction("Add point");
QAction *delPointAction = menu.addAction("Remove point");
QAction *squarizeAction = menu.addAction("Squarize :)");
if ( QAction *selectedAction = menu.exec(event->screenPos()) ) {
if ( selectedAction == delPointAction ) {
int i = getPoint( event->pos() );
if ( i != -1 ) {
prepareGeometryChange();
m_line.remove(i);
longPart = 0;
update();
}
} else if ( selectedAction == addPointAction ) {
for ( int i = 0; i < m_line.size()-1; i++ ) {
QPainterPath path;
QPainterPathStroker ps;
ps.setWidth(kvadratik);
path.moveTo(m_line[i]);
path.lineTo(m_line[i+1]);
if ( ps.createStroke(path).contains(event->pos()) ) {
m_line.insert(i+1,event->pos());
update();
break;
}
}
} else if ( selectedAction == squarizeAction ) {
prepareGeometryChange();
for ( int i = 0; i < m_line.size()-1; i++ ) {
QLineF line(m_line[i],m_line[i+1]);
if ( qAbs(line.dx()) < qAbs(line.dy()) ) {
m_line[i+1].setX(m_line[i].x());
} else {
m_line[i+1].setY(m_line[i].y());
}
}
adjustLink();
update();
}
}
}
void EdgeElement::adjustLink()
{
prepareGeometryChange();
if ( src )
m_line[0] = mapFromItem(src, src->getPortPos(portFrom) );
if ( dst )
m_line[m_line.size()-1] = mapFromItem(dst, dst->getPortPos(portTo) );
updateLongestPart();
}
void EdgeElement::updateData()
{
if ( moving )
return;
Element::updateData();
setPos(dataIndex.data(Unreal::PositionRole).toPointF());
QPolygonF newLine = dataIndex.data(Unreal::ConfigurationRole).value<QPolygon>();
if ( !newLine.isEmpty() )
m_line = newLine;
qDebug() << "from role: " << Unreal::krneRelationship::fromRole
<< "to role: " << Unreal::krneRelationship::toRole;
int uuidFrom = dataIndex.data(Unreal::krneRelationship::fromRole).toInt();
int uuidTo = dataIndex.data(Unreal::krneRelationship::toRole).toInt();
qDebug() << "from: " << uuidFrom << ", to: " << uuidTo;
if ( src )
src->delEdge(this);
if ( dst )
dst->delEdge(this);
src = dynamic_cast<NodeElement *>( static_cast<EditorViewScene *>(scene())->getElem(uuidFrom) );
dst = dynamic_cast<NodeElement *>( static_cast<EditorViewScene *>(scene())->getElem(uuidTo) );
if ( src )
src->addEdge(this);
if ( dst )
dst->addEdge(this);
setFlag(ItemIsMovable, !(dst||src) );
portFrom = dataIndex.data(Unreal::krneRelationship::fromPortRole).toDouble();
portTo = dataIndex.data(Unreal::krneRelationship::toPortRole).toDouble();
adjustLink();
}
<|endoftext|> |
<commit_before>/*
* Copyright 2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "folly/experimental/symbolizer/test/SignalHandlerTest.h"
#include "folly/experimental/symbolizer/SignalHandler.h"
#include <gtest/gtest.h>
#include "folly/FileUtil.h"
#include "folly/Range.h"
#include "folly/CPortability.h"
namespace folly { namespace symbolizer { namespace test {
namespace {
void print(StringPiece sp) {
writeFull(STDERR_FILENO, sp.data(), sp.size());
}
void callback1() {
print("Callback1\n");
}
void callback2() {
print("Callback2\n");
}
} // namespace
TEST(SignalHandler, Simple) {
addFatalSignalCallback(callback1);
addFatalSignalCallback(callback2);
installFatalSignalHandler();
installFatalSignalCallbacks();
EXPECT_DEATH(
failHard(),
#ifdef FOLLY_SANITIZE_ADDRESS
// Testing an ASAN-enabled binary evokes a different diagnostic.
// Use a regexp that requires only the first line of that output:
"^ASAN:SIGSEGV\n.*"
#else
"^\\*\\*\\* Aborted at [0-9]+ \\(Unix time, try 'date -d @[0-9]+'\\) "
"\\*\\*\\*\n"
"\\*\\*\\* Signal 11 \\(SIGSEGV\\) \\(0x2a\\) received by PID [0-9]+ "
"\\(TID 0x[0-9a-f]+\\), stack trace: \\*\\*\\*\n"
".*\n"
" @ [0-9a-f]+ folly::symbolizer::test::SignalHandler_Simple_Test"
"::TestBody\\(\\)\n"
".*\n"
" @ [0-9a-f]+ main\n"
".*\n"
"Callback1\n"
"Callback2\n"
#endif
);
}
}}} // namespaces
<commit_msg>Make header compatible with warp<commit_after>/*
* Copyright 2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "folly/experimental/symbolizer/test/SignalHandlerTest.h"
#include "folly/experimental/symbolizer/SignalHandler.h"
#include <gtest/gtest.h>
#include "folly/FileUtil.h"
#include "folly/Range.h"
#include "folly/CPortability.h"
namespace folly { namespace symbolizer { namespace test {
namespace {
void print(StringPiece sp) {
writeFull(STDERR_FILENO, sp.data(), sp.size());
}
void callback1() {
print("Callback1\n");
}
void callback2() {
print("Callback2\n");
}
} // namespace
TEST(SignalHandler, Simple) {
addFatalSignalCallback(callback1);
addFatalSignalCallback(callback2);
installFatalSignalHandler();
installFatalSignalCallbacks();
#ifdef FOLLY_SANITIZE_ADDRESS
EXPECT_DEATH(
failHard(),
// Testing an ASAN-enabled binary evokes a different diagnostic.
// Use a regexp that requires only the first line of that output:
"^ASAN:SIGSEGV\n.*");
#else
EXPECT_DEATH(
failHard(),
"^\\*\\*\\* Aborted at [0-9]+ \\(Unix time, try 'date -d @[0-9]+'\\) "
"\\*\\*\\*\n"
"\\*\\*\\* Signal 11 \\(SIGSEGV\\) \\(0x2a\\) received by PID [0-9]+ "
"\\(TID 0x[0-9a-f]+\\), stack trace: \\*\\*\\*\n"
".*\n"
" @ [0-9a-f]+ folly::symbolizer::test::SignalHandler_Simple_Test"
"::TestBody\\(\\)\n"
".*\n"
" @ [0-9a-f]+ main\n"
".*\n"
"Callback1\n"
"Callback2\n"
);
#endif
}
}}} // namespaces
<|endoftext|> |
<commit_before>//
// Created by Luris on 3/20/16.
//
#include "Planet_object.h"
#include "Global_constant.h"
#include <cmath>
Planet::Planet(int x, int y, double mass, float radius, std::string path, sf::Font* font) {
setMass(mass);
setRadius(radius);
createShape();
createSprite(path);
setPosition(x, y);
createText(font);
}
void Planet::setPosition(int a, int b) {
x_center = a;
y_center = b;
shape.setPosition(x_center, y_center);
}
void Planet::setMass(double m) {
mass = m;
}
void Planet::setRadius(float r) {
radius = r;
}
double Planet::getMass() {
return mass;
}
double Planet::getRadius() {
return radius;
}
double Planet::getCircumference() {
return (radius * 2 * PI);
}
double Planet::getArea() {
return (radius * radius * PI);
}
sf::Vector2f Planet::getGravity(float bullet_x, float bullet_y) {
float distance_x = x_center - bullet_x;
float distance_y = y_center - bullet_y;
float distance = sqrt(pow(distance_x, 2) + pow(distance_y, 2));
float force_mag = G*mass*BULLET_MASS / distance;
sf::Vector2f r_hat(distance_x / distance, distance_y / distance); //Unit vector of distance/force
sf::Vector2f gravity_force(0, 0);
gravity_force.x = force_mag*r_hat.x;
gravity_force.y = force_mag*r_hat.y;
return(gravity_force);
}
void Planet::createShape() {
sf::CircleShape base_circle(radius);
shape = base_circle;
shape.setOrigin(sf::Vector2f(radius, radius));
}
void Planet::createSprite(std::string path) {
if (!planetTexture.loadFromFile(path))
{
std::cout << "Error could not load planet image" << std::endl;
}
planetTexture.setSmooth(true);
shape.setTexture(&planetTexture);
}
int Planet::getCenterX() {
return x_center;
}
int Planet::getCenterY() {
return y_center;
}
double Planet::getAngle(double edge_distance) {
return(360.0 * (edge_distance / getCircumference()));
}
void Planet::createText(sf::Font *font) {
Mass_text.setFont(*font);
Mass_text.setCharacterSize(MASS_TEXTSIZE);
Mass_text.setString("Mass: " + std::to_string((int)mass) + "KG");
Mass_text.setColor(sf::Color::White);
Mass_text.setStyle(sf::Text::Bold);
Mass_text.setOrigin(70, 20);
Mass_text.setPosition(x_center,y_center);
}
<commit_msg>Orbit added [2]<commit_after>//
// Created by Luris on 3/20/16.
//
#include "Planet_object.h"
#include "Global_constant.h"
#include <cmath>
Planet::Planet(int x, int y, double mass, float radius, std::string path, sf::Font* font) {
setMass(mass);
setRadius(radius);
createShape();
createSprite(path);
setPosition(x, y);
createText(font);
}
void Planet::setPosition(int a, int b) {
x_center = a;
y_center = b;
shape.setPosition(x_center, y_center);
}
void Planet::setMass(double m) {
mass = m;
}
void Planet::setRadius(float r) {
radius = r;
}
double Planet::getMass() {
return mass;
}
double Planet::getRadius() {
return radius;
}
double Planet::getCircumference() {
return (radius * 2 * PI);
}
double Planet::getArea() {
return (radius * radius * PI);
}
sf::Vector2f Planet::getGravity(float bullet_x, float bullet_y) {
float distance_x = x_center - bullet_x;
float distance_y = y_center - bullet_y;
float distance = sqrt(pow(distance_x, 2) + pow(distance_y, 2));
float force_mag = G*mass*BULLET_MASS / distance;
sf::Vector2f r_hat(distance_x / distance, distance_y / distance); //Unit vector of distance/force
sf::Vector2f gravity_force(0, 0);
gravity_force.x = force_mag*r_hat.x;
gravity_force.y = force_mag*r_hat.y;
return(gravity_force);
}
void Planet::createShape() {
sf::CircleShape base_circle(radius);
shape = base_circle;
shape.setOrigin(sf::Vector2f(radius, radius));
}
void Planet::createSprite(std::string path) {
if (!planetTexture.loadFromFile(path))
{
std::cout << "Error could not load planet image" << std::endl;
}
planetTexture.setSmooth(true);
shape.setTexture(&planetTexture);
}
int Planet::getCenterX() {
return x_center;
}
int Planet::getCenterY() {
return y_center;
}
double Planet::getAngle(double edge_distance) {
return(360.0 * (edge_distance / getCircumference()));
}
void Planet::createText(sf::Font *font) {
Mass_text.setFont(*font);
Mass_text.setCharacterSize(MASS_TEXTSIZE);
Mass_text.setString("Mass: " + std::to_string((int)mass) + "KG");
Mass_text.setColor(sf::Color::White);
Mass_text.setStyle(sf::Text::Bold);
Mass_text.setOrigin(70, 20);
Mass_text.setPosition(x_center,y_center);
}
void Planet::move(int xmove, int ymove)
{
x_center += xmove;
y_center += ymove;
shape.move(xmove, ymove);
}
void Planet::orbit(double angle, Planet* source)
{
int delta_y = y_center - source->y_center;
int delta_x = x_center - source->x_center;
double length = sqrt(delta_y*delta_y + delta_x*delta_x);
double ang = atan2(delta_x, delta_y);
ang += angle;
x_center = source->x_center + length * sin(ang);
y_center = source->y_center + length * cos(ang);
shape.setPosition(x_center, y_center);
}
<|endoftext|> |
<commit_before>// Copyright (C) 2009-2013 CEA/DEN, EDF R&D, OPEN CASCADE
//
// 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.
//
// 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
//
// See http://www.salome-platform.org/ or email : [email protected]
//
// Author: André RIBES - EDF R&D
//
#include "Launcher_Job_SALOME.hxx"
#include "Basics_DirUtils.hxx"
#ifdef WITH_LIBBATCH
#include <libbatch/Constants.hxx>
#endif
#ifdef WNT
#include <io.h>
#define _chmod chmod
#endif
Launcher::Job_SALOME::Job_SALOME() {}
Launcher::Job_SALOME::~Job_SALOME() {}
void
Launcher::Job_SALOME::setResourceDefinition(const ParserResourcesType & resource_definition)
{
// Check resource_definition
if (resource_definition.AppliPath == "")
{
std::string mess = "Resource definition must define an application path !, resource name is: " + resource_definition.Name;
throw LauncherException(mess);
}
Launcher::Job::setResourceDefinition(resource_definition);
}
void
Launcher::Job_SALOME::update_job()
{
#ifdef WITH_LIBBATCH
Batch::Parametre params = common_job_params();
params[Batch::EXECUTABLE] = buildSalomeScript(params);
params[Batch::EXCLUSIVE] = true;
_batch_job->setParametre(params);
#endif
}
#ifdef WITH_LIBBATCH
std::string
Launcher::Job_SALOME::buildSalomeScript(Batch::Parametre params)
{
// parameters
std::string work_directory = params[Batch::WORKDIR].str();
std::string launch_script = Kernel_Utils::GetTmpDir() + "runSalome_" + _job_file_name + "_" + _launch_date + ".sh";
std::ofstream launch_script_stream;
launch_script_stream.open(launch_script.c_str(),
std::ofstream::out
#ifdef WIN32
| std::ofstream::binary //rnv: to avoid CL+RF end of line on windows
#endif
);
// Begin of script
launch_script_stream << "#!/bin/sh -f" << std::endl;
launch_script_stream << "cd " << work_directory << std::endl;
launch_script_stream << "export PYTHONPATH=" << work_directory << ":$PYTHONPATH" << std::endl;
launch_script_stream << "export PATH=" << work_directory << ":$PATH" << std::endl;
if (_env_file != "")
{
std::string::size_type last = _env_file.find_last_of("/");
launch_script_stream << ". " << _env_file.substr(last+1) << std::endl;
}
launch_script_stream << "export SALOME_TMP_DIR=" << work_directory << "/logs" << std::endl;
// -- Generates Catalog Resources
std::string resource_protocol = _resource_definition.getClusterInternalProtocolStr();
launch_script_stream << "if [ \"x$LIBBATCH_NODEFILE\" != \"x\" ]; then " << std::endl;
launch_script_stream << "CATALOG_FILE=" << "CatalogResources_" << _launch_date << ".xml" << std::endl;
launch_script_stream << "export USER_CATALOG_RESOURCES_FILE=" << "$CATALOG_FILE" << std::endl;
launch_script_stream << "echo '<!DOCTYPE ResourcesCatalog>' > $CATALOG_FILE" << std::endl;
launch_script_stream << "echo '<resources>' >> $CATALOG_FILE" << std::endl;
launch_script_stream << "cat $LIBBATCH_NODEFILE | sort | uniq -c | while read nbproc host" << std::endl;
launch_script_stream << "do" << std::endl;
// Full name doesn't work. eg: sagittaire-7 instead of sagittaire-7.lyon.grid5000.fr
launch_script_stream << "host_basename=$(echo $host | cut -f1 -d.)" << std::endl;
launch_script_stream << "echo '<machine hostname='\\\"$host_basename\\\" >> $CATALOG_FILE" << std::endl;
launch_script_stream << "echo ' protocol=\"" << resource_protocol << "\"' >> $CATALOG_FILE" << std::endl;
launch_script_stream << "echo ' userName=\"" << _resource_definition.UserName << "\"' >> $CATALOG_FILE" << std::endl;
launch_script_stream << "echo ' appliPath=\"" << _resource_definition.AppliPath << "\"' >> $CATALOG_FILE" << std::endl;
launch_script_stream << "echo ' mpi=\"" << _resource_definition.getMpiImplTypeStr() << "\"' >> $CATALOG_FILE" << std::endl;
launch_script_stream << "echo ' nbOfNodes='\\\"$nbproc\\\" >> $CATALOG_FILE" << std::endl;
launch_script_stream << "echo ' nbOfProcPerNode=\"1\"' >> $CATALOG_FILE" << std::endl;
launch_script_stream << "echo ' canRunContainers=\"true\"' >> $CATALOG_FILE" << std::endl;
launch_script_stream << "echo '/>' >> $CATALOG_FILE" << std::endl;
launch_script_stream << "done" << std::endl;
launch_script_stream << "echo '</resources>' >> $CATALOG_FILE" << std::endl;
launch_script_stream << "fi" << std::endl;
// Create file for ns-port-log
launch_script_stream << "NS_PORT_FILE_PATH=`mktemp " << _resource_definition.AppliPath << "/USERS/nsport_XXXXXX` &&\n";
launch_script_stream << "NS_PORT_FILE_NAME=`basename $NS_PORT_FILE_PATH` &&\n";
// Launch SALOME with an appli
launch_script_stream << _resource_definition.AppliPath << "/runAppli --terminal --ns-port-log=$NS_PORT_FILE_NAME --server-launch-mode=fork ";
launch_script_stream << "> logs/salome_" << _launch_date << ".log 2>&1 &&" << std::endl;
launch_script_stream << "current=0 &&\n"
<< "stop=20 &&\n"
<< "while ! test -s $NS_PORT_FILE_PATH\n"
<< "do\n"
<< " sleep 2\n"
<< " current=$((current+1))\n"
<< " if [ \"$current\" -eq \"$stop\" ] ; then\n"
<< " echo Error Naming Service failed ! >&2\n"
<< " exit\n"
<< " fi\n"
<< "done &&\n"
<< "appli_port=`cat $NS_PORT_FILE_PATH` &&\n"
<< "rm $NS_PORT_FILE_PATH &&\n";
// Call real job type
addJobTypeSpecificScript(launch_script_stream);
// End
launch_script_stream << _resource_definition.AppliPath << "/runSession -p $appli_port shutdownSalome.py" << std::endl;
launch_script_stream << "sleep 10" << std::endl;
// Return
launch_script_stream.flush();
launch_script_stream.close();
chmod(launch_script.c_str(), 0x1ED);
return launch_script;
}
#endif
<commit_msg>Remove warning messages on resources when launching batch jobs<commit_after>// Copyright (C) 2009-2013 CEA/DEN, EDF R&D, OPEN CASCADE
//
// 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.
//
// 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
//
// See http://www.salome-platform.org/ or email : [email protected]
//
// Author: André RIBES - EDF R&D
//
#include "Launcher_Job_SALOME.hxx"
#include "Basics_DirUtils.hxx"
#ifdef WITH_LIBBATCH
#include <libbatch/Constants.hxx>
#endif
#ifdef WNT
#include <io.h>
#define _chmod chmod
#endif
Launcher::Job_SALOME::Job_SALOME() {}
Launcher::Job_SALOME::~Job_SALOME() {}
void
Launcher::Job_SALOME::setResourceDefinition(const ParserResourcesType & resource_definition)
{
// Check resource_definition
if (resource_definition.AppliPath == "")
{
std::string mess = "Resource definition must define an application path !, resource name is: " + resource_definition.Name;
throw LauncherException(mess);
}
Launcher::Job::setResourceDefinition(resource_definition);
}
void
Launcher::Job_SALOME::update_job()
{
#ifdef WITH_LIBBATCH
Batch::Parametre params = common_job_params();
params[Batch::EXECUTABLE] = buildSalomeScript(params);
params[Batch::EXCLUSIVE] = true;
_batch_job->setParametre(params);
#endif
}
#ifdef WITH_LIBBATCH
std::string
Launcher::Job_SALOME::buildSalomeScript(Batch::Parametre params)
{
// parameters
std::string work_directory = params[Batch::WORKDIR].str();
std::string launch_script = Kernel_Utils::GetTmpDir() + "runSalome_" + _job_file_name + "_" + _launch_date + ".sh";
std::ofstream launch_script_stream;
launch_script_stream.open(launch_script.c_str(),
std::ofstream::out
#ifdef WIN32
| std::ofstream::binary //rnv: to avoid CL+RF end of line on windows
#endif
);
// Begin of script
launch_script_stream << "#!/bin/sh -f" << std::endl;
launch_script_stream << "cd " << work_directory << std::endl;
launch_script_stream << "export PYTHONPATH=" << work_directory << ":$PYTHONPATH" << std::endl;
launch_script_stream << "export PATH=" << work_directory << ":$PATH" << std::endl;
if (_env_file != "")
{
std::string::size_type last = _env_file.find_last_of("/");
launch_script_stream << ". " << _env_file.substr(last+1) << std::endl;
}
launch_script_stream << "export SALOME_TMP_DIR=" << work_directory << "/logs" << std::endl;
// -- Generates Catalog Resources
std::string resource_protocol = _resource_definition.getClusterInternalProtocolStr();
launch_script_stream << "if [ \"x$LIBBATCH_NODEFILE\" != \"x\" ]; then " << std::endl;
launch_script_stream << "CATALOG_FILE=" << "CatalogResources_" << _launch_date << ".xml" << std::endl;
launch_script_stream << "export USER_CATALOG_RESOURCES_FILE=" << "$CATALOG_FILE" << std::endl;
launch_script_stream << "echo '<!DOCTYPE ResourcesCatalog>' > $CATALOG_FILE" << std::endl;
launch_script_stream << "echo '<resources>' >> $CATALOG_FILE" << std::endl;
launch_script_stream << "cat $LIBBATCH_NODEFILE | sort | uniq -c | while read nbproc host" << std::endl;
launch_script_stream << "do" << std::endl;
// Full name doesn't work. eg: sagittaire-7 instead of sagittaire-7.lyon.grid5000.fr
launch_script_stream << "host_basename=$(echo $host | cut -f1 -d.)" << std::endl;
launch_script_stream << "echo '<machine name='\\\"$host_basename\\\" >> $CATALOG_FILE" << std::endl;
launch_script_stream << "echo ' hostname='\\\"$host_basename\\\" >> $CATALOG_FILE" << std::endl;
launch_script_stream << "echo ' type=\"single_machine\"' >> $CATALOG_FILE" << std::endl;
launch_script_stream << "echo ' protocol=\"" << resource_protocol << "\"' >> $CATALOG_FILE" << std::endl;
launch_script_stream << "echo ' userName=\"" << _resource_definition.UserName << "\"' >> $CATALOG_FILE" << std::endl;
launch_script_stream << "echo ' appliPath=\"" << _resource_definition.AppliPath << "\"' >> $CATALOG_FILE" << std::endl;
launch_script_stream << "echo ' mpi=\"" << _resource_definition.getMpiImplTypeStr() << "\"' >> $CATALOG_FILE" << std::endl;
launch_script_stream << "echo ' nbOfNodes='\\\"$nbproc\\\" >> $CATALOG_FILE" << std::endl;
launch_script_stream << "echo ' nbOfProcPerNode=\"1\"' >> $CATALOG_FILE" << std::endl;
launch_script_stream << "echo ' canRunContainers=\"true\"' >> $CATALOG_FILE" << std::endl;
launch_script_stream << "echo '/>' >> $CATALOG_FILE" << std::endl;
launch_script_stream << "done" << std::endl;
launch_script_stream << "echo '</resources>' >> $CATALOG_FILE" << std::endl;
launch_script_stream << "fi" << std::endl;
// Create file for ns-port-log
launch_script_stream << "NS_PORT_FILE_PATH=`mktemp " << _resource_definition.AppliPath << "/USERS/nsport_XXXXXX` &&\n";
launch_script_stream << "NS_PORT_FILE_NAME=`basename $NS_PORT_FILE_PATH` &&\n";
// Launch SALOME with an appli
launch_script_stream << _resource_definition.AppliPath << "/runAppli --terminal --ns-port-log=$NS_PORT_FILE_NAME --server-launch-mode=fork ";
launch_script_stream << "> logs/salome_" << _launch_date << ".log 2>&1 &&" << std::endl;
launch_script_stream << "current=0 &&\n"
<< "stop=20 &&\n"
<< "while ! test -s $NS_PORT_FILE_PATH\n"
<< "do\n"
<< " sleep 2\n"
<< " current=$((current+1))\n"
<< " if [ \"$current\" -eq \"$stop\" ] ; then\n"
<< " echo Error Naming Service failed ! >&2\n"
<< " exit\n"
<< " fi\n"
<< "done &&\n"
<< "appli_port=`cat $NS_PORT_FILE_PATH` &&\n"
<< "rm $NS_PORT_FILE_PATH &&\n";
// Call real job type
addJobTypeSpecificScript(launch_script_stream);
// End
launch_script_stream << _resource_definition.AppliPath << "/runSession -p $appli_port shutdownSalome.py" << std::endl;
launch_script_stream << "sleep 10" << std::endl;
// Return
launch_script_stream.flush();
launch_script_stream.close();
chmod(launch_script.c_str(), 0x1ED);
return launch_script;
}
#endif
<|endoftext|> |
<commit_before>/* -*- mode: C++; c-basic-offset: 4; -*- */
/* ex: set shiftwidth=4 tabstop=4 expandtab: */
/*
* Copyright (c) 2015-2016, Rice University
* All rights reserved.
*
* Author(s): Neil T. Dantam <[email protected]>
*
* 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 copyright holder the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "amino.h"
#include "amino/rx/rxerr.h"
#include "amino/rx/rxtype.h"
#include "amino/rx/scenegraph.h"
#include "amino/rx/scene_ik.h"
#include "amino/rx/scene_sub.h"
#include "amino/rx/scene_collision.h"
#include "amino/rx/ompl/scene_state_validity_checker.h"
namespace amino {
sgStateValidityChecker::sgStateValidityChecker(sgSpaceInformation *si)
:
TypedStateValidityChecker(si),
q_all(new double[getTypedStateSpace()->config_count_all()]),
cl(aa_rx_cl_create(getTypedStateSpace()->scene_graph)),
collisions(NULL)
{
this->allow();
}
sgStateValidityChecker::~sgStateValidityChecker()
{
delete [] q_all;
aa_rx_cl_destroy(this->cl);
}
bool sgStateValidityChecker::isValid(const ompl::base::State *state) const
{
sgStateSpace *space = getTypedStateSpace();
size_t n_f = space->frame_count();
int is_collision;
// check collision
{
std::lock_guard<std::mutex> lock(mutex);
const sgSpaceInformation::StateType* state_ = state->as<sgSpaceInformation::StateType>();
double *TF_abs = space->get_tf_abs(state, state_->values);
is_collision = aa_rx_cl_check( this->cl, n_f, TF_abs, 7, this->collisions );
space->region_pop(TF_abs);
}
return !is_collision;
}
void sgStateValidityChecker::set_start( size_t n_q, double *q_initial)
{
assert( n_q == getTypedStateSpace()->config_count_all() );
std::copy( q_initial, q_initial + n_q, q_all );
this->allow();
}
void sgStateValidityChecker::allow( )
{
aa_rx_cl_allow_set( cl, getTypedStateSpace()->allowed );
}
} /* namespace amino */
<commit_msg>change to use q_all to avoid random joint location<commit_after>/* -*- mode: C++; c-basic-offset: 4; -*- */
/* ex: set shiftwidth=4 tabstop=4 expandtab: */
/*
* Copyright (c) 2015-2016, Rice University
* All rights reserved.
*
* Author(s): Neil T. Dantam <[email protected]>
*
* 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 copyright holder the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "amino.h"
#include "amino/rx/rxerr.h"
#include "amino/rx/rxtype.h"
#include "amino/rx/scenegraph.h"
#include "amino/rx/scene_ik.h"
#include "amino/rx/scene_sub.h"
#include "amino/rx/scene_collision.h"
#include "amino/rx/ompl/scene_state_validity_checker.h"
namespace amino {
sgStateValidityChecker::sgStateValidityChecker(sgSpaceInformation *si)
:
TypedStateValidityChecker(si),
q_all(new double[getTypedStateSpace()->config_count_all()]),
cl(aa_rx_cl_create(getTypedStateSpace()->scene_graph)),
collisions(NULL)
{
this->allow();
}
sgStateValidityChecker::~sgStateValidityChecker()
{
delete [] q_all;
aa_rx_cl_destroy(this->cl);
}
bool sgStateValidityChecker::isValid(const ompl::base::State *state) const
{
sgStateSpace *space = getTypedStateSpace();
size_t n_f = space->frame_count();
int is_collision;
// check collision
{
std::lock_guard<std::mutex> lock(mutex);
const sgSpaceInformation::StateType* state_ = state->as<sgSpaceInformation::StateType>();
double *TF_abs = space->get_tf_abs(state, this->q_all);
is_collision = aa_rx_cl_check( this->cl, n_f, TF_abs, 7, this->collisions );
space->region_pop(TF_abs);
}
return !is_collision;
}
void sgStateValidityChecker::set_start( size_t n_q, double *q_initial)
{
assert( n_q == getTypedStateSpace()->config_count_all() );
std::copy( q_initial, q_initial + n_q, q_all );
this->allow();
}
void sgStateValidityChecker::allow( )
{
aa_rx_cl_allow_set( cl, getTypedStateSpace()->allowed );
}
} /* namespace amino */
<|endoftext|> |
<commit_before>//-----------------------------------------------------------------------------
// File: list.cpp
//
// Class: list
// Functions: main
//-----------------------------------------------------------------------------
#include "list.h"
using namespace std;
namespace NP_ADT
{
//-------------------------------------------------------------------------
// constructor
//-------------------------------------------------------------------------
template<class datatype>
CDLL<datatype>::CDLL(size_t n_elements, datatype datum)
:m_size(0), handle(nullptr)
{
if (n_elements <= 0)
throw out_of_range("Empty list");
for (size_t i = 0; i < n_elements; i++)
push_front(datum);
}
//-------------------------------------------------------------------------
// copy constructor
//-------------------------------------------------------------------------
template<typename datatype>
NP_ADT::CDLL<datatype>::CDLL(const CDLL<datatype> & cdll)
: m_size(0), handle(nullptr)
{
if (!cdll.empty()) {
CDLL::iterator r_it = cdll.begin();
push_front(*r_it++);
while (r_it != cdll.begin())
push_front(*r_it++);
}
}
//-------------------------------------------------------------------------
// insert element at front of list
//-------------------------------------------------------------------------
template<typename datatype>
void CDLL<datatype>::push_front(datatype datum)
{
node * temp = new node(datum, nullptr, nullptr);
if (m_size++ == 0)
{
temp->next = temp;
temp->prev = temp;
}
else {
node * before = handle->prev;
temp->next = handle;
handle->prev = temp;
temp->prev = before;
before->next = temp;
}
handle = temp;
}
//-------------------------------------------------------------------------
// insert element at end of list
//-------------------------------------------------------------------------
template<typename datatype>
void CDLL<datatype>::push_back(datatype datum)
{
node * temp = new node(datum, nullptr, nullptr);
if (m_size++ == 0)
{
temp->next = temp;
temp->prev = temp;
handle = temp;
}
else {
node * before = handle->prev;
temp->next = handle;
handle->prev = temp;
temp->prev = before;
before->next = temp;
}
}
//-------------------------------------------------------------------------
// removes front element and returns the data from that element
//-------------------------------------------------------------------------
template<typename datatype>
datatype NP_ADT::CDLL<datatype>::pop_front()
{
if (handle == nullptr)
throw runtime_error("Empty list");
datatype poppedData = head()->data;
if (m_size-- == 1) {
handle = nullptr;
}
else {
node * oldHead = head();
node * newHead = head()->next;
newHead->prev = head()->prev;
head()->prev->next = newHead;
handle = newHead;
delete oldHead;
}
return poppedData;
}
//-------------------------------------------------------------------------
// removes back element and returns the data from that element
//-------------------------------------------------------------------------
template<typename datatype>
datatype NP_ADT::CDLL<datatype>::pop_back()
{
if (handle == nullptr)
throw runtime_error("Empty list");
datatype poppedData = tail()->data;
if (m_size-- == 1) {
handle = nullptr;
}
else {
node * oldTail = tail();
node * newTail = tail()->prev;
newTail->next = tail()->next;
tail()->next->prev = newTail;
delete oldTail;
}
return poppedData;
}
//-------------------------------------------------------------------------
// returns data of the first item
//-------------------------------------------------------------------------
template<class datatype>
datatype & CDLL<datatype>::front() const
{
if (head() != nullptr)
return head()->data;
else
throw runtime_error("Empty list");
}
//-------------------------------------------------------------------------
// returns data of the last item
//-------------------------------------------------------------------------
template<class datatype>
inline datatype & CDLL<datatype>::back() const
{
if (tail() != nullptr)
return tail()->data;
else
throw runtime_error("Empty list");
}
//-----------------------------------------------------------------------------
// empties the list
//-----------------------------------------------------------------------------
template<typename datatype>
inline void NP_ADT::CDLL<datatype>::release()
{
while (handle != nullptr)
pop_front();
}
//-------------------------------------------------------------------------
// constructor using iterators, copies from begin to one before end
//-------------------------------------------------------------------------
template<typename datatype>
NP_ADT::CDLL<datatype>::CDLL(iterator begin, iterator end)
:m_size(0), handle(nullptr)
{
while (begin != end)
push_back(*begin++);
push_back(*begin++);
}
//-------------------------------------------------------------------------
// prints out a list
//-------------------------------------------------------------------------
/*template<typename datatype>
const datatype & NP_ADT::CDLL<datatype>::operator[](int index) const
{
CDLL::iterator p = x.begin(); // gets x.h
sout << "(";
while (p != nullptr)
{
sout << *p;
if (p != x.end())
sout << ",";
++p; // advances iterator using next
}
sout << ")\n";
return sout;
}*/
//-------------------------------------------------------------------------
// returns a copy of rlist
//-------------------------------------------------------------------------
/*template<typename datatype>
CDLL<datatype> NP_ADT::CDLL<datatype>::operator=(const CDLL & rlist)
{
if (&rlist != this)
{
CDLL<datatype>::iterator r_it = rlist.begin();
release();
while (r_it != 0)
push_front(*r_it++);
}
return *this;
}*/
//-------------------------------------------------------------------------
// pre-increment
//-------------------------------------------------------------------------
template<typename datatype>
inline typename CDLL<datatype>::iterator NP_ADT::CDLL<datatype>::iterator::operator++()
{
if (ptr == nullptr)
throw runtime_error("nullptr pointer");
ptr = ptr->next;
return *this;
}
//-------------------------------------------------------------------------
// post-increment
//-------------------------------------------------------------------------
template<typename datatype>
inline typename CDLL<datatype>::iterator NP_ADT::CDLL<datatype>::iterator::operator++(int)
{
if (ptr == nullptr)
throw runtime_error("nullptr pointer");
iterator temp = *this;
ptr = ptr->next;
return temp;
}
//-------------------------------------------------------------------------
// pre-decrement
//-------------------------------------------------------------------------
template<typename datatype>
inline typename CDLL<datatype>::iterator NP_ADT::CDLL<datatype>::iterator::operator--()
{
if (ptr == nullptr)
throw runtime_error("nullptr pointer");
ptr = ptr->prev;
return *this;
}
//-------------------------------------------------------------------------
// post-decrement
//-------------------------------------------------------------------------
template<typename datatype>
inline typename CDLL<datatype>::iterator NP_ADT::CDLL<datatype>::iterator::operator--(int)
{
if (ptr == nullptr)
throw runtime_error("nullptr pointer");
iterator temp = *this;
ptr = ptr->prev;
return temp;
}
//-------------------------------------------------------------------------
// [] operator -- l-value
//-------------------------------------------------------------------------
/*template<typename datatype>
datatype & NP_ADT::CDLL<datatype>::operator[](int index)
{
iterator it;
if (index >= 0)
{
if (index >= static_cast<int>(getSize()))
throw out_of_range("index out-of-range");
it = begin();
for (int i = 0; i < index; i++)
it++;
}
else
{
if (index < -(static_cast<int>(getSize())))
throw out_of_range("index out-of-range");
it = end();
for (int i = -1; i > index; i--)
it--;
}
return *it;
}*/
//-------------------------------------------------------------------------
// ostream << overload
//-------------------------------------------------------------------------
template <typename datatype>
ostream & operator << (ostream& sout, const CDLL<datatype> & cdll)
{
auto it = cdll.begin();
sout << "["
while (it != cdll.end())
sout << *it++ << ", ";
sout << *it << "]";
return sout;
}
} // end namespace NP_ADT
<commit_msg>fix syntax error<commit_after>//-----------------------------------------------------------------------------
// File: list.cpp
//
// Class: list
// Functions: main
//-----------------------------------------------------------------------------
#include "list.h"
using namespace std;
namespace NP_ADT
{
//-------------------------------------------------------------------------
// constructor
//-------------------------------------------------------------------------
template<class datatype>
CDLL<datatype>::CDLL(size_t n_elements, datatype datum)
:m_size(0), handle(nullptr)
{
if (n_elements <= 0)
throw out_of_range("Empty list");
for (size_t i = 0; i < n_elements; i++)
push_front(datum);
}
//-------------------------------------------------------------------------
// copy constructor
//-------------------------------------------------------------------------
template<typename datatype>
NP_ADT::CDLL<datatype>::CDLL(const CDLL<datatype> & cdll)
: m_size(0), handle(nullptr)
{
if (!cdll.empty()) {
CDLL::iterator r_it = cdll.begin();
push_front(*r_it++);
while (r_it != cdll.begin())
push_front(*r_it++);
}
}
//-------------------------------------------------------------------------
// insert element at front of list
//-------------------------------------------------------------------------
template<typename datatype>
void CDLL<datatype>::push_front(datatype datum)
{
node * temp = new node(datum, nullptr, nullptr);
if (m_size++ == 0)
{
temp->next = temp;
temp->prev = temp;
}
else {
node * before = handle->prev;
temp->next = handle;
handle->prev = temp;
temp->prev = before;
before->next = temp;
}
handle = temp;
}
//-------------------------------------------------------------------------
// insert element at end of list
//-------------------------------------------------------------------------
template<typename datatype>
void CDLL<datatype>::push_back(datatype datum)
{
node * temp = new node(datum, nullptr, nullptr);
if (m_size++ == 0)
{
temp->next = temp;
temp->prev = temp;
handle = temp;
}
else {
node * before = handle->prev;
temp->next = handle;
handle->prev = temp;
temp->prev = before;
before->next = temp;
}
}
//-------------------------------------------------------------------------
// removes front element and returns the data from that element
//-------------------------------------------------------------------------
template<typename datatype>
datatype NP_ADT::CDLL<datatype>::pop_front()
{
if (handle == nullptr)
throw runtime_error("Empty list");
datatype poppedData = head()->data;
if (m_size-- == 1) {
handle = nullptr;
}
else {
node * oldHead = head();
node * newHead = head()->next;
newHead->prev = head()->prev;
head()->prev->next = newHead;
handle = newHead;
delete oldHead;
}
return poppedData;
}
//-------------------------------------------------------------------------
// removes back element and returns the data from that element
//-------------------------------------------------------------------------
template<typename datatype>
datatype NP_ADT::CDLL<datatype>::pop_back()
{
if (handle == nullptr)
throw runtime_error("Empty list");
datatype poppedData = tail()->data;
if (m_size-- == 1) {
handle = nullptr;
}
else {
node * oldTail = tail();
node * newTail = tail()->prev;
newTail->next = tail()->next;
tail()->next->prev = newTail;
delete oldTail;
}
return poppedData;
}
//-------------------------------------------------------------------------
// returns data of the first item
//-------------------------------------------------------------------------
template<class datatype>
datatype & CDLL<datatype>::front() const
{
if (head() != nullptr)
return head()->data;
else
throw runtime_error("Empty list");
}
//-------------------------------------------------------------------------
// returns data of the last item
//-------------------------------------------------------------------------
template<class datatype>
inline datatype & CDLL<datatype>::back() const
{
if (tail() != nullptr)
return tail()->data;
else
throw runtime_error("Empty list");
}
//-----------------------------------------------------------------------------
// empties the list
//-----------------------------------------------------------------------------
template<typename datatype>
inline void NP_ADT::CDLL<datatype>::release()
{
while (handle != nullptr)
pop_front();
}
//-------------------------------------------------------------------------
// constructor using iterators, copies from begin to one before end
//-------------------------------------------------------------------------
template<typename datatype>
NP_ADT::CDLL<datatype>::CDLL(iterator begin, iterator end)
:m_size(0), handle(nullptr)
{
while (begin != end)
push_back(*begin++);
push_back(*begin++);
}
//-------------------------------------------------------------------------
// prints out a list
//-------------------------------------------------------------------------
/*template<typename datatype>
const datatype & NP_ADT::CDLL<datatype>::operator[](int index) const
{
CDLL::iterator p = x.begin(); // gets x.h
sout << "(";
while (p != nullptr)
{
sout << *p;
if (p != x.end())
sout << ",";
++p; // advances iterator using next
}
sout << ")\n";
return sout;
}*/
//-------------------------------------------------------------------------
// returns a copy of rlist
//-------------------------------------------------------------------------
/*template<typename datatype>
CDLL<datatype> NP_ADT::CDLL<datatype>::operator=(const CDLL & rlist)
{
if (&rlist != this)
{
CDLL<datatype>::iterator r_it = rlist.begin();
release();
while (r_it != 0)
push_front(*r_it++);
}
return *this;
}*/
//-------------------------------------------------------------------------
// pre-increment
//-------------------------------------------------------------------------
template<typename datatype>
inline typename CDLL<datatype>::iterator NP_ADT::CDLL<datatype>::iterator::operator++()
{
if (ptr == nullptr)
throw runtime_error("nullptr pointer");
ptr = ptr->next;
return *this;
}
//-------------------------------------------------------------------------
// post-increment
//-------------------------------------------------------------------------
template<typename datatype>
inline typename CDLL<datatype>::iterator NP_ADT::CDLL<datatype>::iterator::operator++(int)
{
if (ptr == nullptr)
throw runtime_error("nullptr pointer");
iterator temp = *this;
ptr = ptr->next;
return temp;
}
//-------------------------------------------------------------------------
// pre-decrement
//-------------------------------------------------------------------------
template<typename datatype>
inline typename CDLL<datatype>::iterator NP_ADT::CDLL<datatype>::iterator::operator--()
{
if (ptr == nullptr)
throw runtime_error("nullptr pointer");
ptr = ptr->prev;
return *this;
}
//-------------------------------------------------------------------------
// post-decrement
//-------------------------------------------------------------------------
template<typename datatype>
inline typename CDLL<datatype>::iterator NP_ADT::CDLL<datatype>::iterator::operator--(int)
{
if (ptr == nullptr)
throw runtime_error("nullptr pointer");
iterator temp = *this;
ptr = ptr->prev;
return temp;
}
//-------------------------------------------------------------------------
// [] operator -- l-value
//-------------------------------------------------------------------------
/*template<typename datatype>
datatype & NP_ADT::CDLL<datatype>::operator[](int index)
{
iterator it;
if (index >= 0)
{
if (index >= static_cast<int>(getSize()))
throw out_of_range("index out-of-range");
it = begin();
for (int i = 0; i < index; i++)
it++;
}
else
{
if (index < -(static_cast<int>(getSize())))
throw out_of_range("index out-of-range");
it = end();
for (int i = -1; i > index; i--)
it--;
}
return *it;
}*/
//-------------------------------------------------------------------------
// ostream << overload
//-------------------------------------------------------------------------
template <typename datatype>
ostream & operator << (ostream& sout, const CDLL<datatype> & cdll)
{
auto it = cdll.begin();
sout << "[";
while (it != cdll.end())
sout << *it++ << ", ";
sout << *it << "]";
return sout;
}
} // end namespace NP_ADT
<|endoftext|> |
<commit_before>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright (C) 2011 - 2014 *
* Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENCE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#ifndef CAF_DETAIL_MEMORY_HPP
#define CAF_DETAIL_MEMORY_HPP
#include <new>
#include <vector>
#include <memory>
#include <utility>
#include <typeinfo>
#include "caf/config.hpp"
#include "caf/ref_counted.hpp"
namespace caf {
class mailbox_element;
} // namespace caf
namespace caf {
namespace detail {
namespace {
constexpr size_t s_alloc_size = 1024 * 1024; // allocate ~1mb chunks
constexpr size_t s_cache_size = 10 * 1024 * 1024; // cache about 10mb per thread
constexpr size_t s_min_elements = 5; // don't create < 5 elements
} // namespace <anonymous>
struct disposer {
inline void operator()(memory_managed* ptr) const {
ptr->request_deletion();
}
};
class instance_wrapper {
public:
virtual ~instance_wrapper();
// calls the destructor
virtual void destroy() = 0;
// releases memory
virtual void deallocate() = 0;
};
class memory_cache {
public:
virtual ~memory_cache();
// calls dtor and either releases memory or re-uses it later
virtual void release_instance(void*) = 0;
virtual std::pair<instance_wrapper*, void*> new_instance() = 0;
// casts `ptr` to the derived type and returns it
virtual void* downcast(memory_managed* ptr) = 0;
};
class instance_wrapper;
template <class T>
class basic_memory_cache;
#ifdef CAF_NO_MEM_MANAGEMENT
class memory {
memory() = delete;
public:
// Allocates storage, initializes a new object, and returns the new instance.
template <class T, class... Ts>
static T* create(Ts&&... args) {
return new T(std::forward<Ts>(args)...);
}
static inline memory_cache* get_cache_map_entry(const std::type_info*) {
return nullptr;
}
};
#else // CAF_NO_MEM_MANAGEMENT
template <class T>
class basic_memory_cache : public memory_cache {
static constexpr size_t ne = s_alloc_size / sizeof(T);
static constexpr size_t dsize = ne > s_min_elements ? ne : s_min_elements;
struct wrapper : instance_wrapper {
ref_counted* parent;
union {
T instance;
};
wrapper() : parent(nullptr) {}
~wrapper() {}
void destroy() { instance.~T(); }
void deallocate() { parent->deref(); }
};
class storage : public ref_counted {
public:
storage() {
for (auto& elem : data) {
// each instance has a reference to its parent
elem.parent = this;
ref(); // deref() is called in wrapper::deallocate
}
}
using iterator = wrapper*;
iterator begin() { return data; }
iterator end() { return begin() + dsize; }
private:
wrapper data[dsize];
};
public:
std::vector<wrapper*> cached_elements;
basic_memory_cache() { cached_elements.reserve(dsize); }
~basic_memory_cache() {
for (auto e : cached_elements) e->deallocate();
}
void* downcast(memory_managed* ptr) { return static_cast<T*>(ptr); }
void release_instance(void* vptr) override {
CAF_REQUIRE(vptr != nullptr);
auto ptr = reinterpret_cast<T*>(vptr);
CAF_REQUIRE(ptr->outer_memory != nullptr);
auto wptr = static_cast<wrapper*>(ptr->outer_memory);
wptr->destroy();
wptr->deallocate();
}
std::pair<instance_wrapper*, void*> new_instance() override {
if (cached_elements.empty()) {
auto elements = new storage;
for (auto i = elements->begin(); i != elements->end(); ++i) {
cached_elements.push_back(i);
}
}
wrapper* wptr = cached_elements.back();
cached_elements.pop_back();
return std::make_pair(wptr, &(wptr->instance));
}
};
class memory {
memory() = delete;
template <class>
friend class basic_memory_cache;
public:
// Allocates storage, initializes a new object, and returns the new instance.
template <class T, class... Ts>
static T* create(Ts&&... args) {
auto mc = get_or_set_cache_map_entry<T>();
auto p = mc->new_instance();
auto result = new (p.second) T(std::forward<Ts>(args)...);
result->outer_memory = p.first;
return result;
}
static memory_cache* get_cache_map_entry(const std::type_info* tinf);
private:
static void add_cache_map_entry(const std::type_info* tinf,
memory_cache* instance);
template <class T>
static inline memory_cache* get_or_set_cache_map_entry() {
auto mc = get_cache_map_entry(&typeid(T));
if (!mc) {
mc = new basic_memory_cache<T>;
add_cache_map_entry(&typeid(T), mc);
}
return mc;
}
};
#endif // CAF_NO_MEM_MANAGEMENT
} // namespace detail
} // namespace caf
#endif // CAF_DETAIL_MEMORY_HPP
<commit_msg>Add a maximum for pre-allocated objects<commit_after>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright (C) 2011 - 2014 *
* Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENCE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#ifndef CAF_DETAIL_MEMORY_HPP
#define CAF_DETAIL_MEMORY_HPP
#include <new>
#include <vector>
#include <memory>
#include <utility>
#include <typeinfo>
#include "caf/config.hpp"
#include "caf/ref_counted.hpp"
namespace caf {
class mailbox_element;
} // namespace caf
namespace caf {
namespace detail {
namespace {
constexpr size_t s_alloc_size = 1024 * 1024; // allocate ~1mb chunks
constexpr size_t s_cache_size = 10 * 1024 * 1024; // cache about 10mb per thread
constexpr size_t s_min_elements = 5; // don't create < 5 elements
constexpr size_t s_max_elements = 20; // don't create > 20 elements
} // namespace <anonymous>
struct disposer {
inline void operator()(memory_managed* ptr) const {
ptr->request_deletion();
}
};
class instance_wrapper {
public:
virtual ~instance_wrapper();
// calls the destructor
virtual void destroy() = 0;
// releases memory
virtual void deallocate() = 0;
};
class memory_cache {
public:
virtual ~memory_cache();
// calls dtor and either releases memory or re-uses it later
virtual void release_instance(void*) = 0;
virtual std::pair<instance_wrapper*, void*> new_instance() = 0;
// casts `ptr` to the derived type and returns it
virtual void* downcast(memory_managed* ptr) = 0;
};
class instance_wrapper;
template <class T>
class basic_memory_cache;
#ifdef CAF_NO_MEM_MANAGEMENT
class memory {
memory() = delete;
public:
// Allocates storage, initializes a new object, and returns the new instance.
template <class T, class... Ts>
static T* create(Ts&&... args) {
return new T(std::forward<Ts>(args)...);
}
static inline memory_cache* get_cache_map_entry(const std::type_info*) {
return nullptr;
}
};
#else // CAF_NO_MEM_MANAGEMENT
template <class T>
class basic_memory_cache : public memory_cache {
static constexpr size_t ne = s_alloc_size / sizeof(T);
static constexpr size_t ms = ne < s_min_elements ? s_min_elements : ne;
static constexpr size_t dsize = ms > s_max_elements ? s_max_elements : ms;
struct wrapper : instance_wrapper {
ref_counted* parent;
union {
T instance;
};
wrapper() : parent(nullptr) {}
~wrapper() {}
void destroy() { instance.~T(); }
void deallocate() { parent->deref(); }
};
class storage : public ref_counted {
public:
storage() {
for (auto& elem : data) {
// each instance has a reference to its parent
elem.parent = this;
ref(); // deref() is called in wrapper::deallocate
}
}
using iterator = wrapper*;
iterator begin() { return data; }
iterator end() { return begin() + dsize; }
private:
wrapper data[dsize];
};
public:
std::vector<wrapper*> cached_elements;
basic_memory_cache() { cached_elements.reserve(dsize); }
~basic_memory_cache() {
for (auto e : cached_elements) e->deallocate();
}
void* downcast(memory_managed* ptr) { return static_cast<T*>(ptr); }
void release_instance(void* vptr) override {
CAF_REQUIRE(vptr != nullptr);
auto ptr = reinterpret_cast<T*>(vptr);
CAF_REQUIRE(ptr->outer_memory != nullptr);
auto wptr = static_cast<wrapper*>(ptr->outer_memory);
wptr->destroy();
wptr->deallocate();
}
std::pair<instance_wrapper*, void*> new_instance() override {
if (cached_elements.empty()) {
auto elements = new storage;
for (auto i = elements->begin(); i != elements->end(); ++i) {
cached_elements.push_back(i);
}
}
wrapper* wptr = cached_elements.back();
cached_elements.pop_back();
return std::make_pair(wptr, &(wptr->instance));
}
};
class memory {
memory() = delete;
template <class>
friend class basic_memory_cache;
public:
// Allocates storage, initializes a new object, and returns the new instance.
template <class T, class... Ts>
static T* create(Ts&&... args) {
auto mc = get_or_set_cache_map_entry<T>();
auto p = mc->new_instance();
auto result = new (p.second) T(std::forward<Ts>(args)...);
result->outer_memory = p.first;
return result;
}
static memory_cache* get_cache_map_entry(const std::type_info* tinf);
private:
static void add_cache_map_entry(const std::type_info* tinf,
memory_cache* instance);
template <class T>
static inline memory_cache* get_or_set_cache_map_entry() {
auto mc = get_cache_map_entry(&typeid(T));
if (!mc) {
mc = new basic_memory_cache<T>;
add_cache_map_entry(&typeid(T), mc);
}
return mc;
}
};
#endif // CAF_NO_MEM_MANAGEMENT
} // namespace detail
} // namespace caf
#endif // CAF_DETAIL_MEMORY_HPP
<|endoftext|> |
<commit_before>#include "xor.h"
#include "../../utils/cz.h"
#include "../../utils/utils.h"
using namespace dariadb;
using namespace dariadb::compression::v2;
XorCompressor::XorCompressor(const ByteBuffer_Ptr &bw_)
: BaseCompressor(bw_), _is_first(true), _first(0), _prev_value(0) {}
bool XorCompressor::append(Value v) {
static_assert(sizeof(Value) == 8, "Value no x64 value");
auto flat = inner::flat_double_to_int(v);
if (_is_first) {
_first = flat;
_is_first = false;
_prev_value = flat;
return true;
}
uint64_t xor_val = _prev_value ^ flat;
if (xor_val == 0) {
if (bw->free_size() < 1) {
return false;
}
bw->write<uint8_t>(0);
return true;
}
uint8_t flag_byte=0;
auto lead = dariadb::utils::clz(xor_val);
auto tail = dariadb::utils::ctz(xor_val);
const size_t total_bits = sizeof(Value) * 8;
uint8_t count_of_bytes=(total_bits - lead - tail)/8+1;
flag_byte = count_of_bytes;
if (bw->free_size() < (count_of_bytes + 2)) {
return false;
}
bw->write(flag_byte);
bw->write(tail);
auto moved_value = xor_val >> tail;
const size_t buff_size = sizeof(uint64_t);
uint8_t buff[buff_size];
*reinterpret_cast<uint64_t*>(buff) = moved_value;
for (size_t i = 0; i < count_of_bytes; ++i) {
bw->write(buff[i]);
}
_prev_value = flat;
return true;
}
XorDeCompressor::XorDeCompressor(const ByteBuffer_Ptr &bw_, Value first)
: BaseCompressor(bw_), _prev_value(inner::flat_double_to_int(first)){}
dariadb::Value XorDeCompressor::read() {
static_assert(sizeof(dariadb::Value) == 8, "Value no x64 value");
auto flag_byte = bw->read<uint8_t>();
if (flag_byte == 0) {//prev==current
return inner::flat_int_to_double(_prev_value);
}
else {
auto byte_count = flag_byte;
auto move_count = bw->read<uint8_t>();
const size_t buff_size = sizeof(uint64_t);
uint8_t buff[buff_size];
std::fill_n(buff, buff_size, 0);
for (size_t i = 0; i < byte_count; ++i) {
buff[i] = bw->read<uint8_t>();
}
uint64_t raw_value = *reinterpret_cast<uint64_t*>(buff);
auto moved = raw_value << move_count;
auto ret = moved ^ _prev_value;
_prev_value = ret;
return inner::flat_int_to_double(ret);
}
}
<commit_msg>build. issue #210.<commit_after>#include "xor.h"
#include "../../utils/cz.h"
#include "../../utils/utils.h"
using namespace dariadb;
using namespace dariadb::compression::v2;
XorCompressor::XorCompressor(const ByteBuffer_Ptr &bw_)
: BaseCompressor(bw_), _is_first(true), _first(0), _prev_value(0) {}
bool XorCompressor::append(Value v) {
static_assert(sizeof(Value) == 8, "Value no x64 value");
auto flat = inner::flat_double_to_int(v);
if (_is_first) {
_first = flat;
_is_first = false;
_prev_value = flat;
return true;
}
uint64_t xor_val = _prev_value ^ flat;
if (xor_val == 0) {
if (bw->free_size() < 1) {
return false;
}
bw->write<uint8_t>(0);
return true;
}
uint8_t flag_byte=0;
auto lead = dariadb::utils::clz(xor_val);
auto tail = dariadb::utils::ctz(xor_val);
const size_t total_bits = sizeof(Value) * 8;
uint8_t count_of_bytes=(total_bits - lead - tail)/8+1;
flag_byte = count_of_bytes;
if (bw->free_size() < size_t(count_of_bytes + 2)) {
return false;
}
bw->write(flag_byte);
bw->write(tail);
auto moved_value = xor_val >> tail;
const size_t buff_size = sizeof(uint64_t);
uint8_t buff[buff_size];
*reinterpret_cast<uint64_t*>(buff) = moved_value;
for (size_t i = 0; i < count_of_bytes; ++i) {
bw->write(buff[i]);
}
_prev_value = flat;
return true;
}
XorDeCompressor::XorDeCompressor(const ByteBuffer_Ptr &bw_, Value first)
: BaseCompressor(bw_), _prev_value(inner::flat_double_to_int(first)){}
dariadb::Value XorDeCompressor::read() {
static_assert(sizeof(dariadb::Value) == 8, "Value no x64 value");
auto flag_byte = bw->read<uint8_t>();
if (flag_byte == 0) {//prev==current
return inner::flat_int_to_double(_prev_value);
}
else {
auto byte_count = flag_byte;
auto move_count = bw->read<uint8_t>();
const size_t buff_size = sizeof(uint64_t);
uint8_t buff[buff_size];
std::fill_n(buff, buff_size, 0);
for (size_t i = 0; i < byte_count; ++i) {
buff[i] = bw->read<uint8_t>();
}
uint64_t raw_value = *reinterpret_cast<uint64_t*>(buff);
auto moved = raw_value << move_count;
auto ret = moved ^ _prev_value;
_prev_value = ret;
return inner::flat_int_to_double(ret);
}
}
<|endoftext|> |
<commit_before>#include <assert.h>
#include "stdafx.h"
#include "overflow.h"
#include "kmp.h"
#include "aho-corasick.h"
struct num {
size_t val;
dequeue list;
};
int _tmain (int argc, TCHAR *argv[]) {
int32_t a = INT32_MIN, b = INT32_MIN;
int32_t c = 0;
assert (true == checked_add_32 (a, b, &c));
/*====================*/
const char *barn = "Loremipsumdolorsitamet,consecteturadipisicingelit,seddoeiusmodtemporincididuntutlaboreetdoloremagnaaliqua.Utenimadminimveniam,quisnostrudexercitationullamcolaborisnisiutaliquipexeacommodoconsequat.Duisauteiruredolorinreprehenderitinvoluptatevelitessecillumdoloreeufugiatnullapariatur.Excepteursintoccaecatcupidatatnonproident,suntinculpaquiofficiadeseruntmollitanimidestlaborum.";
const char test_success[] = "tempor";
const char test_fail[] = "participate in parachute";
int ff1[sizeof test_success] = {0};
kmp_ff (test_success, ff1, sizeof ff1 / sizeof *ff1);
assert (kmp (barn, test_success, ff1) == strstr(barn, test_success) - barn);
int ff2[sizeof test_fail] = {0};
kmp_ff (test_fail, ff2, sizeof ff2 / sizeof *ff2);
assert (kmp (barn, test_fail, ff2) == -1);
/*======================*/
dequeue (q1);
struct num n0, n1, n2;
n0.val = 0; n1.val = 1; n2.val = 2;
dequeue_enqueue (&q1, &n0.list);
dequeue_enqueue (&q1, &n1.list);
dequeue_enqueue (&q1, &n2.list);
for (; !dequeue_is_empty (&q1); ) {
struct num *t = dequeue_data (dequeue_pop_front (&q1), struct num, list);
printf ("%zu\n", t->val);
}
/*======================*/
struct ac_trie trie;
ac_trie_init (&trie);
ac_trie_insert (&trie, "she");
ac_trie_insert (&trie, "hers");
ac_trie_insert (&trie, "he");
ac_build_failure_function (&trie);
ac_result res = ac_search (&trie, "head of hers, OK?",
sizeof "head of hers, OK?", 0);
printf ("%zu %zu %zu", res.id, res.start, res.end);
for (size_t i = res.start; i < res.end; ++i) {
printf ("%c", "head of hers, OK?"[i]);
}
return 0;
}
<commit_msg>Remove redundant #include<commit_after>#include "stdafx.h"
#include "overflow.h"
#include "kmp.h"
#include "aho-corasick.h"
struct num {
size_t val;
dequeue list;
};
int _tmain (int argc, TCHAR *argv[]) {
int32_t a = INT32_MIN, b = INT32_MIN;
int32_t c = 0;
assert (true == checked_add_32 (a, b, &c));
/*====================*/
const char *barn = "Loremipsumdolorsitamet,consecteturadipisicingelit,seddoeiusmodtemporincididuntutlaboreetdoloremagnaaliqua.Utenimadminimveniam,quisnostrudexercitationullamcolaborisnisiutaliquipexeacommodoconsequat.Duisauteiruredolorinreprehenderitinvoluptatevelitessecillumdoloreeufugiatnullapariatur.Excepteursintoccaecatcupidatatnonproident,suntinculpaquiofficiadeseruntmollitanimidestlaborum.";
const char test_success[] = "tempor";
const char test_fail[] = "participate in parachute";
int ff1[sizeof test_success] = {0};
kmp_ff (test_success, ff1, sizeof ff1 / sizeof *ff1);
assert (kmp (barn, test_success, ff1) == strstr(barn, test_success) - barn);
int ff2[sizeof test_fail] = {0};
kmp_ff (test_fail, ff2, sizeof ff2 / sizeof *ff2);
assert (kmp (barn, test_fail, ff2) == -1);
/*======================*/
dequeue (q1);
struct num n0, n1, n2;
n0.val = 0; n1.val = 1; n2.val = 2;
dequeue_enqueue (&q1, &n0.list);
dequeue_enqueue (&q1, &n1.list);
dequeue_enqueue (&q1, &n2.list);
for (; !dequeue_is_empty (&q1); ) {
struct num *t = dequeue_data (dequeue_pop_front (&q1), struct num, list);
printf ("%zu\n", t->val);
}
/*======================*/
struct ac_trie trie;
ac_trie_init (&trie);
ac_trie_insert (&trie, "she");
ac_trie_insert (&trie, "hers");
ac_trie_insert (&trie, "he");
ac_build_failure_function (&trie);
ac_result res = ac_search (&trie, "head of hers, OK?",
sizeof "head of hers, OK?", 0);
printf ("%zu %zu %zu", res.id, res.start, res.end);
for (size_t i = res.start; i < res.end; ++i) {
printf ("%c", "head of hers, OK?"[i]);
}
return 0;
}
<|endoftext|> |
<commit_before>#include "Scale9.h"
#include "S2_Sprite.h"
#include "S2_Symbol.h"
#include "DrawNode.h"
#include <SM_Calc.h>
#include <string.h>
#include <assert.h>
namespace s2
{
Scale9::Scale9()
: m_type(S9_NULL)
, m_width(0)
, m_height(0)
{
memset(m_grids, 0, sizeof(m_grids));
}
Scale9::Scale9(const Scale9& s9)
{
this->operator = (s9);
}
Scale9& Scale9::operator = (const Scale9& s9)
{
m_type = s9.m_type;
m_width = s9.m_width;
m_height = s9.m_height;
for (int i = 0; i < 9; ++i) {
Sprite* spr = s9.m_grids[i];
if (spr) {
#ifdef S2_VIRTUAL_INHERITANCE
m_grids[i] = dynamic_cast<Sprite*>(((cu::Cloneable*)spr)->Clone());
#else
m_grids[i] = spr->Clone();
#endif // S2_VIRTUAL_INHERITANCE
} else {
m_grids[i] = NULL;
}
}
return *this;
}
Scale9::~Scale9()
{
for (int i = 0; i < 9; ++i) {
if (m_grids[i]) {
m_grids[i]->RemoveReference();
}
}
}
void Scale9::Draw(const RenderParams& params) const
{
for (int i = 0; i < 9; ++i) {
if (m_grids[i]) {
DrawNode::Draw(m_grids[i], params);
}
}
}
void Scale9::SetSize(float width, float height)
{
if (m_width == width && m_height == height) {
return;
}
m_width = width;
m_height = height;
switch (m_type)
{
case S9_9GRID:
{
float w0 = m_grids[S9_DOWN_LEFT]->GetSymbol()->GetBounding().Size().x,
w2 = m_grids[S9_DOWN_RIGHT]->GetSymbol()->GetBounding().Size().x,
w1 = width - w0 - w2;
float h0 = m_grids[S9_DOWN_LEFT]->GetSymbol()->GetBounding().Size().y,
h2 = m_grids[S9_DOWN_RIGHT]->GetSymbol()->GetBounding().Size().y,
h1 = height - h0 - h2;
ResizeSprite(m_grids[S9_DOWN_LEFT], sm::vec2(-w0*0.5f-w1*0.5f, -h0*0.5f-h1*0.5f), w0, h0);
ResizeSprite(m_grids[S9_DOWN_CENTER], sm::vec2(0.0f, -h0*0.5f-h1*0.5f), w1, h0);
ResizeSprite(m_grids[S9_DOWN_RIGHT], sm::vec2(w1*0.5f+w2*0.5f, -h0*0.5f-h1*0.5f), w2, h0);
ResizeSprite(m_grids[S9_MID_LEFT], sm::vec2(-w0*0.5f-w1*0.5f, 0.0f), w0, h1);
ResizeSprite(m_grids[S9_MID_CENTER], sm::vec2(0.0f, 0.0f), w1, h1);
ResizeSprite(m_grids[S9_MID_RIGHT], sm::vec2(w1*0.5f+w2*0.5f, 0.0f), w2, h1);
ResizeSprite(m_grids[S9_TOP_LEFT], sm::vec2(-w0*0.5f-w1*0.5f, h1*0.5f+h2*0.5f), w0, h2);
ResizeSprite(m_grids[S9_TOP_CENTER], sm::vec2(0.0f, h1*0.5f+h2*0.5f), w1, h2);
ResizeSprite(m_grids[S9_TOP_RIGHT], sm::vec2(w1*0.5f+w2*0.5f, h1*0.5f+h2*0.5f), w2, h2);
}
break;
case S9_9GRID_HOLLOW:
{
float w0 = m_grids[S9_DOWN_LEFT]->GetSymbol()->GetBounding().Size().x,
w2 = m_grids[S9_DOWN_RIGHT]->GetSymbol()->GetBounding().Size().x,
w1 = width - w0 - w2;
float h0 = m_grids[S9_DOWN_LEFT]->GetSymbol()->GetBounding().Size().y,
h2 = m_grids[S9_DOWN_RIGHT]->GetSymbol()->GetBounding().Size().y,
h1 = height - h0 - h2;
ResizeSprite(m_grids[S9_DOWN_LEFT], sm::vec2(-w0*0.5f-w1*0.5f, -h0*0.5f-h1*0.5f), w0, h0);
ResizeSprite(m_grids[S9_DOWN_CENTER], sm::vec2(0.0f, -h0*0.5f-h1*0.5f), w1, h0);
ResizeSprite(m_grids[S9_DOWN_RIGHT], sm::vec2(w1*0.5f+w2*0.5f, -h0*0.5f-h1*0.5f), w2, h0);
ResizeSprite(m_grids[S9_MID_LEFT], sm::vec2(-w0*0.5f-w1*0.5f, 0.0f), w0, h1);
ResizeSprite(m_grids[S9_MID_RIGHT], sm::vec2(w1*0.5f+w2*0.5f, 0.0f), w2, h1);
ResizeSprite(m_grids[S9_TOP_LEFT], sm::vec2(-w0*0.5f-w1*0.5f, h1*0.5f+h2*0.5f), w0, h2);
ResizeSprite(m_grids[S9_TOP_CENTER], sm::vec2(0.0f, h1*0.5f+h2*0.5f), w1, h2);
ResizeSprite(m_grids[S9_TOP_RIGHT], sm::vec2(w1*0.5f+w2*0.5f, h1*0.5f+h2*0.5f), w2, h2);
}
break;
case S9_6GRID_UPPER:
{
float w0 = m_grids[S9_TOP_LEFT]->GetSymbol()->GetBounding().Size().x,
w2 = m_grids[S9_TOP_RIGHT]->GetSymbol()->GetBounding().Size().x,
w1 = width - w0 - w2;
float h2 = m_grids[S9_TOP_LEFT]->GetSymbol()->GetBounding().Size().y,
h1 = height - h2;
ResizeSprite(m_grids[S9_MID_LEFT], sm::vec2(-w0*0.5f-w1*0.5f, 0.0f), w0, h1);
ResizeSprite(m_grids[S9_MID_CENTER], sm::vec2(0.0f, 0.0f), w1, h1);
ResizeSprite(m_grids[S9_MID_RIGHT], sm::vec2(w1*0.5f+w2*0.5f, 0.0f), w2, h1);
ResizeSprite(m_grids[S9_TOP_LEFT], sm::vec2(-w0*0.5f-w1*0.5f, h1*0.5f+h2*0.5f), w0, h2);
ResizeSprite(m_grids[S9_TOP_CENTER], sm::vec2(0.0f, h1*0.5f+h2*0.5f), w1, h2);
ResizeSprite(m_grids[S9_TOP_RIGHT], sm::vec2(w1*0.5f+w2*0.5f, h1*0.5f+h2*0.5f), w2, h2);
}
break;
case S9_3GRID_HORI:
{
float w0 = m_grids[S9_MID_LEFT]->GetSymbol()->GetBounding().Size().x,
w2 = m_grids[S9_MID_RIGHT]->GetSymbol()->GetBounding().Size().x,
w1 = width - w0 - w2;
ResizeSprite(m_grids[S9_MID_LEFT], sm::vec2(-w0*0.5f-w1*0.5f, 0.0f), w0, height);
ResizeSprite(m_grids[S9_MID_CENTER], sm::vec2(0.0f, 0.0f), w1, height);
ResizeSprite(m_grids[S9_MID_RIGHT], sm::vec2(w1*0.5f+w2*0.5f, 0.0f), w2, height);
}
break;
case S9_3GRID_VERT:
{
float h0 = m_grids[S9_DOWN_CENTER]->GetSymbol()->GetBounding().Size().y,
h2 = m_grids[S9_TOP_CENTER]->GetSymbol()->GetBounding().Size().y,
h1 = height - h0 - h2;
ResizeSprite(m_grids[S9_DOWN_CENTER], sm::vec2(0.0f, -h0*0.5f-h1*0.5f), width, h0);
ResizeSprite(m_grids[S9_MID_CENTER], sm::vec2(0.0f, 0.0f), width, h1);
ResizeSprite(m_grids[S9_TOP_CENTER], sm::vec2(0.0f, h1*0.5f+h2*0.5f), width, h2);
}
break;
}
}
void Scale9::Build(SCALE9_TYPE type, int w, int h, Sprite* grids[9])
{
m_type = type;
for (int i = 0; i < 9; ++i)
{
Sprite* dst = m_grids[i];
if (dst) {
dst->RemoveReference();
}
Sprite* src = grids[i];
if (src) {
#ifdef S2_VIRTUAL_INHERITANCE
m_grids[i] = dynamic_cast<Sprite*>(((cu::Cloneable*)src)->Clone());
#else
m_grids[i] = src->Clone();
#endif // S2_VIRTUAL_INHERITANCE
} else {
m_grids[i] = NULL;
}
}
SetSize(w, h);
}
void Scale9::GetGrids(std::vector<Sprite*>& grids) const
{
for (int i = 0; i < 9; ++i) {
if (m_grids[i]) {
grids.push_back(m_grids[i]);
}
}
}
SCALE9_TYPE Scale9::CheckType(Sprite* grids[9])
{
SCALE9_TYPE type = S9_NULL;
do {
// S9_9GRID
type = S9_9GRID;
for (int i = 0; i < 9; ++i) {
if (!grids[i]) {
type = S9_NULL;
break;
}
}
if (type != S9_NULL) break;
// S9_9GRID_HOLLOW
type = S9_9GRID_HOLLOW;
for (int i = 0; i < 9; ++i) {
if (i == 4) {
continue;
}
if (!grids[i]) {
type = S9_NULL;
break;
}
}
if (type != S9_NULL) break;
// S9_6GRID_UPPER
type = S9_6GRID_UPPER;
for (int i = 3; i < 9; ++i) {
if (!grids[i]) {
type = S9_NULL;
break;
}
}
if (type != S9_NULL) break;
// S9_3GRID_HORI
if (grids[3] && grids[4] && grids[5]) {
type = S9_3GRID_HORI;
}
// S9_3GRID_VERT
if (grids[1] && grids[4] && grids[7]) {
type = S9_3GRID_VERT;
}
} while (false);
return type;
}
void Scale9::ResizeSprite(Sprite* spr, const sm::vec2& center,
float width, float height)
{
if (width < 0) { width = 1; }
if (height < 0) { height = 1; }
Symbol* sym = spr->GetSymbol();
sm::vec2 sz = sym->GetBounding(spr).Size();
assert(sz.x != 0 && sz.y != 0);
spr->SetPosition(center);
const sm::vec2& old_scale = spr->GetScale();
sm::vec2 new_scale;
const float times = spr->GetAngle() / SM_PI;
if (times - (int)(times + 0.01f) < 0.3f) {
new_scale.Set(width / sz.x, height / sz.y);
} else {
new_scale.Set(height / sz.x, width / sz.y);
}
if (old_scale.x < 0) {
new_scale.x = -new_scale.x;
}
if (old_scale.y < 0) {
new_scale.y = -new_scale.y;
}
spr->SetScale(new_scale);
spr->Translate(sm::rotate_vector(spr->GetOffset(), spr->GetAngle()) - spr->GetOffset());
}
}<commit_msg>[FIXED] s9 build<commit_after>#include "Scale9.h"
#include "S2_Sprite.h"
#include "S2_Symbol.h"
#include "DrawNode.h"
#include <SM_Calc.h>
#include <string.h>
#include <assert.h>
namespace s2
{
Scale9::Scale9()
: m_type(S9_NULL)
, m_width(0)
, m_height(0)
{
memset(m_grids, 0, sizeof(m_grids));
}
Scale9::Scale9(const Scale9& s9)
{
this->operator = (s9);
}
Scale9& Scale9::operator = (const Scale9& s9)
{
m_type = s9.m_type;
m_width = s9.m_width;
m_height = s9.m_height;
for (int i = 0; i < 9; ++i) {
Sprite* spr = s9.m_grids[i];
if (spr) {
#ifdef S2_VIRTUAL_INHERITANCE
m_grids[i] = dynamic_cast<Sprite*>(((cu::Cloneable*)spr)->Clone());
#else
m_grids[i] = spr->Clone();
#endif // S2_VIRTUAL_INHERITANCE
} else {
m_grids[i] = NULL;
}
}
return *this;
}
Scale9::~Scale9()
{
for (int i = 0; i < 9; ++i) {
if (m_grids[i]) {
m_grids[i]->RemoveReference();
}
}
}
void Scale9::Draw(const RenderParams& params) const
{
for (int i = 0; i < 9; ++i) {
if (m_grids[i]) {
DrawNode::Draw(m_grids[i], params);
}
}
}
void Scale9::SetSize(float width, float height)
{
if (m_width == width && m_height == height) {
return;
}
m_width = width;
m_height = height;
switch (m_type)
{
case S9_9GRID:
{
float w0 = m_grids[S9_DOWN_LEFT]->GetSymbol()->GetBounding().Size().x,
w2 = m_grids[S9_DOWN_RIGHT]->GetSymbol()->GetBounding().Size().x,
w1 = width - w0 - w2;
float h0 = m_grids[S9_DOWN_LEFT]->GetSymbol()->GetBounding().Size().y,
h2 = m_grids[S9_DOWN_RIGHT]->GetSymbol()->GetBounding().Size().y,
h1 = height - h0 - h2;
ResizeSprite(m_grids[S9_DOWN_LEFT], sm::vec2(-w0*0.5f-w1*0.5f, -h0*0.5f-h1*0.5f), w0, h0);
ResizeSprite(m_grids[S9_DOWN_CENTER], sm::vec2(0.0f, -h0*0.5f-h1*0.5f), w1, h0);
ResizeSprite(m_grids[S9_DOWN_RIGHT], sm::vec2(w1*0.5f+w2*0.5f, -h0*0.5f-h1*0.5f), w2, h0);
ResizeSprite(m_grids[S9_MID_LEFT], sm::vec2(-w0*0.5f-w1*0.5f, 0.0f), w0, h1);
ResizeSprite(m_grids[S9_MID_CENTER], sm::vec2(0.0f, 0.0f), w1, h1);
ResizeSprite(m_grids[S9_MID_RIGHT], sm::vec2(w1*0.5f+w2*0.5f, 0.0f), w2, h1);
ResizeSprite(m_grids[S9_TOP_LEFT], sm::vec2(-w0*0.5f-w1*0.5f, h1*0.5f+h2*0.5f), w0, h2);
ResizeSprite(m_grids[S9_TOP_CENTER], sm::vec2(0.0f, h1*0.5f+h2*0.5f), w1, h2);
ResizeSprite(m_grids[S9_TOP_RIGHT], sm::vec2(w1*0.5f+w2*0.5f, h1*0.5f+h2*0.5f), w2, h2);
}
break;
case S9_9GRID_HOLLOW:
{
float w0 = m_grids[S9_DOWN_LEFT]->GetSymbol()->GetBounding().Size().x,
w2 = m_grids[S9_DOWN_RIGHT]->GetSymbol()->GetBounding().Size().x,
w1 = width - w0 - w2;
float h0 = m_grids[S9_DOWN_LEFT]->GetSymbol()->GetBounding().Size().y,
h2 = m_grids[S9_DOWN_RIGHT]->GetSymbol()->GetBounding().Size().y,
h1 = height - h0 - h2;
ResizeSprite(m_grids[S9_DOWN_LEFT], sm::vec2(-w0*0.5f-w1*0.5f, -h0*0.5f-h1*0.5f), w0, h0);
ResizeSprite(m_grids[S9_DOWN_CENTER], sm::vec2(0.0f, -h0*0.5f-h1*0.5f), w1, h0);
ResizeSprite(m_grids[S9_DOWN_RIGHT], sm::vec2(w1*0.5f+w2*0.5f, -h0*0.5f-h1*0.5f), w2, h0);
ResizeSprite(m_grids[S9_MID_LEFT], sm::vec2(-w0*0.5f-w1*0.5f, 0.0f), w0, h1);
ResizeSprite(m_grids[S9_MID_RIGHT], sm::vec2(w1*0.5f+w2*0.5f, 0.0f), w2, h1);
ResizeSprite(m_grids[S9_TOP_LEFT], sm::vec2(-w0*0.5f-w1*0.5f, h1*0.5f+h2*0.5f), w0, h2);
ResizeSprite(m_grids[S9_TOP_CENTER], sm::vec2(0.0f, h1*0.5f+h2*0.5f), w1, h2);
ResizeSprite(m_grids[S9_TOP_RIGHT], sm::vec2(w1*0.5f+w2*0.5f, h1*0.5f+h2*0.5f), w2, h2);
}
break;
case S9_6GRID_UPPER:
{
float w0 = m_grids[S9_TOP_LEFT]->GetSymbol()->GetBounding().Size().x,
w2 = m_grids[S9_TOP_RIGHT]->GetSymbol()->GetBounding().Size().x,
w1 = width - w0 - w2;
float h2 = m_grids[S9_TOP_LEFT]->GetSymbol()->GetBounding().Size().y,
h1 = height - h2;
ResizeSprite(m_grids[S9_MID_LEFT], sm::vec2(-w0*0.5f-w1*0.5f, 0.0f), w0, h1);
ResizeSprite(m_grids[S9_MID_CENTER], sm::vec2(0.0f, 0.0f), w1, h1);
ResizeSprite(m_grids[S9_MID_RIGHT], sm::vec2(w1*0.5f+w2*0.5f, 0.0f), w2, h1);
ResizeSprite(m_grids[S9_TOP_LEFT], sm::vec2(-w0*0.5f-w1*0.5f, h1*0.5f+h2*0.5f), w0, h2);
ResizeSprite(m_grids[S9_TOP_CENTER], sm::vec2(0.0f, h1*0.5f+h2*0.5f), w1, h2);
ResizeSprite(m_grids[S9_TOP_RIGHT], sm::vec2(w1*0.5f+w2*0.5f, h1*0.5f+h2*0.5f), w2, h2);
}
break;
case S9_3GRID_HORI:
{
float w0 = m_grids[S9_MID_LEFT]->GetSymbol()->GetBounding().Size().x,
w2 = m_grids[S9_MID_RIGHT]->GetSymbol()->GetBounding().Size().x,
w1 = width - w0 - w2;
ResizeSprite(m_grids[S9_MID_LEFT], sm::vec2(-w0*0.5f-w1*0.5f, 0.0f), w0, height);
ResizeSprite(m_grids[S9_MID_CENTER], sm::vec2(0.0f, 0.0f), w1, height);
ResizeSprite(m_grids[S9_MID_RIGHT], sm::vec2(w1*0.5f+w2*0.5f, 0.0f), w2, height);
}
break;
case S9_3GRID_VERT:
{
float h0 = m_grids[S9_DOWN_CENTER]->GetSymbol()->GetBounding().Size().y,
h2 = m_grids[S9_TOP_CENTER]->GetSymbol()->GetBounding().Size().y,
h1 = height - h0 - h2;
ResizeSprite(m_grids[S9_DOWN_CENTER], sm::vec2(0.0f, -h0*0.5f-h1*0.5f), width, h0);
ResizeSprite(m_grids[S9_MID_CENTER], sm::vec2(0.0f, 0.0f), width, h1);
ResizeSprite(m_grids[S9_TOP_CENTER], sm::vec2(0.0f, h1*0.5f+h2*0.5f), width, h2);
}
break;
}
}
void Scale9::Build(SCALE9_TYPE type, int w, int h, Sprite* grids[9])
{
m_type = type;
m_width = m_height = 0;
for (int i = 0; i < 9; ++i)
{
Sprite* dst = m_grids[i];
if (dst) {
dst->RemoveReference();
}
Sprite* src = grids[i];
if (src) {
#ifdef S2_VIRTUAL_INHERITANCE
m_grids[i] = dynamic_cast<Sprite*>(((cu::Cloneable*)src)->Clone());
#else
m_grids[i] = src->Clone();
#endif // S2_VIRTUAL_INHERITANCE
} else {
m_grids[i] = NULL;
}
}
SetSize(w, h);
}
void Scale9::GetGrids(std::vector<Sprite*>& grids) const
{
for (int i = 0; i < 9; ++i) {
if (m_grids[i]) {
grids.push_back(m_grids[i]);
}
}
}
SCALE9_TYPE Scale9::CheckType(Sprite* grids[9])
{
SCALE9_TYPE type = S9_NULL;
do {
// S9_9GRID
type = S9_9GRID;
for (int i = 0; i < 9; ++i) {
if (!grids[i]) {
type = S9_NULL;
break;
}
}
if (type != S9_NULL) break;
// S9_9GRID_HOLLOW
type = S9_9GRID_HOLLOW;
for (int i = 0; i < 9; ++i) {
if (i == 4) {
continue;
}
if (!grids[i]) {
type = S9_NULL;
break;
}
}
if (type != S9_NULL) break;
// S9_6GRID_UPPER
type = S9_6GRID_UPPER;
for (int i = 3; i < 9; ++i) {
if (!grids[i]) {
type = S9_NULL;
break;
}
}
if (type != S9_NULL) break;
// S9_3GRID_HORI
if (grids[3] && grids[4] && grids[5]) {
type = S9_3GRID_HORI;
}
// S9_3GRID_VERT
if (grids[1] && grids[4] && grids[7]) {
type = S9_3GRID_VERT;
}
} while (false);
return type;
}
void Scale9::ResizeSprite(Sprite* spr, const sm::vec2& center,
float width, float height)
{
if (width < 0) { width = 1; }
if (height < 0) { height = 1; }
Symbol* sym = spr->GetSymbol();
sm::vec2 sz = sym->GetBounding(spr).Size();
assert(sz.x != 0 && sz.y != 0);
spr->SetPosition(center);
const sm::vec2& old_scale = spr->GetScale();
sm::vec2 new_scale;
const float times = spr->GetAngle() / SM_PI;
if (times - (int)(times + 0.01f) < 0.3f) {
new_scale.Set(width / sz.x, height / sz.y);
} else {
new_scale.Set(height / sz.x, width / sz.y);
}
if (old_scale.x < 0) {
new_scale.x = -new_scale.x;
}
if (old_scale.y < 0) {
new_scale.y = -new_scale.y;
}
spr->SetScale(new_scale);
spr->Translate(sm::rotate_vector(spr->GetOffset(), spr->GetAngle()) - spr->GetOffset());
}
}<|endoftext|> |
<commit_before>#include "InventoryTransitions.h"
#include "com/mojang/minecraftpe/client/gui/screen/Screen.h"
std::shared_ptr<Touch::TButton> InventoryTransitions::forwardButton = NULL;
std::shared_ptr<Touch::TButton> InventoryTransitions::backButton = NULL;
void InventoryTransitions::init(Screen* self)
{
if(!forwardButton)
{
forwardButton = std::make_shared<Touch::TButton>(0, ">", self->mcClient, false, 0x7FFFFFFF);
forwardButton->init(self->mcClient);
}
if(!backButton)
{
backButton = std::make_shared<Touch::TButton>(1, "<", self->mcClient, false, 0x7FFFFFFF);
backButton->init(self->mcClient);
}
self->buttonList.emplace_back(forwardButton);
self->buttonList.emplace_back(backButton);
}
void InventoryTransitions::setupPositions(Screen* self)
{
forwardButton->xPosition = self->width - 25;
forwardButton->yPosition = self->height - 20;
forwardButton->width = 20;
forwardButton->height = 20;
backButton->xPosition = self->width - 50;
backButton->yPosition = self->height - 20;
backButton->width = 20;
backButton->height = 20;
}
void InventoryTransitions::render(Screen* self, int i1, int i2, float f1)
{
self->drawString(self->font, "1 / 2", 5, self->height - 15, Color::WHITE);
}
void InventoryTransitions::_buttonClicked(Screen* self, Button& button)
{
}<commit_msg>Take A Look<commit_after>#include "InventoryTransitions.h"
#include "com/mojang/minecraftpe/client/gui/screen/Screen.h"
std::shared_ptr<Touch::TButton> InventoryTransitions::forwardButton = NULL;
std::shared_ptr<Touch::TButton> InventoryTransitions::backButton = NULL;
void InventoryTransitions::init(Screen* self)
{
//if gamemode == creative
if(!forwardButton)
{
forwardButton = std::make_shared<Touch::TButton>(0, ">", self->mcClient, false, 0x7FFFFFFF);
forwardButton->init(self->mcClient);
}
if(!backButton)
{
backButton = std::make_shared<Touch::TButton>(1, "<", self->mcClient, false, 0x7FFFFFFF);
backButton->init(self->mcClient);
}
self->buttonList.emplace_back(forwardButton);
self->buttonList.emplace_back(backButton);
}
void InventoryTransitions::setupPositions(Screen* self)
{
forwardButton->xPosition = self->width - 25;
forwardButton->yPosition = self->height - 20;
forwardButton->width = 20;
forwardButton->height = 20;
backButton->xPosition = self->width - 50;
backButton->yPosition = self->height - 20;
backButton->width = 20;
backButton->height = 20;
}
void InventoryTransitions::render(Screen* self, int i1, int i2, float f1)
{
self->drawString(self->font, "1 / 2", 5, self->height - 15, Color::WHITE);
}
void InventoryTransitions::_buttonClicked(Screen* self, Button& button)
{
if(forwardButton->pressed)
{
//do code here
}
if(backButton->pressed)
{
//do code here
}
}<|endoftext|> |
<commit_before>#include "builders/terrain/TerraGenerator.hpp"
#include <functional>
#include <unordered_map>
using namespace ClipperLib;
using namespace utymap::builders;
using namespace utymap::mapcss;
using namespace utymap::meshing;
using namespace utymap::utils;
using namespace std::placeholders;
namespace {
const double AreaTolerance = 1000; // Tolerance for meshing
const double Scale = 1E7;
const std::string TerrainMeshName = "terrain";
const std::string ColorNoiseFreqKey = "color-noise-freq";
const std::string EleNoiseFreqKey = "ele-noise-freq";
const std::string GradientKey = "color";
const std::string MaxAreaKey = "max-area";
const std::string HeightOffsetKey = "height-offset";
const std::string LayerPriorityKey = "layer-priority";
const std::string MeshNameKey = "mesh-name";
const std::string MeshExtrasKey = "mesh-extras";
const std::string GridCellSize = "grid-cell-size";
const std::unordered_map<std::string, TerraExtras::ExtrasFunc> ExtrasFuncs =
{
{ "forest", std::bind(&TerraExtras::addForest, _1, _2) },
{ "water", std::bind(&TerraExtras::addWater, _1, _2) },
};
};
TerraGenerator::TerraGenerator(const BuilderContext& context, const Style& style, ClipperEx& foregroundClipper) :
context_(context),
style_(style),
foregroundClipper_(foregroundClipper),
backGroundClipper_(),
mesh_(TerrainMeshName),
rect_(context.boundingBox.minPoint.longitude,
context.boundingBox.minPoint.latitude,
context.boundingBox.maxPoint.longitude,
context.boundingBox.maxPoint.latitude)
{
}
void TerraGenerator::addRegion(const std::string& type, std::unique_ptr<Region> region)
{
layers_[type].push(std::move(region));
}
void TerraGenerator::generate(Path& tileRect)
{
double size = style_.getValue(GridCellSize,
context_.boundingBox.maxPoint.latitude - context_.boundingBox.minPoint.latitude,
context_.boundingBox.center());
splitter_.setParams(Scale, size);
buildLayers();
buildBackground(tileRect);
context_.meshCallback(mesh_);
}
// process all found layers.
void TerraGenerator::buildLayers()
{
// 1. process layers: regions with shared properties.
std::stringstream ss(style_.getString(LayerPriorityKey));
while (ss.good()) {
std::string name;
getline(ss, name, ',');
auto layer = layers_.find(name);
if (layer != layers_.end()) {
buildFromRegions(layer->second, createRegionContext(style_, name + "-"));
layers_.erase(layer);
}
}
// 2. Process the rest: each region has already its own properties.
for (auto& layer : layers_)
while (!layer.second.empty()) {
auto& region = layer.second.top();
buildFromPaths(region->points, *region->context);
layer.second.pop();
}
}
// process the rest area.
void TerraGenerator::buildBackground(Path& tileRect)
{
backGroundClipper_.AddPath(tileRect, ptSubject, true);
Paths background;
backGroundClipper_.Execute(ctDifference, background, pftNonZero, pftNonZero);
backGroundClipper_.Clear();
if (!background.empty())
populateMesh(background, createRegionContext(style_, ""));
}
TerraGenerator::RegionContext TerraGenerator::createRegionContext(const Style& style, const std::string& prefix) const
{
double quadKeyWidth = context_.boundingBox.maxPoint.latitude - context_.boundingBox.minPoint.latitude;
MeshBuilder::GeometryOptions geometryOptions(
style.getValue(prefix + MaxAreaKey, quadKeyWidth * quadKeyWidth),
style.getValue(prefix + EleNoiseFreqKey, quadKeyWidth),
std::numeric_limits<double>::lowest(), // no fixed elevation
style.getValue(prefix + HeightOffsetKey, quadKeyWidth),
false, // no flip
false, // no back side
1 // no new vertices on boundaries
);
MeshBuilder::AppearanceOptions apperanceOptions(
context_.styleProvider.getGradient(style.getString(prefix + GradientKey)),
style.getValue(prefix + ColorNoiseFreqKey, quadKeyWidth),
utymap::mapcss::TextureRegion(),
0 // texture scale
);
return TerraGenerator::RegionContext(style, prefix, geometryOptions, apperanceOptions);
}
void TerraGenerator::buildFromRegions(Regions& regions, const RegionContext& regionContext)
{
// merge all regions together
Clipper clipper;
while (!regions.empty()) {
clipper.AddPaths(regions.top()->points, ptSubject, true);
regions.pop();
}
Paths result;
clipper.Execute(ctUnion, result, pftNonZero, pftNonZero);
buildFromPaths(result, regionContext);
}
void TerraGenerator::buildFromPaths(const Paths& paths, const RegionContext& regionContext)
{
Paths solution;
foregroundClipper_.AddPaths(paths, ptSubject, true);
foregroundClipper_.Execute(ctDifference, solution, pftNonZero, pftNonZero);
foregroundClipper_.moveSubjectToClip();
populateMesh(solution, regionContext);
}
void TerraGenerator::populateMesh(Paths& paths, const RegionContext& regionContext)
{
ClipperLib::SimplifyPolygons(paths);
ClipperLib::CleanPolygons(paths);
bool hasHeightOffset = std::abs(regionContext.geometryOptions.heightOffset) > 1E-8;
// calculate approximate size of overall points
double size = 0;
for (std::size_t i = 0; i < paths.size(); ++i)
size += paths[i].size() * 1.5;
Polygon polygon(static_cast<std::size_t>(size));
for (const Path& path : paths) {
double area = ClipperLib::Area(path);
bool isHole = area < 0;
if (std::abs(area) < AreaTolerance)
continue;
backGroundClipper_.AddPath(path, ptClip, true);
Points points = restorePoints(path);
if (isHole)
polygon.addHole(points);
else
polygon.addContour(points);
if (hasHeightOffset)
processHeightOffset(points, regionContext);
}
if (!polygon.points.empty())
fillMesh(polygon, regionContext);
}
// restores mesh points from clipper points and injects new ones according to grid.
TerraGenerator::Points TerraGenerator::restorePoints(const Path& path) const
{
auto lastItemIndex = path.size() - 1;
Points points;
points.reserve(path.size());
for (int i = 0; i <= lastItemIndex; i++)
splitter_.split(path[i], path[i == lastItemIndex ? 0 : i + 1], points);
return std::move(points);
}
void TerraGenerator::fillMesh(Polygon& polygon, const RegionContext& regionContext)
{
std::string meshName = regionContext.style.getString(regionContext.prefix + MeshNameKey);
if (!meshName.empty()) {
Mesh polygonMesh(meshName);
TerraExtras::Context extrasContext(polygonMesh, regionContext.style);
context_.meshBuilder.addPolygon(polygonMesh,
polygon,
regionContext.geometryOptions,
regionContext.appearanceOptions);
addExtrasIfNecessary(polygonMesh, extrasContext, regionContext);
context_.meshCallback(polygonMesh);
}
else {
TerraExtras::Context extrasContext(mesh_, regionContext.style);
context_.meshBuilder.addPolygon(mesh_,
polygon,
regionContext.geometryOptions,
regionContext.appearanceOptions);
addExtrasIfNecessary(mesh_, extrasContext, regionContext);
}
}
void TerraGenerator::addExtrasIfNecessary(utymap::meshing::Mesh& mesh,
TerraExtras::Context& extrasContext,
const RegionContext& regionContext) const
{
std::string meshExtras = regionContext.style.getString(regionContext.prefix + MeshExtrasKey);
if (meshExtras.empty())
return;
ExtrasFuncs.at(meshExtras)(context_, extrasContext);
}
void TerraGenerator::processHeightOffset(const Points& points, const RegionContext& regionContext)
{
// do not use elevation noise for height offset.
auto newGeometryOptions = regionContext.geometryOptions;
newGeometryOptions.eleNoiseFreq = 0;
for (std::size_t i = 0; i < points.size(); ++i) {
Vector2 p1 = points[i];
Vector2 p2 = points[i == (points.size() - 1) ? 0 : i + 1];
// check whether two points are on cell rect
if (rect_.isOnBorder(p1) && rect_.isOnBorder(p2))
continue;
context_.meshBuilder.addPlane(mesh_, p1, p2, newGeometryOptions, regionContext.appearanceOptions);
}
}
<commit_msg>core: use texture in terrain generator<commit_after>#include "builders/terrain/TerraGenerator.hpp"
#include <functional>
#include <unordered_map>
using namespace ClipperLib;
using namespace utymap::builders;
using namespace utymap::mapcss;
using namespace utymap::meshing;
using namespace utymap::utils;
using namespace std::placeholders;
namespace {
const double AreaTolerance = 1000; // Tolerance for meshing
const double Scale = 1E7;
const std::string TerrainMeshName = "terrain";
const std::string ColorNoiseFreqKey = "color-noise-freq";
const std::string EleNoiseFreqKey = "ele-noise-freq";
const std::string GradientKey = "color";
const std::string MaterialKey = "material";
const std::string MaxAreaKey = "max-area";
const std::string HeightOffsetKey = "height-offset";
const std::string LayerPriorityKey = "layer-priority";
const std::string MeshNameKey = "mesh-name";
const std::string MeshExtrasKey = "mesh-extras";
const std::string GridCellSize = "grid-cell-size";
const std::unordered_map<std::string, TerraExtras::ExtrasFunc> ExtrasFuncs =
{
{ "forest", std::bind(&TerraExtras::addForest, _1, _2) },
{ "water", std::bind(&TerraExtras::addWater, _1, _2) },
};
};
TerraGenerator::TerraGenerator(const BuilderContext& context, const Style& style, ClipperEx& foregroundClipper) :
context_(context),
style_(style),
foregroundClipper_(foregroundClipper),
backGroundClipper_(),
mesh_(TerrainMeshName),
rect_(context.boundingBox.minPoint.longitude,
context.boundingBox.minPoint.latitude,
context.boundingBox.maxPoint.longitude,
context.boundingBox.maxPoint.latitude)
{
}
void TerraGenerator::addRegion(const std::string& type, std::unique_ptr<Region> region)
{
layers_[type].push(std::move(region));
}
void TerraGenerator::generate(Path& tileRect)
{
double size = style_.getValue(GridCellSize,
context_.boundingBox.maxPoint.latitude - context_.boundingBox.minPoint.latitude,
context_.boundingBox.center());
splitter_.setParams(Scale, size);
buildLayers();
buildBackground(tileRect);
context_.meshCallback(mesh_);
}
// process all found layers.
void TerraGenerator::buildLayers()
{
// 1. process layers: regions with shared properties.
std::stringstream ss(style_.getString(LayerPriorityKey));
while (ss.good()) {
std::string name;
getline(ss, name, ',');
auto layer = layers_.find(name);
if (layer != layers_.end()) {
buildFromRegions(layer->second, createRegionContext(style_, name + "-"));
layers_.erase(layer);
}
}
// 2. Process the rest: each region has already its own properties.
for (auto& layer : layers_)
while (!layer.second.empty()) {
auto& region = layer.second.top();
buildFromPaths(region->points, *region->context);
layer.second.pop();
}
}
// process the rest area.
void TerraGenerator::buildBackground(Path& tileRect)
{
backGroundClipper_.AddPath(tileRect, ptSubject, true);
Paths background;
backGroundClipper_.Execute(ctDifference, background, pftNonZero, pftNonZero);
backGroundClipper_.Clear();
if (!background.empty())
populateMesh(background, createRegionContext(style_, ""));
}
TerraGenerator::RegionContext TerraGenerator::createRegionContext(const Style& style, const std::string& prefix) const
{
double quadKeyWidth = context_.boundingBox.maxPoint.latitude - context_.boundingBox.minPoint.latitude;
MeshBuilder::GeometryOptions geometryOptions(
style.getValue(prefix + MaxAreaKey, quadKeyWidth * quadKeyWidth),
style.getValue(prefix + EleNoiseFreqKey, quadKeyWidth),
std::numeric_limits<double>::lowest(), // no fixed elevation
style.getValue(prefix + HeightOffsetKey, quadKeyWidth),
false, // no flip
false, // no back side
1 // no new vertices on boundaries
);
// TODO use seed for randomization
auto textureRegion = context_.styleProvider
.getTexture(style.getString(prefix + MaterialKey))
.random(0);
MeshBuilder::AppearanceOptions appearanceOptions(
context_.styleProvider.getGradient(style.getString(prefix + GradientKey)),
style.getValue(prefix + ColorNoiseFreqKey, quadKeyWidth),
textureRegion,
0 // texture scale
);
return RegionContext(style, prefix, geometryOptions, appearanceOptions);
}
void TerraGenerator::buildFromRegions(Regions& regions, const RegionContext& regionContext)
{
// merge all regions together
Clipper clipper;
while (!regions.empty()) {
clipper.AddPaths(regions.top()->points, ptSubject, true);
regions.pop();
}
Paths result;
clipper.Execute(ctUnion, result, pftNonZero, pftNonZero);
buildFromPaths(result, regionContext);
}
void TerraGenerator::buildFromPaths(const Paths& paths, const RegionContext& regionContext)
{
Paths solution;
foregroundClipper_.AddPaths(paths, ptSubject, true);
foregroundClipper_.Execute(ctDifference, solution, pftNonZero, pftNonZero);
foregroundClipper_.moveSubjectToClip();
populateMesh(solution, regionContext);
}
void TerraGenerator::populateMesh(Paths& paths, const RegionContext& regionContext)
{
ClipperLib::SimplifyPolygons(paths);
ClipperLib::CleanPolygons(paths);
bool hasHeightOffset = std::abs(regionContext.geometryOptions.heightOffset) > 1E-8;
// calculate approximate size of overall points
double size = 0;
for (std::size_t i = 0; i < paths.size(); ++i)
size += paths[i].size() * 1.5;
Polygon polygon(static_cast<std::size_t>(size));
for (const Path& path : paths) {
double area = ClipperLib::Area(path);
bool isHole = area < 0;
if (std::abs(area) < AreaTolerance)
continue;
backGroundClipper_.AddPath(path, ptClip, true);
Points points = restorePoints(path);
if (isHole)
polygon.addHole(points);
else
polygon.addContour(points);
if (hasHeightOffset)
processHeightOffset(points, regionContext);
}
if (!polygon.points.empty())
fillMesh(polygon, regionContext);
}
// restores mesh points from clipper points and injects new ones according to grid.
TerraGenerator::Points TerraGenerator::restorePoints(const Path& path) const
{
auto lastItemIndex = path.size() - 1;
Points points;
points.reserve(path.size());
for (int i = 0; i <= lastItemIndex; i++)
splitter_.split(path[i], path[i == lastItemIndex ? 0 : i + 1], points);
return std::move(points);
}
void TerraGenerator::fillMesh(Polygon& polygon, const RegionContext& regionContext)
{
std::string meshName = regionContext.style.getString(regionContext.prefix + MeshNameKey);
if (!meshName.empty()) {
Mesh polygonMesh(meshName);
TerraExtras::Context extrasContext(polygonMesh, regionContext.style);
context_.meshBuilder.addPolygon(polygonMesh,
polygon,
regionContext.geometryOptions,
regionContext.appearanceOptions);
addExtrasIfNecessary(polygonMesh, extrasContext, regionContext);
context_.meshCallback(polygonMesh);
}
else {
TerraExtras::Context extrasContext(mesh_, regionContext.style);
context_.meshBuilder.addPolygon(mesh_,
polygon,
regionContext.geometryOptions,
regionContext.appearanceOptions);
addExtrasIfNecessary(mesh_, extrasContext, regionContext);
}
}
void TerraGenerator::addExtrasIfNecessary(utymap::meshing::Mesh& mesh,
TerraExtras::Context& extrasContext,
const RegionContext& regionContext) const
{
std::string meshExtras = regionContext.style.getString(regionContext.prefix + MeshExtrasKey);
if (meshExtras.empty())
return;
ExtrasFuncs.at(meshExtras)(context_, extrasContext);
}
void TerraGenerator::processHeightOffset(const Points& points, const RegionContext& regionContext)
{
// do not use elevation noise for height offset.
auto newGeometryOptions = regionContext.geometryOptions;
newGeometryOptions.eleNoiseFreq = 0;
for (std::size_t i = 0; i < points.size(); ++i) {
Vector2 p1 = points[i];
Vector2 p2 = points[i == (points.size() - 1) ? 0 : i + 1];
// check whether two points are on cell rect
if (rect_.isOnBorder(p1) && rect_.isOnBorder(p2))
continue;
context_.meshBuilder.addPlane(mesh_, p1, p2, newGeometryOptions, regionContext.appearanceOptions);
}
}
<|endoftext|> |
<commit_before>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2011 Sergey Lisitsyn
* Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society
*/
#include <shogun/evaluation/MeanSquaredError.h>
#include <shogun/labels/Labels.h>
#include <shogun/labels/RegressionLabels.h>
#include <shogun/mathematics/Math.h>
using namespace shogun;
float64_t CMeanSquaredError::evaluate(CLabels* predicted, CLabels* ground_truth)
{
ASSERT(predicted && ground_truth)
ASSERT(predicted->get_num_labels() == ground_truth->get_num_labels())
ASSERT(predicted->get_label_type() == LT_REGRESSION)
ASSERT(ground_truth->get_label_type() == LT_REGRESSION)
int32_t length = predicted->get_num_labels();
float64_t mse = 0.0;
for (int32_t i=0; i<length; i++)
mse += CMath::sq(((CRegressionLabels*) predicted)->get_label(i) - ((CRegressionLabels*) ground_truth)->get_label(i));
mse /= length;
return mse;
}
<commit_msg>From from ASSERT to REQUIRE in MeanSquaredError.<commit_after>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2011 Sergey Lisitsyn
* Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society
*/
#include <shogun/evaluation/MeanSquaredError.h>
#include <shogun/labels/Labels.h>
#include <shogun/labels/RegressionLabels.h>
#include <shogun/mathematics/Math.h>
using namespace shogun;
float64_t CMeanSquaredError::evaluate(CLabels* predicted, CLabels* ground_truth)
{
REQUIRE(predicted, "Predicted labels must be not null.\n")
REQUIRE(ground_truth, "Ground truth labels must be not null.\n")
REQUIRE(predicted->get_num_labels() == ground_truth->get_num_labels(), "The number of predicted labels (%d) must be equal to the number of ground truth labels (%d).\n")
REQUIRE(predicted->get_label_type() == LT_REGRESSION, "Predicted label type (%d) must be regression (%d).\n", predicted->get_label_type(), LT_REGRESSION)
REQUIRE(ground_truth->get_label_type() == LT_REGRESSION, "Ground truth label type (%d) must be regression (%d).\n", ground_truth->get_label_type(), LT_REGRESSION)
int32_t length = predicted->get_num_labels();
float64_t mse = 0.0;
for (int32_t i=0; i<length; i++)
mse += CMath::sq(((CRegressionLabels*) predicted)->get_label(i) - ((CRegressionLabels*) ground_truth)->get_label(i));
mse /= length;
return mse;
}
<|endoftext|> |
<commit_before>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2015 Wu Lin
* Written (W) 2012 Jacob Walker
*
* Adapted from WeightedDegreeRBFKernel.cpp
*/
#include <shogun/kernel/ExponentialARDKernel.h>
#include <shogun/features/DenseFeatures.h>
#include <shogun/mathematics/Math.h>
#ifdef HAVE_LINALG_LIB
#include <shogun/mathematics/linalg/linalg.h>
#endif
using namespace shogun;
CExponentialARDKernel::CExponentialARDKernel() : CDotKernel()
{
init();
}
CExponentialARDKernel::~CExponentialARDKernel()
{
CKernel::cleanup();
}
void CExponentialARDKernel::init()
{
m_ARD_type=KT_SCALAR;
m_log_weights=SGVector<float64_t>(1);
m_log_weights.set_const(0.0);
m_weights_rows=1.0;
m_weights_cols=1.0;
SG_ADD(&m_log_weights, "log_weights", "Feature weights in log domain", MS_AVAILABLE,
GRADIENT_AVAILABLE);
SG_ADD(&m_weights_rows, "weights_rows", "Row of feature weights", MS_NOT_AVAILABLE);
SG_ADD(&m_weights_cols, "weights_cols", "Column of feature weights", MS_NOT_AVAILABLE);
SG_ADD((int *)(&m_ARD_type), "type", "ARD kernel type", MS_NOT_AVAILABLE);
m_weights_raw=SGMatrix<float64_t>();
SG_ADD(&m_weights_raw, "weights_raw", "Features weights in standard domain", MS_NOT_AVAILABLE);
}
SGVector<float64_t> CExponentialARDKernel::get_feature_vector(int32_t idx, CFeatures* hs)
{
REQUIRE(hs, "Features not set!\n");
CDenseFeatures<float64_t> * dense_hs=dynamic_cast<CDenseFeatures<float64_t> *>(hs);
if (dense_hs)
return dense_hs->get_feature_vector(idx);
CDotFeatures * dot_hs=dynamic_cast<CDotFeatures *>(hs);
REQUIRE(dot_hs, "Kernel only supports DotFeatures\n");
return dot_hs->get_computed_dot_feature_vector(idx);
}
#ifdef HAVE_LINALG_LIB
void CExponentialARDKernel::set_weights(SGMatrix<float64_t> weights)
{
REQUIRE(weights.num_rows>0 && weights.num_cols>0, "Weights matrix is non-empty\n");
if (weights.num_rows==1)
{
if(weights.num_cols>1)
{
SGVector<float64_t> vec(weights.matrix,weights.num_cols,false);
set_vector_weights(vec);
}
else
set_scalar_weights(weights[0]);
}
else
set_matrix_weights(weights);
}
void CExponentialARDKernel::lazy_update_weights()
{
if (parameter_hash_changed())
{
if (m_ARD_type==KT_SCALAR || m_ARD_type==KT_DIAG)
{
SGMatrix<float64_t> log_weights(m_log_weights.vector,1,m_log_weights.vlen,false);
m_weights_raw=linalg::elementwise_compute(m_log_weights,
[ ](float64_t& value)
{
return CMath::exp(value);
});
}
else if (m_ARD_type==KT_FULL)
{
m_weights_raw=SGMatrix<float64_t>(m_weights_rows,m_weights_cols);
m_weights_raw.set_const(0.0);
index_t offset=0;
for (int i=0;i<m_weights_raw.num_cols && i<m_weights_raw.num_rows;i++)
{
float64_t* begin=m_weights_raw.get_column_vector(i);
std::copy(m_log_weights.vector+offset,m_log_weights.vector+offset+m_weights_raw.num_rows-i,begin+i);
begin[i]=CMath::exp(begin[i]);
offset+=m_weights_raw.num_rows-i;
}
}
else
{
SG_ERROR("Unsupported ARD type\n");
}
update_parameter_hash();
}
}
SGMatrix<float64_t> CExponentialARDKernel::get_weights()
{
lazy_update_weights();
return SGMatrix<float64_t>(m_weights_raw);
}
void CExponentialARDKernel::set_scalar_weights(float64_t weight)
{
REQUIRE(weight>0, "Scalar (%f) weight should be positive\n",weight);
m_log_weights=SGVector<float64_t>(1);
m_log_weights.set_const(CMath::log(weight));
m_ARD_type=KT_SCALAR;
m_weights_rows=1.0;
m_weights_cols=1.0;
}
void CExponentialARDKernel::set_vector_weights(SGVector<float64_t> weights)
{
REQUIRE(rhs==NULL && lhs==NULL,
"Setting vector weights must be before initialize features\n");
REQUIRE(weights.vlen>0, "Vector weight should be non-empty\n");
m_log_weights=SGVector<float64_t>(weights.vlen);
for(index_t i=0; i<weights.vlen; i++)
{
REQUIRE(weights[i]>0, "Each entry of vector weight (v[%d]=%f) should be positive\n",
i,weights[i]);
m_log_weights[i]=CMath::log(weights[i]);
}
m_ARD_type=KT_DIAG;
m_weights_rows=1.0;
m_weights_cols=weights.vlen;
}
void CExponentialARDKernel::set_matrix_weights(SGMatrix<float64_t> weights)
{
REQUIRE(rhs==NULL && lhs==NULL,
"Setting matrix weights must be before initialize features\n");
REQUIRE(weights.num_cols>0, "Matrix weight should be non-empty");
REQUIRE(weights.num_rows>=weights.num_cols,
"Number of row (%d) must be not less than number of column (%d)",
weights.num_rows, weights.num_cols);
m_weights_rows=weights.num_rows;
m_weights_cols=weights.num_cols;
m_ARD_type=KT_FULL;
index_t len=(2*m_weights_rows+1-m_weights_cols)*m_weights_cols/2;
m_log_weights=SGVector<float64_t>(len);
index_t offset=0;
for (int i=0; i<weights.num_cols && i<weights.num_rows; i++)
{
float64_t* begin=weights.get_column_vector(i);
REQUIRE(begin[i]>0, "The diagonal entry of matrix weight (w(%d,%d)=%f) should be positive\n",
i,i,begin[i]);
std::copy(begin+i,begin+weights.num_rows,m_log_weights.vector+offset);
m_log_weights[offset]=CMath::log(m_log_weights[offset]);
offset+=weights.num_rows-i;
}
}
CExponentialARDKernel::CExponentialARDKernel(int32_t size) : CDotKernel(size)
{
init();
}
CExponentialARDKernel::CExponentialARDKernel(CDotFeatures* l,
CDotFeatures* r, int32_t size) : CDotKernel(size)
{
init();
init(l,r);
}
bool CExponentialARDKernel::init(CFeatures* l, CFeatures* r)
{
cleanup();
CDotKernel::init(l, r);
int32_t dim=((CDotFeatures*) l)->get_dim_feature_space();
if (m_ARD_type==KT_FULL)
{
REQUIRE(m_weights_rows==dim, "Dimension mismatch between features (%d) and weights (%d)\n",
dim, m_weights_rows);
}
else if (m_ARD_type==KT_DIAG)
{
REQUIRE(m_log_weights.vlen==dim, "Dimension mismatch between features (%d) and weights (%d)\n",
dim, m_log_weights.vlen);
}
return init_normalizer();
}
SGMatrix<float64_t> CExponentialARDKernel::get_weighted_vector(SGVector<float64_t> vec)
{
REQUIRE(m_ARD_type==KT_FULL || m_ARD_type==KT_DIAG, "This method only supports vector weights or matrix weights\n");
SGMatrix<float64_t> res;
if (m_ARD_type==KT_FULL)
{
res=SGMatrix<float64_t>(m_weights_cols,1);
index_t offset=0;
//can be done it in parallel
for (int i=0;i<m_weights_rows && i<m_weights_cols;i++)
{
SGMatrix<float64_t> weights(m_log_weights.vector+offset,1,m_weights_rows-i,false);
weights[0]=CMath::exp(weights[0]);
SGMatrix<float64_t> rtmp(vec.vector+i,vec.vlen-i,1,false);
SGMatrix<float64_t> s=linalg::matrix_product(weights,rtmp);
weights[0]=CMath::log(weights[0]);
res[i]=s[0];
offset+=m_weights_rows-i;
}
}
else
{
SGMatrix<float64_t> rtmp(vec.vector,vec.vlen,1,false);
SGMatrix<float64_t> weights=linalg::elementwise_compute(m_log_weights,
[ ](float64_t& value)
{
return CMath::exp(value);
});
res=linalg::elementwise_product(weights, rtmp);
}
return res;
}
SGMatrix<float64_t> CExponentialARDKernel::compute_right_product(SGVector<float64_t>vec,
float64_t & scalar_weight)
{
SGMatrix<float64_t> right;
if (m_ARD_type==KT_SCALAR)
{
right=SGMatrix<float64_t>(vec.vector,vec.vlen,1,false);
scalar_weight*=CMath::exp(m_log_weights[0]);
}
else if (m_ARD_type==KT_DIAG || m_ARD_type==KT_FULL)
right=get_weighted_vector(vec);
else
{
SG_ERROR("Unsupported ARD type\n");
}
return right;
}
void CExponentialARDKernel::check_weight_gradient_index(index_t index)
{
REQUIRE(lhs, "Left features not set!\n");
REQUIRE(rhs, "Right features not set!\n");
if (m_ARD_type!=KT_SCALAR)
{
REQUIRE(index>=0, "Index (%d) must be non-negative\n",index);
REQUIRE(index<m_log_weights.vlen, "Index (%d) must be within #dimension of weights (%d)\n",
index, m_log_weights.vlen);
}
}
#endif //HAVE_LINALG_LIB
<commit_msg>Make ExponentialARDKernel::get_weighted_vector thread-safe<commit_after>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2015 Wu Lin
* Written (W) 2012 Jacob Walker
*
* Adapted from WeightedDegreeRBFKernel.cpp
*/
#include <shogun/kernel/ExponentialARDKernel.h>
#include <shogun/features/DenseFeatures.h>
#include <shogun/mathematics/Math.h>
#ifdef HAVE_LINALG_LIB
#include <shogun/mathematics/linalg/linalg.h>
#endif
using namespace shogun;
CExponentialARDKernel::CExponentialARDKernel() : CDotKernel()
{
init();
}
CExponentialARDKernel::~CExponentialARDKernel()
{
CKernel::cleanup();
}
void CExponentialARDKernel::init()
{
m_ARD_type=KT_SCALAR;
m_log_weights=SGVector<float64_t>(1);
m_log_weights.set_const(0.0);
m_weights_rows=1.0;
m_weights_cols=1.0;
SG_ADD(&m_log_weights, "log_weights", "Feature weights in log domain", MS_AVAILABLE,
GRADIENT_AVAILABLE);
SG_ADD(&m_weights_rows, "weights_rows", "Row of feature weights", MS_NOT_AVAILABLE);
SG_ADD(&m_weights_cols, "weights_cols", "Column of feature weights", MS_NOT_AVAILABLE);
SG_ADD((int *)(&m_ARD_type), "type", "ARD kernel type", MS_NOT_AVAILABLE);
m_weights_raw=SGMatrix<float64_t>();
SG_ADD(&m_weights_raw, "weights_raw", "Features weights in standard domain", MS_NOT_AVAILABLE);
}
SGVector<float64_t> CExponentialARDKernel::get_feature_vector(int32_t idx, CFeatures* hs)
{
REQUIRE(hs, "Features not set!\n");
CDenseFeatures<float64_t> * dense_hs=dynamic_cast<CDenseFeatures<float64_t> *>(hs);
if (dense_hs)
return dense_hs->get_feature_vector(idx);
CDotFeatures * dot_hs=dynamic_cast<CDotFeatures *>(hs);
REQUIRE(dot_hs, "Kernel only supports DotFeatures\n");
return dot_hs->get_computed_dot_feature_vector(idx);
}
#ifdef HAVE_LINALG_LIB
void CExponentialARDKernel::set_weights(SGMatrix<float64_t> weights)
{
REQUIRE(weights.num_rows>0 && weights.num_cols>0, "Weights matrix is non-empty\n");
if (weights.num_rows==1)
{
if(weights.num_cols>1)
{
SGVector<float64_t> vec(weights.matrix,weights.num_cols,false);
set_vector_weights(vec);
}
else
set_scalar_weights(weights[0]);
}
else
set_matrix_weights(weights);
}
void CExponentialARDKernel::lazy_update_weights()
{
if (parameter_hash_changed())
{
if (m_ARD_type==KT_SCALAR || m_ARD_type==KT_DIAG)
{
SGMatrix<float64_t> log_weights(m_log_weights.vector,1,m_log_weights.vlen,false);
m_weights_raw=linalg::elementwise_compute(m_log_weights,
[ ](float64_t& value)
{
return CMath::exp(value);
});
}
else if (m_ARD_type==KT_FULL)
{
m_weights_raw=SGMatrix<float64_t>(m_weights_rows,m_weights_cols);
m_weights_raw.set_const(0.0);
index_t offset=0;
for (int i=0;i<m_weights_raw.num_cols && i<m_weights_raw.num_rows;i++)
{
float64_t* begin=m_weights_raw.get_column_vector(i);
std::copy(m_log_weights.vector+offset,m_log_weights.vector+offset+m_weights_raw.num_rows-i,begin+i);
begin[i]=CMath::exp(begin[i]);
offset+=m_weights_raw.num_rows-i;
}
}
else
{
SG_ERROR("Unsupported ARD type\n");
}
update_parameter_hash();
}
}
SGMatrix<float64_t> CExponentialARDKernel::get_weights()
{
lazy_update_weights();
return SGMatrix<float64_t>(m_weights_raw);
}
void CExponentialARDKernel::set_scalar_weights(float64_t weight)
{
REQUIRE(weight>0, "Scalar (%f) weight should be positive\n",weight);
m_log_weights=SGVector<float64_t>(1);
m_log_weights.set_const(CMath::log(weight));
m_ARD_type=KT_SCALAR;
m_weights_rows=1.0;
m_weights_cols=1.0;
}
void CExponentialARDKernel::set_vector_weights(SGVector<float64_t> weights)
{
REQUIRE(rhs==NULL && lhs==NULL,
"Setting vector weights must be before initialize features\n");
REQUIRE(weights.vlen>0, "Vector weight should be non-empty\n");
m_log_weights=SGVector<float64_t>(weights.vlen);
for(index_t i=0; i<weights.vlen; i++)
{
REQUIRE(weights[i]>0, "Each entry of vector weight (v[%d]=%f) should be positive\n",
i,weights[i]);
m_log_weights[i]=CMath::log(weights[i]);
}
m_ARD_type=KT_DIAG;
m_weights_rows=1.0;
m_weights_cols=weights.vlen;
}
void CExponentialARDKernel::set_matrix_weights(SGMatrix<float64_t> weights)
{
REQUIRE(rhs==NULL && lhs==NULL,
"Setting matrix weights must be before initialize features\n");
REQUIRE(weights.num_cols>0, "Matrix weight should be non-empty");
REQUIRE(weights.num_rows>=weights.num_cols,
"Number of row (%d) must be not less than number of column (%d)",
weights.num_rows, weights.num_cols);
m_weights_rows=weights.num_rows;
m_weights_cols=weights.num_cols;
m_ARD_type=KT_FULL;
index_t len=(2*m_weights_rows+1-m_weights_cols)*m_weights_cols/2;
m_log_weights=SGVector<float64_t>(len);
index_t offset=0;
for (int i=0; i<weights.num_cols && i<weights.num_rows; i++)
{
float64_t* begin=weights.get_column_vector(i);
REQUIRE(begin[i]>0, "The diagonal entry of matrix weight (w(%d,%d)=%f) should be positive\n",
i,i,begin[i]);
std::copy(begin+i,begin+weights.num_rows,m_log_weights.vector+offset);
m_log_weights[offset]=CMath::log(m_log_weights[offset]);
offset+=weights.num_rows-i;
}
}
CExponentialARDKernel::CExponentialARDKernel(int32_t size) : CDotKernel(size)
{
init();
}
CExponentialARDKernel::CExponentialARDKernel(CDotFeatures* l,
CDotFeatures* r, int32_t size) : CDotKernel(size)
{
init();
init(l,r);
}
bool CExponentialARDKernel::init(CFeatures* l, CFeatures* r)
{
cleanup();
CDotKernel::init(l, r);
int32_t dim=((CDotFeatures*) l)->get_dim_feature_space();
if (m_ARD_type==KT_FULL)
{
REQUIRE(m_weights_rows==dim, "Dimension mismatch between features (%d) and weights (%d)\n",
dim, m_weights_rows);
}
else if (m_ARD_type==KT_DIAG)
{
REQUIRE(m_log_weights.vlen==dim, "Dimension mismatch between features (%d) and weights (%d)\n",
dim, m_log_weights.vlen);
}
return init_normalizer();
}
SGMatrix<float64_t> CExponentialARDKernel::get_weighted_vector(SGVector<float64_t> vec)
{
REQUIRE(m_ARD_type==KT_FULL || m_ARD_type==KT_DIAG, "This method only supports vector weights or matrix weights\n");
SGMatrix<float64_t> res;
if (m_ARD_type==KT_FULL)
{
res=SGMatrix<float64_t>(m_weights_cols,1);
index_t offset=0;
// TODO: investigate a better way to make this
// block thread-safe
SGVector<float64_t> log_weights = m_log_weights.clone();
//can be done it in parallel
for (index_t i=0;i<m_weights_rows && i<m_weights_cols;i++)
{
SGMatrix<float64_t> weights(log_weights.vector+offset,1,m_weights_rows-i,false);
weights[0]=CMath::exp(weights[0]);
SGMatrix<float64_t> rtmp(vec.vector+i,vec.vlen-i,1,false);
SGMatrix<float64_t> s=linalg::matrix_product(weights,rtmp);
weights[0]=CMath::log(weights[0]);
res[i]=s[0];
offset+=m_weights_rows-i;
}
}
else
{
SGMatrix<float64_t> rtmp(vec.vector,vec.vlen,1,false);
SGMatrix<float64_t> weights=linalg::elementwise_compute(m_log_weights,
[ ](float64_t& value)
{
return CMath::exp(value);
});
res=linalg::elementwise_product(weights, rtmp);
}
return res;
}
SGMatrix<float64_t> CExponentialARDKernel::compute_right_product(SGVector<float64_t>vec,
float64_t & scalar_weight)
{
SGMatrix<float64_t> right;
if (m_ARD_type==KT_SCALAR)
{
right=SGMatrix<float64_t>(vec.vector,vec.vlen,1,false);
scalar_weight*=CMath::exp(m_log_weights[0]);
}
else if (m_ARD_type==KT_DIAG || m_ARD_type==KT_FULL)
right=get_weighted_vector(vec);
else
{
SG_ERROR("Unsupported ARD type\n");
}
return right;
}
void CExponentialARDKernel::check_weight_gradient_index(index_t index)
{
REQUIRE(lhs, "Left features not set!\n");
REQUIRE(rhs, "Right features not set!\n");
if (m_ARD_type!=KT_SCALAR)
{
REQUIRE(index>=0, "Index (%d) must be non-negative\n",index);
REQUIRE(index<m_log_weights.vlen, "Index (%d) must be within #dimension of weights (%d)\n",
index, m_log_weights.vlen);
}
}
#endif //HAVE_LINALG_LIB
<|endoftext|> |
<commit_before>/* This software is distributed under BSD 3-clause license (see LICENSE file).
*
* Copyright (c) 2012-2013 Sergey Lisitsyn
*/
#ifndef TAPKEE_VPTREE_H_
#define TAPKEE_VPTREE_H_
#include <tapkee_defines.hpp>
#include <vector>
#include <queue>
#include <algorithm>
#include <limits>
namespace tapkee
{
namespace tapkee_internal
{
template<bool, class RandomAccessIterator, class DistanceCallback>
struct compare_if_kernel;
template<class RandomAccessIterator, class DistanceCallback>
struct DistanceComparator
{
DistanceCallback callback;
const RandomAccessIterator item;
DistanceComparator(const DistanceCallback& c, const RandomAccessIterator& i) :
callback(c), item(i) {}
inline bool operator()(const RandomAccessIterator& a, const RandomAccessIterator& b)
{
return compare_if_kernel<DistanceCallback::is_kernel,RandomAccessIterator,DistanceCallback>()
(callback,item,a,b);
}
};
template<class RandomAccessIterator, class DistanceCallback>
struct compare_if_kernel<true,RandomAccessIterator,DistanceCallback>
{
inline bool operator()(DistanceCallback& callback, const RandomAccessIterator& item,
const RandomAccessIterator& a, const RandomAccessIterator& b)
{
return (-2*callback(item,a) + callback(a,a)) < (-2*callback(item,b) + callback(b,b));
}
};
template<class RandomAccessIterator, class DistanceCallback>
struct compare_if_kernel<false,RandomAccessIterator,DistanceCallback>
{
inline bool operator()(DistanceCallback& callback, const RandomAccessIterator& item,
const RandomAccessIterator& a, const RandomAccessIterator& b)
{
return callback(item,a) < callback(item,b);
}
};
template<class RandomAccessIterator, class DistanceCallback>
class VantagePointTree
{
public:
// Default constructor
VantagePointTree(RandomAccessIterator b, RandomAccessIterator e, DistanceCallback c) :
begin(b), items(), callback(c), tau(0.0), root(0)
{
items.reserve(e-b);
for (RandomAccessIterator i=b; i!=e; ++i)
items.push_back(i);
root = buildFromPoints(0, items.size());
}
// Destructor
~VantagePointTree()
{
delete root;
}
// Function that uses the tree to find the k nearest neighbors of target
std::vector<IndexType> search(const RandomAccessIterator& target, int k)
{
std::vector<IndexType> results;
// Use a priority queue to store intermediate results on
std::priority_queue<HeapItem> heap;
// Variable that tracks the distance to the farthest point in our results
tau = std::numeric_limits<double>::max();
// Perform the searcg
search(root, target, k, heap);
// Gather final results
results.reserve(k);
while(!heap.empty()) {
results.push_back(items[heap.top().index]-begin);
heap.pop();
}
return results;
}
private:
VantagePointTree(const VantagePointTree&);
VantagePointTree& operator=(const VantagePointTree&);
RandomAccessIterator begin;
std::vector<RandomAccessIterator> items;
DistanceCallback callback;
double tau;
struct Node
{
int index;
double threshold;
Node* left;
Node* right;
Node() :
index(0), threshold(0.),
left(0), right(0)
{
}
~Node()
{
delete left;
delete right;
}
Node(const Node&);
Node& operator=(const Node&);
}* root;
struct HeapItem {
HeapItem(int i, double d) :
index(i), distance(d) {}
int index;
double distance;
bool operator<(const HeapItem& o) const {
return distance < o.distance;
}
};
Node* buildFromPoints(int lower, int upper)
{
if (upper == lower)
{
return NULL;
}
Node* node = new Node();
node->index = lower;
if (upper - lower > 1)
{
int i = (int) ((double)rand() / RAND_MAX * (upper - lower - 1)) + lower;
std::swap(items[lower], items[i]);
int median = (upper + lower) / 2;
std::nth_element(items.begin() + lower + 1, items.begin() + median, items.begin() + upper,
DistanceComparator<RandomAccessIterator,DistanceCallback>(callback,items[lower]));
node->threshold = callback.distance(items[lower], items[median]);
node->index = lower;
node->left = buildFromPoints(lower + 1, median);
node->right = buildFromPoints(median, upper);
}
return node;
}
void search(Node* node, const RandomAccessIterator& target, int k, std::priority_queue<HeapItem>& heap)
{
if (node == NULL)
return;
double distance = callback.distance(items[node->index], target);
if (distance < tau)
{
if (heap.size() == static_cast<size_t>(k))
heap.pop();
heap.push(HeapItem(node->index, distance));
if (heap.size() == static_cast<size_t>(k))
tau = heap.top().distance;
}
if (node->left == NULL && node->right == NULL)
{
return;
}
if (distance < node->threshold)
{
if ((distance - tau) <= node->threshold)
search(node->left, target, k, heap);
if ((distance + tau) >= node->threshold)
search(node->right, target, k, heap);
}
else
{
if ((distance + tau) >= node->threshold)
search(node->right, target, k, heap);
if ((distance - tau) <= node->threshold)
search(node->left, target, k, heap);
}
}
};
}
}
#endif
<commit_msg>Fixed include in vptree<commit_after>/* This software is distributed under BSD 3-clause license (see LICENSE file).
*
* Copyright (c) 2012-2013 Sergey Lisitsyn
*/
#ifndef TAPKEE_VPTREE_H_
#define TAPKEE_VPTREE_H_
/* Tapkee include */
#include <shogun/lib/tapkee/tapkee_defines.hpp>
/* End of Tapkee includes */
#include <vector>
#include <queue>
#include <algorithm>
#include <limits>
namespace tapkee
{
namespace tapkee_internal
{
template<bool, class RandomAccessIterator, class DistanceCallback>
struct compare_if_kernel;
template<class RandomAccessIterator, class DistanceCallback>
struct DistanceComparator
{
DistanceCallback callback;
const RandomAccessIterator item;
DistanceComparator(const DistanceCallback& c, const RandomAccessIterator& i) :
callback(c), item(i) {}
inline bool operator()(const RandomAccessIterator& a, const RandomAccessIterator& b)
{
return compare_if_kernel<DistanceCallback::is_kernel,RandomAccessIterator,DistanceCallback>()
(callback,item,a,b);
}
};
template<class RandomAccessIterator, class DistanceCallback>
struct compare_if_kernel<true,RandomAccessIterator,DistanceCallback>
{
inline bool operator()(DistanceCallback& callback, const RandomAccessIterator& item,
const RandomAccessIterator& a, const RandomAccessIterator& b)
{
return (-2*callback(item,a) + callback(a,a)) < (-2*callback(item,b) + callback(b,b));
}
};
template<class RandomAccessIterator, class DistanceCallback>
struct compare_if_kernel<false,RandomAccessIterator,DistanceCallback>
{
inline bool operator()(DistanceCallback& callback, const RandomAccessIterator& item,
const RandomAccessIterator& a, const RandomAccessIterator& b)
{
return callback(item,a) < callback(item,b);
}
};
template<class RandomAccessIterator, class DistanceCallback>
class VantagePointTree
{
public:
// Default constructor
VantagePointTree(RandomAccessIterator b, RandomAccessIterator e, DistanceCallback c) :
begin(b), items(), callback(c), tau(0.0), root(0)
{
items.reserve(e-b);
for (RandomAccessIterator i=b; i!=e; ++i)
items.push_back(i);
root = buildFromPoints(0, items.size());
}
// Destructor
~VantagePointTree()
{
delete root;
}
// Function that uses the tree to find the k nearest neighbors of target
std::vector<IndexType> search(const RandomAccessIterator& target, int k)
{
std::vector<IndexType> results;
// Use a priority queue to store intermediate results on
std::priority_queue<HeapItem> heap;
// Variable that tracks the distance to the farthest point in our results
tau = std::numeric_limits<double>::max();
// Perform the searcg
search(root, target, k, heap);
// Gather final results
results.reserve(k);
while(!heap.empty()) {
results.push_back(items[heap.top().index]-begin);
heap.pop();
}
return results;
}
private:
VantagePointTree(const VantagePointTree&);
VantagePointTree& operator=(const VantagePointTree&);
RandomAccessIterator begin;
std::vector<RandomAccessIterator> items;
DistanceCallback callback;
double tau;
struct Node
{
int index;
double threshold;
Node* left;
Node* right;
Node() :
index(0), threshold(0.),
left(0), right(0)
{
}
~Node()
{
delete left;
delete right;
}
Node(const Node&);
Node& operator=(const Node&);
}* root;
struct HeapItem {
HeapItem(int i, double d) :
index(i), distance(d) {}
int index;
double distance;
bool operator<(const HeapItem& o) const {
return distance < o.distance;
}
};
Node* buildFromPoints(int lower, int upper)
{
if (upper == lower)
{
return NULL;
}
Node* node = new Node();
node->index = lower;
if (upper - lower > 1)
{
int i = (int) ((double)rand() / RAND_MAX * (upper - lower - 1)) + lower;
std::swap(items[lower], items[i]);
int median = (upper + lower) / 2;
std::nth_element(items.begin() + lower + 1, items.begin() + median, items.begin() + upper,
DistanceComparator<RandomAccessIterator,DistanceCallback>(callback,items[lower]));
node->threshold = callback.distance(items[lower], items[median]);
node->index = lower;
node->left = buildFromPoints(lower + 1, median);
node->right = buildFromPoints(median, upper);
}
return node;
}
void search(Node* node, const RandomAccessIterator& target, int k, std::priority_queue<HeapItem>& heap)
{
if (node == NULL)
return;
double distance = callback.distance(items[node->index], target);
if (distance < tau)
{
if (heap.size() == static_cast<size_t>(k))
heap.pop();
heap.push(HeapItem(node->index, distance));
if (heap.size() == static_cast<size_t>(k))
tau = heap.top().distance;
}
if (node->left == NULL && node->right == NULL)
{
return;
}
if (distance < node->threshold)
{
if ((distance - tau) <= node->threshold)
search(node->left, target, k, heap);
if ((distance + tau) >= node->threshold)
search(node->right, target, k, heap);
}
else
{
if ((distance + tau) >= node->threshold)
search(node->right, target, k, heap);
if ((distance - tau) <= node->threshold)
search(node->left, target, k, heap);
}
}
};
}
}
#endif
<|endoftext|> |
<commit_before>// Problem 10 from Project Euler
// http://projecteuler.net/problem=10
#include <iostream>
#include <algorithm>
#include <unordered_map>
int main()
{
std::unordered_map<unsigned int, bool> number_map;
unsigned int size = 100;
unsigned int iter = 2;
while (iter <= size)
{
// number_map[iter] = true;
number_map.emplace(iter, true);
++iter;
}
// The Sieve of Eratosthenes (WIP)
for (auto keyValue : number_map)
{
if (keyValue.second)
{
unsigned int n_product = 0;
// While the product is less than the greatest element of number_map
for (unsigned int multiplicand = 2; n_product < size; ++multiplicand)
{
n_product = keyValue.first * multiplicand;
number_map[n_product] = false;
}
}
}
unsigned int primes_sum = 0;
// for (auto keyValue : number_map)
// {
// std::cout << keyValue.first << std::endl;
// }
// std::cout << primes_sum << std::endl;
}
<commit_msg>Fixed implementation, it now works correctly for seemingly every number except for 2,000,000<commit_after>// Problem 10 from Project Euler
// http://projecteuler.net/problem=10
#include <vector>
#include <iostream>
#include <algorithm>
#include <unordered_map>
int main()
{
std::unordered_map<unsigned long long, bool> number_map;
unsigned long long size = 2000000;
unsigned long long iter = 2;
while (iter <= size)
{
number_map[iter] = true;
++iter;
}
// The Sieve of Eratosthenes
for (auto keyValue : number_map)
{
if (keyValue.second)
{
unsigned long long multiplicand = 2;
unsigned long long n_product = multiplicand * keyValue.first;
// While the product is less than the greatest element of number_map
while (n_product <= size)
{
number_map[n_product] = false;
++multiplicand;
n_product = multiplicand * keyValue.first;
}
}
}
unsigned long long primes_sum = 0;
for (auto keyValue : number_map)
{
if (keyValue.second)
{
primes_sum += keyValue.first;
//std::cout << keyValue.first << std::endl;
}
}
std::cout << primes_sum << std::endl;
}
<|endoftext|> |
<commit_before>/// HEADER
#include <csapex_core_plugins/interactive_node.h>
/// SYSTEM
#include <chrono>
using namespace csapex;
InteractiveNode::InteractiveNode()
: stopped_(false), done_(false)
{
}
void InteractiveNode::process()
{
throw std::runtime_error("not implemented");
}
void InteractiveNode::process(Parameterizable ¶meters)
{
throw std::runtime_error("not implemented");
}
void InteractiveNode::process(Parameterizable ¶meters, std::function<void (std::function<void ()>)> continuation)
{
continuation_ = continuation;
done_ = false;
beginProcess();
}
bool InteractiveNode::isAsynchronous() const
{
return true;
}
void InteractiveNode::done()
{
if(!done_){
done_ = true;
continuation_([this](){ finishProcess(); });
}
}
void InteractiveNode::abort()
{
stopped_ = true;
continuation_([](){});
}
<commit_msg>fixed error with not initialized continuation<commit_after>/// HEADER
#include <csapex_core_plugins/interactive_node.h>
/// SYSTEM
#include <chrono>
using namespace csapex;
InteractiveNode::InteractiveNode()
: stopped_(false), done_(false)
{
}
void InteractiveNode::process()
{
throw std::runtime_error("not implemented");
}
void InteractiveNode::process(Parameterizable ¶meters)
{
throw std::runtime_error("not implemented");
}
void InteractiveNode::process(Parameterizable ¶meters, std::function<void (std::function<void ()>)> continuation)
{
continuation_ = continuation;
done_ = false;
beginProcess();
}
bool InteractiveNode::isAsynchronous() const
{
return true;
}
void InteractiveNode::done()
{
if(!done_){
done_ = true;
continuation_([this](){ finishProcess(); });
}
}
void InteractiveNode::abort()
{
stopped_ = true;
if(continuation_) {
continuation_([](){});
}
}
<|endoftext|> |
<commit_before>/**
* This file is part of the "libfnord" project
* Copyright (c) 2015 Paul Asmuth
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <fnord-base/io/file.h>
#include <fnord-base/io/fileutil.h>
#include <fnord-base/io/mmappedfile.h>
#include <fnord-base/logging.h>
#include <fnord-base/io/fileutil.h>
#include <fnord-dproc/LocalScheduler.h>
namespace fnord {
namespace dproc {
LocalScheduler::LocalScheduler(
const String& tempdir /* = "/tmp" */,
size_t max_threads /* = 8 */) :
tempdir_(tempdir),
tpool_(max_threads) {}
void LocalScheduler::start() {
tpool_.start();
}
void LocalScheduler::stop() {
tpool_.stop();
}
RefPtr<VFSFile> LocalScheduler::run(
Application* app,
TaskSpec task) {
const auto& params = task.params();
return run(app, task.task_name(), Buffer(params.data(), params.size()));
}
RefPtr<VFSFile> LocalScheduler::run(
Application* app,
const String& task,
const Buffer& params) {
RefPtr<LocalTaskRef> head_task(
new LocalTaskRef(app->getTaskInstance(task, params)));
LocalTaskPipeline pipeline;
pipeline.tasks.push_back(head_task);
run(app, &pipeline);
BufferRef buf(new Buffer());
return buf.get();
}
void LocalScheduler::run(
Application* app,
LocalTaskPipeline* pipeline) {
fnord::logInfo(
"fnord.dproc",
"Starting local pipeline id=$0 tasks=$1",
(void*) pipeline,
pipeline->tasks.size());
std::unique_lock<std::mutex> lk(pipeline->mutex);
while (pipeline->tasks.size() > 0) {
bool waiting = true;
size_t num_waiting = 0;
size_t num_running = 0;
size_t num_completed = 0;
for (auto& taskref : pipeline->tasks) {
if (taskref->finished) {
++num_completed;
continue;
}
if (taskref->running) {
++num_running;
continue;
}
if (!taskref->expanded) {
taskref->expanded = true;
auto parent_task = taskref;
for (const auto& dep : taskref->task->dependencies()) {
RefPtr<LocalTaskRef> depref(new LocalTaskRef(
app->getTaskInstance(dep.task_name, dep.params)));
parent_task->dependencies.emplace_back(depref);
pipeline->tasks.emplace_back(depref);
}
waiting = false;
break;
}
bool deps_finished = true;
for (const auto& dep : taskref->dependencies) {
if (!dep->finished) {
deps_finished = false;
}
}
if (!deps_finished) {
++num_waiting;
continue;
}
taskref->running = true;
tpool_.run(std::bind(&LocalScheduler::runTask, this, pipeline, taskref));
waiting = false;
}
fnord::logInfo(
"fnord.dproc",
"Running local pipeline... id=$0 tasks=$1, running=$2, waiting=$3, completed=$4",
(void*) pipeline,
pipeline->tasks.size(),
num_running,
num_waiting,
num_completed);
if (waiting) {
pipeline->wakeup.wait(lk);
}
while (pipeline->tasks.size() > 0 && pipeline->tasks.back()->finished) {
pipeline->tasks.pop_back();
}
}
fnord::logInfo(
"fnord.dproc",
"Completed local pipeline id=$0",
(void*) pipeline);
}
void LocalScheduler::runTask(
LocalTaskPipeline* pipeline,
RefPtr<LocalTaskRef> task) {
auto output_file = FileUtil::joinPaths(tempdir_, rnd_.hex128() + ".tmp");
try {
auto res = task->task->run(task.get());
auto file = File::openFile(
output_file + "~",
File::O_CREATEOROPEN | File::O_WRITE);
file.write(res->data(), res->size());
FileUtil::mv(output_file + "~", output_file);
} catch (const std::exception& e) {
fnord::logError("fnord.dproc", e, "error");
}
std::unique_lock<std::mutex> lk(pipeline->mutex);
task->output_filename = output_file;
task->finished = true;
lk.unlock();
pipeline->wakeup.notify_all();
}
LocalScheduler::LocalTaskRef::LocalTaskRef(RefPtr<Task> _task) :
task(_task),
running(false),
expanded(false),
finished(false) {}
RefPtr<VFSFile> LocalScheduler::LocalTaskRef::getDependency(size_t index) {
if (index >= dependencies.size()) {
RAISEF(kIndexError, "invalid dependecy index: $0", index);
}
const auto& dep = dependencies[index];
if (!FileUtil::exists(dep->output_filename)) {
RAISEF(kRuntimeError, "missing upstream output: $0", dep->output_filename);
}
return RefPtr<VFSFile>(
new io::MmappedFile(
File::openFile(dep->output_filename, File::O_READ)));
}
size_t LocalScheduler::LocalTaskRef::numDependencies() const {
return dependencies.size();
}
} // namespace dproc
} // namespace fnord
<commit_msg>fixes<commit_after>/**
* This file is part of the "libfnord" project
* Copyright (c) 2015 Paul Asmuth
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <fnord-base/io/file.h>
#include <fnord-base/io/fileutil.h>
#include <fnord-base/io/mmappedfile.h>
#include <fnord-base/logging.h>
#include <fnord-base/io/fileutil.h>
#include <fnord-dproc/LocalScheduler.h>
namespace fnord {
namespace dproc {
LocalScheduler::LocalScheduler(
const String& tempdir /* = "/tmp" */,
size_t max_threads /* = 8 */) :
tempdir_(tempdir),
tpool_(max_threads) {}
void LocalScheduler::start() {
tpool_.start();
}
void LocalScheduler::stop() {
tpool_.stop();
}
RefPtr<VFSFile> LocalScheduler::run(
Application* app,
TaskSpec task) {
const auto& params = task.params();
return run(app, task.task_name(), Buffer(params.data(), params.size()));
}
RefPtr<VFSFile> LocalScheduler::run(
Application* app,
const String& task,
const Buffer& params) {
RefPtr<LocalTaskRef> head_task(
new LocalTaskRef(app->getTaskInstance(task, params)));
LocalTaskPipeline pipeline;
pipeline.tasks.push_back(head_task);
run(app, &pipeline);
return RefPtr<VFSFile>(
new io::MmappedFile(
File::openFile(head_task->output_filename, File::O_READ)));
}
void LocalScheduler::run(
Application* app,
LocalTaskPipeline* pipeline) {
fnord::logInfo(
"fnord.dproc",
"Starting local pipeline id=$0 tasks=$1",
(void*) pipeline,
pipeline->tasks.size());
std::unique_lock<std::mutex> lk(pipeline->mutex);
while (pipeline->tasks.size() > 0) {
bool waiting = true;
size_t num_waiting = 0;
size_t num_running = 0;
size_t num_completed = 0;
for (auto& taskref : pipeline->tasks) {
if (taskref->finished) {
++num_completed;
continue;
}
if (taskref->running) {
++num_running;
continue;
}
if (!taskref->expanded) {
taskref->expanded = true;
auto parent_task = taskref;
for (const auto& dep : taskref->task->dependencies()) {
RefPtr<LocalTaskRef> depref(new LocalTaskRef(
app->getTaskInstance(dep.task_name, dep.params)));
parent_task->dependencies.emplace_back(depref);
pipeline->tasks.emplace_back(depref);
}
waiting = false;
break;
}
bool deps_finished = true;
for (const auto& dep : taskref->dependencies) {
if (!dep->finished) {
deps_finished = false;
}
}
if (!deps_finished) {
++num_waiting;
continue;
}
taskref->running = true;
tpool_.run(std::bind(&LocalScheduler::runTask, this, pipeline, taskref));
waiting = false;
}
fnord::logInfo(
"fnord.dproc",
"Running local pipeline... id=$0 tasks=$1, running=$2, waiting=$3, completed=$4",
(void*) pipeline,
pipeline->tasks.size(),
num_running,
num_waiting,
num_completed);
if (waiting) {
pipeline->wakeup.wait(lk);
}
while (pipeline->tasks.size() > 0 && pipeline->tasks.back()->finished) {
pipeline->tasks.pop_back();
}
}
fnord::logInfo(
"fnord.dproc",
"Completed local pipeline id=$0",
(void*) pipeline);
}
void LocalScheduler::runTask(
LocalTaskPipeline* pipeline,
RefPtr<LocalTaskRef> task) {
auto output_file = FileUtil::joinPaths(tempdir_, rnd_.hex128() + ".tmp");
try {
auto res = task->task->run(task.get());
auto file = File::openFile(
output_file + "~",
File::O_CREATEOROPEN | File::O_WRITE);
file.write(res->data(), res->size());
FileUtil::mv(output_file + "~", output_file);
} catch (const std::exception& e) {
fnord::logError("fnord.dproc", e, "error");
}
std::unique_lock<std::mutex> lk(pipeline->mutex);
task->output_filename = output_file;
task->finished = true;
lk.unlock();
pipeline->wakeup.notify_all();
}
LocalScheduler::LocalTaskRef::LocalTaskRef(RefPtr<Task> _task) :
task(_task),
running(false),
expanded(false),
finished(false) {}
RefPtr<VFSFile> LocalScheduler::LocalTaskRef::getDependency(size_t index) {
if (index >= dependencies.size()) {
RAISEF(kIndexError, "invalid dependecy index: $0", index);
}
const auto& dep = dependencies[index];
if (!FileUtil::exists(dep->output_filename)) {
RAISEF(kRuntimeError, "missing upstream output: $0", dep->output_filename);
}
return RefPtr<VFSFile>(
new io::MmappedFile(
File::openFile(dep->output_filename, File::O_READ)));
}
size_t LocalScheduler::LocalTaskRef::numDependencies() const {
return dependencies.size();
}
} // namespace dproc
} // namespace fnord
<|endoftext|> |
<commit_before>// Copyright © 2015 Mikko Ronkainen <[email protected]>
// License: MIT, see the LICENSE file.
#include <cmath>
#include "Raytracing/Primitives/Sphere.h"
#include "Raytracing/Ray.h"
#include "Raytracing/Intersection.h"
using namespace Raycer;
void Sphere::initialize()
{
}
void Sphere::intersect(Ray& ray) const
{
Vector3 originToCenter = position - ray.origin;
double originToSphereDistance2 = originToCenter.lengthSquared();
double radius2 = radius * radius;
// ray origin inside the sphere
if (originToSphereDistance2 < radius2)
return;
double ta = originToCenter.dot(ray.direction);
// sphere is behind the ray
if (ta < 0.0)
return;
double sphereToRayDistance2 = originToSphereDistance2 - (ta * ta);
// ray misses the sphere
if (sphereToRayDistance2 > radius2)
return;
double tb = sqrt(radius2 - sphereToRayDistance2);
double t = ta - tb;
// there was another intersection closer to camera
if (t > ray.intersection.distance)
return;
Vector3 intersectionPosition = ray.origin + (t * ray.direction);
Vector3 intersectionNormal = (intersectionPosition - position).normalized();
ray.intersection.wasFound = true;
ray.intersection.distance = t;
ray.intersection.position = intersectionPosition;
ray.intersection.normal = intersectionNormal;
ray.intersection.materialId = materialId;
double u = 0.5 + atan2(intersectionNormal.z, intersectionNormal.x) / (2.0 * M_PI);
double v = 0.5 - asin(intersectionNormal.y) / M_PI;
u /= texcoordScale.x;
v /= texcoordScale.y;
ray.intersection.texcoord.x = u - floor(u);
ray.intersection.texcoord.y = v - floor(v);
}
<commit_msg>Improved ray sphere intersection logic<commit_after>// Copyright © 2015 Mikko Ronkainen <[email protected]>
// License: MIT, see the LICENSE file.
#include <cmath>
#include "Raytracing/Primitives/Sphere.h"
#include "Raytracing/Ray.h"
#include "Raytracing/Intersection.h"
using namespace Raycer;
void Sphere::initialize()
{
}
void Sphere::intersect(Ray& ray) const
{
Vector3 rayOriginToSphere = position - ray.origin;
double rayOriginToSphereDistance2 = rayOriginToSphere.lengthSquared();
double radius2 = radius * radius;
double t1 = rayOriginToSphere.dot(ray.direction);
double sphereToRayDistance2 = rayOriginToSphereDistance2 - (t1 * t1);
bool rayOriginIsOutside = (rayOriginToSphereDistance2 >= radius2);
if (rayOriginIsOutside)
{
// whole sphere is behind the ray origin
if (t1 < 0.0)
return;
// ray misses the sphere completely
if (sphereToRayDistance2 > radius2)
return;
}
double t2 = sqrt(radius2 - sphereToRayDistance2);
double t = (rayOriginIsOutside) ? (t1 - t2) : (t1 + t2);
// there was another intersection closer to camera
if (t > ray.intersection.distance)
return;
Vector3 intersectionPosition = ray.origin + (t * ray.direction);
Vector3 intersectionNormal = (intersectionPosition - position).normalized();
ray.intersection.wasFound = true;
ray.intersection.distance = t;
ray.intersection.position = intersectionPosition;
ray.intersection.normal = rayOriginIsOutside ? intersectionNormal : -intersectionNormal;
ray.intersection.materialId = materialId;
// spherical texture coordinate calculation
double u = 0.5 + atan2(intersectionNormal.z, intersectionNormal.x) / (2.0 * M_PI);
double v = 0.5 - asin(intersectionNormal.y) / M_PI;
u /= texcoordScale.x;
v /= texcoordScale.y;
ray.intersection.texcoord.x = u - floor(u);
ray.intersection.texcoord.y = v - floor(v);
}
<|endoftext|> |
<commit_before>#include "SettingsWindow.hpp"
#include <imgui.h>
#include "../ImGui/Theme.hpp"
using namespace GUI;
SettingsWindow::SettingsWindow() {
themes.push_back("Default");
}
void SettingsWindow::Show() {
if (ImGui::Begin("Settings", &visible)) {
// Show drop down list to select theme.
if (dropDownItems != nullptr)
delete[] dropDownItems;
dropDownItems = new const char*[themes.size()];
for (std::size_t i=0; i < themes.size(); ++i) {
dropDownItems[i] = themes[i].c_str();
}
ImGui::Combo("Theme", &theme, dropDownItems, themes.size());
// Clone current theme to create a new theme.
if (ImGui::Button("Clone")) {
ImGui::OpenPopup("Theme Name");
themeName[0] = '\0';
}
if (ImGui::BeginPopupModal("Theme Name", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) {
ImGui::InputText("Name", themeName, 128);
if (ImGui::Button("Create")) {
ImGui::SaveTheme(themeName);
themes.push_back(themeName);
ImGui::CloseCurrentPopup();
}
ImGui::SameLine();
if (ImGui::Button("Cancel"))
ImGui::CloseCurrentPopup();
ImGui::EndPopup();
}
ImGui::Separator();
// Edit the current theme.
if (theme != 0)
ImGui::ShowStyleEditor();
}
ImGui::End();
}
bool SettingsWindow::IsVisible() const {
return visible;
}
void SettingsWindow::SetVisible(bool visible) {
this->visible = visible;
}
<commit_msg>Show list of available themes<commit_after>#include "SettingsWindow.hpp"
#include <imgui.h>
#include "../ImGui/Theme.hpp"
#include <Engine/Util/FileSystem.hpp>
using namespace GUI;
SettingsWindow::SettingsWindow() {
themes.push_back("Default");
std::vector<std::string> themeFiles = FileSystem::DirectoryContents(FileSystem::DataPath("Hymn to Beauty") + FileSystem::DELIMITER + "Themes", FileSystem::FILE);
for (std::string theme : themeFiles) {
if (FileSystem::GetExtension(theme) == "json")
themes.push_back(theme.substr(0, theme.find_last_of(".")));
}
}
void SettingsWindow::Show() {
if (ImGui::Begin("Settings", &visible)) {
// Show drop down list to select theme.
if (dropDownItems != nullptr)
delete[] dropDownItems;
dropDownItems = new const char*[themes.size()];
for (std::size_t i=0; i < themes.size(); ++i) {
dropDownItems[i] = themes[i].c_str();
}
ImGui::Combo("Theme", &theme, dropDownItems, themes.size());
// Clone current theme to create a new theme.
if (ImGui::Button("Clone")) {
ImGui::OpenPopup("Theme Name");
themeName[0] = '\0';
}
if (ImGui::BeginPopupModal("Theme Name", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) {
ImGui::InputText("Name", themeName, 128);
if (ImGui::Button("Create")) {
ImGui::SaveTheme(themeName);
themes.push_back(themeName);
ImGui::CloseCurrentPopup();
}
ImGui::SameLine();
if (ImGui::Button("Cancel"))
ImGui::CloseCurrentPopup();
ImGui::EndPopup();
}
ImGui::Separator();
// Edit the current theme.
if (theme != 0)
ImGui::ShowStyleEditor();
}
ImGui::End();
}
bool SettingsWindow::IsVisible() const {
return visible;
}
void SettingsWindow::SetVisible(bool visible) {
this->visible = visible;
}
<|endoftext|> |
<commit_before>#include "window.h"
#include <algorithm>
#include "augs/log.h"
#include "augs/templates/string_templates.h"
#include "platform_utils.h"
#ifdef PLATFORM_WINDOWS
#include "augs/window_framework/translate_windows_enums.h"
namespace augs {
namespace window {
LRESULT CALLBACK wndproc(HWND hwnd, UINT umsg, WPARAM wParam, LPARAM lParam) {
if (umsg == WM_GETMINMAXINFO || umsg == WM_INPUT)
return DefWindowProc(hwnd, umsg, wParam, lParam);
static glwindow* wnd;
wnd = (glwindow*)GetWindowLongPtr(hwnd, GWLP_USERDATA);
if (umsg == WM_CREATE)
AddClipboardFormatListener(hwnd);
if (wnd) {
if (umsg == WM_DESTROY) {
RemoveClipboardFormatListener(hwnd);
}
else if (umsg == WM_SYSCOMMAND || umsg == WM_ACTIVATE || umsg == WM_INPUT) {
(PostMessage(hwnd, umsg, wParam, lParam));
return 0;
}
else if (umsg == WM_GETMINMAXINFO) {
UINT in = umsg;
wnd->_poll(in, wParam, lParam);
return 0;
}
else if (umsg == WM_SIZE) {
LRESULT res = DefWindowProc(hwnd, umsg, wParam, lParam);
return res;
}
}
return DefWindowProc(hwnd, umsg, wParam, lParam);
}
void glwindow::_poll(UINT& m, WPARAM wParam, LPARAM lParam) {
using namespace event::keys;
using namespace event;
static POINTS p;
static RECT* r;
static long rw, rh;
static MINMAXINFO* mi;
static BYTE lpb[40];
static UINT dwSize = 40;
static RAWINPUT* raw;
latest_change = change();
auto& events = latest_change;
switch (m) {
case WM_CHAR:
events.character.utf16 = wchar_t(wParam);
if (events.character.utf16 > 255) {
break;
}
//events.utf32 = unsigned(wParam);
events.repeated = ((lParam & (1 << 30)) != 0);
break;
case WM_UNICHAR:
//events.utf32 = unsigned(wParam);
//events.repeated = ((lParam & (1 << 30)) != 0);
break;
case SC_CLOSE:
break;
case WM_KEYUP:
events.key.key = translate_key_with_lparam(lParam, wParam);
break;
case WM_KEYDOWN:
events.key.key = translate_key_with_lparam(lParam, wParam);
events.repeated = ((lParam & (1 << 30)) != 0);
break;
case WM_SYSKEYUP:
events.key.key = translate_key_with_lparam(lParam, wParam);
break;
case WM_SYSKEYDOWN:
events.key.key = translate_key_with_lparam(lParam, wParam);
events.repeated = ((lParam & (1 << 30)) != 0);
break;
case WM_MOUSEWHEEL:
events.scroll.amount = GET_WHEEL_DELTA_WPARAM(wParam) / WHEEL_DELTA;
break;
case WM_LBUTTONDBLCLK:
case WM_LBUTTONDOWN:
events.key.key = key::LMOUSE;
SetCapture(hwnd);
if (m == WM_LBUTTONDOWN) {
if (doubled && triple_timer.extract<std::chrono::milliseconds>() < triple_click_delay) {
m = unsigned(message::ltripleclick);
doubled = false;
}
}
else {
triple_timer.extract<std::chrono::microseconds>();
doubled = true;
}
break;
case WM_RBUTTONDBLCLK:
case WM_RBUTTONDOWN:
events.key.key = key::RMOUSE;
break;
case WM_MBUTTONDBLCLK:
case WM_MBUTTONDOWN:
events.key.key = key::MMOUSE;
break;
case WM_XBUTTONDBLCLK:
case WM_XBUTTONDOWN:
events.key.key = key::MOUSE4;
break;
case WM_XBUTTONUP:
events.key.key = key::MOUSE4;
break;
case WM_LBUTTONUP:
events.key.key = key::LMOUSE;
if (GetCapture() == hwnd) ReleaseCapture(); break;
case WM_RBUTTONUP:
events.key.key = key::RMOUSE;
break;
case WM_MBUTTONUP:
events.key.key = key::MMOUSE;
break;
case WM_MOUSEMOVE:
if (!raw_mouse_input) {
p = MAKEPOINTS(lParam);
events.mouse.rel.x = p.x - last_mouse_pos.x;
events.mouse.rel.y = p.y - last_mouse_pos.y;
if (events.mouse.rel.x || events.mouse.rel.y) doubled = false;
last_mouse_pos.x = p.x;
last_mouse_pos.y = p.y;
m = WM_MOUSEMOVE;
}
break;
case WM_INPUT:
if (raw_mouse_input) {
GetRawInputData(reinterpret_cast<HRAWINPUT>(lParam), RID_INPUT,
lpb, &dwSize, sizeof(RAWINPUTHEADER));
raw = reinterpret_cast<RAWINPUT*>(lpb);
if (raw->header.dwType == RIM_TYPEMOUSE) {
events.mouse.rel.x = static_cast<short>(raw->data.mouse.lLastX);
events.mouse.rel.y = static_cast<short>(raw->data.mouse.lLastY);
m = WM_MOUSEMOVE;
}
}
break;
case WM_ACTIVATE:
active = LOWORD(wParam) == WA_ACTIVE;
break;
case WM_GETMINMAXINFO:
mi = (MINMAXINFO*)lParam;
mi->ptMinTrackSize.x = min_window_size.x;
mi->ptMinTrackSize.y = min_window_size.y;
mi->ptMaxTrackSize.x = max_window_size.x;
mi->ptMaxTrackSize.y = max_window_size.y;
break;
case WM_SYSCOMMAND:
m = wParam;
switch (wParam) {
default: DefWindowProc(hwnd, m, wParam, lParam); break;
}
m = wParam;
break;
default: DefWindowProc(hwnd, m, wParam, lParam); break;
}
events.msg = translate_enum(m);
}
glwindow* glwindow::context = nullptr;
glwindow::glwindow() {
triple_click_delay = GetDoubleClickTime();
}
void glwindow::set_window_name(const std::string& name) {
SetWindowText(hwnd, to_wstring(name).c_str());
}
void glwindow::create(
const int bpp
) {
if(!window_class_registered) {
WNDCLASSEX wcl = { 0 };
wcl.cbSize = sizeof(wcl);
wcl.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS;
wcl.lpfnWndProc = window::wndproc;
wcl.cbClsExtra = 0;
wcl.cbWndExtra = 0;
wcl.hInstance = GetModuleHandle(NULL);
wcl.hIcon = LoadIcon(0, IDI_APPLICATION);
wcl.hCursor = LoadCursor(0, IDC_ARROW);
wcl.hbrBackground = 0;
wcl.lpszMenuName = 0;
wcl.lpszClassName = L"AugmentedWindow";
wcl.hIconSm = 0;
ensure(RegisterClassEx(&wcl) != 0 && "class registering");
window_class_registered = true;
}
ensure((hwnd = CreateWindowEx(0, L"AugmentedWindow", L"invalid_name", 0, 0, 0, 0, 0, 0, 0, GetModuleHandle(NULL), this)));
PIXELFORMATDESCRIPTOR p;
ZeroMemory(&p, sizeof(p));
p.nSize = sizeof(p);
p.nVersion = 1;
p.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
p.iPixelType = PFD_TYPE_RGBA;
p.cColorBits = bpp;
p.cAlphaBits = 8;
p.cDepthBits = 16;
p.iLayerType = PFD_MAIN_PLANE;
ensure(hdc = GetDC(hwnd));
GLuint pf;
ensure(pf = ChoosePixelFormat(hdc, &p));
ensure(SetPixelFormat(hdc, pf, &p));
ensure(hglrc = wglCreateContext(hdc));
set_as_current();
show();
SetLastError(0);
ensure(!(SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR)this) == 0 && GetLastError() != 0));
#ifndef HID_USAGE_PAGE_GENERIC
#define HID_USAGE_PAGE_GENERIC ((USHORT) 0x01)
#endif
#ifndef HID_USAGE_GENERIC_MOUSE
#define HID_USAGE_GENERIC_MOUSE ((USHORT) 0x02)
#endif
RAWINPUTDEVICE Rid[1];
Rid[0].usUsagePage = HID_USAGE_PAGE_GENERIC;
Rid[0].usUsage = HID_USAGE_GENERIC_MOUSE;
Rid[0].dwFlags = RIDEV_INPUTSINK;
Rid[0].hwndTarget = hwnd;
RegisterRawInputDevices(Rid, 1, sizeof(Rid[0]));
}
void glwindow::set_window_border_enabled(const bool f) {
const auto menu = f ? WS_CAPTION | WS_SYSMENU : 0;
style = menu ? (WS_OVERLAPPED | menu) | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_THICKFRAME | WS_SYSMENU | WS_MAXIMIZEBOX | WS_MINIMIZEBOX : WS_POPUP;
exstyle = menu ? WS_EX_WINDOWEDGE : WS_EX_APPWINDOW;
SetWindowLongPtr(hwnd, GWL_EXSTYLE, exstyle);
SetWindowLongPtr(hwnd, GWL_STYLE, style);
SetWindowPos(hwnd, NULL, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
set_window_rect(get_window_rect());
show();
}
bool glwindow::swap_buffers() {
if (this != context) set_as_current();
return SwapBuffers(hdc) != FALSE;
}
void glwindow::show() {
ShowWindow(hwnd, SW_SHOW);
}
bool glwindow::set_as_current_impl() {
return wglMakeCurrent(hdc, hglrc);
}
bool glwindow::poll_event(UINT& out) {
if (PeekMessageW(&wmsg, hwnd, 0, 0, PM_REMOVE)) {
//DispatchMessage(&wmsg);
out = wmsg.message;
_poll(out, wmsg.wParam, wmsg.lParam);
TranslateMessage(&wmsg);
return true;
}
return false;
}
std::vector<event::change> glwindow::poll_events(const bool should_clip_cursor) {
ensure(is_current());
UINT msg;
std::vector<event::change> output;
while (poll_event(msg)) {
auto& state = latest_change;
if (!state.repeated) {
output.push_back(state);
}
}
if (should_clip_cursor && GetFocus() == hwnd) {
enable_cursor_clipping(get_window_rect());
}
else {
disable_cursor_clipping();
}
return output;
}
void glwindow::set_window_rect(const xywhi r) {
static RECT wr = { 0 };
ensure(SetRect(&wr, r.x, r.y, r.r(), r.b()));
ensure(AdjustWindowRectEx(&wr, style, FALSE, exstyle));
ensure(MoveWindow(hwnd, wr.left, wr.top, wr.right - wr.left, wr.bottom - wr.top, TRUE));
}
vec2i glwindow::get_screen_size() const {
return get_window_rect().get_size();
}
xywhi glwindow::get_window_rect() const {
static RECT r;
GetClientRect(hwnd, &r);
ClientToScreen(hwnd, (POINT*)&r);
ClientToScreen(hwnd, (POINT*)&r + 1);
return ltrbi(r.left, r.top, r.right, r.bottom);
}
bool glwindow::is_active() const {
return active;
}
void glwindow::destroy() {
if (hwnd) {
if (is_current()) {
wglMakeCurrent(NULL, NULL);
wglDeleteContext(hglrc);
set_current_to_none();
}
ReleaseDC(hwnd, hdc);
DestroyWindow(hwnd);
hwnd = nullptr;
hdc = nullptr;
hglrc = nullptr;
}
}
glwindow::~glwindow() {
destroy();
}
}
}
bool augs::window::glwindow::window_class_registered = false;
#elif PLATFORM_LINUX
#endif
<commit_msg>window bugfix<commit_after>#include "window.h"
#include <algorithm>
#include "augs/log.h"
#include "augs/templates/string_templates.h"
#include "platform_utils.h"
#ifdef PLATFORM_WINDOWS
#include "augs/window_framework/translate_windows_enums.h"
namespace augs {
namespace window {
LRESULT CALLBACK wndproc(HWND hwnd, UINT umsg, WPARAM wParam, LPARAM lParam) {
if (umsg == WM_GETMINMAXINFO || umsg == WM_INPUT)
return DefWindowProc(hwnd, umsg, wParam, lParam);
static glwindow* wnd;
wnd = (glwindow*)GetWindowLongPtr(hwnd, GWLP_USERDATA);
if (umsg == WM_CREATE)
AddClipboardFormatListener(hwnd);
if (wnd) {
if (umsg == WM_DESTROY) {
RemoveClipboardFormatListener(hwnd);
}
else if (umsg == WM_SYSCOMMAND || umsg == WM_ACTIVATE || umsg == WM_INPUT) {
(PostMessage(hwnd, umsg, wParam, lParam));
return 0;
}
else if (umsg == WM_GETMINMAXINFO) {
UINT in = umsg;
wnd->_poll(in, wParam, lParam);
return 0;
}
else if (umsg == WM_SIZE) {
LRESULT res = DefWindowProc(hwnd, umsg, wParam, lParam);
return res;
}
}
return DefWindowProc(hwnd, umsg, wParam, lParam);
}
void glwindow::_poll(UINT& m, WPARAM wParam, LPARAM lParam) {
using namespace event::keys;
using namespace event;
static POINTS p;
static RECT* r;
static long rw, rh;
static MINMAXINFO* mi;
static BYTE lpb[40];
static UINT dwSize = 40;
static RAWINPUT* raw;
latest_change = change();
auto& events = latest_change;
switch (m) {
case WM_CHAR:
events.character.utf16 = wchar_t(wParam);
if (events.character.utf16 > 255) {
break;
}
//events.utf32 = unsigned(wParam);
events.repeated = ((lParam & (1 << 30)) != 0);
break;
case WM_UNICHAR:
//events.utf32 = unsigned(wParam);
//events.repeated = ((lParam & (1 << 30)) != 0);
break;
case SC_CLOSE:
break;
case WM_KEYUP:
events.key.key = translate_key_with_lparam(lParam, wParam);
break;
case WM_KEYDOWN:
events.key.key = translate_key_with_lparam(lParam, wParam);
events.repeated = ((lParam & (1 << 30)) != 0);
break;
case WM_SYSKEYUP:
events.key.key = translate_key_with_lparam(lParam, wParam);
break;
case WM_SYSKEYDOWN:
events.key.key = translate_key_with_lparam(lParam, wParam);
events.repeated = ((lParam & (1 << 30)) != 0);
break;
case WM_MOUSEWHEEL:
events.scroll.amount = GET_WHEEL_DELTA_WPARAM(wParam) / WHEEL_DELTA;
break;
case WM_LBUTTONDBLCLK:
case WM_LBUTTONDOWN:
events.key.key = key::LMOUSE;
SetCapture(hwnd);
if (m == WM_LBUTTONDOWN) {
if (doubled && triple_timer.extract<std::chrono::milliseconds>() < triple_click_delay) {
m = unsigned(message::ltripleclick);
doubled = false;
}
}
else {
triple_timer.extract<std::chrono::microseconds>();
doubled = true;
}
break;
case WM_RBUTTONDBLCLK:
case WM_RBUTTONDOWN:
events.key.key = key::RMOUSE;
break;
case WM_MBUTTONDBLCLK:
case WM_MBUTTONDOWN:
events.key.key = key::MMOUSE;
break;
case WM_XBUTTONDBLCLK:
case WM_XBUTTONDOWN:
events.key.key = key::MOUSE4;
break;
case WM_XBUTTONUP:
events.key.key = key::MOUSE4;
break;
case WM_LBUTTONUP:
events.key.key = key::LMOUSE;
if (GetCapture() == hwnd) ReleaseCapture(); break;
case WM_RBUTTONUP:
events.key.key = key::RMOUSE;
break;
case WM_MBUTTONUP:
events.key.key = key::MMOUSE;
break;
case WM_MOUSEMOVE:
if (!raw_mouse_input) {
p = MAKEPOINTS(lParam);
events.mouse.rel.x = p.x - last_mouse_pos.x;
events.mouse.rel.y = p.y - last_mouse_pos.y;
if (events.mouse.rel.x || events.mouse.rel.y) doubled = false;
last_mouse_pos.x = p.x;
last_mouse_pos.y = p.y;
m = WM_MOUSEMOVE;
}
break;
case WM_INPUT:
if (raw_mouse_input) {
GetRawInputData(reinterpret_cast<HRAWINPUT>(lParam), RID_INPUT,
lpb, &dwSize, sizeof(RAWINPUTHEADER));
raw = reinterpret_cast<RAWINPUT*>(lpb);
if (raw->header.dwType == RIM_TYPEMOUSE) {
events.mouse.rel.x = static_cast<short>(raw->data.mouse.lLastX);
events.mouse.rel.y = static_cast<short>(raw->data.mouse.lLastY);
m = WM_MOUSEMOVE;
}
}
break;
case WM_ACTIVATE:
active = LOWORD(wParam) == WA_ACTIVE;
break;
case WM_GETMINMAXINFO:
mi = (MINMAXINFO*)lParam;
mi->ptMinTrackSize.x = min_window_size.x;
mi->ptMinTrackSize.y = min_window_size.y;
mi->ptMaxTrackSize.x = max_window_size.x;
mi->ptMaxTrackSize.y = max_window_size.y;
break;
case WM_SYSCOMMAND:
switch (wParam) {
default: DefWindowProc(hwnd, m, wParam, lParam); break;
}
m = wParam;
break;
default: DefWindowProc(hwnd, m, wParam, lParam); break;
}
events.msg = translate_enum(m);
}
glwindow* glwindow::context = nullptr;
glwindow::glwindow() {
triple_click_delay = GetDoubleClickTime();
}
void glwindow::set_window_name(const std::string& name) {
SetWindowText(hwnd, to_wstring(name).c_str());
}
void glwindow::create(
const int bpp
) {
if(!window_class_registered) {
WNDCLASSEX wcl = { 0 };
wcl.cbSize = sizeof(wcl);
wcl.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS;
wcl.lpfnWndProc = window::wndproc;
wcl.cbClsExtra = 0;
wcl.cbWndExtra = 0;
wcl.hInstance = GetModuleHandle(NULL);
wcl.hIcon = LoadIcon(0, IDI_APPLICATION);
wcl.hCursor = LoadCursor(0, IDC_ARROW);
wcl.hbrBackground = 0;
wcl.lpszMenuName = 0;
wcl.lpszClassName = L"AugmentedWindow";
wcl.hIconSm = 0;
ensure(RegisterClassEx(&wcl) != 0 && "class registering");
window_class_registered = true;
}
ensure((hwnd = CreateWindowEx(0, L"AugmentedWindow", L"invalid_name", 0, 0, 0, 0, 0, 0, 0, GetModuleHandle(NULL), this)));
PIXELFORMATDESCRIPTOR p;
ZeroMemory(&p, sizeof(p));
p.nSize = sizeof(p);
p.nVersion = 1;
p.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
p.iPixelType = PFD_TYPE_RGBA;
p.cColorBits = bpp;
p.cAlphaBits = 8;
p.cDepthBits = 16;
p.iLayerType = PFD_MAIN_PLANE;
ensure(hdc = GetDC(hwnd));
GLuint pf;
ensure(pf = ChoosePixelFormat(hdc, &p));
ensure(SetPixelFormat(hdc, pf, &p));
ensure(hglrc = wglCreateContext(hdc));
set_as_current();
show();
SetLastError(0);
ensure(!(SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR)this) == 0 && GetLastError() != 0));
#ifndef HID_USAGE_PAGE_GENERIC
#define HID_USAGE_PAGE_GENERIC ((USHORT) 0x01)
#endif
#ifndef HID_USAGE_GENERIC_MOUSE
#define HID_USAGE_GENERIC_MOUSE ((USHORT) 0x02)
#endif
RAWINPUTDEVICE Rid[1];
Rid[0].usUsagePage = HID_USAGE_PAGE_GENERIC;
Rid[0].usUsage = HID_USAGE_GENERIC_MOUSE;
Rid[0].dwFlags = RIDEV_INPUTSINK;
Rid[0].hwndTarget = hwnd;
RegisterRawInputDevices(Rid, 1, sizeof(Rid[0]));
}
void glwindow::set_window_border_enabled(const bool f) {
const auto menu = f ? WS_CAPTION | WS_SYSMENU : 0;
style = menu ? (WS_OVERLAPPED | menu) | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_THICKFRAME | WS_SYSMENU | WS_MAXIMIZEBOX | WS_MINIMIZEBOX : WS_POPUP;
exstyle = menu ? WS_EX_WINDOWEDGE : WS_EX_APPWINDOW;
SetWindowLongPtr(hwnd, GWL_EXSTYLE, exstyle);
SetWindowLongPtr(hwnd, GWL_STYLE, style);
SetWindowPos(hwnd, NULL, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
set_window_rect(get_window_rect());
show();
}
bool glwindow::swap_buffers() {
if (this != context) set_as_current();
return SwapBuffers(hdc) != FALSE;
}
void glwindow::show() {
ShowWindow(hwnd, SW_SHOW);
}
bool glwindow::set_as_current_impl() {
return wglMakeCurrent(hdc, hglrc);
}
bool glwindow::poll_event(UINT& out) {
if (PeekMessageW(&wmsg, hwnd, 0, 0, PM_REMOVE)) {
//DispatchMessage(&wmsg);
out = wmsg.message;
_poll(out, wmsg.wParam, wmsg.lParam);
TranslateMessage(&wmsg);
return true;
}
return false;
}
std::vector<event::change> glwindow::poll_events(const bool should_clip_cursor) {
ensure(is_current());
UINT msg;
std::vector<event::change> output;
while (poll_event(msg)) {
auto& state = latest_change;
if (!state.repeated) {
output.push_back(state);
}
}
if (should_clip_cursor && GetFocus() == hwnd) {
enable_cursor_clipping(get_window_rect());
}
else {
disable_cursor_clipping();
}
return output;
}
void glwindow::set_window_rect(const xywhi r) {
static RECT wr = { 0 };
ensure(SetRect(&wr, r.x, r.y, r.r(), r.b()));
ensure(AdjustWindowRectEx(&wr, style, FALSE, exstyle));
ensure(MoveWindow(hwnd, wr.left, wr.top, wr.right - wr.left, wr.bottom - wr.top, TRUE));
}
vec2i glwindow::get_screen_size() const {
return get_window_rect().get_size();
}
xywhi glwindow::get_window_rect() const {
static RECT r;
GetClientRect(hwnd, &r);
ClientToScreen(hwnd, (POINT*)&r);
ClientToScreen(hwnd, (POINT*)&r + 1);
return ltrbi(r.left, r.top, r.right, r.bottom);
}
bool glwindow::is_active() const {
return active;
}
void glwindow::destroy() {
if (hwnd) {
if (is_current()) {
wglMakeCurrent(NULL, NULL);
wglDeleteContext(hglrc);
set_current_to_none();
}
ReleaseDC(hwnd, hdc);
DestroyWindow(hwnd);
hwnd = nullptr;
hdc = nullptr;
hglrc = nullptr;
}
}
glwindow::~glwindow() {
destroy();
}
}
}
bool augs::window::glwindow::window_class_registered = false;
#elif PLATFORM_LINUX
#endif
<|endoftext|> |
<commit_before>#pragma once
#include <queue>
#include <boost/asio.hpp>
#include <blackhole/formatter/string.hpp>
#include <blackhole/log.hpp>
#include <blackhole/logger.hpp>
#include <blackhole/sink/stream.hpp>
#include <blackhole/synchronized.hpp>
#include <blackhole/utils/atomic.hpp>
#include <blackhole/utils/format.hpp>
#include "elasticsearch/client.hpp"
#include "elasticsearch/result.hpp"
#include "elasticsearch/settings.hpp"
#include "elasticsearch/queue.hpp"
namespace blackhole {
namespace sink {
namespace elasticsearch_ {
struct config_t {
int bulk;
int interval;
elasticsearch::settings_t settings;
};
} // namespace elasticsearch
class elasticsearch_t {
public:
typedef elasticsearch_::config_t config_type;
private:
synchronized<logger_base_t> log;
boost::posix_time::milliseconds interval;
std::atomic<bool> stopped;
boost::asio::io_service loop;
boost::asio::deadline_timer timer;
std::thread thread;
bulk::queue_t<std::string> queue;
elasticsearch::client_t client;
public:
elasticsearch_t(std::uint16_t bulk = 100,
std::uint32_t interval = 1000,
elasticsearch::settings_t settings = elasticsearch::settings_t()) :
log(elasticsearch::logger_factory_t::create()),
interval(interval),
stopped(true),
timer(loop),
thread(start()),
queue(bulk, std::bind(&elasticsearch_t::on_bulk, this, std::placeholders::_1)),
client(settings, loop, log)
{}
elasticsearch_t(const config_type& config) :
log(elasticsearch::logger_factory_t::create()),
interval(config.interval),
stopped(true),
timer(loop),
thread(start()),
queue(config.bulk, std::bind(&elasticsearch_t::on_bulk, this, std::placeholders::_1)),
client(config.settings, loop, log)
{}
~elasticsearch_t() {
stop();
}
void consume(std::string message) {
if (stopped) {
ES_LOG(log, "dropping '%s', because worker thread is stopped", message);
return;
}
ES_LOG(log, "pushing '%s' to the queue", message);
queue.push(std::move(message));
}
private:
std::thread start() {
std::mutex mutex;
std::unique_lock<std::mutex> lock(mutex);
std::condition_variable started;
std::thread thread(
std::bind(&elasticsearch_t::run, this, std::ref(started))
);
started.wait(lock);
return std::move(thread);
}
void run(std::condition_variable& started) {
BOOST_ASSERT(stopped);
ES_LOG(log, "starting elasticsearch sink ...");
loop.post(
std::bind(&elasticsearch_t::on_started, this, std::ref(started))
);
timer.expires_from_now(interval);
timer.async_wait(
std::bind(&elasticsearch_t::on_timer, this, std::placeholders::_1)
);
boost::system::error_code ec;
loop.run(ec);
ES_LOG(log, "elasticsearch sink has been stopped: %s", ec ? ec.message() : "ok");
}
void stop() {
stopped = true;
timer.cancel();
client.stop();
if (thread.joinable()) {
ES_LOG(log, "stopping worker thread ...");
thread.join();
}
}
void on_started(std::condition_variable& started) {
ES_LOG(log, "elasticsearch sink has been started");
stopped = false;
started.notify_all();
}
void on_bulk(std::vector<std::string>&& result) {
loop.post(
std::bind(&elasticsearch_t::handle_bulk, this, std::move(result))
);
}
void handle_bulk(std::vector<std::string> result) {
ES_LOG(log, "processing bulk event ...");
process(std::move(result));
}
void on_timer(const boost::system::error_code& ec) {
if (ec) {
ES_LOG(log, "processing timer event failed: %s", ec.message());
} else {
ES_LOG(log, "processing timer event ...");
process(std::move(queue.dump()));
}
}
void process(std::vector<std::string>&& result) {
if (stopped) {
ES_LOG(log, "dropping %d messages, because worker thread is stopped",
result.size());
return;
}
ES_LOG(log, "processing bulk containing %d messages ...", result.size());
client.bulk_write(
std::move(result),
std::bind(&elasticsearch_t::on_response, this, std::placeholders::_1)
);
timer.expires_from_now(interval);
timer.async_wait(
std::bind(&elasticsearch_t::on_timer, this, std::placeholders::_1)
);
}
void on_response(elasticsearch::result_t<
elasticsearch::response::bulk_write_t
>::type&& result) {
if (boost::get<elasticsearch::error_t>(&result)) {
ES_LOG(log, "bulk write failed");
return;
}
ES_LOG(log, "success!");
}
};
} // namespace sink
} // namespace blackhole
<commit_msg>[Elasticsearch] Elasticsearch sink now has own name.<commit_after>#pragma once
#include <queue>
#include <boost/asio.hpp>
#include <blackhole/formatter/string.hpp>
#include <blackhole/log.hpp>
#include <blackhole/logger.hpp>
#include <blackhole/sink/stream.hpp>
#include <blackhole/synchronized.hpp>
#include <blackhole/utils/atomic.hpp>
#include <blackhole/utils/format.hpp>
#include "elasticsearch/client.hpp"
#include "elasticsearch/result.hpp"
#include "elasticsearch/settings.hpp"
#include "elasticsearch/queue.hpp"
namespace blackhole {
namespace sink {
namespace elasticsearch_ {
struct config_t {
int bulk;
int interval;
elasticsearch::settings_t settings;
};
} // namespace elasticsearch
class elasticsearch_t {
public:
typedef elasticsearch_::config_t config_type;
private:
synchronized<logger_base_t> log;
boost::posix_time::milliseconds interval;
std::atomic<bool> stopped;
boost::asio::io_service loop;
boost::asio::deadline_timer timer;
std::thread thread;
bulk::queue_t<std::string> queue;
elasticsearch::client_t client;
public:
elasticsearch_t(std::uint16_t bulk = 100,
std::uint32_t interval = 1000,
elasticsearch::settings_t settings = elasticsearch::settings_t()) :
log(elasticsearch::logger_factory_t::create()),
interval(interval),
stopped(true),
timer(loop),
thread(start()),
queue(bulk, std::bind(&elasticsearch_t::on_bulk, this, std::placeholders::_1)),
client(settings, loop, log)
{}
elasticsearch_t(const config_type& config) :
log(elasticsearch::logger_factory_t::create()),
interval(config.interval),
stopped(true),
timer(loop),
thread(start()),
queue(config.bulk, std::bind(&elasticsearch_t::on_bulk, this, std::placeholders::_1)),
client(config.settings, loop, log)
{}
~elasticsearch_t() {
stop();
}
static const char* name() {
return "elasticsearch";
}
void consume(std::string message) {
if (stopped) {
ES_LOG(log, "dropping '%s', because worker thread is stopped", message);
return;
}
ES_LOG(log, "pushing '%s' to the queue", message);
queue.push(std::move(message));
}
private:
std::thread start() {
std::mutex mutex;
std::unique_lock<std::mutex> lock(mutex);
std::condition_variable started;
std::thread thread(
std::bind(&elasticsearch_t::run, this, std::ref(started))
);
started.wait(lock);
return std::move(thread);
}
void run(std::condition_variable& started) {
BOOST_ASSERT(stopped);
ES_LOG(log, "starting elasticsearch sink ...");
loop.post(
std::bind(&elasticsearch_t::on_started, this, std::ref(started))
);
timer.expires_from_now(interval);
timer.async_wait(
std::bind(&elasticsearch_t::on_timer, this, std::placeholders::_1)
);
boost::system::error_code ec;
loop.run(ec);
ES_LOG(log, "elasticsearch sink has been stopped: %s", ec ? ec.message() : "ok");
}
void stop() {
stopped = true;
timer.cancel();
client.stop();
if (thread.joinable()) {
ES_LOG(log, "stopping worker thread ...");
thread.join();
}
}
void on_started(std::condition_variable& started) {
ES_LOG(log, "elasticsearch sink has been started");
stopped = false;
started.notify_all();
}
void on_bulk(std::vector<std::string>&& result) {
loop.post(
std::bind(&elasticsearch_t::handle_bulk, this, std::move(result))
);
}
void handle_bulk(std::vector<std::string> result) {
ES_LOG(log, "processing bulk event ...");
process(std::move(result));
}
void on_timer(const boost::system::error_code& ec) {
if (ec) {
ES_LOG(log, "processing timer event failed: %s", ec.message());
} else {
ES_LOG(log, "processing timer event ...");
process(std::move(queue.dump()));
}
}
void process(std::vector<std::string>&& result) {
if (stopped) {
ES_LOG(log, "dropping %d messages, because worker thread is stopped",
result.size());
return;
}
ES_LOG(log, "processing bulk containing %d messages ...", result.size());
client.bulk_write(
std::move(result),
std::bind(&elasticsearch_t::on_response, this, std::placeholders::_1)
);
timer.expires_from_now(interval);
timer.async_wait(
std::bind(&elasticsearch_t::on_timer, this, std::placeholders::_1)
);
}
void on_response(elasticsearch::result_t<
elasticsearch::response::bulk_write_t
>::type&& result) {
if (boost::get<elasticsearch::error_t>(&result)) {
ES_LOG(log, "bulk write failed");
return;
}
ES_LOG(log, "success!");
}
};
} // namespace sink
} // namespace blackhole
<|endoftext|> |
<commit_before><commit_msg>Glyph cache optimization<commit_after><|endoftext|> |
<commit_before>#include "http.h"
#include "Configuration.h"
#include "ServerConnection.h"
#include "../IPC/Message.h"
#include "../IPOCS/Message.h"
#include "ArduinoConnection.h"
#include "LedControl.hpp"
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <WiFiClient.h>
#include <list>
#include <EEPROM.h>
#define MIN_LOOP_TIME 100
#define PING_TIME 500
#define WIFI_CONNECT 30000
std::list<WiFiEventHandler> wifiHandlers;
enum EWiFiMode {
None,
Normal,
AP
};
unsigned long connectionInitiated = 0;
enum EWiFiMode wifiMode = None;
int attemptNo = 0;
unsigned long lastPing = 0;
int onStationModeConnected(const WiFiEventStationModeConnected& change) {
return 0;
}
int onStationModeDisconnected(const WiFiEventStationModeDisconnected& change) {
esp::ServerConnection::instance().disconnect();
wifiMode = None;
return 0;
}
int onStationModeGotIP(const WiFiEventStationModeGotIP& change) {
char name[20];
sprintf(name, "ipocs_%03d", Configuration::getUnitID());
MDNS.begin(name, WiFi.localIP());
return 0;
}
int onSoftAPModeStationConnected(const WiFiEventSoftAPModeStationConnected& change) {
return 0;
}
int onSoftAPModeStationDisconnected(const WiFiEventSoftAPModeStationDisconnected& change) {
return 0;
}
int onSoftAPModeProbeRequestReceived(const WiFiEventSoftAPModeProbeRequestReceived& change) {
return 0;
}
void setup(void)
{
esp::LedControl::instance().begin();
char name[20];
sprintf(name, "ipocs_%03d", Configuration::getUnitID());
WiFi.setOutputPower(20.5);
WiFi.hostname(name);
MDNS.begin(name);
MDNS.addService("http", "tcp", 80);
esp::Http::instance().setup();
esp::ArduinoConnection::instance().begin();
wifiHandlers.push_back(WiFi.onStationModeDisconnected(onStationModeDisconnected));
wifiHandlers.push_back(WiFi.onStationModeGotIP(onStationModeGotIP));
lastPing = millis();
}
void setupWiFi(void) {
char name[20];
sprintf(name, "ipocs_%03d", Configuration::getUnitID());
char password[61];
Configuration::getPassword(password);
char cSSID[33];
Configuration::getSSID(cSSID);
esp::Http::instance().log("Connecting to SSID: " + String(cSSID));
WiFi.disconnect();
WiFi.hostname(name);
WiFi.mode(WIFI_STA);
WiFi.begin((const char*)String(cSSID).c_str(), (const char*)String(password).c_str());
}
void loop(void)
{
MDNS.update();
int wiFiStatus = WiFi.status();
if (wifiMode == None) {
connectionInitiated = millis();
wifiMode = Normal;
esp::LedControl::instance().setState(BLINK, 100);
setupWiFi();
}
if (wiFiStatus != WL_CONNECTED)
{
if (wifiMode == Normal)
{
if (connectionInitiated != 0 && (millis() - connectionInitiated) >= WIFI_CONNECT)
{
esp::LedControl::instance().setState(BLINK, 500);
// WiFi failed to reconnect - go into soft AP mode
WiFi.mode(WIFI_AP);
char name[20];
sprintf(name, "IPOCS_%03d", Configuration::getUnitID());
WiFi.softAP(name);
connectionInitiated = 0;
wifiMode = AP;
delay(500); // Let the AP settle
}
}
}
else
{
if (connectionInitiated != 0)
{
esp::LedControl::instance().setState(BLINK, 1000);
// WiFi connected. Don't care if it's AP or Station mode.
connectionInitiated = 0;
esp::Http::instance().log(String("IP address: ") + WiFi.localIP().toString());
MDNS.notifyAPChange();
}
}
esp::LedControl::instance().loop();
esp::Http::instance().loop();
esp::ServerConnection::instance().loop(wifi_station_get_connect_status() == STATION_GOT_IP);
esp::ArduinoConnection::instance().loop();
MDNS.update();
unsigned long loopEnd = millis();
if ((loopEnd - lastPing) >= PING_TIME) {
lastPing = loopEnd;
IPC::Message* ipcPing = IPC::Message::create();
ipcPing->RT_TYPE = IPC::IPING;
ipcPing->setPayload();
esp::ArduinoConnection::instance().send(ipcPing);
delete ipcPing;
}
}
<commit_msg>Fix connection bug<commit_after>#include "http.h"
#include "Configuration.h"
#include "ServerConnection.h"
#include "../IPC/Message.h"
#include "../IPOCS/Message.h"
#include "ArduinoConnection.h"
#include "LedControl.hpp"
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <WiFiClient.h>
#include <list>
#include <EEPROM.h>
#define MIN_LOOP_TIME 100
#define PING_TIME 500
#define WIFI_CONNECT 30000
std::list<WiFiEventHandler> wifiHandlers;
enum EWiFiMode {
None,
Normal,
AP
};
unsigned long connectionInitiated = 0;
enum EWiFiMode wifiMode = None;
int attemptNo = 0;
unsigned long lastPing = 0;
int onStationModeConnected(const WiFiEventStationModeConnected& change) {
return 0;
}
int onStationModeDisconnected(const WiFiEventStationModeDisconnected& change) {
esp::ServerConnection::instance().disconnect();
if (connectionInitiated == 0) {
wifiMode = None;
}
return 0;
}
int onStationModeGotIP(const WiFiEventStationModeGotIP& change) {
char name[20];
sprintf(name, "ipocs_%03d", Configuration::getUnitID());
MDNS.begin(name, WiFi.localIP());
return 0;
}
int onSoftAPModeStationConnected(const WiFiEventSoftAPModeStationConnected& change) {
return 0;
}
int onSoftAPModeStationDisconnected(const WiFiEventSoftAPModeStationDisconnected& change) {
return 0;
}
int onSoftAPModeProbeRequestReceived(const WiFiEventSoftAPModeProbeRequestReceived& change) {
return 0;
}
void setup(void)
{
esp::LedControl::instance().begin();
char name[20];
sprintf(name, "ipocs_%03d", Configuration::getUnitID());
WiFi.setOutputPower(20.5);
WiFi.hostname(name);
MDNS.begin(name);
MDNS.addService("http", "tcp", 80);
esp::Http::instance().setup();
esp::ArduinoConnection::instance().begin();
wifiHandlers.push_back(WiFi.onStationModeDisconnected(onStationModeDisconnected));
wifiHandlers.push_back(WiFi.onStationModeGotIP(onStationModeGotIP));
lastPing = millis();
}
void setupWiFi(void) {
char name[20];
sprintf(name, "ipocs_%03d", Configuration::getUnitID());
char password[61];
Configuration::getPassword(password);
char cSSID[33];
Configuration::getSSID(cSSID);
esp::Http::instance().log("Connecting to SSID: " + String(cSSID));
WiFi.disconnect();
WiFi.hostname(name);
WiFi.mode(WIFI_STA);
WiFi.begin((const char*)String(cSSID).c_str(), (const char*)String(password).c_str());
}
void loop(void)
{
MDNS.update();
int wiFiStatus = WiFi.status();
if (wifiMode == None) {
connectionInitiated = millis();
wifiMode = Normal;
esp::LedControl::instance().setState(BLINK, 100);
setupWiFi();
}
if (wiFiStatus != WL_CONNECTED)
{
if (wifiMode == Normal)
{
if (connectionInitiated != 0 && (millis() - connectionInitiated) >= WIFI_CONNECT)
{
esp::LedControl::instance().setState(BLINK, 500);
// WiFi failed to reconnect - go into soft AP mode
WiFi.mode(WIFI_AP);
char name[20];
sprintf(name, "IPOCS_%03d", Configuration::getUnitID());
WiFi.softAP(name);
connectionInitiated = 0;
wifiMode = AP;
delay(500); // Let the AP settle
}
}
}
else
{
if (connectionInitiated != 0)
{
esp::LedControl::instance().setState(BLINK, 1000);
// WiFi connected. Don't care if it's AP or Station mode.
connectionInitiated = 0;
esp::Http::instance().log(String("IP address: ") + WiFi.localIP().toString());
MDNS.notifyAPChange();
}
}
esp::LedControl::instance().loop();
esp::Http::instance().loop();
esp::ServerConnection::instance().loop(wifi_station_get_connect_status() == STATION_GOT_IP);
esp::ArduinoConnection::instance().loop();
MDNS.update();
unsigned long loopEnd = millis();
if ((loopEnd - lastPing) >= PING_TIME) {
lastPing = loopEnd;
IPC::Message* ipcPing = IPC::Message::create();
ipcPing->RT_TYPE = IPC::IPING;
ipcPing->setPayload();
esp::ArduinoConnection::instance().send(ipcPing);
delete ipcPing;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2019 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
// CLASS HEADER
#include <dali/public-api/adaptor-framework/window.h>
// EXTERNAL INCLUDES
#include <dali/integration-api/debug.h>
// INTERNAL INCLUDES
#include <dali/public-api/actors/actor.h>
#include <dali/internal/window-system/common/window-impl.h>
#include <dali/internal/window-system/common/orientation-impl.h>
namespace Dali
{
class DALI_INTERNAL DragAndDropDetector : public BaseHandle {}; // Empty class only required to compile Deprecated API GetDragAndDropDetector
Window Window::New(PositionSize posSize, const std::string& name, bool isTransparent)
{
Internal::Adaptor::Window* window = Internal::Adaptor::Window::New(posSize, name, "", isTransparent);
Dali::Adaptor& adaptor = Internal::Adaptor::Adaptor::Get();
if( Internal::Adaptor::Adaptor::GetImplementation( adaptor ).IsMultipleWindowSupported() )
{
Integration::SceneHolder sceneHolder = Integration::SceneHolder( window );
Internal::Adaptor::Adaptor::GetImplementation( adaptor ).AddWindow( sceneHolder, name, "", isTransparent );
return Window(window);
}
else
{
DALI_LOG_ERROR("This device can't support multiple windows.\n");
return Window();
}
}
Window Window::New(PositionSize posSize, const std::string& name, const std::string& className, bool isTransparent)
{
Internal::Adaptor::Window* window = Internal::Adaptor::Window::New(posSize, name, className, isTransparent);
Dali::Adaptor& adaptor = Internal::Adaptor::Adaptor::Get();
if( Internal::Adaptor::Adaptor::GetImplementation( adaptor ).IsMultipleWindowSupported() )
{
Integration::SceneHolder sceneHolder = Integration::SceneHolder( window );
Internal::Adaptor::Adaptor::GetImplementation( adaptor ).AddWindow( sceneHolder, name, className, isTransparent );
return Window(window);
}
else
{
DALI_LOG_ERROR("This device can't support multiple windows.\n");
return Window();
}
}
Window::Window()
{
}
Window::~Window()
{
}
Window::Window(const Window& handle)
: BaseHandle(handle)
{
}
Window& Window::operator=(const Window& rhs)
{
BaseHandle::operator=(rhs);
return *this;
}
void Window::Add( Dali::Actor actor )
{
GetImplementation( *this ).Add( actor );
}
void Window::Remove( Dali::Actor actor )
{
GetImplementation( *this ).Remove( actor );
}
void Window::SetBackgroundColor( const Vector4& color )
{
GetImplementation( *this ).SetBackgroundColor( color );
}
Vector4 Window::GetBackgroundColor() const
{
return GetImplementation( *this ).GetBackgroundColor();
}
Layer Window::GetRootLayer() const
{
return GetImplementation( *this ).GetRootLayer();
}
uint32_t Window::GetLayerCount() const
{
return GetImplementation( *this ).GetLayerCount();
}
Layer Window::GetLayer( uint32_t depth ) const
{
return GetImplementation( *this ).GetLayer( depth );
}
void Window::ShowIndicator( IndicatorVisibleMode visibleMode )
{
DALI_LOG_WARNING_NOFN("DEPRECATION WARNING: ShowIndicator is deprecated and will be removed from next release.\n" );
GetImplementation(*this).ShowIndicator( visibleMode );
}
Window::IndicatorSignalType& Window::IndicatorVisibilityChangedSignal()
{
DALI_LOG_WARNING_NOFN("DEPRECATION WARNING: IndicatorVisibilityChangedSignal is deprecated and will be removed from next release.\n" );
return GetImplementation(*this).IndicatorVisibilityChangedSignal();
}
void Window::SetIndicatorBgOpacity( IndicatorBgOpacity opacity )
{
DALI_LOG_WARNING_NOFN("DEPRECATION WARNING: SetIndicatorBgOpacity is deprecated and will be removed from next release.\n" );
GetImplementation(*this).SetIndicatorBgOpacity( opacity );
}
void Window::RotateIndicator( WindowOrientation orientation )
{
DALI_LOG_WARNING_NOFN("DEPRECATION WARNING: RotateIndicator is deprecated and will be removed from next release.\n" );
GetImplementation(*this).RotateIndicator( orientation );
}
void Window::SetClass( std::string name, std::string klass )
{
GetImplementation(*this).SetClass( name, klass );
}
void Window::Raise()
{
GetImplementation(*this).Raise();
}
void Window::Lower()
{
GetImplementation(*this).Lower();
}
void Window::Activate()
{
GetImplementation(*this).Activate();
}
void Window::AddAvailableOrientation( WindowOrientation orientation )
{
GetImplementation(*this).AddAvailableOrientation( orientation );
}
void Window::RemoveAvailableOrientation( WindowOrientation orientation )
{
GetImplementation(*this).RemoveAvailableOrientation( orientation );
}
void Window::SetPreferredOrientation( WindowOrientation orientation )
{
GetImplementation(*this).SetPreferredOrientation( orientation );
}
Dali::Window::WindowOrientation Window::GetPreferredOrientation()
{
return GetImplementation(*this).GetPreferredOrientation();
}
DragAndDropDetector Window::GetDragAndDropDetector() const
{
DALI_LOG_WARNING_NOFN("DEPRECATION WARNING: GetDragAndDropDetector is deprecated and will be removed from the next release.\n" );
DALI_ASSERT_ALWAYS( &GetImplementation( *this ) == GetObjectPtr() && "Empty Handle" );
return Dali::DragAndDropDetector();
}
Any Window::GetNativeHandle() const
{
return GetImplementation(*this).GetNativeHandle();
}
Window::FocusSignalType& Window::FocusChangedSignal()
{
DALI_LOG_WARNING_NOFN("DEPRECATION WARNING: FocusChangedSignal is deprecated and will be removed from next release.\n" );
return GetImplementation(*this).FocusChangedSignal();
}
Window::FocusChangeSignalType& Window::FocusChangeSignal()
{
return GetImplementation(*this).FocusChangeSignal();
}
void Window::SetAcceptFocus( bool accept )
{
GetImplementation(*this).SetAcceptFocus( accept );
}
bool Window::IsFocusAcceptable() const
{
return GetImplementation(*this).IsFocusAcceptable();
}
void Window::Show()
{
GetImplementation(*this).Show();
}
void Window::Hide()
{
GetImplementation(*this).Hide();
}
bool Window::IsVisible() const
{
return GetImplementation(*this).IsVisible();
}
unsigned int Window::GetSupportedAuxiliaryHintCount() const
{
return GetImplementation(*this).GetSupportedAuxiliaryHintCount();
}
std::string Window::GetSupportedAuxiliaryHint( unsigned int index ) const
{
return GetImplementation(*this).GetSupportedAuxiliaryHint( index );
}
unsigned int Window::AddAuxiliaryHint( const std::string& hint, const std::string& value )
{
return GetImplementation(*this).AddAuxiliaryHint( hint, value );
}
bool Window::RemoveAuxiliaryHint( unsigned int id )
{
return GetImplementation(*this).RemoveAuxiliaryHint( id );
}
bool Window::SetAuxiliaryHintValue( unsigned int id, const std::string& value )
{
return GetImplementation(*this).SetAuxiliaryHintValue( id, value );
}
std::string Window::GetAuxiliaryHintValue( unsigned int id ) const
{
return GetImplementation(*this).GetAuxiliaryHintValue( id );
}
unsigned int Window::GetAuxiliaryHintId( const std::string& hint ) const
{
return GetImplementation(*this).GetAuxiliaryHintId( hint );
}
void Window::SetInputRegion( const Rect< int >& inputRegion )
{
return GetImplementation(*this).SetInputRegion( inputRegion );
}
void Window::SetType( Window::Type type )
{
GetImplementation(*this).SetType( type );
}
Window::Type Window::GetType() const
{
return GetImplementation(*this).GetType();
}
bool Window::SetNotificationLevel( Window::NotificationLevel::Type level )
{
return GetImplementation(*this).SetNotificationLevel( level );
}
Window::NotificationLevel::Type Window::GetNotificationLevel() const
{
return GetImplementation(*this).GetNotificationLevel();
}
void Window::SetOpaqueState( bool opaque )
{
GetImplementation(*this).SetOpaqueState( opaque );
}
bool Window::IsOpaqueState() const
{
return GetImplementation(*this).IsOpaqueState();
}
bool Window::SetScreenOffMode(Window::ScreenOffMode::Type screenMode)
{
return GetImplementation(*this).SetScreenOffMode(screenMode);
}
Window::ScreenOffMode::Type Window::GetScreenOffMode() const
{
return GetImplementation(*this).GetScreenOffMode();
}
bool Window::SetBrightness( int brightness )
{
return GetImplementation(*this).SetBrightness( brightness );
}
int Window::GetBrightness() const
{
return GetImplementation(*this).GetBrightness();
}
Window::ResizedSignalType& Window::ResizedSignal()
{
DALI_LOG_WARNING_NOFN("DEPRECATION WARNING: ResizedSignal is deprecated and will be removed from next release.\n" );
return GetImplementation(*this).ResizedSignal();
}
Window::ResizeSignalType& Window::ResizeSignal()
{
return GetImplementation(*this).ResizeSignal();
}
void Window::SetSize( Window::WindowSize size )
{
GetImplementation(*this).SetSize( size );
}
Window::WindowSize Window::GetSize() const
{
return GetImplementation(*this).GetSize();
}
void Window::SetPosition( Window::WindowPosition position )
{
GetImplementation(*this).SetPosition( position );
}
Window::WindowPosition Window::GetPosition() const
{
return GetImplementation(*this).GetPosition();
}
void Window::SetTransparency( bool transparent )
{
GetImplementation(*this).SetTransparency( transparent );
}
Window::Window( Internal::Adaptor::Window* window )
: BaseHandle( window )
{
}
} // namespace Dali
<commit_msg>Window - Constructor refactor.<commit_after>/*
* Copyright (c) 2019 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
// CLASS HEADER
#include <dali/public-api/adaptor-framework/window.h>
// EXTERNAL INCLUDES
#include <dali/integration-api/debug.h>
// INTERNAL INCLUDES
#include <dali/public-api/actors/actor.h>
#include <dali/internal/window-system/common/window-impl.h>
#include <dali/internal/window-system/common/orientation-impl.h>
namespace Dali
{
class DALI_INTERNAL DragAndDropDetector : public BaseHandle {}; // Empty class only required to compile Deprecated API GetDragAndDropDetector
Window Window::New(PositionSize posSize, const std::string& name, bool isTransparent)
{
return Dali::Window::New(posSize, name, "", isTransparent);
}
Window Window::New(PositionSize posSize, const std::string& name, const std::string& className, bool isTransparent)
{
Window newWindow;
const bool isAdaptorAvailable = Dali::Adaptor::IsAvailable();
bool isNewWindowAllowed = true;
if (isAdaptorAvailable)
{
Dali::Adaptor& adaptor = Internal::Adaptor::Adaptor::Get();
isNewWindowAllowed = Internal::Adaptor::Adaptor::GetImplementation(adaptor).IsMultipleWindowSupported();
}
if (isNewWindowAllowed)
{
Internal::Adaptor::Window* window = Internal::Adaptor::Window::New(posSize, name, className, isTransparent);
Integration::SceneHolder sceneHolder = Integration::SceneHolder(window);
if (isAdaptorAvailable)
{
Dali::Adaptor& adaptor = Internal::Adaptor::Adaptor::Get();
Internal::Adaptor::Adaptor::GetImplementation(adaptor).AddWindow(sceneHolder, name, className, isTransparent);
}
newWindow = Window(window);
}
else
{
DALI_LOG_ERROR("This device can't support multiple windows.\n");
}
return newWindow;
}
Window::Window()
{
}
Window::~Window()
{
}
Window::Window(const Window& handle)
: BaseHandle(handle)
{
}
Window& Window::operator=(const Window& rhs)
{
BaseHandle::operator=(rhs);
return *this;
}
void Window::Add( Dali::Actor actor )
{
GetImplementation( *this ).Add( actor );
}
void Window::Remove( Dali::Actor actor )
{
GetImplementation( *this ).Remove( actor );
}
void Window::SetBackgroundColor( const Vector4& color )
{
GetImplementation( *this ).SetBackgroundColor( color );
}
Vector4 Window::GetBackgroundColor() const
{
return GetImplementation( *this ).GetBackgroundColor();
}
Layer Window::GetRootLayer() const
{
return GetImplementation( *this ).GetRootLayer();
}
uint32_t Window::GetLayerCount() const
{
return GetImplementation( *this ).GetLayerCount();
}
Layer Window::GetLayer( uint32_t depth ) const
{
return GetImplementation( *this ).GetLayer( depth );
}
void Window::ShowIndicator( IndicatorVisibleMode visibleMode )
{
DALI_LOG_WARNING_NOFN("DEPRECATION WARNING: ShowIndicator is deprecated and will be removed from next release.\n" );
GetImplementation(*this).ShowIndicator( visibleMode );
}
Window::IndicatorSignalType& Window::IndicatorVisibilityChangedSignal()
{
DALI_LOG_WARNING_NOFN("DEPRECATION WARNING: IndicatorVisibilityChangedSignal is deprecated and will be removed from next release.\n" );
return GetImplementation(*this).IndicatorVisibilityChangedSignal();
}
void Window::SetIndicatorBgOpacity( IndicatorBgOpacity opacity )
{
DALI_LOG_WARNING_NOFN("DEPRECATION WARNING: SetIndicatorBgOpacity is deprecated and will be removed from next release.\n" );
GetImplementation(*this).SetIndicatorBgOpacity( opacity );
}
void Window::RotateIndicator( WindowOrientation orientation )
{
DALI_LOG_WARNING_NOFN("DEPRECATION WARNING: RotateIndicator is deprecated and will be removed from next release.\n" );
GetImplementation(*this).RotateIndicator( orientation );
}
void Window::SetClass( std::string name, std::string klass )
{
GetImplementation(*this).SetClass( name, klass );
}
void Window::Raise()
{
GetImplementation(*this).Raise();
}
void Window::Lower()
{
GetImplementation(*this).Lower();
}
void Window::Activate()
{
GetImplementation(*this).Activate();
}
void Window::AddAvailableOrientation( WindowOrientation orientation )
{
GetImplementation(*this).AddAvailableOrientation( orientation );
}
void Window::RemoveAvailableOrientation( WindowOrientation orientation )
{
GetImplementation(*this).RemoveAvailableOrientation( orientation );
}
void Window::SetPreferredOrientation( WindowOrientation orientation )
{
GetImplementation(*this).SetPreferredOrientation( orientation );
}
Dali::Window::WindowOrientation Window::GetPreferredOrientation()
{
return GetImplementation(*this).GetPreferredOrientation();
}
DragAndDropDetector Window::GetDragAndDropDetector() const
{
DALI_LOG_WARNING_NOFN("DEPRECATION WARNING: GetDragAndDropDetector is deprecated and will be removed from the next release.\n" );
DALI_ASSERT_ALWAYS( &GetImplementation( *this ) == GetObjectPtr() && "Empty Handle" );
return Dali::DragAndDropDetector();
}
Any Window::GetNativeHandle() const
{
return GetImplementation(*this).GetNativeHandle();
}
Window::FocusSignalType& Window::FocusChangedSignal()
{
DALI_LOG_WARNING_NOFN("DEPRECATION WARNING: FocusChangedSignal is deprecated and will be removed from next release.\n" );
return GetImplementation(*this).FocusChangedSignal();
}
Window::FocusChangeSignalType& Window::FocusChangeSignal()
{
return GetImplementation(*this).FocusChangeSignal();
}
void Window::SetAcceptFocus( bool accept )
{
GetImplementation(*this).SetAcceptFocus( accept );
}
bool Window::IsFocusAcceptable() const
{
return GetImplementation(*this).IsFocusAcceptable();
}
void Window::Show()
{
GetImplementation(*this).Show();
}
void Window::Hide()
{
GetImplementation(*this).Hide();
}
bool Window::IsVisible() const
{
return GetImplementation(*this).IsVisible();
}
unsigned int Window::GetSupportedAuxiliaryHintCount() const
{
return GetImplementation(*this).GetSupportedAuxiliaryHintCount();
}
std::string Window::GetSupportedAuxiliaryHint( unsigned int index ) const
{
return GetImplementation(*this).GetSupportedAuxiliaryHint( index );
}
unsigned int Window::AddAuxiliaryHint( const std::string& hint, const std::string& value )
{
return GetImplementation(*this).AddAuxiliaryHint( hint, value );
}
bool Window::RemoveAuxiliaryHint( unsigned int id )
{
return GetImplementation(*this).RemoveAuxiliaryHint( id );
}
bool Window::SetAuxiliaryHintValue( unsigned int id, const std::string& value )
{
return GetImplementation(*this).SetAuxiliaryHintValue( id, value );
}
std::string Window::GetAuxiliaryHintValue( unsigned int id ) const
{
return GetImplementation(*this).GetAuxiliaryHintValue( id );
}
unsigned int Window::GetAuxiliaryHintId( const std::string& hint ) const
{
return GetImplementation(*this).GetAuxiliaryHintId( hint );
}
void Window::SetInputRegion( const Rect< int >& inputRegion )
{
return GetImplementation(*this).SetInputRegion( inputRegion );
}
void Window::SetType( Window::Type type )
{
GetImplementation(*this).SetType( type );
}
Window::Type Window::GetType() const
{
return GetImplementation(*this).GetType();
}
bool Window::SetNotificationLevel( Window::NotificationLevel::Type level )
{
return GetImplementation(*this).SetNotificationLevel( level );
}
Window::NotificationLevel::Type Window::GetNotificationLevel() const
{
return GetImplementation(*this).GetNotificationLevel();
}
void Window::SetOpaqueState( bool opaque )
{
GetImplementation(*this).SetOpaqueState( opaque );
}
bool Window::IsOpaqueState() const
{
return GetImplementation(*this).IsOpaqueState();
}
bool Window::SetScreenOffMode(Window::ScreenOffMode::Type screenMode)
{
return GetImplementation(*this).SetScreenOffMode(screenMode);
}
Window::ScreenOffMode::Type Window::GetScreenOffMode() const
{
return GetImplementation(*this).GetScreenOffMode();
}
bool Window::SetBrightness( int brightness )
{
return GetImplementation(*this).SetBrightness( brightness );
}
int Window::GetBrightness() const
{
return GetImplementation(*this).GetBrightness();
}
Window::ResizedSignalType& Window::ResizedSignal()
{
DALI_LOG_WARNING_NOFN("DEPRECATION WARNING: ResizedSignal is deprecated and will be removed from next release.\n" );
return GetImplementation(*this).ResizedSignal();
}
Window::ResizeSignalType& Window::ResizeSignal()
{
return GetImplementation(*this).ResizeSignal();
}
void Window::SetSize( Window::WindowSize size )
{
GetImplementation(*this).SetSize( size );
}
Window::WindowSize Window::GetSize() const
{
return GetImplementation(*this).GetSize();
}
void Window::SetPosition( Window::WindowPosition position )
{
GetImplementation(*this).SetPosition( position );
}
Window::WindowPosition Window::GetPosition() const
{
return GetImplementation(*this).GetPosition();
}
void Window::SetTransparency( bool transparent )
{
GetImplementation(*this).SetTransparency( transparent );
}
Window::Window( Internal::Adaptor::Window* window )
: BaseHandle( window )
{
}
} // namespace Dali
<|endoftext|> |
<commit_before>/* __ __ _
* / // /_____ ____ (_)
* / // // ___// __ \ / /
* / // // /__ / /_/ // /
* /_//_/ \___/ \____//_/
* https://bitbucket.org/galaktor/llcoi
* copyright (c) 2014, llcoi Team
* MIT license applies - see file "LICENSE" for details.
*/
#include "ogre_interface.h"
#include <OgreQuaternion.h>
#include <OgreMatrix3.h>
QuaternionHandle quaternion_from_rotation_matrix(coiMatrix3 *rot) {
Ogre::Matrix3 * mat = new Ogre::Matrix3(rot->m[0][0], rot->m[0][1],
rot->m[0][2], rot->m[1][0], rot->m[1][1], rot->m[1][2], rot->m[2][0], rot->m[2][1],
rot->m[2][2]);
Ogre::Quaternion * quat = new Ogre::Quaternion(*mat);
delete mat;
reinterpret_cast<QuaternionHandle>(quat);
}
void quaternion_to_rotation_matrix(QuaternionHandle handle, coiMatrix3 *rot) {
Ogre::Matrix3 *mat = new Ogre::Matrix3();
Ogre::Quaternion *quat = reinterpret_cast<Ogre::Quaternion*>(handle);
quat->ToRotationMatrix(*mat);
rot->m[0][0] = *mat[0][0];
rot->m[0][1] = *mat[0][1];
rot->m[0][2] = *mat[0][2];
rot->m[1][0] = *mat[1][0];
rot->m[1][1] = *mat[1][1];
rot->m[1][2] = *mat[1][2];
rot->m[2][0] = *mat[2][0];
rot->m[2][1] = *mat[2][1];
rot->m[2][2] = *mat[2][2];
delete mat;
}
<commit_msg>Actually return the QuaternionHandle.<commit_after>/* __ __ _
* / // /_____ ____ (_)
* / // // ___// __ \ / /
* / // // /__ / /_/ // /
* /_//_/ \___/ \____//_/
* https://bitbucket.org/galaktor/llcoi
* copyright (c) 2014, llcoi Team
* MIT license applies - see file "LICENSE" for details.
*/
#include "ogre_interface.h"
#include <OgreQuaternion.h>
#include <OgreMatrix3.h>
QuaternionHandle quaternion_from_rotation_matrix(coiMatrix3 *rot) {
Ogre::Matrix3 * mat = new Ogre::Matrix3(rot->m[0][0], rot->m[0][1],
rot->m[0][2], rot->m[1][0], rot->m[1][1], rot->m[1][2], rot->m[2][0], rot->m[2][1],
rot->m[2][2]);
Ogre::Quaternion * quat = new Ogre::Quaternion(*mat);
delete mat;
return reinterpret_cast<QuaternionHandle>(quat);
}
void quaternion_to_rotation_matrix(QuaternionHandle handle, coiMatrix3 *rot) {
Ogre::Matrix3 *mat = new Ogre::Matrix3();
Ogre::Quaternion *quat = reinterpret_cast<Ogre::Quaternion*>(handle);
quat->ToRotationMatrix(*mat);
rot->m[0][0] = *mat[0][0];
rot->m[0][1] = *mat[0][1];
rot->m[0][2] = *mat[0][2];
rot->m[1][0] = *mat[1][0];
rot->m[1][1] = *mat[1][1];
rot->m[1][2] = *mat[1][2];
rot->m[2][0] = *mat[2][0];
rot->m[2][1] = *mat[2][1];
rot->m[2][2] = *mat[2][2];
delete mat;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015 Luke San Antonio
* All rights reserved.
*/
#include <iostream>
#include <thread>
#include <chrono>
#include <random>
#include "stratlib/event.h"
constexpr char const* const RESET_C = "\x1b[0m";
constexpr char const* const RED_C = "\x1b[95m";
constexpr char const* const CLEAR_C = "\x1b[2J";
int main(int argc, char** argv) noexcept
{
using namespace game;
namespace chrono = std::chrono;
auto const map_size = Vec<int>{35,35};
auto prng = std::mt19937(std::random_device{}());
auto dist = std::uniform_real_distribution<float>{0.0f, 2.5f};
// Initialize, allocate, and populate the cost map.
strat::Cost_Map cm; cm.allocate(map_size);
for(int i = 0; i < cm.extents.y; ++i)
{
for(int j = 0; j < cm.extents.x; ++j)
{
// One second per square.
cm.at({j,i}) = dist(prng);
}
}
strat::Event_Map event_map;
event_map.visited_map.allocate(map_size);
event_map.event_timer_map.allocate(map_size);
event_map.event_timer_map.at({0,0}).active = true;
strat::Value_Map<char> cmap;
cmap.allocate(map_size);
using clock_t = chrono::high_resolution_clock;
auto now = clock_t::now();
auto before = now;
// Keep doing shit for 5 seconds.
while(true)
{
// How much time has elapsed.
before = now;
now = clock_t::now();
auto dt = chrono::duration_cast<chrono::milliseconds>(now - before)
.count() / 1000.0f;
std::cout << RED_C << dt << RESET_C << std::endl;
if(spread(cm, event_map, dt))
{
spread(cm, event_map, 0.0f);
}
// Set some cells to pound signs.
for(int i = 0; i < cmap.extents.y; ++i)
{
for(int j = 0; j < cmap.extents.x; ++j)
{
cmap.at({j,i}) = event_map.visited_map.at({j,i}) ? '#' : ' ';
}
}
// Print the grid
for(int i = 0; i < cmap.extents.y; ++i)
{
for(int j = 0; j < cmap.extents.x; ++j)
{
std::cout << cmap.at({i,j});
}
std::cout << std::endl;
}
std::cout << CLEAR_C;
// Sleep for a bit then grab the time.
std::this_thread::sleep_for(chrono::milliseconds(200));
}
return 0;
}
<commit_msg>Smaller distribution of costs to speed the simulation up.<commit_after>/*
* Copyright (C) 2015 Luke San Antonio
* All rights reserved.
*/
#include <iostream>
#include <thread>
#include <chrono>
#include <random>
#include "stratlib/event.h"
constexpr char const* const RESET_C = "\x1b[0m";
constexpr char const* const RED_C = "\x1b[95m";
constexpr char const* const CLEAR_C = "\x1b[2J";
int main(int argc, char** argv) noexcept
{
using namespace game;
namespace chrono = std::chrono;
auto const map_size = Vec<int>{35,35};
auto prng = std::mt19937(std::random_device{}());
auto dist = std::uniform_real_distribution<float>{0.0f, .9f};
// Initialize, allocate, and populate the cost map.
strat::Cost_Map cm; cm.allocate(map_size);
for(int i = 0; i < cm.extents.y; ++i)
{
for(int j = 0; j < cm.extents.x; ++j)
{
// One second per square.
cm.at({j,i}) = dist(prng);
}
}
strat::Event_Map event_map;
event_map.visited_map.allocate(map_size);
event_map.event_timer_map.allocate(map_size);
event_map.event_timer_map.at({0,0}).active = true;
strat::Value_Map<char> cmap;
cmap.allocate(map_size);
using clock_t = chrono::high_resolution_clock;
auto now = clock_t::now();
auto before = now;
// Keep doing shit for 5 seconds.
while(true)
{
// How much time has elapsed.
before = now;
now = clock_t::now();
auto dt = chrono::duration_cast<chrono::milliseconds>(now - before)
.count() / 1000.0f;
std::cout << RED_C << dt << RESET_C << std::endl;
if(spread(cm, event_map, dt))
{
spread(cm, event_map, 0.0f);
}
// Set some cells to pound signs.
for(int i = 0; i < cmap.extents.y; ++i)
{
for(int j = 0; j < cmap.extents.x; ++j)
{
cmap.at({j,i}) = event_map.visited_map.at({j,i}) ? '#' : ' ';
}
}
// Print the grid
for(int i = 0; i < cmap.extents.y; ++i)
{
for(int j = 0; j < cmap.extents.x; ++j)
{
std::cout << cmap.at({i,j});
}
std::cout << std::endl;
}
std::cout << CLEAR_C;
// Sleep for a bit then grab the time.
std::this_thread::sleep_for(chrono::milliseconds(200));
}
return 0;
}
<|endoftext|> |
<commit_before>// Copyright 2010-2012 RethinkDB, all rights reserved.
#ifndef EXTPROC_POOL_HPP_
#define EXTPROC_POOL_HPP_
#include <sys/types.h> // pid_t
#include "errors.hpp"
#include "concurrency/one_per_thread.hpp"
#include "concurrency/semaphore.hpp"
#include "concurrency/signal.hpp"
#include "containers/archive/interruptible_stream.hpp"
#include "containers/archive/socket_stream.hpp"
#include "containers/intrusive_list.hpp"
#include "extproc/job.hpp"
#include "extproc/spawner.hpp"
namespace extproc {
class job_handle_t;
class pool_t;
// Use this to create one process pool per thread, and access the appropriate
// one (via `get()`).
class pool_group_t
{
friend class pool_t;
public:
static const int DEFAULT_MIN_WORKERS = 2;
static const int DEFAULT_MAX_WORKERS = 2;
struct config_t {
config_t()
: min_workers(DEFAULT_MIN_WORKERS), max_workers(DEFAULT_MAX_WORKERS) {}
int min_workers; // >= 0
int max_workers; // >= min_workers, > 0
};
static const config_t DEFAULTS;
pool_group_t(spawner_t::info_t *info, const config_t &config);
pool_t *get() { return pool_maker_.get(); }
private:
spawner_t spawner_;
config_t config_;
one_per_thread_t<pool_t> pool_maker_;
};
// A per-thread worker pool.
class pool_t :
public home_thread_mixin_debug_only_t
{
friend class job_handle_t;
public:
explicit pool_t(pool_group_t *group);
~pool_t();
private:
pool_group_t::config_t *config() { return &group_->config_; }
spawner_t *spawner() { return &group_->spawner_; }
// A worker process.
class worker_t :
public intrusive_list_node_t<worker_t>,
public unix_socket_stream_t
{
friend class job_handle_t;
public:
worker_t(pool_t *pool, pid_t pid, scoped_fd_t *fd);
~worker_t();
// Called when we get an error on a worker process socket, which usually
// indicates the worker process' death.
void on_error();
// Inherited from unix_socket_stream_t. Called when epoll finds an error
// condition on our socket. Calls on_error().
virtual void do_on_event(int events);
pool_t *const pool_;
const pid_t pid_;
bool attached_;
private:
DISABLE_COPYING(worker_t);
};
typedef intrusive_list_t<worker_t> workers_t;
private:
// Checks & repairs invariants, namely:
// - num_workers() >= config()->min_workers
void repair_invariants();
// Connects us to a worker. Private; used only by job_handle_t::spawn().
worker_t *acquire_worker();
// Called by job_handle_t to indicate the job has finished or errored.
void release_worker(worker_t *worker) THROWS_NOTHING;
// Called by job_handle_t to interrupt a running job.
void interrupt_worker(worker_t *worker) THROWS_NOTHING;
// Detaches the worker from the pool, sends it SIGKILL, and ignores further
// errors from it (ie. on_event will not call on_error, and hence will not
// crash). Does not block.
//
// This is used by the interruptor-signal logic in
// job_handle_t::{read,write}_interruptible(), where interrupt_worker()
// cannot be used because it destroys the worker.
//
// It is the caller's responsibility to call cleanup_detached_worker() at
// some point in the near future.
void detach_worker(worker_t *worker);
// Cleans up after a detached worker. Destroys the worker. May block.
void cleanup_detached_worker(worker_t *worker);
void spawn_workers(int n);
void end_worker(workers_t *list, worker_t *worker);
int num_workers() {
return idle_workers_.size() + busy_workers_.size() + num_spawning_workers_;
}
private:
pool_group_t *group_;
// Worker processes.
workers_t idle_workers_, busy_workers_;
// Count of the number of workers in the process of being spawned. Necessary
// in order to maintain (min_workers, max_workers) bounds without race
// conditions.
int num_spawning_workers_;
// Used to signify that you're using a worker. In particular, lets us block
// for a worker to become available when we already have
// config_->max_workers workers running.
semaphore_t worker_semaphore_;
};
// A handle to a running job.
class job_handle_t :
public interruptible_read_stream_t, public interruptible_write_stream_t
{
friend class pool_t;
friend class interruptor_wrapper_t;
public:
// When constructed, job handles are "disconnected", not associated with a
// job. They are connected by pool_t::spawn_job().
job_handle_t();
// You MUST call release() to finish a job normally, and you SHOULD call
// interrupt() explicitly to interrupt a job (or signal the interruptor
// during {read,write}_interruptible()).
//
// However, as a convenience in the case of exception-raising code, if the
// handle is connected, the destructor will log a warning and interrupt the
// job.
virtual ~job_handle_t();
bool connected() { return NULL != worker_; }
// Begins running `job` on `pool`. Must be disconnected beforehand. On
// success, returns 0 and connects us to the spawned job. Returns -1 on
// error.
int begin(pool_t *pool, const job_t &job);
// Indicates the job has either finished normally or experienced an I/O
// error; disconnects the job handle.
void release() THROWS_NOTHING;
// Forcibly interrupts a running job; disconnects the job handle.
//
// MAY NOT be called concurrently with any I/O methods. Instead, pass a
// signal to {read,write}_interruptible().
void interrupt() THROWS_NOTHING;
// On either read or write error or interruption, the job handle becomes
// disconnected and must not be used.
virtual MUST_USE int64_t read_interruptible(void *p, int64_t n, signal_t *interruptor);
virtual int64_t write_interruptible(const void *p, int64_t n, signal_t *interruptor);
private:
void check_attached();
class interruptor_wrapper_t : public signal_t, public signal_t::subscription_t {
public:
interruptor_wrapper_t(job_handle_t *handle, signal_t *signal);
virtual void run() THROWS_NOTHING;
job_handle_t *handle_;
};
private:
pool_t::worker_t *worker_;
};
} // namespace extproc
#endif // EXTPROC_POOL_HPP_
<commit_msg>Made pool_t::worker_t fields be private.<commit_after>// Copyright 2010-2012 RethinkDB, all rights reserved.
#ifndef EXTPROC_POOL_HPP_
#define EXTPROC_POOL_HPP_
#include <sys/types.h> // pid_t
#include "errors.hpp"
#include "concurrency/one_per_thread.hpp"
#include "concurrency/semaphore.hpp"
#include "concurrency/signal.hpp"
#include "containers/archive/interruptible_stream.hpp"
#include "containers/archive/socket_stream.hpp"
#include "containers/intrusive_list.hpp"
#include "extproc/job.hpp"
#include "extproc/spawner.hpp"
namespace extproc {
class job_handle_t;
class pool_t;
// Use this to create one process pool per thread, and access the appropriate
// one (via `get()`).
class pool_group_t
{
friend class pool_t;
public:
static const int DEFAULT_MIN_WORKERS = 2;
static const int DEFAULT_MAX_WORKERS = 2;
struct config_t {
config_t()
: min_workers(DEFAULT_MIN_WORKERS), max_workers(DEFAULT_MAX_WORKERS) {}
int min_workers; // >= 0
int max_workers; // >= min_workers, > 0
};
static const config_t DEFAULTS;
pool_group_t(spawner_t::info_t *info, const config_t &config);
pool_t *get() { return pool_maker_.get(); }
private:
spawner_t spawner_;
config_t config_;
one_per_thread_t<pool_t> pool_maker_;
};
// A per-thread worker pool.
class pool_t :
public home_thread_mixin_debug_only_t
{
friend class job_handle_t;
public:
explicit pool_t(pool_group_t *group);
~pool_t();
private:
pool_group_t::config_t *config() { return &group_->config_; }
spawner_t *spawner() { return &group_->spawner_; }
// A worker process.
class worker_t :
public intrusive_list_node_t<worker_t>,
public unix_socket_stream_t
{
friend class job_handle_t;
public:
worker_t(pool_t *pool, pid_t pid, scoped_fd_t *fd);
~worker_t();
// Called when we get an error on a worker process socket, which usually
// indicates the worker process' death.
void on_error();
// Inherited from unix_socket_stream_t. Called when epoll finds an error
// condition on our socket. Calls on_error().
virtual void do_on_event(int events);
private:
friend class pool_t;
pool_t *const pool_;
const pid_t pid_;
bool attached_;
DISABLE_COPYING(worker_t);
};
typedef intrusive_list_t<worker_t> workers_t;
private:
// Checks & repairs invariants, namely:
// - num_workers() >= config()->min_workers
void repair_invariants();
// Connects us to a worker. Private; used only by job_handle_t::spawn().
worker_t *acquire_worker();
// Called by job_handle_t to indicate the job has finished or errored.
void release_worker(worker_t *worker) THROWS_NOTHING;
// Called by job_handle_t to interrupt a running job.
void interrupt_worker(worker_t *worker) THROWS_NOTHING;
// Detaches the worker from the pool, sends it SIGKILL, and ignores further
// errors from it (ie. on_event will not call on_error, and hence will not
// crash). Does not block.
//
// This is used by the interruptor-signal logic in
// job_handle_t::{read,write}_interruptible(), where interrupt_worker()
// cannot be used because it destroys the worker.
//
// It is the caller's responsibility to call cleanup_detached_worker() at
// some point in the near future.
void detach_worker(worker_t *worker);
// Cleans up after a detached worker. Destroys the worker. May block.
void cleanup_detached_worker(worker_t *worker);
void spawn_workers(int n);
void end_worker(workers_t *list, worker_t *worker);
int num_workers() {
return idle_workers_.size() + busy_workers_.size() + num_spawning_workers_;
}
private:
pool_group_t *group_;
// Worker processes.
workers_t idle_workers_, busy_workers_;
// Count of the number of workers in the process of being spawned. Necessary
// in order to maintain (min_workers, max_workers) bounds without race
// conditions.
int num_spawning_workers_;
// Used to signify that you're using a worker. In particular, lets us block
// for a worker to become available when we already have
// config_->max_workers workers running.
semaphore_t worker_semaphore_;
};
// A handle to a running job.
class job_handle_t :
public interruptible_read_stream_t, public interruptible_write_stream_t
{
friend class pool_t;
friend class interruptor_wrapper_t;
public:
// When constructed, job handles are "disconnected", not associated with a
// job. They are connected by pool_t::spawn_job().
job_handle_t();
// You MUST call release() to finish a job normally, and you SHOULD call
// interrupt() explicitly to interrupt a job (or signal the interruptor
// during {read,write}_interruptible()).
//
// However, as a convenience in the case of exception-raising code, if the
// handle is connected, the destructor will log a warning and interrupt the
// job.
virtual ~job_handle_t();
bool connected() { return NULL != worker_; }
// Begins running `job` on `pool`. Must be disconnected beforehand. On
// success, returns 0 and connects us to the spawned job. Returns -1 on
// error.
int begin(pool_t *pool, const job_t &job);
// Indicates the job has either finished normally or experienced an I/O
// error; disconnects the job handle.
void release() THROWS_NOTHING;
// Forcibly interrupts a running job; disconnects the job handle.
//
// MAY NOT be called concurrently with any I/O methods. Instead, pass a
// signal to {read,write}_interruptible().
void interrupt() THROWS_NOTHING;
// On either read or write error or interruption, the job handle becomes
// disconnected and must not be used.
virtual MUST_USE int64_t read_interruptible(void *p, int64_t n, signal_t *interruptor);
virtual int64_t write_interruptible(const void *p, int64_t n, signal_t *interruptor);
private:
void check_attached();
class interruptor_wrapper_t : public signal_t, public signal_t::subscription_t {
public:
interruptor_wrapper_t(job_handle_t *handle, signal_t *signal);
virtual void run() THROWS_NOTHING;
job_handle_t *handle_;
};
private:
pool_t::worker_t *worker_;
};
} // namespace extproc
#endif // EXTPROC_POOL_HPP_
<|endoftext|> |
<commit_before>#ifndef DAVFILE_HPP
#define DAVFILE_HPP
#include <davixcontext.hpp>
#include <params/davixrequestparams.hpp>
#include <posix/davposix.hpp>
#include <davix_types.h>
#ifndef __DAVIX_INSIDE__
#error "Only davix.h or davix.hpp should be included."
#endif
///
/// @file davfile.hpp
/// @author Devresse Adrien
///
/// File API of Davix
namespace Davix{
struct DavFileInternal;
typedef std::vector<Uri> ReplicaVec;
class DavFile
{
public:
DavFile(Context & c, const Uri & url);
virtual ~DavFile();
///
/// @brief return all replicas associated to this file
///
/// Replicas are found using a corresponding meta-link file or Webdav extensions if supported
///
/// @param params Davix Request parameters
/// @param vec Replica vector
/// @param err DavixError error report
/// @return the number of replicas if found, -1 if error.
dav_ssize_t getAllReplicas(const RequestParams* params,
ReplicaVec & vec,
DavixError** err);
///
/// @brief Vector read operation
/// Allow to do several read several data chunk in one single operation
/// Use Http multi-part when supported by the server,
/// simulate a vector read operation in the other case
///
/// @param params Davix request Parameters
/// @param input_vec input vectors, parameters
/// @param ioutput_vec output vectors, results
/// @param count_vec number of vector struct
/// @param err Davix Error report
/// @return total number of bytes read, or -1 if error occures
///
dav_ssize_t readPartialBufferVec(const RequestParams* params,
const DavIOVecInput * input_vec,
DavIOVecOuput * ioutput_vec,
const dav_size_t count_vec,
DavixError** err);
///
/// @brief Partial position independant read.
///
///
/// Use Ranged request when supported by the server,
/// simulate a ranged request when not supported
///
/// @param params: Davix request Parameters
/// @param buff buffer
/// @param count maximum read size
/// @param offset start offset for the read operation
/// @param err Davix Error report
/// @return total number of bytes read, or -1 if error occures
///
dav_ssize_t readPartial(const RequestParams* params,
void* buff,
dav_size_t count,
dav_off_t offset,
DavixError** err);
///
/// @brief Get the full file content and write it to fd
///
/// @param params Davix request Parameters
/// @param fd file descriptor for write operation
/// @param err Davix Error report
/// @return total number of bytes read, or -1 if error occures
///
dav_ssize_t getToFd(const RequestParams* params,
int fd,
DavixError** err);
///
/// @brief Get the first 'size_read' bytes of the file and write it to fd
///
/// @param params: Davix request Parameters
/// @param fd file descriptor for write operation
/// @param size_read number of bytes to read
/// @param err Davix Error report
/// @return total number of bytes read, or -1 if error occures
///
dav_ssize_t getToFd(const RequestParams* params,
int fd,
dav_size_t size_read,
DavixError** err);
///
/// @brief Get the full file content in a dynamically allocated buffer
///
/// @param params Davix request Parameters
/// @param buffer reference to a vector for the result
/// @param err Davix Error report
/// @return total number of bytes read, or -1 if error occures
///
dav_ssize_t getFull(const RequestParams* params,
std::vector<char> & buffer,
DavixError** err);
///
/// @brief create and replace the file with the content
/// of the file descriptor fd
///
/// @param params Davix request Parameters
/// @param fd file descriptor
/// @param size_write number of bytes to write
/// @param err Davix Error report
/// @return 0 if success, or -1 if error occures
///
int putFromFd(const RequestParams* params,
int fd,
dav_size_t size_write,
DavixError** err);
///
/// @brief Suppress the current entity.
/// able to suppress collection too
///
/// @param params Davix request Parameters
/// @param err Davix Error report
/// @return 0 if success, or -1 if error occures
///
int deletion(const RequestParams* params,
DavixError** err);
///
/// @brief create a collection ( directory or bucket) at the current file url
///
/// @param params Davix request Parameters
/// @param err Davix Error report
/// @return 0 if success, or -1 if error occures
///
int makeCollection(const RequestParams* params,
DavixError** err);
///
/// @brief execute a POSIX-like stat() query
///
/// @param params: Davix request Parameters
/// @param st stat struct
/// @param err Davix Error report
/// @return 0 if success, or -1 if error occures
///
int stat(const RequestParams* params, struct stat * st, DavixError** err);
private:
DavFileInternal* d_ptr;
DavFile(const DavFile & f);
DavFile & operator=(const DavFile & f);
};
} // Davix
#endif // DAVFILE_HPP
<commit_msg>- improve documentation of davix file api<commit_after>#ifndef DAVFILE_HPP
#define DAVFILE_HPP
#include <davixcontext.hpp>
#include <params/davixrequestparams.hpp>
#include <posix/davposix.hpp>
#include <davix_types.h>
#ifndef __DAVIX_INSIDE__
#error "Only davix.h or davix.hpp should be included."
#endif
///
/// @file davfile.hpp
/// @author Devresse Adrien
///
/// File API of Davix
namespace Davix{
struct DavFileInternal;
typedef std::vector<Uri> ReplicaVec;
///
/// @class DavFile
/// @brief Davix File API
///
/// Davix File interface
class DAVIX_EXPORT DavFile
{
public:
DavFile(Context & c, const Uri & url);
virtual ~DavFile();
///
/// @brief return all replicas associated to this file
///
/// Replicas are found using a corresponding meta-link file or Webdav extensions if supported
///
/// @param params Davix Request parameters
/// @param vec Replica vector
/// @param err DavixError error report
/// @return the number of replicas if found, -1 if error.
dav_ssize_t getAllReplicas(const RequestParams* params,
ReplicaVec & vec,
DavixError** err);
///
/// @brief Vector read operation
/// Allow to do several read several data chunk in one single operation
/// Use Http multi-part when supported by the server,
/// simulate a vector read operation in the other case
///
/// @param params Davix request Parameters
/// @param input_vec input vectors, parameters
/// @param ioutput_vec output vectors, results
/// @param count_vec number of vector struct
/// @param err Davix Error report
/// @return total number of bytes read, or -1 if error occures
///
dav_ssize_t readPartialBufferVec(const RequestParams* params,
const DavIOVecInput * input_vec,
DavIOVecOuput * ioutput_vec,
const dav_size_t count_vec,
DavixError** err);
///
/// @brief Partial position independant read.
///
///
/// Use Ranged request when supported by the server,
/// simulate a ranged request when not supported
///
/// @param params: Davix request Parameters
/// @param buff buffer
/// @param count maximum read size
/// @param offset start offset for the read operation
/// @param err Davix Error report
/// @return total number of bytes read, or -1 if error occures
///
dav_ssize_t readPartial(const RequestParams* params,
void* buff,
dav_size_t count,
dav_off_t offset,
DavixError** err);
///
/// @brief Get the full file content and write it to fd
///
/// @param params Davix request Parameters
/// @param fd file descriptor for write operation
/// @param err Davix Error report
/// @return total number of bytes read, or -1 if error occures
///
dav_ssize_t getToFd(const RequestParams* params,
int fd,
DavixError** err);
///
/// @brief Get the first 'size_read' bytes of the file and write it to fd
///
/// @param params: Davix request Parameters
/// @param fd file descriptor for write operation
/// @param size_read number of bytes to read
/// @param err Davix Error report
/// @return total number of bytes read, or -1 if error occures
///
dav_ssize_t getToFd(const RequestParams* params,
int fd,
dav_size_t size_read,
DavixError** err);
///
/// @brief Get the full file content in a dynamically allocated buffer
///
/// @param params Davix request Parameters
/// @param buffer reference to a vector for the result
/// @param err Davix Error report
/// @return total number of bytes read, or -1 if error occures
///
dav_ssize_t getFull(const RequestParams* params,
std::vector<char> & buffer,
DavixError** err);
///
/// @brief create and replace the file with the content
/// of the file descriptor fd
///
/// @param params Davix request Parameters
/// @param fd file descriptor
/// @param size_write number of bytes to write
/// @param err Davix Error report
/// @return 0 if success, or -1 if error occures
///
int putFromFd(const RequestParams* params,
int fd,
dav_size_t size_write,
DavixError** err);
///
/// @brief Suppress the current entity.
/// able to suppress collection too
///
/// @param params Davix request Parameters
/// @param err Davix Error report
/// @return 0 if success, or -1 if error occures
///
int deletion(const RequestParams* params,
DavixError** err);
///
/// @brief create a collection ( directory or bucket) at the current file url
///
/// @param params Davix request Parameters
/// @param err Davix Error report
/// @return 0 if success, or -1 if error occures
///
int makeCollection(const RequestParams* params,
DavixError** err);
///
/// @brief execute a POSIX-like stat() query
///
/// @param params: Davix request Parameters
/// @param st stat struct
/// @param err Davix Error report
/// @return 0 if success, or -1 if error occures
///
int stat(const RequestParams* params, struct stat * st, DavixError** err);
private:
DavFileInternal* d_ptr;
DavFile(const DavFile & f);
DavFile & operator=(const DavFile & f);
};
} // Davix
#endif // DAVFILE_HPP
<|endoftext|> |
<commit_before>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban
// =============================================================================
//
// Benchmark test for HMMWV double lane change.
//
// =============================================================================
#include "chrono/utils/ChBenchmark.h"
#include "chrono_vehicle/ChVehicleModelData.h"
#include "chrono_vehicle/driver/ChPathFollowerDriver.h"
#include "chrono_vehicle/terrain/RigidTerrain.h"
#include "chrono_vehicle/utils/ChVehiclePath.h"
#include "chrono_vehicle/wheeled_vehicle/utils/ChWheeledVehicleIrrApp.h"
#include "chrono_models/vehicle/hmmwv/HMMWV.h"
using namespace chrono;
using namespace chrono::vehicle;
using namespace chrono::vehicle::hmmwv;
// =============================================================================
template <typename EnumClass, EnumClass TIRE_MODEL>
class HmmwvDlcTest : public utils::ChBenchmarkTest {
public:
HmmwvDlcTest();
~HmmwvDlcTest();
ChSystem* GetSystem() override { return m_hmmwv->GetSystem(); }
void ExecuteStep() override;
void SimulateVis();
double GetTime() const { return m_hmmwv->GetSystem()->GetChTime(); }
double GetLocation() const { return m_hmmwv->GetVehicle().GetVehiclePos().x(); }
private:
HMMWV_Full* m_hmmwv;
RigidTerrain* m_terrain;
ChPathFollowerDriver* m_driver;
double m_step_veh;
double m_step_tire;
};
template <typename EnumClass, EnumClass TIRE_MODEL>
HmmwvDlcTest<EnumClass, TIRE_MODEL>::HmmwvDlcTest() : m_step_veh(2e-3), m_step_tire(1e-3) {
PowertrainModelType powertrain_model = PowertrainModelType::SHAFTS;
TireModelType tire_model = TireModelType::RIGID_MESH;
DrivelineType drive_type = DrivelineType::AWD;
// Create the HMMWV vehicle, set parameters, and initialize.
m_hmmwv = new HMMWV_Full();
m_hmmwv->SetContactMethod(ChMaterialSurface::SMC);
m_hmmwv->SetChassisFixed(false);
m_hmmwv->SetInitPosition(ChCoordsys<>(ChVector<>(-120, 0, 0.7), ChQuaternion<>(1, 0, 0, 0)));
m_hmmwv->SetPowertrainType(powertrain_model);
m_hmmwv->SetDriveType(drive_type);
m_hmmwv->SetTireType(TIRE_MODEL);
m_hmmwv->SetTireStepSize(m_step_tire);
m_hmmwv->SetVehicleStepSize(m_step_veh);
m_hmmwv->SetAerodynamicDrag(0.5, 5.0, 1.2);
m_hmmwv->Initialize();
m_hmmwv->SetChassisVisualizationType(VisualizationType::PRIMITIVES);
m_hmmwv->SetSuspensionVisualizationType(VisualizationType::PRIMITIVES);
m_hmmwv->SetSteeringVisualizationType(VisualizationType::PRIMITIVES);
m_hmmwv->SetWheelVisualizationType(VisualizationType::NONE);
m_hmmwv->SetTireVisualizationType(VisualizationType::PRIMITIVES);
// Create the terrain
m_terrain = new RigidTerrain(m_hmmwv->GetSystem());
auto patch = m_terrain->AddPatch(ChCoordsys<>(ChVector<>(0, 0, -5), QUNIT), ChVector<>(300, 20, 10));
patch->SetContactFrictionCoefficient(0.9f);
patch->SetContactRestitutionCoefficient(0.01f);
patch->SetContactMaterialProperties(2e7f, 0.3f);
patch->SetColor(ChColor(0.8f, 0.8f, 0.8f));
patch->SetTexture(vehicle::GetDataFile("terrain/textures/tile4.jpg"), 300, 20);
m_terrain->Initialize();
// Parameterized NATO double lane change (to right)
auto path = DoubleLaneChangePath(ChVector<>(-125, 0, 0.1), 28.93, 3.6105, 25.0, 50.0, false);
m_driver = new ChPathFollowerDriver(m_hmmwv->GetVehicle(), path, "my_path", 12.0);
m_driver->GetSteeringController().SetLookAheadDistance(5.0);
m_driver->GetSteeringController().SetGains(0.8, 0, 0);
m_driver->GetSpeedController().SetGains(0.4, 0, 0);
m_driver->Initialize();
}
template <typename EnumClass, EnumClass TIRE_MODEL>
HmmwvDlcTest<EnumClass, TIRE_MODEL>::~HmmwvDlcTest() {
delete m_hmmwv;
delete m_terrain;
delete m_driver;
}
template <typename EnumClass, EnumClass TIRE_MODEL>
void HmmwvDlcTest<EnumClass, TIRE_MODEL>::ExecuteStep() {
double time = m_hmmwv->GetSystem()->GetChTime();
// Collect output data from modules (for inter-module communication)
double throttle_input = m_driver->GetThrottle();
double steering_input = m_driver->GetSteering();
double braking_input = m_driver->GetBraking();
// Update modules (process inputs from other modules)
m_driver->Synchronize(time);
m_terrain->Synchronize(time);
m_hmmwv->Synchronize(time, steering_input, braking_input, throttle_input, *m_terrain);
// Advance simulation for one timestep for all modules
m_driver->Advance(m_step_veh);
m_terrain->Advance(m_step_veh);
m_hmmwv->Advance(m_step_veh);
}
template <typename EnumClass, EnumClass TIRE_MODEL>
void HmmwvDlcTest<EnumClass, TIRE_MODEL>::SimulateVis() {
ChWheeledVehicleIrrApp app(&m_hmmwv->GetVehicle(), &m_hmmwv->GetPowertrain(), L"HMMWV acceleration test");
app.SetSkyBox();
app.AddTypicalLights(irr::core::vector3df(30.f, -30.f, 100.f), irr::core::vector3df(30.f, 50.f, 100.f), 250, 130);
app.SetChaseCamera(ChVector<>(0.0, 0.0, 1.75), 6.0, 0.5);
// Visualization of controller points (sentinel & target)
irr::scene::IMeshSceneNode* ballS = app.GetSceneManager()->addSphereSceneNode(0.1f);
irr::scene::IMeshSceneNode* ballT = app.GetSceneManager()->addSphereSceneNode(0.1f);
ballS->getMaterial(0).EmissiveColor = irr::video::SColor(0, 255, 0, 0);
ballT->getMaterial(0).EmissiveColor = irr::video::SColor(0, 0, 255, 0);
app.AssetBindAll();
app.AssetUpdateAll();
while (app.GetDevice()->run()) {
const ChVector<>& pS = m_driver->GetSteeringController().GetSentinelLocation();
const ChVector<>& pT = m_driver->GetSteeringController().GetTargetLocation();
ballS->setPosition(irr::core::vector3df((irr::f32)pS.x(), (irr::f32)pS.y(), (irr::f32)pS.z()));
ballT->setPosition(irr::core::vector3df((irr::f32)pT.x(), (irr::f32)pT.y(), (irr::f32)pT.z()));
app.BeginScene();
app.DrawAll();
ExecuteStep();
app.Synchronize("Acceleration test", m_driver->GetSteering(), m_driver->GetThrottle(), m_driver->GetBraking());
app.Advance(m_step_veh);
app.EndScene();
}
std::cout << "Time: " << GetTime() << " location: " << GetLocation() << std::endl;
}
// =============================================================================
#define NUM_SKIP_STEPS 2500 // number of steps for hot start (2e-3 * 2500 = 5s)
#define NUM_SIM_STEPS 5000 // number of simulation steps for each benchmark (2e-3 * 5000 = 10s)
#define REPEATS 10
// NOTE: trick to prevent erros in expanding macros due to types that contain a comma.
typedef HmmwvDlcTest<TireModelType, TireModelType::TMEASY> tmeasy_test_type;
typedef HmmwvDlcTest<TireModelType, TireModelType::FIALA> fiala_test_type;
typedef HmmwvDlcTest<TireModelType, TireModelType::RIGID> rigid_test_type;
typedef HmmwvDlcTest<TireModelType, TireModelType::RIGID_MESH> rigidmesh_test_type;
CH_BM_SIMULATION_ONCE(HmmwvDLC_TMEASY, tmeasy_test_type, NUM_SKIP_STEPS, NUM_SIM_STEPS, REPEATS);
CH_BM_SIMULATION_ONCE(HmmwvDLC_FIALA, fiala_test_type, NUM_SKIP_STEPS, NUM_SIM_STEPS, REPEATS);
CH_BM_SIMULATION_ONCE(HmmwvDLC_RIGID, rigid_test_type, NUM_SKIP_STEPS, NUM_SIM_STEPS, REPEATS);
CH_BM_SIMULATION_ONCE(HmmwvDLC_RIGIDMESH, rigidmesh_test_type, NUM_SKIP_STEPS, NUM_SIM_STEPS, REPEATS);
// =============================================================================
int main(int argc, char* argv[]) {
::benchmark::Initialize(&argc, argv);
if (::benchmark::ReportUnrecognizedArguments(argc, argv)) {
HmmwvDlcTest<TireModelType, TireModelType::TMEASY> test;
////HmmwvDlcTest<TireModelType, TireModelType::FIALA> test;
////HmmwvDlcTest<TireModelType, TireModelType::RIGID> test;
////HmmwvDlcTest<TireModelType, TireModelType::RIGID_MESH> test;
test.SimulateVis();
return 0;
}
::benchmark::RunSpecifiedBenchmarks();
}
<commit_msg>Fix test to work even if Chrono::Irrlicht is not enabled<commit_after>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban
// =============================================================================
//
// Benchmark test for HMMWV double lane change.
//
// =============================================================================
#include "chrono/utils/ChBenchmark.h"
#include "chrono_vehicle/ChVehicleModelData.h"
#include "chrono_vehicle/driver/ChPathFollowerDriver.h"
#include "chrono_vehicle/terrain/RigidTerrain.h"
#include "chrono_vehicle/utils/ChVehiclePath.h"
#include "chrono_models/vehicle/hmmwv/HMMWV.h"
#ifdef CHRONO_IRRLICHT
#include "chrono_vehicle/wheeled_vehicle/utils/ChWheeledVehicleIrrApp.h"
#endif
using namespace chrono;
using namespace chrono::vehicle;
using namespace chrono::vehicle::hmmwv;
// =============================================================================
template <typename EnumClass, EnumClass TIRE_MODEL>
class HmmwvDlcTest : public utils::ChBenchmarkTest {
public:
HmmwvDlcTest();
~HmmwvDlcTest();
ChSystem* GetSystem() override { return m_hmmwv->GetSystem(); }
void ExecuteStep() override;
void SimulateVis();
double GetTime() const { return m_hmmwv->GetSystem()->GetChTime(); }
double GetLocation() const { return m_hmmwv->GetVehicle().GetVehiclePos().x(); }
private:
HMMWV_Full* m_hmmwv;
RigidTerrain* m_terrain;
ChPathFollowerDriver* m_driver;
double m_step_veh;
double m_step_tire;
};
template <typename EnumClass, EnumClass TIRE_MODEL>
HmmwvDlcTest<EnumClass, TIRE_MODEL>::HmmwvDlcTest() : m_step_veh(2e-3), m_step_tire(1e-3) {
PowertrainModelType powertrain_model = PowertrainModelType::SHAFTS;
TireModelType tire_model = TireModelType::RIGID_MESH;
DrivelineType drive_type = DrivelineType::AWD;
// Create the HMMWV vehicle, set parameters, and initialize.
m_hmmwv = new HMMWV_Full();
m_hmmwv->SetContactMethod(ChMaterialSurface::SMC);
m_hmmwv->SetChassisFixed(false);
m_hmmwv->SetInitPosition(ChCoordsys<>(ChVector<>(-120, 0, 0.7), ChQuaternion<>(1, 0, 0, 0)));
m_hmmwv->SetPowertrainType(powertrain_model);
m_hmmwv->SetDriveType(drive_type);
m_hmmwv->SetTireType(TIRE_MODEL);
m_hmmwv->SetTireStepSize(m_step_tire);
m_hmmwv->SetVehicleStepSize(m_step_veh);
m_hmmwv->SetAerodynamicDrag(0.5, 5.0, 1.2);
m_hmmwv->Initialize();
m_hmmwv->SetChassisVisualizationType(VisualizationType::PRIMITIVES);
m_hmmwv->SetSuspensionVisualizationType(VisualizationType::PRIMITIVES);
m_hmmwv->SetSteeringVisualizationType(VisualizationType::PRIMITIVES);
m_hmmwv->SetWheelVisualizationType(VisualizationType::NONE);
m_hmmwv->SetTireVisualizationType(VisualizationType::PRIMITIVES);
// Create the terrain
m_terrain = new RigidTerrain(m_hmmwv->GetSystem());
auto patch = m_terrain->AddPatch(ChCoordsys<>(ChVector<>(0, 0, -5), QUNIT), ChVector<>(300, 20, 10));
patch->SetContactFrictionCoefficient(0.9f);
patch->SetContactRestitutionCoefficient(0.01f);
patch->SetContactMaterialProperties(2e7f, 0.3f);
patch->SetColor(ChColor(0.8f, 0.8f, 0.8f));
patch->SetTexture(vehicle::GetDataFile("terrain/textures/tile4.jpg"), 300, 20);
m_terrain->Initialize();
// Parameterized NATO double lane change (to right)
auto path = DoubleLaneChangePath(ChVector<>(-125, 0, 0.1), 28.93, 3.6105, 25.0, 50.0, false);
m_driver = new ChPathFollowerDriver(m_hmmwv->GetVehicle(), path, "my_path", 12.0);
m_driver->GetSteeringController().SetLookAheadDistance(5.0);
m_driver->GetSteeringController().SetGains(0.8, 0, 0);
m_driver->GetSpeedController().SetGains(0.4, 0, 0);
m_driver->Initialize();
}
template <typename EnumClass, EnumClass TIRE_MODEL>
HmmwvDlcTest<EnumClass, TIRE_MODEL>::~HmmwvDlcTest() {
delete m_hmmwv;
delete m_terrain;
delete m_driver;
}
template <typename EnumClass, EnumClass TIRE_MODEL>
void HmmwvDlcTest<EnumClass, TIRE_MODEL>::ExecuteStep() {
double time = m_hmmwv->GetSystem()->GetChTime();
// Collect output data from modules (for inter-module communication)
double throttle_input = m_driver->GetThrottle();
double steering_input = m_driver->GetSteering();
double braking_input = m_driver->GetBraking();
// Update modules (process inputs from other modules)
m_driver->Synchronize(time);
m_terrain->Synchronize(time);
m_hmmwv->Synchronize(time, steering_input, braking_input, throttle_input, *m_terrain);
// Advance simulation for one timestep for all modules
m_driver->Advance(m_step_veh);
m_terrain->Advance(m_step_veh);
m_hmmwv->Advance(m_step_veh);
}
template <typename EnumClass, EnumClass TIRE_MODEL>
void HmmwvDlcTest<EnumClass, TIRE_MODEL>::SimulateVis() {
#ifdef CHRONO_IRRLICHT
ChWheeledVehicleIrrApp app(&m_hmmwv->GetVehicle(), &m_hmmwv->GetPowertrain(), L"HMMWV acceleration test");
app.SetSkyBox();
app.AddTypicalLights(irr::core::vector3df(30.f, -30.f, 100.f), irr::core::vector3df(30.f, 50.f, 100.f), 250, 130);
app.SetChaseCamera(ChVector<>(0.0, 0.0, 1.75), 6.0, 0.5);
// Visualization of controller points (sentinel & target)
irr::scene::IMeshSceneNode* ballS = app.GetSceneManager()->addSphereSceneNode(0.1f);
irr::scene::IMeshSceneNode* ballT = app.GetSceneManager()->addSphereSceneNode(0.1f);
ballS->getMaterial(0).EmissiveColor = irr::video::SColor(0, 255, 0, 0);
ballT->getMaterial(0).EmissiveColor = irr::video::SColor(0, 0, 255, 0);
app.AssetBindAll();
app.AssetUpdateAll();
while (app.GetDevice()->run()) {
const ChVector<>& pS = m_driver->GetSteeringController().GetSentinelLocation();
const ChVector<>& pT = m_driver->GetSteeringController().GetTargetLocation();
ballS->setPosition(irr::core::vector3df((irr::f32)pS.x(), (irr::f32)pS.y(), (irr::f32)pS.z()));
ballT->setPosition(irr::core::vector3df((irr::f32)pT.x(), (irr::f32)pT.y(), (irr::f32)pT.z()));
app.BeginScene();
app.DrawAll();
ExecuteStep();
app.Synchronize("Acceleration test", m_driver->GetSteering(), m_driver->GetThrottle(), m_driver->GetBraking());
app.Advance(m_step_veh);
app.EndScene();
}
std::cout << "Time: " << GetTime() << " location: " << GetLocation() << std::endl;
#endif
}
// =============================================================================
#define NUM_SKIP_STEPS 2500 // number of steps for hot start (2e-3 * 2500 = 5s)
#define NUM_SIM_STEPS 5000 // number of simulation steps for each benchmark (2e-3 * 5000 = 10s)
#define REPEATS 10
// NOTE: trick to prevent erros in expanding macros due to types that contain a comma.
typedef HmmwvDlcTest<TireModelType, TireModelType::TMEASY> tmeasy_test_type;
typedef HmmwvDlcTest<TireModelType, TireModelType::FIALA> fiala_test_type;
typedef HmmwvDlcTest<TireModelType, TireModelType::RIGID> rigid_test_type;
typedef HmmwvDlcTest<TireModelType, TireModelType::RIGID_MESH> rigidmesh_test_type;
CH_BM_SIMULATION_ONCE(HmmwvDLC_TMEASY, tmeasy_test_type, NUM_SKIP_STEPS, NUM_SIM_STEPS, REPEATS);
CH_BM_SIMULATION_ONCE(HmmwvDLC_FIALA, fiala_test_type, NUM_SKIP_STEPS, NUM_SIM_STEPS, REPEATS);
CH_BM_SIMULATION_ONCE(HmmwvDLC_RIGID, rigid_test_type, NUM_SKIP_STEPS, NUM_SIM_STEPS, REPEATS);
CH_BM_SIMULATION_ONCE(HmmwvDLC_RIGIDMESH, rigidmesh_test_type, NUM_SKIP_STEPS, NUM_SIM_STEPS, REPEATS);
// =============================================================================
int main(int argc, char* argv[]) {
::benchmark::Initialize(&argc, argv);
#ifdef CHRONO_IRRLICHT
if (::benchmark::ReportUnrecognizedArguments(argc, argv)) {
HmmwvDlcTest<TireModelType, TireModelType::TMEASY> test;
////HmmwvDlcTest<TireModelType, TireModelType::FIALA> test;
////HmmwvDlcTest<TireModelType, TireModelType::RIGID> test;
////HmmwvDlcTest<TireModelType, TireModelType::RIGID_MESH> test;
test.SimulateVis();
return 0;
}
#endif
::benchmark::RunSpecifiedBenchmarks();
}
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file socket_can_client.cc
* @brief the encapsulate call the api of socket can card according to
*can_client.h interface
**/
#include "modules/drivers/canbus/can_client/socket/socket_can_client_raw.h"
namespace apollo {
namespace drivers {
namespace canbus {
namespace can {
using apollo::common::ErrorCode;
bool SocketCanClientRaw::Init(const CANCardParameter ¶meter) {
if (!parameter.has_channel_id()) {
AERROR << "Init CAN failed: parameter does not have channel id. The "
"parameter is "
<< parameter.DebugString();
return false;
}
port_ = parameter.channel_id();
return true;
}
ErrorCode SocketCanClientRaw::Start() {
if (is_started_) {
return ErrorCode::OK;
}
struct sockaddr_can addr;
struct ifreq ifr;
// open device
// guss net is the device minor number, if one card is 0,1
// if more than one card, when install driver u can specify the minior id
// int32_t ret = canOpen(net, pCtx->mode, txbufsize, rxbufsize, 0, 0,
// &dev_handler_);
if (port_ > MAX_CAN_PORT || port_ < 0) {
AERROR << "can port number [" << port_ << "] is out of the range [0,"
<< MAX_CAN_PORT << "]";
return ErrorCode::CAN_CLIENT_ERROR_BASE;
}
dev_handler_ = socket(PF_CAN, SOCK_RAW, CAN_RAW);
if (dev_handler_ < 0) {
AERROR << "open device error code [" << dev_handler_ << "]: ";
return ErrorCode::CAN_CLIENT_ERROR_BASE;
}
// init config and state
// 1. set receive message_id filter, ie white list
struct can_filter filter[2048];
for (int i = 0; i < 2048; ++i) {
filter[i].can_id = 0x000 + i;
filter[i].can_mask = CAN_SFF_MASK;
}
int ret = setsockopt(dev_handler_, SOL_CAN_RAW, CAN_RAW_FILTER, &filter,
sizeof(filter));
if (ret < 0) {
AERROR << "add receive msg id filter error code: " << ret;
return ErrorCode::CAN_CLIENT_ERROR_BASE;
}
// 2. enable reception of can frames.
int enable = 1;
ret = ::setsockopt(dev_handler_, SOL_CAN_RAW, CAN_RAW_FD_FRAMES, &enable,
sizeof(enable));
if (ret < 0) {
AERROR << "enable reception of can frame error code: " << ret;
return ErrorCode::CAN_CLIENT_ERROR_BASE;
}
// strcpy(ifr.ifr_name, "can0");
std::strncpy(ifr.ifr_name, "can0", IFNAMSIZ);
if (ioctl(dev_handler_, SIOCGIFINDEX, &ifr) < 0) {
AERROR << "ioctl error";
return ErrorCode::CAN_CLIENT_ERROR_BASE;
}
// bind socket to network interface
addr.can_family = AF_CAN;
addr.can_ifindex = ifr.ifr_ifindex;
ret = ::bind(dev_handler_, reinterpret_cast<struct sockaddr *>(&addr),
sizeof(addr));
if (ret < 0) {
AERROR << "bind socket to network interface error code: " << ret;
return ErrorCode::CAN_CLIENT_ERROR_BASE;
}
is_started_ = true;
return ErrorCode::OK;
}
void SocketCanClientRaw::Stop() {
if (is_started_) {
is_started_ = false;
int ret = close(dev_handler_);
if (ret < 0) {
AERROR << "close error code:" << ret << ", " << GetErrorString(ret);
} else {
AINFO << "close socket can ok. port:" << port_;
}
}
}
// Synchronous transmission of CAN messages
ErrorCode SocketCanClientRaw::Send(const std::vector<CanFrame> &frames,
int32_t *const frame_num) {
CHECK_NOTNULL(frame_num);
CHECK_EQ(frames.size(), static_cast<size_t>(*frame_num));
if (!is_started_) {
AERROR << "Nvidia can client has not been initiated! Please init first!";
return ErrorCode::CAN_CLIENT_ERROR_SEND_FAILED;
}
for (size_t i = 0; i < frames.size() && i < MAX_CAN_SEND_FRAME_LEN; ++i) {
send_frames_[i].can_id = frames[i].id;
send_frames_[i].can_dlc = frames[i].len;
std::memcpy(send_frames_[i].data, frames[i].data, frames[i].len);
// Synchronous transmission of CAN messages
int ret = write(dev_handler_, &send_frames_[i], sizeof(send_frames_[i]));
if (ret <= 0) {
AERROR << "send message failed, error code: " << ret;
return ErrorCode::CAN_CLIENT_ERROR_BASE;
}
}
return ErrorCode::OK;
}
// buf size must be 8 bytes, every time, we receive only one frame
ErrorCode SocketCanClientRaw::Receive(std::vector<CanFrame> *const frames,
int32_t *const frame_num) {
if (!is_started_) {
AERROR << "Nvidia can client is not init! Please init first!";
return ErrorCode::CAN_CLIENT_ERROR_RECV_FAILED;
}
if (*frame_num > MAX_CAN_RECV_FRAME_LEN || *frame_num < 0) {
AERROR << "recv can frame num not in range[0, " << MAX_CAN_RECV_FRAME_LEN
<< "], frame_num:" << *frame_num;
// TODO(Authors): check the difference of returning frame_num/error_code
return ErrorCode::CAN_CLIENT_ERROR_FRAME_NUM;
}
for (int32_t i = 0; i < *frame_num && i < MAX_CAN_RECV_FRAME_LEN; ++i) {
CanFrame cf;
int ret = read(dev_handler_, &recv_frames_[i], sizeof(recv_frames_[i]));
if (ret < 0) {
AERROR << "receive message failed, error code: " << ret;
return ErrorCode::CAN_CLIENT_ERROR_BASE;
}
cf.id = recv_frames_[i].can_id;
cf.len = recv_frames_[i].can_dlc;
std::memcpy(cf.data, recv_frames_[i].data, recv_frames_[i].can_dlc);
frames->push_back(cf);
}
return ErrorCode::OK;
}
std::string SocketCanClientRaw::GetErrorString(const int32_t /*status*/) {
return "";
}
} // namespace can
} // namespace canbus
} // namespace drivers
} // namespace apollo
<commit_msg>Planning: fixed a safety bug in socket_can_client_raw.cc -- do not memcy when the returned can msg length is invalid.<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file socket_can_client.cc
* @brief the encapsulate call the api of socket can card according to
*can_client.h interface
**/
#include "modules/drivers/canbus/can_client/socket/socket_can_client_raw.h"
namespace apollo {
namespace drivers {
namespace canbus {
namespace can {
using apollo::common::ErrorCode;
bool SocketCanClientRaw::Init(const CANCardParameter ¶meter) {
if (!parameter.has_channel_id()) {
AERROR << "Init CAN failed: parameter does not have channel id. The "
"parameter is "
<< parameter.DebugString();
return false;
}
port_ = parameter.channel_id();
return true;
}
ErrorCode SocketCanClientRaw::Start() {
if (is_started_) {
return ErrorCode::OK;
}
struct sockaddr_can addr;
struct ifreq ifr;
// open device
// guss net is the device minor number, if one card is 0,1
// if more than one card, when install driver u can specify the minior id
// int32_t ret = canOpen(net, pCtx->mode, txbufsize, rxbufsize, 0, 0,
// &dev_handler_);
if (port_ > MAX_CAN_PORT || port_ < 0) {
AERROR << "can port number [" << port_ << "] is out of the range [0,"
<< MAX_CAN_PORT << "]";
return ErrorCode::CAN_CLIENT_ERROR_BASE;
}
dev_handler_ = socket(PF_CAN, SOCK_RAW, CAN_RAW);
if (dev_handler_ < 0) {
AERROR << "open device error code [" << dev_handler_ << "]: ";
return ErrorCode::CAN_CLIENT_ERROR_BASE;
}
// init config and state
// 1. set receive message_id filter, ie white list
struct can_filter filter[2048];
for (int i = 0; i < 2048; ++i) {
filter[i].can_id = 0x000 + i;
filter[i].can_mask = CAN_SFF_MASK;
}
int ret = setsockopt(dev_handler_, SOL_CAN_RAW, CAN_RAW_FILTER, &filter,
sizeof(filter));
if (ret < 0) {
AERROR << "add receive msg id filter error code: " << ret;
return ErrorCode::CAN_CLIENT_ERROR_BASE;
}
// 2. enable reception of can frames.
int enable = 1;
ret = ::setsockopt(dev_handler_, SOL_CAN_RAW, CAN_RAW_FD_FRAMES, &enable,
sizeof(enable));
if (ret < 0) {
AERROR << "enable reception of can frame error code: " << ret;
return ErrorCode::CAN_CLIENT_ERROR_BASE;
}
// strcpy(ifr.ifr_name, "can0");
std::strncpy(ifr.ifr_name, "can0", IFNAMSIZ);
if (ioctl(dev_handler_, SIOCGIFINDEX, &ifr) < 0) {
AERROR << "ioctl error";
return ErrorCode::CAN_CLIENT_ERROR_BASE;
}
// bind socket to network interface
addr.can_family = AF_CAN;
addr.can_ifindex = ifr.ifr_ifindex;
ret = ::bind(dev_handler_, reinterpret_cast<struct sockaddr *>(&addr),
sizeof(addr));
if (ret < 0) {
AERROR << "bind socket to network interface error code: " << ret;
return ErrorCode::CAN_CLIENT_ERROR_BASE;
}
is_started_ = true;
return ErrorCode::OK;
}
void SocketCanClientRaw::Stop() {
if (is_started_) {
is_started_ = false;
int ret = close(dev_handler_);
if (ret < 0) {
AERROR << "close error code:" << ret << ", " << GetErrorString(ret);
} else {
AINFO << "close socket can ok. port:" << port_;
}
}
}
// Synchronous transmission of CAN messages
ErrorCode SocketCanClientRaw::Send(const std::vector<CanFrame> &frames,
int32_t *const frame_num) {
CHECK_NOTNULL(frame_num);
CHECK_EQ(frames.size(), static_cast<size_t>(*frame_num));
if (!is_started_) {
AERROR << "Nvidia can client has not been initiated! Please init first!";
return ErrorCode::CAN_CLIENT_ERROR_SEND_FAILED;
}
for (size_t i = 0; i < frames.size() && i < MAX_CAN_SEND_FRAME_LEN; ++i) {
send_frames_[i].can_id = frames[i].id;
send_frames_[i].can_dlc = frames[i].len;
std::memcpy(send_frames_[i].data, frames[i].data, frames[i].len);
// Synchronous transmission of CAN messages
int ret = write(dev_handler_, &send_frames_[i], sizeof(send_frames_[i]));
if (ret <= 0) {
AERROR << "send message failed, error code: " << ret;
return ErrorCode::CAN_CLIENT_ERROR_BASE;
}
}
return ErrorCode::OK;
}
// buf size must be 8 bytes, every time, we receive only one frame
ErrorCode SocketCanClientRaw::Receive(std::vector<CanFrame> *const frames,
int32_t *const frame_num) {
if (!is_started_) {
AERROR << "Nvidia can client is not init! Please init first!";
return ErrorCode::CAN_CLIENT_ERROR_RECV_FAILED;
}
if (*frame_num > MAX_CAN_RECV_FRAME_LEN || *frame_num < 0) {
AERROR << "recv can frame num not in range[0, " << MAX_CAN_RECV_FRAME_LEN
<< "], frame_num:" << *frame_num;
// TODO(Authors): check the difference of returning frame_num/error_code
return ErrorCode::CAN_CLIENT_ERROR_FRAME_NUM;
}
for (int32_t i = 0; i < *frame_num && i < MAX_CAN_RECV_FRAME_LEN; ++i) {
CanFrame cf;
int ret = read(dev_handler_, &recv_frames_[i], sizeof(recv_frames_[i]));
if (ret < 0) {
AERROR << "receive message failed, error code: " << ret;
return ErrorCode::CAN_CLIENT_ERROR_BASE;
}
cf.id = recv_frames_[i].can_id;
cf.len = recv_frames_[i].can_dlc;
if (recv_frames_[i].can_dlc <= MAX_CAN_RECV_FRAME_LEN) {
std::memcpy(cf.data, recv_frames_[i].data, recv_frames_[i].can_dlc);
} else {
AERROR << "recv_frames_[" << i << "].can_dlc = " << cf.len
<< ", which exceeds max can received frame length ("
<< MAX_CAN_RECV_FRAME_LEN;
}
frames->push_back(cf);
}
return ErrorCode::OK;
}
std::string SocketCanClientRaw::GetErrorString(const int32_t /*status*/) {
return "";
}
} // namespace can
} // namespace canbus
} // namespace drivers
} // namespace apollo
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "cuda_xengine.h" // For Complex and CompexInput typedefs
// Normally distributed random numbers with standard deviation of 2.5,
// quantized to integer values and saturated to the range -7.0 to +7.0. For
// the fixed point case, the values are then converted to ints, scaled by 16
// (i.e. -112 to +112), and finally stored as signed chars.
void random_complex(ComplexInput* random_num, int length) {
double u1,u2,r,theta,a,b;
double stddev=2.5;
for(int i=0; i<length; i++){
u1 = (rand() / (double)(RAND_MAX));
u2 = (rand() / (double)(RAND_MAX));
if(u1==0.0) u1=0.5/RAND_MAX;
if(u2==0.0) u2=0.5/RAND_MAX;
// Do Box-Muller transform
r = stddev * sqrt(-2.0*log(u1));
theta = 2*M_PI*u2;
a = r * cos(theta);
b = r * sin(theta);
// Quantize (TODO: unbiased rounding?)
a = round(a);
b = round(b);
// Saturate
if(a > 7.0) a = 7.0;
if(a < -7.0) a = -7.0;
if(b > 7.0) b = 7.0;
if(b < -7.0) b = -7.0;
#ifndef FIXED_POINT
// Simulate 4 bit data that has been converted to floats
// (i.e. {-7.0, -6.0, ..., +6.0, +7.0})
//random_num[i] = ComplexInput( a, b );
random_num[i].real = a;
random_num[i].imag = b;
#else
// Simulate 4 bit data that has been multipled by 16 (via left shift by 4;
// could multiply by 18 to maximize range, but that might be more expensive
// than left shift by 4).
// (i.e. {-112, -96, -80, ..., +80, +96, +112})
//random_num[i] = ComplexInput( ((int)a) << 4, ((int)b) << 4 );
random_num[i].real = ((int)a) << 4;
random_num[i].imag = ((int)b) << 4;
// Uncomment next line to simulate all zeros for every input.
// Interestingly, it does not give exactly zeros on the output.
//random_num[i] = ComplexInput(0,0);
#endif
}
}
void reorderMatrix(Complex *matrix) {
#if MATRIX_ORDER == REGISTER_TILE_TRIANGULAR_ORDER
// reorder the matrix from REGISTER_TILE_TRIANGULAR_ORDER to TRIANGULAR_ORDER
size_t matLength = NFREQUENCY * ((NSTATION/2+1)*(NSTATION/4)*NPOL*NPOL*4) * (NPULSAR + 1);
Complex *tmp = new Complex[matLength];
memset(tmp, '0', matLength);
for(int f=0; f<NFREQUENCY; f++) {
for(int i=0; i<NSTATION/2; i++) {
for (int rx=0; rx<2; rx++) {
for (int j=0; j<=i; j++) {
for (int ry=0; ry<2; ry++) {
int k = f*(NSTATION+1)*(NSTATION/2) + (2*i+rx)*(2*i+rx+1)/2 + 2*j+ry;
int l = f*4*(NSTATION/2+1)*(NSTATION/4) + (2*ry+rx)*(NSTATION/2+1)*(NSTATION/4) + i*(i+1)/2 + j;
for (int pol1=0; pol1<NPOL; pol1++) {
for (int pol2=0; pol2<NPOL; pol2++) {
size_t tri_index = (k*NPOL+pol1)*NPOL+pol2;
size_t reg_index = (l*NPOL+pol1)*NPOL+pol2;
//tmp[tri_index] =
// Complex(((float*)matrix)[reg_index], ((float*)matrix)[reg_index+matLength]);
tmp[tri_index].real =
((float*)matrix)[reg_index];
tmp[tri_index].imag =
((float*)matrix)[reg_index+matLength];
}
}
}
}
}
}
}
memcpy(matrix, tmp, matLength*sizeof(Complex));
delete []tmp;
#elif MATRIX_ORDER == REAL_IMAG_TRIANGULAR_ORDER
// reorder the matrix from REAL_IMAG_TRIANGULAR_ORDER to TRIANGULAR_ORDER
size_t matLength = NFREQUENCY * ((NSTATION+1)*(NSTATION/2)*NPOL*NPOL) * (NPULSAR + 1);
Complex *tmp = new Complex[matLength];
for(int f=0; f<NFREQUENCY; f++){
for(int i=0; i<NSTATION; i++){
for (int j=0; j<=i; j++) {
int k = f*(NSTATION+1)*(NSTATION/2) + i*(i+1)/2 + j;
for (int pol1=0; pol1<NPOL; pol1++) {
for (int pol2=0; pol2<NPOL; pol2++) {
size_t index = (k*NPOL+pol1)*NPOL+pol2;
tmp[index].real = ((float*)matrix)[index];
tmp[index].imag = ((float*)matrix)[index+matLength];
}
}
}
}
}
memcpy(matrix, tmp, matLength*sizeof(Complex));
delete []tmp;
#endif
return;
}
#define zabs(z) (sqrt(z.real*z.real+z.imag*z.imag))
//check that GPU calculation matches the CPU
//
// verbose=0 means just print summary.
// verbsoe=1 means print each differing basline/channel.
// verbose=2 and array_h!=0 means print each differing baseline and each input
// sample that contributed to it.
#ifndef FIXED_POINT
#define TOL 1e-12
#else
#define TOL 1e-5
#endif // FIXED_POINT
void checkResult(Complex *gpu, Complex *cpu, int verbose=0, ComplexInput *array_h=0) {
printf("Checking result (tolerance == %g)...\n", TOL); fflush(stdout);
int errorCount=0;
double error = 0.0;
double maxError = 0.0;
for(int i=0; i<NSTATION; i++){
for (int j=0; j<=i; j++) {
for (int pol1=0; pol1<NPOL; pol1++) {
for (int pol2=0; pol2<NPOL; pol2++) {
for(int f=0; f<NFREQUENCY; f++){
int k = f*(NSTATION+1)*(NSTATION/2) + i*(i+1)/2 + j;
int index = (k*NPOL+pol1)*NPOL+pol2;
if(zabs(cpu[index]) == 0) {
error = zabs(gpu[index]);
} else {
Complex delta;
delta.real = cpu[index].real - gpu[index].real;
delta.imag = cpu[index].imag - gpu[index].imag;
error = zabs(delta) / zabs(cpu[index]);
}
if(error > maxError) {
maxError = error;
}
if(error > TOL) {
if(verbose > 0) {
printf("%d %d %d %d %d %d %d %g %g %g %g (%g %g)\n", f, i, j, k, pol1, pol2, index,
cpu[index].real, gpu[index].real, cpu[index].imag, gpu[index].imag, zabs(cpu[index]), zabs(gpu[index]));
if(verbose > 1 && array_h) {
Complex sum;
sum.real = 0;
sum.imag = 0;
for(int t=0; t<NTIME; t++) {
ComplexInput in0 = array_h[t*NFREQUENCY*NSTATION*2 + f*NSTATION*2 + i*2 + pol1];
ComplexInput in1 = array_h[t*NFREQUENCY*NSTATION*2 + f*NSTATION*2 + j*2 + pol2];
//Complex prod = convert(in0) * conj(convert(in1));
Complex prod;
prod.real = in0.real * in1.real + in0.imag * in1.imag;
prod.imag = in0.real * in1.imag + in0.imag * in1.real;
sum.real += prod.real;
sum.imag += prod.imag;
printf(" %4d (%4g,%4g) (%4g,%4g) -> (%6g, %6g)\n", t,
//(float)real(in0), (float)imag(in0),
//(float)real(in1), (float)imag(in1),
//(float)real(prod), (float)imag(prod));
(float)in0.real, (float)in0.imag,
(float)in1.real, (float)in1.imag,
(float)prod.real, (float)prod.imag);
}
printf(" (%6g, %6g)\n", sum.real, sum.imag);
}
}
errorCount++;
}
}
}
}
}
}
if (errorCount) {
printf("Outer product summation failed with %d deviations (max error %g)\n\n", errorCount, maxError);
} else {
printf("Outer product summation successful (max error %g)\n\n", maxError);
}
}
// Extracts the full matrix from the packed Hermitian form
void extractMatrix(Complex *matrix, Complex *packed) {
for(int f=0; f<NFREQUENCY; f++){
for(int i=0; i<NSTATION; i++){
for (int j=0; j<=i; j++) {
int k = f*(NSTATION+1)*(NSTATION/2) + i*(i+1)/2 + j;
for (int pol1=0; pol1<NPOL; pol1++) {
for (int pol2=0; pol2<NPOL; pol2++) {
int index = (k*NPOL+pol1)*NPOL+pol2;
matrix[(((f*NSTATION + i)*NSTATION + j)*NPOL + pol1)*NPOL+pol2].real = packed[index].real;
matrix[(((f*NSTATION + i)*NSTATION + j)*NPOL + pol1)*NPOL+pol2].imag = packed[index].imag;
matrix[(((f*NSTATION + j)*NSTATION + i)*NPOL + pol2)*NPOL+pol1].real = packed[index].real;
matrix[(((f*NSTATION + j)*NSTATION + i)*NPOL + pol2)*NPOL+pol1].imag = -packed[index].imag;
//printf("%d %d %d %d %d %d %d\n",f,i,j,k,pol1,pol2,index);
}
}
}
}
}
}
<commit_msg>Fix verbose output from checkResult<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "cuda_xengine.h" // For Complex and CompexInput typedefs
// Normally distributed random numbers with standard deviation of 2.5,
// quantized to integer values and saturated to the range -7.0 to +7.0. For
// the fixed point case, the values are then converted to ints, scaled by 16
// (i.e. -112 to +112), and finally stored as signed chars.
void random_complex(ComplexInput* random_num, int length) {
double u1,u2,r,theta,a,b;
double stddev=2.5;
for(int i=0; i<length; i++){
u1 = (rand() / (double)(RAND_MAX));
u2 = (rand() / (double)(RAND_MAX));
if(u1==0.0) u1=0.5/RAND_MAX;
if(u2==0.0) u2=0.5/RAND_MAX;
// Do Box-Muller transform
r = stddev * sqrt(-2.0*log(u1));
theta = 2*M_PI*u2;
a = r * cos(theta);
b = r * sin(theta);
// Quantize (TODO: unbiased rounding?)
a = round(a);
b = round(b);
// Saturate
if(a > 7.0) a = 7.0;
if(a < -7.0) a = -7.0;
if(b > 7.0) b = 7.0;
if(b < -7.0) b = -7.0;
#ifndef FIXED_POINT
// Simulate 4 bit data that has been converted to floats
// (i.e. {-7.0, -6.0, ..., +6.0, +7.0})
//random_num[i] = ComplexInput( a, b );
random_num[i].real = a;
random_num[i].imag = b;
#else
// Simulate 4 bit data that has been multipled by 16 (via left shift by 4;
// could multiply by 18 to maximize range, but that might be more expensive
// than left shift by 4).
// (i.e. {-112, -96, -80, ..., +80, +96, +112})
//random_num[i] = ComplexInput( ((int)a) << 4, ((int)b) << 4 );
random_num[i].real = ((int)a) << 4;
random_num[i].imag = ((int)b) << 4;
// Uncomment next line to simulate all zeros for every input.
// Interestingly, it does not give exactly zeros on the output.
//random_num[i] = ComplexInput(0,0);
#endif
}
}
void reorderMatrix(Complex *matrix) {
#if MATRIX_ORDER == REGISTER_TILE_TRIANGULAR_ORDER
// reorder the matrix from REGISTER_TILE_TRIANGULAR_ORDER to TRIANGULAR_ORDER
size_t matLength = NFREQUENCY * ((NSTATION/2+1)*(NSTATION/4)*NPOL*NPOL*4) * (NPULSAR + 1);
Complex *tmp = new Complex[matLength];
memset(tmp, '0', matLength);
for(int f=0; f<NFREQUENCY; f++) {
for(int i=0; i<NSTATION/2; i++) {
for (int rx=0; rx<2; rx++) {
for (int j=0; j<=i; j++) {
for (int ry=0; ry<2; ry++) {
int k = f*(NSTATION+1)*(NSTATION/2) + (2*i+rx)*(2*i+rx+1)/2 + 2*j+ry;
int l = f*4*(NSTATION/2+1)*(NSTATION/4) + (2*ry+rx)*(NSTATION/2+1)*(NSTATION/4) + i*(i+1)/2 + j;
for (int pol1=0; pol1<NPOL; pol1++) {
for (int pol2=0; pol2<NPOL; pol2++) {
size_t tri_index = (k*NPOL+pol1)*NPOL+pol2;
size_t reg_index = (l*NPOL+pol1)*NPOL+pol2;
//tmp[tri_index] =
// Complex(((float*)matrix)[reg_index], ((float*)matrix)[reg_index+matLength]);
tmp[tri_index].real =
((float*)matrix)[reg_index];
tmp[tri_index].imag =
((float*)matrix)[reg_index+matLength];
}
}
}
}
}
}
}
memcpy(matrix, tmp, matLength*sizeof(Complex));
delete []tmp;
#elif MATRIX_ORDER == REAL_IMAG_TRIANGULAR_ORDER
// reorder the matrix from REAL_IMAG_TRIANGULAR_ORDER to TRIANGULAR_ORDER
size_t matLength = NFREQUENCY * ((NSTATION+1)*(NSTATION/2)*NPOL*NPOL) * (NPULSAR + 1);
Complex *tmp = new Complex[matLength];
for(int f=0; f<NFREQUENCY; f++){
for(int i=0; i<NSTATION; i++){
for (int j=0; j<=i; j++) {
int k = f*(NSTATION+1)*(NSTATION/2) + i*(i+1)/2 + j;
for (int pol1=0; pol1<NPOL; pol1++) {
for (int pol2=0; pol2<NPOL; pol2++) {
size_t index = (k*NPOL+pol1)*NPOL+pol2;
tmp[index].real = ((float*)matrix)[index];
tmp[index].imag = ((float*)matrix)[index+matLength];
}
}
}
}
}
memcpy(matrix, tmp, matLength*sizeof(Complex));
delete []tmp;
#endif
return;
}
#define zabs(z) (sqrt(z.real*z.real+z.imag*z.imag))
//check that GPU calculation matches the CPU
//
// verbose=0 means just print summary.
// verbsoe=1 means print each differing basline/channel.
// verbose=2 and array_h!=0 means print each differing baseline and each input
// sample that contributed to it.
#ifndef FIXED_POINT
#define TOL 1e-12
#else
#define TOL 1e-5
#endif // FIXED_POINT
void checkResult(Complex *gpu, Complex *cpu, int verbose=0, ComplexInput *array_h=0) {
printf("Checking result (tolerance == %g)...\n", TOL); fflush(stdout);
int errorCount=0;
double error = 0.0;
double maxError = 0.0;
for(int i=0; i<NSTATION; i++){
for (int j=0; j<=i; j++) {
for (int pol1=0; pol1<NPOL; pol1++) {
for (int pol2=0; pol2<NPOL; pol2++) {
for(int f=0; f<NFREQUENCY; f++){
int k = f*(NSTATION+1)*(NSTATION/2) + i*(i+1)/2 + j;
int index = (k*NPOL+pol1)*NPOL+pol2;
if(zabs(cpu[index]) == 0) {
error = zabs(gpu[index]);
} else {
Complex delta;
delta.real = cpu[index].real - gpu[index].real;
delta.imag = cpu[index].imag - gpu[index].imag;
error = zabs(delta) / zabs(cpu[index]);
}
if(error > maxError) {
maxError = error;
}
if(error > TOL) {
if(verbose > 0) {
printf("%d %d %d %d %d %d %d %g %g %g %g (%g %g)\n", f, i, j, k, pol1, pol2, index,
cpu[index].real, gpu[index].real, cpu[index].imag, gpu[index].imag, zabs(cpu[index]), zabs(gpu[index]));
if(verbose > 1 && array_h) {
Complex sum;
sum.real = 0;
sum.imag = 0;
for(int t=0; t<NTIME; t++) {
ComplexInput in0 = array_h[t*NFREQUENCY*NSTATION*2 + f*NSTATION*2 + i*2 + pol1];
ComplexInput in1 = array_h[t*NFREQUENCY*NSTATION*2 + f*NSTATION*2 + j*2 + pol2];
//Complex prod = convert(in0) * conj(convert(in1));
Complex prod;
prod.real = in0.real * in1.real + in0.imag * in1.imag;
prod.imag = in0.imag * in1.real - in0.real * in1.imag;
sum.real += prod.real;
sum.imag += prod.imag;
printf(" %4d (%4g,%4g) (%4g,%4g) -> (%6g, %6g)\n", t,
//(float)real(in0), (float)imag(in0),
//(float)real(in1), (float)imag(in1),
//(float)real(prod), (float)imag(prod));
(float)in0.real, (float)in0.imag,
(float)in1.real, (float)in1.imag,
(float)prod.real, (float)prod.imag);
}
printf(" (%6g, %6g)\n", sum.real, sum.imag);
}
}
errorCount++;
}
}
}
}
}
}
if (errorCount) {
printf("Outer product summation failed with %d deviations (max error %g)\n\n", errorCount, maxError);
} else {
printf("Outer product summation successful (max error %g)\n\n", maxError);
}
}
// Extracts the full matrix from the packed Hermitian form
void extractMatrix(Complex *matrix, Complex *packed) {
for(int f=0; f<NFREQUENCY; f++){
for(int i=0; i<NSTATION; i++){
for (int j=0; j<=i; j++) {
int k = f*(NSTATION+1)*(NSTATION/2) + i*(i+1)/2 + j;
for (int pol1=0; pol1<NPOL; pol1++) {
for (int pol2=0; pol2<NPOL; pol2++) {
int index = (k*NPOL+pol1)*NPOL+pol2;
matrix[(((f*NSTATION + i)*NSTATION + j)*NPOL + pol1)*NPOL+pol2].real = packed[index].real;
matrix[(((f*NSTATION + i)*NSTATION + j)*NPOL + pol1)*NPOL+pol2].imag = packed[index].imag;
matrix[(((f*NSTATION + j)*NSTATION + i)*NPOL + pol2)*NPOL+pol1].real = packed[index].real;
matrix[(((f*NSTATION + j)*NSTATION + i)*NPOL + pol2)*NPOL+pol1].imag = -packed[index].imag;
//printf("%d %d %d %d %d %d %d\n",f,i,j,k,pol1,pol2,index);
}
}
}
}
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "crypter.h"
#include "script.h"
#include <string>
#include <vector>
#include <boost/foreach.hpp>
#include <openssl/aes.h>
#include <openssl/evp.h>
bool CCrypter::SetKeyFromPassphrase(const SecureString& strKeyData, const std::vector<unsigned char>& chSalt, const unsigned int nRounds, const unsigned int nDerivationMethod)
{
if (nRounds < 1 || chSalt.size() != WALLET_CRYPTO_SALT_SIZE)
return false;
int i = 0;
if (nDerivationMethod == 0)
i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha512(), &chSalt[0],
(unsigned char *)&strKeyData[0], strKeyData.size(), nRounds, chKey, chIV);
if (i != (int)WALLET_CRYPTO_KEY_SIZE)
{
OPENSSL_cleanse(chKey, sizeof(chKey));
OPENSSL_cleanse(chIV, sizeof(chIV));
return false;
}
fKeySet = true;
return true;
}
bool CCrypter::SetKey(const CKeyingMaterial& chNewKey, const std::vector<unsigned char>& chNewIV)
{
if (chNewKey.size() != WALLET_CRYPTO_KEY_SIZE || chNewIV.size() != WALLET_CRYPTO_KEY_SIZE)
return false;
memcpy(&chKey[0], &chNewKey[0], sizeof chKey);
memcpy(&chIV[0], &chNewIV[0], sizeof chIV);
fKeySet = true;
return true;
}
bool CCrypter::Encrypt(const CKeyingMaterial& vchPlaintext, std::vector<unsigned char> &vchCiphertext)
{
if (!fKeySet)
return false;
// max ciphertext len for a n bytes of plaintext is
// n + AES_BLOCK_SIZE - 1 bytes
int nLen = vchPlaintext.size();
int nCLen = nLen + AES_BLOCK_SIZE, nFLen = 0;
vchCiphertext = std::vector<unsigned char> (nCLen);
EVP_CIPHER_CTX ctx;
bool fOk = true;
EVP_CIPHER_CTX_init(&ctx);
if (fOk) fOk = EVP_EncryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, chKey, chIV);
if (fOk) fOk = EVP_EncryptUpdate(&ctx, &vchCiphertext[0], &nCLen, &vchPlaintext[0], nLen);
if (fOk) fOk = EVP_EncryptFinal_ex(&ctx, (&vchCiphertext[0])+nCLen, &nFLen);
EVP_CIPHER_CTX_cleanup(&ctx);
if (!fOk) return false;
vchCiphertext.resize(nCLen + nFLen);
return true;
}
bool CCrypter::Decrypt(const std::vector<unsigned char>& vchCiphertext, CKeyingMaterial& vchPlaintext)
{
if (!fKeySet)
return false;
// plaintext will always be equal to or lesser than length of ciphertext
int nLen = vchCiphertext.size();
int nPLen = nLen, nFLen = 0;
vchPlaintext = CKeyingMaterial(nPLen);
EVP_CIPHER_CTX ctx;
bool fOk = true;
EVP_CIPHER_CTX_init(&ctx);
if (fOk) fOk = EVP_DecryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, chKey, chIV);
if (fOk) fOk = EVP_DecryptUpdate(&ctx, &vchPlaintext[0], &nPLen, &vchCiphertext[0], nLen);
if (fOk) fOk = EVP_DecryptFinal_ex(&ctx, (&vchPlaintext[0])+nPLen, &nFLen);
EVP_CIPHER_CTX_cleanup(&ctx);
if (!fOk) return false;
vchPlaintext.resize(nPLen + nFLen);
return true;
}
bool EncryptSecret(const CKeyingMaterial& vMasterKey, const CKeyingMaterial &vchPlaintext, const uint256& nIV, std::vector<unsigned char> &vchCiphertext)
{
CCrypter cKeyCrypter;
std::vector<unsigned char> chIV(WALLET_CRYPTO_KEY_SIZE);
memcpy(&chIV[0], &nIV, WALLET_CRYPTO_KEY_SIZE);
if(!cKeyCrypter.SetKey(vMasterKey, chIV))
return false;
return cKeyCrypter.Encrypt(*((const CKeyingMaterial*)&vchPlaintext), vchCiphertext);
}
bool DecryptSecret(const CKeyingMaterial& vMasterKey, const std::vector<unsigned char>& vchCiphertext, const uint256& nIV, CKeyingMaterial& vchPlaintext)
{
CCrypter cKeyCrypter;
std::vector<unsigned char> chIV(WALLET_CRYPTO_KEY_SIZE);
memcpy(&chIV[0], &nIV, WALLET_CRYPTO_KEY_SIZE);
if(!cKeyCrypter.SetKey(vMasterKey, chIV))
return false;
return cKeyCrypter.Decrypt(vchCiphertext, *((CKeyingMaterial*)&vchPlaintext));
}
bool CCryptoKeyStore::SetCrypted()
{
LOCK(cs_KeyStore);
if (fUseCrypto)
return true;
if (!mapKeys.empty())
return false;
fUseCrypto = true;
return true;
}
bool CCryptoKeyStore::Lock()
{
if (!SetCrypted())
return false;
{
LOCK(cs_KeyStore);
vMasterKey.clear();
}
NotifyStatusChanged(this);
return true;
}
bool CCryptoKeyStore::Unlock(const CKeyingMaterial& vMasterKeyIn)
{
{
LOCK(cs_KeyStore);
if (!SetCrypted())
return false;
CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
for (; mi != mapCryptedKeys.end(); ++mi)
{
const CPubKey &vchPubKey = (*mi).second.first;
const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
CKeyingMaterial vchSecret;
if(!DecryptSecret(vMasterKeyIn, vchCryptedSecret, vchPubKey.GetHash(), vchSecret))
return false;
if (vchSecret.size() != 32)
return false;
CKey key;
key.Set(vchSecret.begin(), vchSecret.end(), vchPubKey.IsCompressed());
if (key.GetPubKey() == vchPubKey)
break;
return false;
}
vMasterKey = vMasterKeyIn;
}
NotifyStatusChanged(this);
return true;
}
bool CCryptoKeyStore::AddKeyPubKey(const CKey& key, const CPubKey &pubkey)
{
{
LOCK(cs_KeyStore);
if (!IsCrypted())
return CBasicKeyStore::AddKeyPubKey(key, pubkey);
if (IsLocked())
return false;
std::vector<unsigned char> vchCryptedSecret;
CKeyingMaterial vchSecret(key.begin(), key.end());
if (!EncryptSecret(vMasterKey, vchSecret, pubkey.GetHash(), vchCryptedSecret))
return false;
if (!AddCryptedKey(pubkey, vchCryptedSecret))
return false;
}
return true;
}
bool CCryptoKeyStore::AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
{
{
LOCK(cs_KeyStore);
if (!SetCrypted())
return false;
mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret);
}
return true;
}
bool CCryptoKeyStore::GetKey(const CKeyID &address, CKey& keyOut) const
{
{
LOCK(cs_KeyStore);
if (!IsCrypted())
return CBasicKeyStore::GetKey(address, keyOut);
CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
if (mi != mapCryptedKeys.end())
{
const CPubKey &vchPubKey = (*mi).second.first;
const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
CKeyingMaterial vchSecret;
if (!DecryptSecret(vMasterKey, vchCryptedSecret, vchPubKey.GetHash(), vchSecret))
return false;
if (vchSecret.size() != 32)
return false;
keyOut.Set(vchSecret.begin(), vchSecret.end(), vchPubKey.IsCompressed());
return true;
}
}
return false;
}
bool CCryptoKeyStore::GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
{
{
LOCK(cs_KeyStore);
if (!IsCrypted())
return CKeyStore::GetPubKey(address, vchPubKeyOut);
CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
if (mi != mapCryptedKeys.end())
{
vchPubKeyOut = (*mi).second.first;
return true;
}
}
return false;
}
bool CCryptoKeyStore::EncryptKeys(CKeyingMaterial& vMasterKeyIn)
{
{
LOCK(cs_KeyStore);
if (!mapCryptedKeys.empty() || IsCrypted())
return false;
fUseCrypto = true;
BOOST_FOREACH(KeyMap::value_type& mKey, mapKeys)
{
const CKey &key = mKey.second;
CPubKey vchPubKey = key.GetPubKey();
CKeyingMaterial vchSecret(key.begin(), key.end());
std::vector<unsigned char> vchCryptedSecret;
if (!EncryptSecret(vMasterKeyIn, vchSecret, vchPubKey.GetHash(), vchCryptedSecret))
return false;
if (!AddCryptedKey(vchPubKey, vchCryptedSecret))
return false;
}
mapKeys.clear();
}
return true;
}
<commit_msg>Make CCryptoKeyStore::Unlock check all keys.<commit_after>// Copyright (c) 2009-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "crypter.h"
#include "script.h"
#include <string>
#include <vector>
#include <boost/foreach.hpp>
#include <openssl/aes.h>
#include <openssl/evp.h>
bool CCrypter::SetKeyFromPassphrase(const SecureString& strKeyData, const std::vector<unsigned char>& chSalt, const unsigned int nRounds, const unsigned int nDerivationMethod)
{
if (nRounds < 1 || chSalt.size() != WALLET_CRYPTO_SALT_SIZE)
return false;
int i = 0;
if (nDerivationMethod == 0)
i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha512(), &chSalt[0],
(unsigned char *)&strKeyData[0], strKeyData.size(), nRounds, chKey, chIV);
if (i != (int)WALLET_CRYPTO_KEY_SIZE)
{
OPENSSL_cleanse(chKey, sizeof(chKey));
OPENSSL_cleanse(chIV, sizeof(chIV));
return false;
}
fKeySet = true;
return true;
}
bool CCrypter::SetKey(const CKeyingMaterial& chNewKey, const std::vector<unsigned char>& chNewIV)
{
if (chNewKey.size() != WALLET_CRYPTO_KEY_SIZE || chNewIV.size() != WALLET_CRYPTO_KEY_SIZE)
return false;
memcpy(&chKey[0], &chNewKey[0], sizeof chKey);
memcpy(&chIV[0], &chNewIV[0], sizeof chIV);
fKeySet = true;
return true;
}
bool CCrypter::Encrypt(const CKeyingMaterial& vchPlaintext, std::vector<unsigned char> &vchCiphertext)
{
if (!fKeySet)
return false;
// max ciphertext len for a n bytes of plaintext is
// n + AES_BLOCK_SIZE - 1 bytes
int nLen = vchPlaintext.size();
int nCLen = nLen + AES_BLOCK_SIZE, nFLen = 0;
vchCiphertext = std::vector<unsigned char> (nCLen);
EVP_CIPHER_CTX ctx;
bool fOk = true;
EVP_CIPHER_CTX_init(&ctx);
if (fOk) fOk = EVP_EncryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, chKey, chIV);
if (fOk) fOk = EVP_EncryptUpdate(&ctx, &vchCiphertext[0], &nCLen, &vchPlaintext[0], nLen);
if (fOk) fOk = EVP_EncryptFinal_ex(&ctx, (&vchCiphertext[0])+nCLen, &nFLen);
EVP_CIPHER_CTX_cleanup(&ctx);
if (!fOk) return false;
vchCiphertext.resize(nCLen + nFLen);
return true;
}
bool CCrypter::Decrypt(const std::vector<unsigned char>& vchCiphertext, CKeyingMaterial& vchPlaintext)
{
if (!fKeySet)
return false;
// plaintext will always be equal to or lesser than length of ciphertext
int nLen = vchCiphertext.size();
int nPLen = nLen, nFLen = 0;
vchPlaintext = CKeyingMaterial(nPLen);
EVP_CIPHER_CTX ctx;
bool fOk = true;
EVP_CIPHER_CTX_init(&ctx);
if (fOk) fOk = EVP_DecryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, chKey, chIV);
if (fOk) fOk = EVP_DecryptUpdate(&ctx, &vchPlaintext[0], &nPLen, &vchCiphertext[0], nLen);
if (fOk) fOk = EVP_DecryptFinal_ex(&ctx, (&vchPlaintext[0])+nPLen, &nFLen);
EVP_CIPHER_CTX_cleanup(&ctx);
if (!fOk) return false;
vchPlaintext.resize(nPLen + nFLen);
return true;
}
bool EncryptSecret(const CKeyingMaterial& vMasterKey, const CKeyingMaterial &vchPlaintext, const uint256& nIV, std::vector<unsigned char> &vchCiphertext)
{
CCrypter cKeyCrypter;
std::vector<unsigned char> chIV(WALLET_CRYPTO_KEY_SIZE);
memcpy(&chIV[0], &nIV, WALLET_CRYPTO_KEY_SIZE);
if(!cKeyCrypter.SetKey(vMasterKey, chIV))
return false;
return cKeyCrypter.Encrypt(*((const CKeyingMaterial*)&vchPlaintext), vchCiphertext);
}
bool DecryptSecret(const CKeyingMaterial& vMasterKey, const std::vector<unsigned char>& vchCiphertext, const uint256& nIV, CKeyingMaterial& vchPlaintext)
{
CCrypter cKeyCrypter;
std::vector<unsigned char> chIV(WALLET_CRYPTO_KEY_SIZE);
memcpy(&chIV[0], &nIV, WALLET_CRYPTO_KEY_SIZE);
if(!cKeyCrypter.SetKey(vMasterKey, chIV))
return false;
return cKeyCrypter.Decrypt(vchCiphertext, *((CKeyingMaterial*)&vchPlaintext));
}
bool CCryptoKeyStore::SetCrypted()
{
LOCK(cs_KeyStore);
if (fUseCrypto)
return true;
if (!mapKeys.empty())
return false;
fUseCrypto = true;
return true;
}
bool CCryptoKeyStore::Lock()
{
if (!SetCrypted())
return false;
{
LOCK(cs_KeyStore);
vMasterKey.clear();
}
NotifyStatusChanged(this);
return true;
}
bool CCryptoKeyStore::Unlock(const CKeyingMaterial& vMasterKeyIn)
{
{
LOCK(cs_KeyStore);
if (!SetCrypted())
return false;
bool keyPass = false;
bool keyFail = false;
CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
for (; mi != mapCryptedKeys.end(); ++mi)
{
const CPubKey &vchPubKey = (*mi).second.first;
const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
CKeyingMaterial vchSecret;
if(!DecryptSecret(vMasterKeyIn, vchCryptedSecret, vchPubKey.GetHash(), vchSecret))
{
keyFail = true;
break;
}
if (vchSecret.size() != 32)
{
keyFail = true;
break;
}
CKey key;
key.Set(vchSecret.begin(), vchSecret.end(), vchPubKey.IsCompressed());
if (key.GetPubKey() != vchPubKey)
{
keyFail = true;
break;
}
keyPass = true;
}
if (keyPass && keyFail)
{
LogPrintf("The wallet is probably corrupted: Some keys decrypt but not all.");
assert(false);
}
if (keyFail || !keyPass)
return false;
vMasterKey = vMasterKeyIn;
}
NotifyStatusChanged(this);
return true;
}
bool CCryptoKeyStore::AddKeyPubKey(const CKey& key, const CPubKey &pubkey)
{
{
LOCK(cs_KeyStore);
if (!IsCrypted())
return CBasicKeyStore::AddKeyPubKey(key, pubkey);
if (IsLocked())
return false;
std::vector<unsigned char> vchCryptedSecret;
CKeyingMaterial vchSecret(key.begin(), key.end());
if (!EncryptSecret(vMasterKey, vchSecret, pubkey.GetHash(), vchCryptedSecret))
return false;
if (!AddCryptedKey(pubkey, vchCryptedSecret))
return false;
}
return true;
}
bool CCryptoKeyStore::AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
{
{
LOCK(cs_KeyStore);
if (!SetCrypted())
return false;
mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret);
}
return true;
}
bool CCryptoKeyStore::GetKey(const CKeyID &address, CKey& keyOut) const
{
{
LOCK(cs_KeyStore);
if (!IsCrypted())
return CBasicKeyStore::GetKey(address, keyOut);
CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
if (mi != mapCryptedKeys.end())
{
const CPubKey &vchPubKey = (*mi).second.first;
const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
CKeyingMaterial vchSecret;
if (!DecryptSecret(vMasterKey, vchCryptedSecret, vchPubKey.GetHash(), vchSecret))
return false;
if (vchSecret.size() != 32)
return false;
keyOut.Set(vchSecret.begin(), vchSecret.end(), vchPubKey.IsCompressed());
return true;
}
}
return false;
}
bool CCryptoKeyStore::GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
{
{
LOCK(cs_KeyStore);
if (!IsCrypted())
return CKeyStore::GetPubKey(address, vchPubKeyOut);
CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
if (mi != mapCryptedKeys.end())
{
vchPubKeyOut = (*mi).second.first;
return true;
}
}
return false;
}
bool CCryptoKeyStore::EncryptKeys(CKeyingMaterial& vMasterKeyIn)
{
{
LOCK(cs_KeyStore);
if (!mapCryptedKeys.empty() || IsCrypted())
return false;
fUseCrypto = true;
BOOST_FOREACH(KeyMap::value_type& mKey, mapKeys)
{
const CKey &key = mKey.second;
CPubKey vchPubKey = key.GetPubKey();
CKeyingMaterial vchSecret(key.begin(), key.end());
std::vector<unsigned char> vchCryptedSecret;
if (!EncryptSecret(vMasterKeyIn, vchSecret, vchPubKey.GetHash(), vchCryptedSecret))
return false;
if (!AddCryptedKey(vchPubKey, vchCryptedSecret))
return false;
}
mapKeys.clear();
}
return true;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include "common.h"
#include "shader.h"
#include "cubemesh.h"
using namespace std;
namespace Hodhr {
CubeMesh::CubeMesh ()
{
cout << "Created a cube mesh asset" << endl;
}
/**
* Destroy the cube mesh buffers
**/
CubeMesh::~CubeMesh ()
{
cout << "Destroying the cube mesh" << endl;
glDisableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glDeleteBuffers(1, &vboId);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glDeleteBuffers(1, &vboiId);
glBindVertexArray(0);
glDeleteVertexArrays(1, &vaoId);
}
void CubeMesh::init( void )
{
HodhrVertex vertices[30];
/*
float vertices[] = {
-0.5f, 0.5f, 0.5f,
-0.5f, -0.5f, 0.5f,
0.5f, -0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
-0.5f, 0.5f, -0.5f,
0.5f, 0.5f, -0.5f,
-0.5f, -0.5f, -0.5f
};
int numVertices = 21;
*/
/*
short b[][2] = {
{0,0},
{0,1},
{1,0},
{1,1}
};
*/
float nx, ny, nz;
// bottom face
nx = 0;
ny = -1;
nz = 0;
vertices[0].x = -1.0;
vertices[0].y = -1.0;
vertices[0].z = -1.0;
vertices[0].nx = nx;
vertices[0].ny = ny;
vertices[0].nz = nz;
vertices[1].x = -1.0;
vertices[1].y = -1.0;
vertices[1].z = 1.0;
vertices[1].nx = nx;
vertices[1].ny = ny;
vertices[1].nz = nz;
vertices[2].x = 1.0;
vertices[2].y = -1.0;
vertices[2].z = 1.0;
vertices[2].nx = nx;
vertices[2].ny = ny;
vertices[2].nz = nz;
vertices[3].x = 1.0;
vertices[3].y = -1.0;
vertices[3].z = -1.0;
vertices[3].nx = nx;
vertices[3].ny = ny;
vertices[3].nz = nz;
// top face
nx = 0;
ny = 1;
nz = 0;
vertices[4].x = -1.0;
vertices[4].y = 1.0;
vertices[4].z = -1.0;
vertices[4].nx = nx;
vertices[4].ny = ny;
vertices[4].nz = nz;
vertices[5].x = -1.0;
vertices[5].y = 1.0;
vertices[5].z = 1.0;
vertices[5].nx = nx;
vertices[5].ny = ny;
vertices[5].nz = nz;
vertices[6].x = 1.0;
vertices[6].y = 1.0;
vertices[6].z = 1.0;
vertices[6].nx = nx;
vertices[6].ny = ny;
vertices[6].nz = nz;
vertices[7].x = 1.0;
vertices[7].y = 1.0;
vertices[7].z = -1.0;
vertices[7].nx = nx;
vertices[7].ny = ny;
vertices[7].nz = nz;
// front face
nx = 1;
ny = 0;
nz = 0;
vertices[8].x = -1.0;
vertices[8].y = -1.0;
vertices[8].z = -1.0;
vertices[8].nx = nx;
vertices[8].ny = ny;
vertices[8].nz = nz;
vertices[9].x = -1.0;
vertices[9].y = 1.0;
vertices[9].z = -1.0;
vertices[9].nx = nx;
vertices[9].ny = ny;
vertices[9].nz = nz;
vertices[10].x = 1.0;
vertices[10].y = 1.0;
vertices[10].z = -1.0;
vertices[10].nx = nx;
vertices[10].ny = ny;
vertices[10].nz = nz;
vertices[11].x = 1.0;
vertices[11].y = -1.0;
vertices[11].z = -1.0;
vertices[11].nx = nx;
vertices[11].ny = ny;
vertices[11].nz = nz;
// back face
nx = -1;
ny = 0;
nz = 0;
vertices[12].x = -1.0;
vertices[12].y = -1.0;
vertices[12].z = 1.0;
vertices[12].nx = nx;
vertices[12].ny = ny;
vertices[12].nz = nz;
vertices[13].x = -1.0;
vertices[13].y = 1.0;
vertices[13].z = 1.0;
vertices[13].nx = nx;
vertices[13].ny = ny;
vertices[13].nz = nz;
vertices[14].x = 1.0;
vertices[14].y = 1.0;
vertices[14].z = 1.0;
vertices[14].nx = nx;
vertices[14].ny = ny;
vertices[14].nz = nz;
vertices[15].x = 1.0;
vertices[15].y = -1.0;
vertices[15].z = 1.0;
vertices[15].nx = nx;
vertices[15].ny = ny;
vertices[15].nz = nz;
// right face
nx = 0;
ny = 0;
nz = 1;
vertices[16].x = 1.0;
vertices[16].y = -1.0;
vertices[16].z = -1.0;
vertices[16].nx = nx;
vertices[16].ny = ny;
vertices[16].nz = nz;
vertices[17].x = 1.0;
vertices[17].y = 1.0;
vertices[17].z = -1.0;
vertices[17].nx = nx;
vertices[17].ny = ny;
vertices[17].nz = nz;
vertices[18].x = 1.0;
vertices[18].y = 1.0;
vertices[18].z = 1.0;
vertices[18].nx = nx;
vertices[18].ny = ny;
vertices[18].nz = nz;
vertices[19].x = 1.0;
vertices[19].y = -1.0;
vertices[19].z = 1.0;
vertices[19].nx = nx;
vertices[19].ny = ny;
vertices[19].nz = nz;
unsigned short indices[] = {
0, 1, 2,
0, 2, 3,
4, 5, 6,
4, 6, 7,
8, 9, 10,
8, 10, 11,
12, 13, 14,
12, 14, 15,
16, 17, 18,
16, 18, 19
};
numIndices = 39;
glGenVertexArrays(1, &vaoId);
glBindVertexArray(vaoId);
glGenBuffers(1, &vboId);
glBindBuffer(GL_ARRAY_BUFFER, vboId);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(HodhrVertex), BUFFER_OFFSET(0));
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(HodhrVertex), BUFFER_OFFSET(12));
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(HodhrVertex), BUFFER_OFFSET(24));
glBindVertexArray(0);
glGenBuffers(1, &vboiId);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vboiId);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
initialized = true;
}
void CubeMesh::draw(const SceneNode& node)
{
glm::vec3 light_position = glm::vec3(0,5,0);
glm::vec3 light_color = glm::vec3(0.2,0.7,0.2);
glm::vec3 ambient_light = glm::vec3(0.2,0.2,0.3);
if (!initialized)
{
cerr << "Cube is not initialized yet" << endl;
return;
}
glUseProgram(shader->getProgramID());
glm::mat4 mvpMatrix = node.getMVPMatrix();
glm::mat3 normal_matrix = node.getNormalMatrix();
glUniformMatrix4fv( MVPMatrixLocation, 1, GL_FALSE, &mvpMatrix[0][0]);
glUniformMatrix3fv( normal_matrix_loc_, 1, GL_FALSE, &normal_matrix[0][0]);
glUniform3f( ambient_loc_, ambient_light.x, ambient_light.y, ambient_light.z);
glUniform3f( light_color_loc_, light_color.x, light_color.y, light_color.z);
glUniform3f( light_position_loc_, light_position.x, light_position.y, light_position.z);
glUniform1f( constant_attenuation_loc_, .2);
glUniform1f( linear_attenuation_loc_, .2);
glBindAttribLocation(shader->getProgramID(), 0, "VertexPosition");
glBindAttribLocation(shader->getProgramID(), 1, "VertexNormal");
glBindVertexArray(vaoId);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vboiId);
glUseProgram(shader->getProgramID());
//std::cout << "draw cube with indices " << numIndices << std::endl;
//glDrawElements(GL_LINES, numIndices, GL_UNSIGNED_SHORT, NULL);
glDrawElements(GL_TRIANGLES, numIndices, GL_UNSIGNED_SHORT, NULL);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glBindVertexArray(0);
}
void CubeMesh::setShader(Shader* shader)
{
Model::setShader(shader);
MVPMatrixLocation = glGetUniformLocation(shader->getProgramID(), "MVPMatrix");
normal_matrix_loc_ = glGetUniformLocation(shader->getProgramID(), "NormalMatrix");
light_position_loc_ = glGetUniformLocation(shader->getProgramID(), "LightPosition");
eye_direction_loc_ = glGetUniformLocation(shader->getProgramID(), "EyeDirection");
constant_attenuation_loc_ = glGetUniformLocation(shader->getProgramID(), "ConstantAttenuation");
linear_attenuation_loc_ = glGetUniformLocation(shader->getProgramID(), "LinearAttenuation");
quadratic_attenuation_loc_ = glGetUniformLocation(shader->getProgramID(), "QuadraticAttenuation");
shininess_loc_ = glGetUniformLocation(shader->getProgramID(), "Shininess");
strength_loc_ = glGetUniformLocation(shader->getProgramID(), "Strength");
light_color_loc_ = glGetUniformLocation(shader->getProgramID(), "LightColor");
ambient_loc_ = glGetUniformLocation(shader->getProgramID(), "Ambient");
cout << "Set cube shader " << shader->getName()
<< " with pID " << shader->getProgramID()
<< " mvp_matrix: " << MVPMatrixLocation
<< " normal matrix: " << normal_matrix_loc_
<< ", ambient light: " << ambient_loc_ << endl;
}
}
<commit_msg>lighting works<commit_after>#include <iostream>
#include "common.h"
#include "shader.h"
#include "cubemesh.h"
using namespace std;
namespace Hodhr {
CubeMesh::CubeMesh ()
{
cout << "Created a cube mesh asset" << endl;
}
/**
* Destroy the cube mesh buffers
**/
CubeMesh::~CubeMesh ()
{
cout << "Destroying the cube mesh" << endl;
glDisableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glDeleteBuffers(1, &vboId);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glDeleteBuffers(1, &vboiId);
glBindVertexArray(0);
glDeleteVertexArrays(1, &vaoId);
}
void CubeMesh::init( void )
{
HodhrVertex vertices[30];
/*
float vertices[] = {
-0.5f, 0.5f, 0.5f,
-0.5f, -0.5f, 0.5f,
0.5f, -0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
-0.5f, 0.5f, -0.5f,
0.5f, 0.5f, -0.5f,
-0.5f, -0.5f, -0.5f
};
int numVertices = 21;
*/
/*
short b[][2] = {
{0,0},
{0,1},
{1,0},
{1,1}
};
*/
float nx, ny, nz;
// bottom face
nx = 0;
ny = 1;
nz = 0;
vertices[0].x = -1.0;
vertices[0].y = -1.0;
vertices[0].z = -1.0;
vertices[0].nx = nx;
vertices[0].ny = ny;
vertices[0].nz = nz;
vertices[1].x = -1.0;
vertices[1].y = -1.0;
vertices[1].z = 1.0;
vertices[1].nx = nx;
vertices[1].ny = ny;
vertices[1].nz = nz;
vertices[2].x = 1.0;
vertices[2].y = -1.0;
vertices[2].z = 1.0;
vertices[2].nx = nx;
vertices[2].ny = ny;
vertices[2].nz = nz;
vertices[3].x = 1.0;
vertices[3].y = -1.0;
vertices[3].z = -1.0;
vertices[3].nx = nx;
vertices[3].ny = ny;
vertices[3].nz = nz;
// top face
nx = 0;
ny = -1;
nz = 0;
vertices[4].x = -1.0;
vertices[4].y = 1.0;
vertices[4].z = -1.0;
vertices[4].nx = nx;
vertices[4].ny = ny;
vertices[4].nz = nz;
vertices[5].x = -1.0;
vertices[5].y = 1.0;
vertices[5].z = 1.0;
vertices[5].nx = nx;
vertices[5].ny = ny;
vertices[5].nz = nz;
vertices[6].x = 1.0;
vertices[6].y = 1.0;
vertices[6].z = 1.0;
vertices[6].nx = nx;
vertices[6].ny = ny;
vertices[6].nz = nz;
vertices[7].x = 1.0;
vertices[7].y = 1.0;
vertices[7].z = -1.0;
vertices[7].nx = nx;
vertices[7].ny = ny;
vertices[7].nz = nz;
// front face
nx = -1;
ny = 0;
nz = 0;
vertices[8].x = -1.0;
vertices[8].y = -1.0;
vertices[8].z = -1.0;
vertices[8].nx = nx;
vertices[8].ny = ny;
vertices[8].nz = nz;
vertices[9].x = -1.0;
vertices[9].y = 1.0;
vertices[9].z = -1.0;
vertices[9].nx = nx;
vertices[9].ny = ny;
vertices[9].nz = nz;
vertices[10].x = 1.0;
vertices[10].y = 1.0;
vertices[10].z = -1.0;
vertices[10].nx = nx;
vertices[10].ny = ny;
vertices[10].nz = nz;
vertices[11].x = 1.0;
vertices[11].y = -1.0;
vertices[11].z = -1.0;
vertices[11].nx = nx;
vertices[11].ny = ny;
vertices[11].nz = nz;
// back face
nx = 1;
ny = 0;
nz = 0;
vertices[12].x = -1.0;
vertices[12].y = -1.0;
vertices[12].z = 1.0;
vertices[12].nx = nx;
vertices[12].ny = ny;
vertices[12].nz = nz;
vertices[13].x = -1.0;
vertices[13].y = 1.0;
vertices[13].z = 1.0;
vertices[13].nx = nx;
vertices[13].ny = ny;
vertices[13].nz = nz;
vertices[14].x = 1.0;
vertices[14].y = 1.0;
vertices[14].z = 1.0;
vertices[14].nx = nx;
vertices[14].ny = ny;
vertices[14].nz = nz;
vertices[15].x = 1.0;
vertices[15].y = -1.0;
vertices[15].z = 1.0;
vertices[15].nx = nx;
vertices[15].ny = ny;
vertices[15].nz = nz;
// right face
nx = 0;
ny = 0;
nz = -1;
vertices[16].x = 1.0;
vertices[16].y = -1.0;
vertices[16].z = -1.0;
vertices[16].nx = nx;
vertices[16].ny = ny;
vertices[16].nz = nz;
vertices[17].x = 1.0;
vertices[17].y = 1.0;
vertices[17].z = -1.0;
vertices[17].nx = nx;
vertices[17].ny = ny;
vertices[17].nz = nz;
vertices[18].x = 1.0;
vertices[18].y = 1.0;
vertices[18].z = 1.0;
vertices[18].nx = nx;
vertices[18].ny = ny;
vertices[18].nz = nz;
vertices[19].x = 1.0;
vertices[19].y = -1.0;
vertices[19].z = 1.0;
vertices[19].nx = nx;
vertices[19].ny = ny;
vertices[19].nz = nz;
unsigned short indices[] = {
0, 1, 2,
0, 2, 3,
4, 5, 6,
4, 6, 7,
8, 9, 10,
8, 10, 11,
12, 13, 14,
12, 14, 15,
16, 17, 18,
16, 18, 19
};
numIndices = 39;
glGenVertexArrays(1, &vaoId);
glBindVertexArray(vaoId);
glGenBuffers(1, &vboId);
glBindBuffer(GL_ARRAY_BUFFER, vboId);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(HodhrVertex), BUFFER_OFFSET(0));
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(HodhrVertex), BUFFER_OFFSET(12));
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(HodhrVertex), BUFFER_OFFSET(24));
glBindVertexArray(0);
glGenBuffers(1, &vboiId);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vboiId);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
initialized = true;
}
void CubeMesh::draw(const SceneNode& node)
{
glm::vec3 light_position = glm::vec3(0,5,0);
glm::vec3 light_color = glm::vec3(0.2,0.7,0.2);
glm::vec3 ambient_light = glm::vec3(0.2,0.2,0.3);
if (!initialized)
{
cerr << "Cube is not initialized yet" << endl;
return;
}
glUseProgram(shader->getProgramID());
glm::mat4 mvpMatrix = node.getMVPMatrix();
glm::mat3 normal_matrix = node.getNormalMatrix();
glUniformMatrix4fv( MVPMatrixLocation, 1, GL_FALSE, &mvpMatrix[0][0]);
glUniformMatrix3fv( normal_matrix_loc_, 1, GL_FALSE, &normal_matrix[0][0]);
glUniform3f( ambient_loc_, ambient_light.x, ambient_light.y, ambient_light.z);
glUniform3f( light_color_loc_, light_color.x, light_color.y, light_color.z);
glUniform3f( light_position_loc_, light_position.x, light_position.y, light_position.z);
glUniform1f( constant_attenuation_loc_, .2);
glUniform1f( linear_attenuation_loc_, .2);
glBindAttribLocation(shader->getProgramID(), 0, "VertexPosition");
glBindAttribLocation(shader->getProgramID(), 1, "VertexNormal");
glBindVertexArray(vaoId);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vboiId);
glUseProgram(shader->getProgramID());
//std::cout << "draw cube with indices " << numIndices << std::endl;
//glDrawElements(GL_LINES, numIndices, GL_UNSIGNED_SHORT, NULL);
glDrawElements(GL_TRIANGLES, numIndices, GL_UNSIGNED_SHORT, NULL);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glBindVertexArray(0);
}
void CubeMesh::setShader(Shader* shader)
{
Model::setShader(shader);
MVPMatrixLocation = glGetUniformLocation(shader->getProgramID(), "MVPMatrix");
normal_matrix_loc_ = glGetUniformLocation(shader->getProgramID(), "NormalMatrix");
light_position_loc_ = glGetUniformLocation(shader->getProgramID(), "LightPosition");
eye_direction_loc_ = glGetUniformLocation(shader->getProgramID(), "EyeDirection");
constant_attenuation_loc_ = glGetUniformLocation(shader->getProgramID(), "ConstantAttenuation");
linear_attenuation_loc_ = glGetUniformLocation(shader->getProgramID(), "LinearAttenuation");
quadratic_attenuation_loc_ = glGetUniformLocation(shader->getProgramID(), "QuadraticAttenuation");
shininess_loc_ = glGetUniformLocation(shader->getProgramID(), "Shininess");
strength_loc_ = glGetUniformLocation(shader->getProgramID(), "Strength");
light_color_loc_ = glGetUniformLocation(shader->getProgramID(), "LightColor");
ambient_loc_ = glGetUniformLocation(shader->getProgramID(), "Ambient");
cout << "Set cube shader " << shader->getName()
<< " with pID " << shader->getProgramID()
<< " mvp_matrix: " << MVPMatrixLocation
<< " normal matrix: " << normal_matrix_loc_
<< ", ambient light: " << ambient_loc_ << endl;
}
}
<|endoftext|> |
<commit_before>#include "qmlinspectortoolbar.h"
#include "qmljsinspectorconstants.h"
#include <extensionsystem/pluginmanager.h>
#include <coreplugin/icore.h>
#include <debugger/debuggeruiswitcher.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/command.h>
#include <QHBoxLayout>
#include <QAction>
#include <QToolButton>
#include <QMenu>
#include <QActionGroup>
namespace QmlJSInspector {
namespace Internal {
static QToolButton *createToolButton(QAction *action)
{
QToolButton *button = new QToolButton;
button->setDefaultAction(action);
return button;
}
QmlInspectorToolbar::QmlInspectorToolbar(QObject *parent) :
QObject(parent),
m_designmodeAction(0),
m_reloadAction(0),
m_playAction(0),
m_pauseAction(0),
m_selectAction(0),
m_selectMarqueeAction(0),
m_zoomAction(0),
m_colorPickerAction(0),
m_toQmlAction(0),
m_fromQmlAction(0),
m_defaultAnimSpeedAction(0),
m_halfAnimSpeedAction(0),
m_fourthAnimSpeedAction(0),
m_eighthAnimSpeedAction(0),
m_tenthAnimSpeedAction(0),
m_emitSignals(true),
m_isRunning(false),
m_animationSpeed(1.0f),
m_previousAnimationSpeed(0.0f),
m_activeTool(NoTool)
{
}
void QmlInspectorToolbar::setEnabled(bool value)
{
m_designmodeAction->setEnabled(value);
m_reloadAction->setEnabled(value);
m_playAction->setEnabled(value);
m_pauseAction->setEnabled(value);
m_selectAction->setEnabled(value);
m_selectMarqueeAction->setEnabled(value);
m_zoomAction->setEnabled(value);
m_colorPickerAction->setEnabled(value);
m_toQmlAction->setEnabled(value);
m_fromQmlAction->setEnabled(value);
}
void QmlInspectorToolbar::enable()
{
setEnabled(true);
m_emitSignals = false;
changeAnimationSpeed(1.0f);
activateDesignModeOnClick();
m_emitSignals = true;
}
void QmlInspectorToolbar::disable()
{
changeAnimationSpeed(1.0f);
activateSelectTool();
setEnabled(false);
}
void QmlInspectorToolbar::activateColorPicker()
{
m_emitSignals = false;
activateColorPickerOnClick();
m_emitSignals = true;
}
void QmlInspectorToolbar::activateSelectTool()
{
m_emitSignals = false;
activateSelectToolOnClick();
m_emitSignals = true;
}
void QmlInspectorToolbar::activateMarqueeSelectTool()
{
m_emitSignals = false;
activateMarqueeSelectToolOnClick();
m_emitSignals = true;
}
void QmlInspectorToolbar::activateZoomTool()
{
m_emitSignals = false;
activateZoomOnClick();
m_emitSignals = true;
}
void QmlInspectorToolbar::changeAnimationSpeed(qreal slowdownFactor)
{
m_emitSignals = false;
if (slowdownFactor == 0) {
activatePauseOnClick();
} else {
m_animationSpeed = slowdownFactor;
if (slowdownFactor == 1.0f) {
m_defaultAnimSpeedAction->setChecked(true);
} else if (slowdownFactor == 2.0f) {
m_halfAnimSpeedAction->setChecked(true);
} else if (slowdownFactor == 4.0f) {
m_fourthAnimSpeedAction->setChecked(true);
} else if (slowdownFactor == 8.0f) {
m_eighthAnimSpeedAction->setChecked(true);
} else if (slowdownFactor == 10.0f) {
m_tenthAnimSpeedAction->setChecked(true);
}
activatePlayOnClick();
}
m_emitSignals = true;
}
void QmlInspectorToolbar::setDesignModeBehavior(bool inDesignMode)
{
m_emitSignals = false;
m_designmodeAction->setChecked(inDesignMode);
activateDesignModeOnClick();
m_emitSignals = true;
}
void QmlInspectorToolbar::createActions(const Core::Context &context)
{
Core::ICore *core = Core::ICore::instance();
Core::ActionManager *am = core->actionManager();
ExtensionSystem::PluginManager *pluginManager = ExtensionSystem::PluginManager::instance();
Debugger::DebuggerUISwitcher *uiSwitcher = pluginManager->getObject<Debugger::DebuggerUISwitcher>();
m_designmodeAction = new QAction(QIcon(":/qml/images/designmode.png"), "Design Mode", this);
m_reloadAction = new QAction(QIcon(":/qml/images/reload.png"), "Reload", this);
m_playAction = new QAction(QIcon(":/qml/images/play-small.png"), tr("Play animations"), this);
m_pauseAction = new QAction(QIcon(":/qml/images/pause-small.png"), tr("Pause animations"), this);
m_selectAction = new QAction(QIcon(":/qml/images/select-small.png"), tr("Select"), this);
m_selectMarqueeAction = new QAction(QIcon(":/qml/images/select-marquee-small.png"), tr("Select (Marquee)"), this);
m_zoomAction = new QAction(QIcon(":/qml/images/zoom-small.png"), tr("Zoom"), this);
m_colorPickerAction = new QAction(QIcon(":/qml/images/color-picker-small.png"), tr("Color Picker"), this);
m_toQmlAction = new QAction(QIcon(":/qml/images/to-qml-small.png"), tr("Apply Changes to QML Viewer"), this);
m_fromQmlAction = new QAction(QIcon(":/qml/images/from-qml-small.png"), tr("Apply Changes to Document"), this);
m_designmodeAction->setCheckable(true);
m_designmodeAction->setChecked(false);
m_playAction->setCheckable(true);
m_playAction->setChecked(true);
m_pauseAction->setCheckable(true);
m_selectAction->setCheckable(true);
m_selectMarqueeAction->setCheckable(true);
m_zoomAction->setCheckable(true);
m_colorPickerAction->setCheckable(true);
am->registerAction(m_designmodeAction, QmlJSInspector::Constants::DESIGNMODE_ACTION, context);
am->registerAction(m_reloadAction, QmlJSInspector::Constants::RELOAD_ACTION, context);
am->registerAction(m_playAction, QmlJSInspector::Constants::PLAY_ACTION, context);
am->registerAction(m_pauseAction, QmlJSInspector::Constants::PAUSE_ACTION, context);
am->registerAction(m_selectAction, QmlJSInspector::Constants::SELECT_ACTION, context);
am->registerAction(m_selectMarqueeAction, QmlJSInspector::Constants::SELECT_MARQUEE_ACTION, context);
am->registerAction(m_zoomAction, QmlJSInspector::Constants::ZOOM_ACTION, context);
am->registerAction(m_colorPickerAction, QmlJSInspector::Constants::COLOR_PICKER_ACTION, context);
am->registerAction(m_toQmlAction, QmlJSInspector::Constants::TO_QML_ACTION, context);
am->registerAction(m_fromQmlAction, QmlJSInspector::Constants::FROM_QML_ACTION, context);
QWidget *configBar = new QWidget;
configBar->setProperty("topBorder", true);
QHBoxLayout *configBarLayout = new QHBoxLayout(configBar);
configBarLayout->setMargin(0);
configBarLayout->setSpacing(5);
QMenu *playSpeedMenu = new QMenu(configBar);
QActionGroup *playSpeedMenuActions = new QActionGroup(this);
playSpeedMenuActions->setExclusive(true);
m_defaultAnimSpeedAction = playSpeedMenu->addAction(tr("1x"), this, SLOT(changeToDefaultAnimSpeed()));
m_defaultAnimSpeedAction->setCheckable(true);
m_defaultAnimSpeedAction->setChecked(true);
playSpeedMenuActions->addAction(m_defaultAnimSpeedAction);
m_halfAnimSpeedAction = playSpeedMenu->addAction(tr("0.5x"), this, SLOT(changeToHalfAnimSpeed()));
m_halfAnimSpeedAction->setCheckable(true);
playSpeedMenuActions->addAction(m_halfAnimSpeedAction);
m_fourthAnimSpeedAction = playSpeedMenu->addAction(tr("0.25x"), this, SLOT(changeToFourthAnimSpeed()));
m_fourthAnimSpeedAction->setCheckable(true);
playSpeedMenuActions->addAction(m_fourthAnimSpeedAction);
m_eighthAnimSpeedAction = playSpeedMenu->addAction(tr("0.125x"), this, SLOT(changeToEighthAnimSpeed()));
m_eighthAnimSpeedAction->setCheckable(true);
playSpeedMenuActions->addAction(m_eighthAnimSpeedAction);
m_tenthAnimSpeedAction = playSpeedMenu->addAction(tr("0.1x"), this, SLOT(changeToTenthAnimSpeed()));
m_tenthAnimSpeedAction->setCheckable(true);
playSpeedMenuActions->addAction(m_tenthAnimSpeedAction);
configBarLayout->addWidget(createToolButton(am->command(ProjectExplorer::Constants::DEBUG)->action()));
configBarLayout->addWidget(createToolButton(am->command(ProjectExplorer::Constants::STOP)->action()));
configBarLayout->addWidget(createToolButton(am->command(QmlJSInspector::Constants::DESIGNMODE_ACTION)->action()));
configBarLayout->addWidget(createToolButton(am->command(QmlJSInspector::Constants::RELOAD_ACTION)->action()));
QToolButton *playButton = createToolButton(am->command(QmlJSInspector::Constants::PLAY_ACTION)->action());
playButton->setMenu(playSpeedMenu);
configBarLayout->addWidget(playButton);
configBarLayout->addWidget(createToolButton(am->command(QmlJSInspector::Constants::PAUSE_ACTION)->action()));
configBarLayout->addWidget(createToolButton(am->command(QmlJSInspector::Constants::SELECT_ACTION)->action()));
configBarLayout->addWidget(createToolButton(am->command(QmlJSInspector::Constants::SELECT_MARQUEE_ACTION)->action()));
configBarLayout->addWidget(createToolButton(am->command(QmlJSInspector::Constants::ZOOM_ACTION)->action()));
configBarLayout->addWidget(createToolButton(am->command(QmlJSInspector::Constants::COLOR_PICKER_ACTION)->action()));
configBarLayout->addWidget(createToolButton(am->command(QmlJSInspector::Constants::TO_QML_ACTION)->action()));
configBarLayout->addWidget(createToolButton(am->command(QmlJSInspector::Constants::FROM_QML_ACTION)->action()));
configBarLayout->addStretch();
uiSwitcher->setToolbar(QmlJSInspector::Constants::LANG_QML, configBar);
setEnabled(false);
connect(m_designmodeAction, SIGNAL(triggered()), SLOT(activateDesignModeOnClick()));
connect(m_reloadAction, SIGNAL(triggered()), SIGNAL(reloadSelected()));
connect(m_colorPickerAction, SIGNAL(triggered()), SLOT(activateColorPickerOnClick()));
connect(m_playAction, SIGNAL(triggered()), SLOT(activatePlayOnClick()));
connect(m_pauseAction, SIGNAL(triggered()), SLOT(activatePauseOnClick()));
connect(m_zoomAction, SIGNAL(triggered()), SLOT(activateZoomOnClick()));
connect(m_colorPickerAction, SIGNAL(triggered()), SLOT(activateColorPickerOnClick()));
connect(m_selectAction, SIGNAL(triggered()), SLOT(activateSelectToolOnClick()));
connect(m_selectMarqueeAction, SIGNAL(triggered()), SLOT(activateMarqueeSelectToolOnClick()));
connect(m_toQmlAction, SIGNAL(triggered()), SLOT(activateToQml()));
connect(m_fromQmlAction, SIGNAL(triggered()), SLOT(activateFromQml()));
}
void QmlInspectorToolbar::changeToDefaultAnimSpeed()
{
m_animationSpeed = 1.0f;
activatePlayOnClick();
}
void QmlInspectorToolbar::changeToHalfAnimSpeed()
{
m_animationSpeed = 2.0f;
activatePlayOnClick();
}
void QmlInspectorToolbar::changeToFourthAnimSpeed()
{
m_animationSpeed = 4.0f;
activatePlayOnClick();
}
void QmlInspectorToolbar::changeToEighthAnimSpeed()
{
m_animationSpeed = 8.0f;
activatePlayOnClick();
}
void QmlInspectorToolbar::changeToTenthAnimSpeed()
{
m_animationSpeed = 10.0f;
activatePlayOnClick();
}
void QmlInspectorToolbar::activateDesignModeOnClick()
{
bool checked = m_designmodeAction->isChecked();
m_reloadAction->setEnabled(checked);
m_playAction->setEnabled(checked);
m_pauseAction->setEnabled(checked);
m_selectAction->setEnabled(checked);
m_selectMarqueeAction->setEnabled(checked);
m_zoomAction->setEnabled(checked);
m_colorPickerAction->setEnabled(checked);
m_toQmlAction->setEnabled(checked);
m_fromQmlAction->setEnabled(checked);
if (m_emitSignals)
emit designModeSelected(checked);
}
void QmlInspectorToolbar::activatePlayOnClick()
{
m_pauseAction->setChecked(false);
if (!m_isRunning || m_animationSpeed != m_previousAnimationSpeed) {
m_playAction->setChecked(true);
m_isRunning = true;
m_previousAnimationSpeed = m_animationSpeed;
if (m_emitSignals)
emit animationSpeedChanged(m_animationSpeed);
}
}
void QmlInspectorToolbar::activatePauseOnClick()
{
m_playAction->setChecked(false);
if (m_isRunning) {
m_isRunning = false;
m_pauseAction->setChecked(true);
if (m_emitSignals)
emit animationSpeedChanged(0.0f);
}
}
void QmlInspectorToolbar::activateColorPickerOnClick()
{
m_zoomAction->setChecked(false);
m_selectAction->setChecked(false);
m_selectMarqueeAction->setChecked(false);
m_colorPickerAction->setChecked(true);
if (m_activeTool != ColorPickerMode) {
m_activeTool = ColorPickerMode;
if (m_emitSignals)
emit colorPickerSelected();
}
}
void QmlInspectorToolbar::activateSelectToolOnClick()
{
m_zoomAction->setChecked(false);
m_selectMarqueeAction->setChecked(false);
m_colorPickerAction->setChecked(false);
m_selectAction->setChecked(true);
if (m_activeTool != SelectionToolMode) {
m_activeTool = SelectionToolMode;
if (m_emitSignals)
emit selectToolSelected();
}
}
void QmlInspectorToolbar::activateMarqueeSelectToolOnClick()
{
m_zoomAction->setChecked(false);
m_selectAction->setChecked(false);
m_colorPickerAction->setChecked(false);
m_selectMarqueeAction->setChecked(true);
if (m_activeTool != MarqueeSelectionToolMode) {
m_activeTool = MarqueeSelectionToolMode;
if (m_emitSignals)
emit marqueeSelectToolSelected();
}
}
void QmlInspectorToolbar::activateZoomOnClick()
{
m_selectAction->setChecked(false);
m_selectMarqueeAction->setChecked(false);
m_colorPickerAction->setChecked(false);
m_zoomAction->setChecked(true);
if (m_activeTool != ZoomMode) {
m_activeTool = ZoomMode;
if (m_emitSignals)
emit zoomToolSelected();
}
}
void QmlInspectorToolbar::activateFromQml()
{
if (m_emitSignals)
emit applyChangesFromQmlFileSelected();
}
void QmlInspectorToolbar::activateToQml()
{
if (m_emitSignals)
emit applyChangesToQmlFileSelected();
}
} // namespace Internal
} // namespace QmlJSInspector
<commit_msg>reset design mode when disconnected<commit_after>#include "qmlinspectortoolbar.h"
#include "qmljsinspectorconstants.h"
#include <extensionsystem/pluginmanager.h>
#include <coreplugin/icore.h>
#include <debugger/debuggeruiswitcher.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/command.h>
#include <QHBoxLayout>
#include <QAction>
#include <QToolButton>
#include <QMenu>
#include <QActionGroup>
namespace QmlJSInspector {
namespace Internal {
static QToolButton *createToolButton(QAction *action)
{
QToolButton *button = new QToolButton;
button->setDefaultAction(action);
return button;
}
QmlInspectorToolbar::QmlInspectorToolbar(QObject *parent) :
QObject(parent),
m_designmodeAction(0),
m_reloadAction(0),
m_playAction(0),
m_pauseAction(0),
m_selectAction(0),
m_selectMarqueeAction(0),
m_zoomAction(0),
m_colorPickerAction(0),
m_toQmlAction(0),
m_fromQmlAction(0),
m_defaultAnimSpeedAction(0),
m_halfAnimSpeedAction(0),
m_fourthAnimSpeedAction(0),
m_eighthAnimSpeedAction(0),
m_tenthAnimSpeedAction(0),
m_emitSignals(true),
m_isRunning(false),
m_animationSpeed(1.0f),
m_previousAnimationSpeed(0.0f),
m_activeTool(NoTool)
{
}
void QmlInspectorToolbar::setEnabled(bool value)
{
m_designmodeAction->setEnabled(value);
m_reloadAction->setEnabled(value);
m_playAction->setEnabled(value);
m_pauseAction->setEnabled(value);
m_selectAction->setEnabled(value);
m_selectMarqueeAction->setEnabled(value);
m_zoomAction->setEnabled(value);
m_colorPickerAction->setEnabled(value);
m_toQmlAction->setEnabled(value);
m_fromQmlAction->setEnabled(value);
}
void QmlInspectorToolbar::enable()
{
setEnabled(true);
m_emitSignals = false;
m_designmodeAction->setChecked(false);
changeAnimationSpeed(1.0f);
activateDesignModeOnClick();
m_emitSignals = true;
}
void QmlInspectorToolbar::disable()
{
changeAnimationSpeed(1.0f);
activateSelectTool();
setEnabled(false);
}
void QmlInspectorToolbar::activateColorPicker()
{
m_emitSignals = false;
activateColorPickerOnClick();
m_emitSignals = true;
}
void QmlInspectorToolbar::activateSelectTool()
{
m_emitSignals = false;
activateSelectToolOnClick();
m_emitSignals = true;
}
void QmlInspectorToolbar::activateMarqueeSelectTool()
{
m_emitSignals = false;
activateMarqueeSelectToolOnClick();
m_emitSignals = true;
}
void QmlInspectorToolbar::activateZoomTool()
{
m_emitSignals = false;
activateZoomOnClick();
m_emitSignals = true;
}
void QmlInspectorToolbar::changeAnimationSpeed(qreal slowdownFactor)
{
m_emitSignals = false;
if (slowdownFactor == 0) {
activatePauseOnClick();
} else {
m_animationSpeed = slowdownFactor;
if (slowdownFactor == 1.0f) {
m_defaultAnimSpeedAction->setChecked(true);
} else if (slowdownFactor == 2.0f) {
m_halfAnimSpeedAction->setChecked(true);
} else if (slowdownFactor == 4.0f) {
m_fourthAnimSpeedAction->setChecked(true);
} else if (slowdownFactor == 8.0f) {
m_eighthAnimSpeedAction->setChecked(true);
} else if (slowdownFactor == 10.0f) {
m_tenthAnimSpeedAction->setChecked(true);
}
activatePlayOnClick();
}
m_emitSignals = true;
}
void QmlInspectorToolbar::setDesignModeBehavior(bool inDesignMode)
{
m_emitSignals = false;
m_designmodeAction->setChecked(inDesignMode);
activateDesignModeOnClick();
m_emitSignals = true;
}
void QmlInspectorToolbar::createActions(const Core::Context &context)
{
Core::ICore *core = Core::ICore::instance();
Core::ActionManager *am = core->actionManager();
ExtensionSystem::PluginManager *pluginManager = ExtensionSystem::PluginManager::instance();
Debugger::DebuggerUISwitcher *uiSwitcher = pluginManager->getObject<Debugger::DebuggerUISwitcher>();
m_designmodeAction = new QAction(QIcon(":/qml/images/designmode.png"), "Design Mode", this);
m_reloadAction = new QAction(QIcon(":/qml/images/reload.png"), "Reload", this);
m_playAction = new QAction(QIcon(":/qml/images/play-small.png"), tr("Play animations"), this);
m_pauseAction = new QAction(QIcon(":/qml/images/pause-small.png"), tr("Pause animations"), this);
m_selectAction = new QAction(QIcon(":/qml/images/select-small.png"), tr("Select"), this);
m_selectMarqueeAction = new QAction(QIcon(":/qml/images/select-marquee-small.png"), tr("Select (Marquee)"), this);
m_zoomAction = new QAction(QIcon(":/qml/images/zoom-small.png"), tr("Zoom"), this);
m_colorPickerAction = new QAction(QIcon(":/qml/images/color-picker-small.png"), tr("Color Picker"), this);
m_toQmlAction = new QAction(QIcon(":/qml/images/to-qml-small.png"), tr("Apply Changes to QML Viewer"), this);
m_fromQmlAction = new QAction(QIcon(":/qml/images/from-qml-small.png"), tr("Apply Changes to Document"), this);
m_designmodeAction->setCheckable(true);
m_designmodeAction->setChecked(false);
m_playAction->setCheckable(true);
m_playAction->setChecked(true);
m_pauseAction->setCheckable(true);
m_selectAction->setCheckable(true);
m_selectMarqueeAction->setCheckable(true);
m_zoomAction->setCheckable(true);
m_colorPickerAction->setCheckable(true);
am->registerAction(m_designmodeAction, QmlJSInspector::Constants::DESIGNMODE_ACTION, context);
am->registerAction(m_reloadAction, QmlJSInspector::Constants::RELOAD_ACTION, context);
am->registerAction(m_playAction, QmlJSInspector::Constants::PLAY_ACTION, context);
am->registerAction(m_pauseAction, QmlJSInspector::Constants::PAUSE_ACTION, context);
am->registerAction(m_selectAction, QmlJSInspector::Constants::SELECT_ACTION, context);
am->registerAction(m_selectMarqueeAction, QmlJSInspector::Constants::SELECT_MARQUEE_ACTION, context);
am->registerAction(m_zoomAction, QmlJSInspector::Constants::ZOOM_ACTION, context);
am->registerAction(m_colorPickerAction, QmlJSInspector::Constants::COLOR_PICKER_ACTION, context);
am->registerAction(m_toQmlAction, QmlJSInspector::Constants::TO_QML_ACTION, context);
am->registerAction(m_fromQmlAction, QmlJSInspector::Constants::FROM_QML_ACTION, context);
QWidget *configBar = new QWidget;
configBar->setProperty("topBorder", true);
QHBoxLayout *configBarLayout = new QHBoxLayout(configBar);
configBarLayout->setMargin(0);
configBarLayout->setSpacing(5);
QMenu *playSpeedMenu = new QMenu(configBar);
QActionGroup *playSpeedMenuActions = new QActionGroup(this);
playSpeedMenuActions->setExclusive(true);
m_defaultAnimSpeedAction = playSpeedMenu->addAction(tr("1x"), this, SLOT(changeToDefaultAnimSpeed()));
m_defaultAnimSpeedAction->setCheckable(true);
m_defaultAnimSpeedAction->setChecked(true);
playSpeedMenuActions->addAction(m_defaultAnimSpeedAction);
m_halfAnimSpeedAction = playSpeedMenu->addAction(tr("0.5x"), this, SLOT(changeToHalfAnimSpeed()));
m_halfAnimSpeedAction->setCheckable(true);
playSpeedMenuActions->addAction(m_halfAnimSpeedAction);
m_fourthAnimSpeedAction = playSpeedMenu->addAction(tr("0.25x"), this, SLOT(changeToFourthAnimSpeed()));
m_fourthAnimSpeedAction->setCheckable(true);
playSpeedMenuActions->addAction(m_fourthAnimSpeedAction);
m_eighthAnimSpeedAction = playSpeedMenu->addAction(tr("0.125x"), this, SLOT(changeToEighthAnimSpeed()));
m_eighthAnimSpeedAction->setCheckable(true);
playSpeedMenuActions->addAction(m_eighthAnimSpeedAction);
m_tenthAnimSpeedAction = playSpeedMenu->addAction(tr("0.1x"), this, SLOT(changeToTenthAnimSpeed()));
m_tenthAnimSpeedAction->setCheckable(true);
playSpeedMenuActions->addAction(m_tenthAnimSpeedAction);
configBarLayout->addWidget(createToolButton(am->command(ProjectExplorer::Constants::DEBUG)->action()));
configBarLayout->addWidget(createToolButton(am->command(ProjectExplorer::Constants::STOP)->action()));
configBarLayout->addWidget(createToolButton(am->command(QmlJSInspector::Constants::DESIGNMODE_ACTION)->action()));
configBarLayout->addWidget(createToolButton(am->command(QmlJSInspector::Constants::RELOAD_ACTION)->action()));
QToolButton *playButton = createToolButton(am->command(QmlJSInspector::Constants::PLAY_ACTION)->action());
playButton->setMenu(playSpeedMenu);
configBarLayout->addWidget(playButton);
configBarLayout->addWidget(createToolButton(am->command(QmlJSInspector::Constants::PAUSE_ACTION)->action()));
configBarLayout->addWidget(createToolButton(am->command(QmlJSInspector::Constants::SELECT_ACTION)->action()));
configBarLayout->addWidget(createToolButton(am->command(QmlJSInspector::Constants::SELECT_MARQUEE_ACTION)->action()));
configBarLayout->addWidget(createToolButton(am->command(QmlJSInspector::Constants::ZOOM_ACTION)->action()));
configBarLayout->addWidget(createToolButton(am->command(QmlJSInspector::Constants::COLOR_PICKER_ACTION)->action()));
configBarLayout->addWidget(createToolButton(am->command(QmlJSInspector::Constants::TO_QML_ACTION)->action()));
configBarLayout->addWidget(createToolButton(am->command(QmlJSInspector::Constants::FROM_QML_ACTION)->action()));
configBarLayout->addStretch();
uiSwitcher->setToolbar(QmlJSInspector::Constants::LANG_QML, configBar);
setEnabled(false);
connect(m_designmodeAction, SIGNAL(triggered()), SLOT(activateDesignModeOnClick()));
connect(m_reloadAction, SIGNAL(triggered()), SIGNAL(reloadSelected()));
connect(m_colorPickerAction, SIGNAL(triggered()), SLOT(activateColorPickerOnClick()));
connect(m_playAction, SIGNAL(triggered()), SLOT(activatePlayOnClick()));
connect(m_pauseAction, SIGNAL(triggered()), SLOT(activatePauseOnClick()));
connect(m_zoomAction, SIGNAL(triggered()), SLOT(activateZoomOnClick()));
connect(m_colorPickerAction, SIGNAL(triggered()), SLOT(activateColorPickerOnClick()));
connect(m_selectAction, SIGNAL(triggered()), SLOT(activateSelectToolOnClick()));
connect(m_selectMarqueeAction, SIGNAL(triggered()), SLOT(activateMarqueeSelectToolOnClick()));
connect(m_toQmlAction, SIGNAL(triggered()), SLOT(activateToQml()));
connect(m_fromQmlAction, SIGNAL(triggered()), SLOT(activateFromQml()));
}
void QmlInspectorToolbar::changeToDefaultAnimSpeed()
{
m_animationSpeed = 1.0f;
activatePlayOnClick();
}
void QmlInspectorToolbar::changeToHalfAnimSpeed()
{
m_animationSpeed = 2.0f;
activatePlayOnClick();
}
void QmlInspectorToolbar::changeToFourthAnimSpeed()
{
m_animationSpeed = 4.0f;
activatePlayOnClick();
}
void QmlInspectorToolbar::changeToEighthAnimSpeed()
{
m_animationSpeed = 8.0f;
activatePlayOnClick();
}
void QmlInspectorToolbar::changeToTenthAnimSpeed()
{
m_animationSpeed = 10.0f;
activatePlayOnClick();
}
void QmlInspectorToolbar::activateDesignModeOnClick()
{
bool checked = m_designmodeAction->isChecked();
m_reloadAction->setEnabled(checked);
m_playAction->setEnabled(checked);
m_pauseAction->setEnabled(checked);
m_selectAction->setEnabled(checked);
m_selectMarqueeAction->setEnabled(checked);
m_zoomAction->setEnabled(checked);
m_colorPickerAction->setEnabled(checked);
m_toQmlAction->setEnabled(checked);
m_fromQmlAction->setEnabled(checked);
if (m_emitSignals)
emit designModeSelected(checked);
}
void QmlInspectorToolbar::activatePlayOnClick()
{
m_pauseAction->setChecked(false);
if (!m_isRunning || m_animationSpeed != m_previousAnimationSpeed) {
m_playAction->setChecked(true);
m_isRunning = true;
m_previousAnimationSpeed = m_animationSpeed;
if (m_emitSignals)
emit animationSpeedChanged(m_animationSpeed);
}
}
void QmlInspectorToolbar::activatePauseOnClick()
{
m_playAction->setChecked(false);
if (m_isRunning) {
m_isRunning = false;
m_pauseAction->setChecked(true);
if (m_emitSignals)
emit animationSpeedChanged(0.0f);
}
}
void QmlInspectorToolbar::activateColorPickerOnClick()
{
m_zoomAction->setChecked(false);
m_selectAction->setChecked(false);
m_selectMarqueeAction->setChecked(false);
m_colorPickerAction->setChecked(true);
if (m_activeTool != ColorPickerMode) {
m_activeTool = ColorPickerMode;
if (m_emitSignals)
emit colorPickerSelected();
}
}
void QmlInspectorToolbar::activateSelectToolOnClick()
{
m_zoomAction->setChecked(false);
m_selectMarqueeAction->setChecked(false);
m_colorPickerAction->setChecked(false);
m_selectAction->setChecked(true);
if (m_activeTool != SelectionToolMode) {
m_activeTool = SelectionToolMode;
if (m_emitSignals)
emit selectToolSelected();
}
}
void QmlInspectorToolbar::activateMarqueeSelectToolOnClick()
{
m_zoomAction->setChecked(false);
m_selectAction->setChecked(false);
m_colorPickerAction->setChecked(false);
m_selectMarqueeAction->setChecked(true);
if (m_activeTool != MarqueeSelectionToolMode) {
m_activeTool = MarqueeSelectionToolMode;
if (m_emitSignals)
emit marqueeSelectToolSelected();
}
}
void QmlInspectorToolbar::activateZoomOnClick()
{
m_selectAction->setChecked(false);
m_selectMarqueeAction->setChecked(false);
m_colorPickerAction->setChecked(false);
m_zoomAction->setChecked(true);
if (m_activeTool != ZoomMode) {
m_activeTool = ZoomMode;
if (m_emitSignals)
emit zoomToolSelected();
}
}
void QmlInspectorToolbar::activateFromQml()
{
if (m_emitSignals)
emit applyChangesFromQmlFileSelected();
}
void QmlInspectorToolbar::activateToQml()
{
if (m_emitSignals)
emit applyChangesToQmlFileSelected();
}
} // namespace Internal
} // namespace QmlJSInspector
<|endoftext|> |
<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2008 Torsten Rahn <[email protected]>
// Copyright 2010 Cezar Mocan <[email protected]>
//
#include "CrosshairsPlugin.h"
#include "ui_CrosshairsConfigWidget.h"
#include "AbstractProjection.h"
#include "GeoPainter.h"
#include "MarbleDebug.h"
#include "MarbleDirs.h"
#include "ViewportParams.h"
#include <QtCore/QRect>
#include <QtGui/QColor>
#include <QtGui/QPixmap>
#include <QtGui/QPushButton>
#include <QtSvg/QSvgRenderer>
namespace Marble
{
CrosshairsPlugin::CrosshairsPlugin ( )
: m_isInitialized( false ),
m_aboutDialog( 0 ),
m_svgobj( 0 ),
m_configDialog( 0 ),
m_uiConfigWidget( 0 )
{
// nothing to do
}
CrosshairsPlugin::~CrosshairsPlugin ()
{
delete m_svgobj;
}
QStringList CrosshairsPlugin::backendTypes() const
{
return QStringList( "crosshairs" );
}
QString CrosshairsPlugin::renderPolicy() const
{
return QString( "ALWAYS" );
}
QStringList CrosshairsPlugin::renderPosition() const
{
return QStringList( "ALWAYS_ON_TOP" ); // although this is not a float item we choose the position of one
}
QString CrosshairsPlugin::name() const
{
return tr( "Crosshairs" );
}
QString CrosshairsPlugin::guiString() const
{
return tr( "Cross&hairs" );
}
QString CrosshairsPlugin::nameId() const
{
return QString( "crosshairs" );
}
QString CrosshairsPlugin::description() const
{
return tr( "A plugin that shows crosshairs." );
}
QIcon CrosshairsPlugin::icon () const
{
return QIcon( ":/icons/crosshairs.png" );
}
QDialog* CrosshairsPlugin::aboutDialog()
{
if ( !m_aboutDialog ) {
// Initializing about dialog
m_aboutDialog = new PluginAboutDialog();
m_aboutDialog->setName( "Crosshairs Plugin" );
m_aboutDialog->setVersion( "0.1" );
// FIXME: Can we store this string for all of Marble
m_aboutDialog->setAboutText( tr( "<br />(c) 2009, 2010 The Marble Project<br /><br /><a href=\"http://edu.kde.org/marble\">http://edu.kde.org/marble</a>" ) );
QList<Author> authors;
Author tackat, cezar;
cezar.name = QString::fromUtf8( "Cezar Mocan" );
cezar.task = tr( "Developer" );
cezar.email = "[email protected]";
authors.append( cezar );
tackat.name = "Torsten Rahn";
tackat.task = tr( "Developer" );
tackat.email = "[email protected]";
authors.append( tackat );
m_aboutDialog->setAuthors( authors );
}
return m_aboutDialog;
}
void CrosshairsPlugin::initialize ()
{
readSettings();
m_isInitialized = true;
}
bool CrosshairsPlugin::isInitialized () const
{
return m_isInitialized;
}
QDialog *CrosshairsPlugin::configDialog()
{
if ( !m_configDialog ) {
m_configDialog = new QDialog();
m_uiConfigWidget = new Ui::CrosshairsConfigWidget;
m_uiConfigWidget->setupUi( m_configDialog );
readSettings();
connect( m_uiConfigWidget->m_buttonBox, SIGNAL( accepted() ),
SLOT( writeSettings() ) );
connect( m_uiConfigWidget->m_buttonBox, SIGNAL( rejected() ),
SLOT( readSettings() ) );
QPushButton *applyButton = m_uiConfigWidget->m_buttonBox->button( QDialogButtonBox::Apply );
connect( applyButton, SIGNAL( clicked() ),
this, SLOT( writeSettings() ) );
}
return m_configDialog;
}
QHash<QString,QVariant> CrosshairsPlugin::settings() const
{
return m_settings;
}
void CrosshairsPlugin::setSettings( QHash<QString,QVariant> settings )
{
m_settings = settings;
readSettings();
}
void CrosshairsPlugin::readSettings()
{
int index = m_settings.value( "theme", 0 ).toInt();
if ( m_uiConfigWidget && index >= 0 && index < m_uiConfigWidget->m_themeList->count() ) {
m_uiConfigWidget->m_themeList->setCurrentRow( index );
}
QString theme = ":/crosshairs-pointed.svg";
switch( index ) {
case 1:
theme = ":/crosshairs-gun1.svg";
break;
case 2:
theme = ":/crosshairs-gun2.svg";
break;
case 3:
theme = ":/crosshairs-circled.svg";
break;
case 4:
theme = ":/crosshairs-german.svg";
break;
}
delete m_svgobj;
CrosshairsPlugin * me = const_cast<CrosshairsPlugin*>( this );
m_svgobj = new QSvgRenderer( theme, me );
m_crosshairs = QPixmap();
}
void CrosshairsPlugin::writeSettings()
{
if ( m_uiConfigWidget ) {
m_settings["theme"] = m_uiConfigWidget->m_themeList->currentRow();
}
readSettings();
emit settingsChanged( nameId() );
}
bool CrosshairsPlugin::render( GeoPainter *painter, ViewportParams *viewport,
const QString& renderPos,
GeoSceneLayer * layer )
{
Q_UNUSED( layer )
if ( renderPos == "ALWAYS_ON_TOP" ) {
const int width = 21;
const int height = 21;
if ( m_crosshairs.isNull() ) {
painter->setRenderHint( QPainter::Antialiasing, true );
m_crosshairs = QPixmap( QSize( width, height ) );
m_crosshairs.fill( Qt::transparent );
QPainter mapPainter( &m_crosshairs );
mapPainter.setViewport( m_crosshairs.rect() );
m_svgobj->render( &mapPainter );
mapPainter.setViewport( QRect( QPoint( 0, 0 ), viewport->size() ) );
}
qreal centerx = 0.0;
qreal centery = 0.0;
viewport->currentProjection()->screenCoordinates(viewport->focusPoint(), viewport, centerx, centery);
painter->drawPixmap( QPoint ( centerx - width / 2, centery - height / 2 ), m_crosshairs );
}
return true;
}
}
Q_EXPORT_PLUGIN2( CrosshairsPlugin, Marble::CrosshairsPlugin )
#include "CrosshairsPlugin.moc"
<commit_msg>Avoid crosshairs jittering during panning.<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2008 Torsten Rahn <[email protected]>
// Copyright 2010 Cezar Mocan <[email protected]>
//
#include "CrosshairsPlugin.h"
#include "ui_CrosshairsConfigWidget.h"
#include "AbstractProjection.h"
#include "GeoPainter.h"
#include "MarbleDebug.h"
#include "MarbleDirs.h"
#include "ViewportParams.h"
#include <QtCore/QRect>
#include <QtGui/QColor>
#include <QtGui/QPixmap>
#include <QtGui/QPushButton>
#include <QtSvg/QSvgRenderer>
namespace Marble
{
CrosshairsPlugin::CrosshairsPlugin ( )
: m_isInitialized( false ),
m_aboutDialog( 0 ),
m_svgobj( 0 ),
m_configDialog( 0 ),
m_uiConfigWidget( 0 )
{
// nothing to do
}
CrosshairsPlugin::~CrosshairsPlugin ()
{
delete m_svgobj;
}
QStringList CrosshairsPlugin::backendTypes() const
{
return QStringList( "crosshairs" );
}
QString CrosshairsPlugin::renderPolicy() const
{
return QString( "ALWAYS" );
}
QStringList CrosshairsPlugin::renderPosition() const
{
return QStringList( "ALWAYS_ON_TOP" ); // although this is not a float item we choose the position of one
}
QString CrosshairsPlugin::name() const
{
return tr( "Crosshairs" );
}
QString CrosshairsPlugin::guiString() const
{
return tr( "Cross&hairs" );
}
QString CrosshairsPlugin::nameId() const
{
return QString( "crosshairs" );
}
QString CrosshairsPlugin::description() const
{
return tr( "A plugin that shows crosshairs." );
}
QIcon CrosshairsPlugin::icon () const
{
return QIcon( ":/icons/crosshairs.png" );
}
QDialog* CrosshairsPlugin::aboutDialog()
{
if ( !m_aboutDialog ) {
// Initializing about dialog
m_aboutDialog = new PluginAboutDialog();
m_aboutDialog->setName( "Crosshairs Plugin" );
m_aboutDialog->setVersion( "0.1" );
// FIXME: Can we store this string for all of Marble
m_aboutDialog->setAboutText( tr( "<br />(c) 2009, 2010 The Marble Project<br /><br /><a href=\"http://edu.kde.org/marble\">http://edu.kde.org/marble</a>" ) );
QList<Author> authors;
Author tackat, cezar;
cezar.name = QString::fromUtf8( "Cezar Mocan" );
cezar.task = tr( "Developer" );
cezar.email = "[email protected]";
authors.append( cezar );
tackat.name = "Torsten Rahn";
tackat.task = tr( "Developer" );
tackat.email = "[email protected]";
authors.append( tackat );
m_aboutDialog->setAuthors( authors );
}
return m_aboutDialog;
}
void CrosshairsPlugin::initialize ()
{
readSettings();
m_isInitialized = true;
}
bool CrosshairsPlugin::isInitialized () const
{
return m_isInitialized;
}
QDialog *CrosshairsPlugin::configDialog()
{
if ( !m_configDialog ) {
m_configDialog = new QDialog();
m_uiConfigWidget = new Ui::CrosshairsConfigWidget;
m_uiConfigWidget->setupUi( m_configDialog );
readSettings();
connect( m_uiConfigWidget->m_buttonBox, SIGNAL( accepted() ),
SLOT( writeSettings() ) );
connect( m_uiConfigWidget->m_buttonBox, SIGNAL( rejected() ),
SLOT( readSettings() ) );
QPushButton *applyButton = m_uiConfigWidget->m_buttonBox->button( QDialogButtonBox::Apply );
connect( applyButton, SIGNAL( clicked() ),
this, SLOT( writeSettings() ) );
}
return m_configDialog;
}
QHash<QString,QVariant> CrosshairsPlugin::settings() const
{
return m_settings;
}
void CrosshairsPlugin::setSettings( QHash<QString,QVariant> settings )
{
m_settings = settings;
readSettings();
}
void CrosshairsPlugin::readSettings()
{
int index = m_settings.value( "theme", 0 ).toInt();
if ( m_uiConfigWidget && index >= 0 && index < m_uiConfigWidget->m_themeList->count() ) {
m_uiConfigWidget->m_themeList->setCurrentRow( index );
}
QString theme = ":/crosshairs-pointed.svg";
switch( index ) {
case 1:
theme = ":/crosshairs-gun1.svg";
break;
case 2:
theme = ":/crosshairs-gun2.svg";
break;
case 3:
theme = ":/crosshairs-circled.svg";
break;
case 4:
theme = ":/crosshairs-german.svg";
break;
}
delete m_svgobj;
CrosshairsPlugin * me = const_cast<CrosshairsPlugin*>( this );
m_svgobj = new QSvgRenderer( theme, me );
m_crosshairs = QPixmap();
}
void CrosshairsPlugin::writeSettings()
{
if ( m_uiConfigWidget ) {
m_settings["theme"] = m_uiConfigWidget->m_themeList->currentRow();
}
readSettings();
emit settingsChanged( nameId() );
}
bool CrosshairsPlugin::render( GeoPainter *painter, ViewportParams *viewport,
const QString& renderPos,
GeoSceneLayer * layer )
{
Q_UNUSED( layer )
if ( renderPos == "ALWAYS_ON_TOP" ) {
const int width = 21;
const int height = 21;
if ( m_crosshairs.isNull() ) {
painter->setRenderHint( QPainter::Antialiasing, true );
m_crosshairs = QPixmap( QSize( width, height ) );
m_crosshairs.fill( Qt::transparent );
QPainter mapPainter( &m_crosshairs );
mapPainter.setViewport( m_crosshairs.rect() );
m_svgobj->render( &mapPainter );
mapPainter.setViewport( QRect( QPoint( 0, 0 ), viewport->size() ) );
}
GeoDataCoordinates const focusPoint = viewport->focusPoint();
GeoDataCoordinates const centerPoint = GeoDataCoordinates( viewport->centerLongitude(), viewport->centerLatitude() );
if ( focusPoint == centerPoint ) {
// Focus point is in the middle of the screen. Special casing this avoids jittering.
int centerX = viewport->size().width() / 2;
int centerY = viewport->size().height() / 2;
painter->drawPixmap( QPoint ( centerX - width / 2, centerY - height / 2 ), m_crosshairs );
} else {
qreal centerX = 0.0;
qreal centerY = 0.0;
viewport->currentProjection()->screenCoordinates( focusPoint, viewport, centerX, centerY );
painter->drawPixmap( QPoint ( centerX - width / 2, centerY - height / 2 ), m_crosshairs );
}
}
return true;
}
}
Q_EXPORT_PLUGIN2( CrosshairsPlugin, Marble::CrosshairsPlugin )
#include "CrosshairsPlugin.moc"
<|endoftext|> |
<commit_before><commit_msg>fixed crash when undoing removal of a point light<commit_after><|endoftext|> |
<commit_before>/*******************************************************************************
Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you under
the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
*******************************************************************************/
//==============================================================================
// SED-ML file class
//==============================================================================
#include "cellmlfile.h"
#include "corecliutils.h"
#include "sedmlfile.h"
//==============================================================================
#include <QRegularExpression>
#include <QTemporaryFile>
//==============================================================================
#include "sedmlapidisablewarnings.h"
#include "sedml/SedDocument.h"
#include "sedml/SedReader.h"
#include "sedml/SedWriter.h"
#include "sedmlapienablewarnings.h"
//==============================================================================
namespace OpenCOR {
namespace SEDMLSupport {
//==============================================================================
SedmlFile::SedmlFile(const QString &pFileName, const bool &pNew) :
StandardSupport::StandardFile(pFileName),
mSedmlDocument(0),
mCellmlFile(0),
mNew(pNew)
{
// Reset ourselves
reset();
}
//==============================================================================
SedmlFile::~SedmlFile()
{
// Reset ourselves
reset();
}
//==============================================================================
void SedmlFile::reset()
{
// Reset all of our properties
delete mSedmlDocument;
delete mCellmlFile;
mSedmlDocument = 0;
mCellmlFile = 0;
mLoadingNeeded = true;
}
//==============================================================================
libsedml::SedDocument * SedmlFile::sedmlDocument()
{
// Return the SED-ML document associated with our SED-ML file, after loading
// ourselves if necessary
load();
return mSedmlDocument;
}
//==============================================================================
bool SedmlFile::load()
{
// Check whether the file is already loaded and without any issues
if (!mLoadingNeeded)
return !mSedmlDocument->getNumErrors(libsedml::LIBSEDML_SEV_ERROR);
mLoadingNeeded = false;
// Create a new SED-ML document, if needed, or try to load the file
if (mNew) {
mSedmlDocument = new libsedml::SedDocument();
} else {
QByteArray fileNameByteArray = mFileName.toUtf8();
mSedmlDocument = libsedml::readSedML(fileNameByteArray.constData());
}
bool res = !mSedmlDocument->getNumErrors(libsedml::LIBSEDML_SEV_ERROR);
// Update ourselves, if possible
if (res)
update();
return res;
}
//==============================================================================
bool SedmlFile::save(const QString &pNewFileName)
{
// Make sure that we are properly loaded and have no issue
if (mLoadingNeeded || mSedmlDocument->getNumErrors(libsedml::LIBSEDML_SEV_ERROR))
return false;
// Write ourselves after having reformatted ourselves
QDomDocument domDocument;
domDocument.setContent(QString(libsedml::writeSedMLToString(mSedmlDocument)));
bool res = Core::writeTextToFile(pNewFileName, qDomDocumentToString(domDocument));
// Update ourselves, if possible, and make sure that we are not considered
// as new anymore (in case we were)
if (res) {
update();
mNew = false;
}
return res;
}
//==============================================================================
bool SedmlFile::isValid(const QString &pFileContents, SedmlFileIssues &pIssues)
{
// Check whether the given file contents is SED-ML valid and, if not,
// populate pIssues with the problems found (after having emptied its
// contents)
// Note: normally, we would create a temporary SED-ML document using
// libsedml::readSedMLFromString(), but if the given file contents
// doesn't start with:
// <?xml version='1.0' encoding='UTF-8'?>
// then libsedml::readSedMLFromString() will prepend it to our given
// file contents, which is not what we want. So, instead, we create a
// temporary file which contents is that of our given file contents,
// and simply call libsedml::readSedML()...
pIssues.clear();
QTemporaryFile file;
QByteArray fileContentsByteArray = pFileContents.toUtf8();
file.open();
file.write(fileContentsByteArray);
file.flush();
QByteArray fileNameByteArray = file.fileName().toUtf8();
libsedml::SedDocument *sedmlDocument = libsedml::readSedML(fileNameByteArray.constData());
libsedml::SedErrorLog *errorLog = sedmlDocument->getErrorLog();
for (unsigned int i = 0, iMax = errorLog->getNumErrors(); i < iMax; ++i) {
const libsedml::SedError *error = errorLog->getError(i);
SedmlFileIssue::Type issueType;
switch (error->getSeverity()) {
case LIBSBML_SEV_INFO:
issueType = SedmlFileIssue::Information;
break;
case LIBSBML_SEV_ERROR:
issueType = SedmlFileIssue::Error;
break;
case LIBSBML_SEV_WARNING:
issueType = SedmlFileIssue::Warning;
break;
case LIBSBML_SEV_FATAL:
issueType = SedmlFileIssue::Fatal;
break;
}
static const QRegularExpression TrailingEmptyLinesRegEx = QRegularExpression("[\\n]*$");
QString errorMessage = QString::fromStdString(error->getMessage()).remove(TrailingEmptyLinesRegEx);
pIssues << SedmlFileIssue(issueType, error->getLine(), error->getColumn(), errorMessage);
}
file.close();
// Only consider the given file contents SED-ML valid if it has no errors
return sedmlDocument->getNumErrors(libsedml::LIBSEDML_SEV_ERROR) == 0;
}
//==============================================================================
CellMLSupport::CellmlFile * SedmlFile::cellmlFile()
{
// Return our CellML file, after loading ourselves if necessary
load();
return mCellmlFile;
}
//==============================================================================
CellMLSupport::CellmlFileRuntime * SedmlFile::runtime()
{
// Return the runtime for our CellML file, if any, after loading ourselves
// if necessary
load();
return mCellmlFile?mCellmlFile->runtime():0;
}
//==============================================================================
void SedmlFile::update()
{
//---GRY--- TO BE DONE...
}
//==============================================================================
} // namespace SEDMLSupport
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<commit_msg>Some minor cleaning up [ci skip].<commit_after>/*******************************************************************************
Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you under
the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
*******************************************************************************/
//==============================================================================
// SED-ML file class
//==============================================================================
#include "cellmlfile.h"
#include "corecliutils.h"
#include "sedmlfile.h"
//==============================================================================
#include <QRegularExpression>
#include <QTemporaryFile>
//==============================================================================
#include "sedmlapidisablewarnings.h"
#include "sedml/SedDocument.h"
#include "sedml/SedReader.h"
#include "sedml/SedWriter.h"
#include "sedmlapienablewarnings.h"
//==============================================================================
namespace OpenCOR {
namespace SEDMLSupport {
//==============================================================================
SedmlFile::SedmlFile(const QString &pFileName, const bool &pNew) :
StandardSupport::StandardFile(pFileName),
mSedmlDocument(0),
mCellmlFile(0),
mNew(pNew)
{
// Reset ourselves
reset();
}
//==============================================================================
SedmlFile::~SedmlFile()
{
// Reset ourselves
reset();
}
//==============================================================================
void SedmlFile::reset()
{
// Reset all of our properties
delete mSedmlDocument;
delete mCellmlFile;
mSedmlDocument = 0;
mCellmlFile = 0;
mLoadingNeeded = true;
}
//==============================================================================
libsedml::SedDocument * SedmlFile::sedmlDocument()
{
// Return the SED-ML document associated with our SED-ML file, after loading
// ourselves if necessary
load();
return mSedmlDocument;
}
//==============================================================================
bool SedmlFile::load()
{
// Check whether the file is already loaded and without any issues
if (!mLoadingNeeded)
return !mSedmlDocument->getNumErrors(libsedml::LIBSEDML_SEV_ERROR);
mLoadingNeeded = false;
// Create a new SED-ML document, if needed, or try to load our file
if (mNew) {
mSedmlDocument = new libsedml::SedDocument();
} else {
QByteArray fileNameByteArray = mFileName.toUtf8();
mSedmlDocument = libsedml::readSedML(fileNameByteArray.constData());
}
bool res = !mSedmlDocument->getNumErrors(libsedml::LIBSEDML_SEV_ERROR);
// Update ourselves, if possible
if (res)
update();
return res;
}
//==============================================================================
bool SedmlFile::save(const QString &pNewFileName)
{
// Make sure that we are properly loaded and have no issue
if (mLoadingNeeded || mSedmlDocument->getNumErrors(libsedml::LIBSEDML_SEV_ERROR))
return false;
// Write ourselves after having reformatted ourselves
QDomDocument domDocument;
domDocument.setContent(QString(libsedml::writeSedMLToString(mSedmlDocument)));
bool res = Core::writeTextToFile(pNewFileName, qDomDocumentToString(domDocument));
// Update ourselves, if possible, and make sure that we are not considered
// as new anymore (in case we were)
if (res) {
update();
mNew = false;
}
return res;
}
//==============================================================================
bool SedmlFile::isValid(const QString &pFileContents, SedmlFileIssues &pIssues)
{
// Check whether the given file contents is SED-ML valid and, if not,
// populate pIssues with the problems found (after having emptied its
// contents)
// Note: normally, we would create a temporary SED-ML document using
// libsedml::readSedMLFromString(), but if the given file contents
// doesn't start with:
// <?xml version='1.0' encoding='UTF-8'?>
// then libsedml::readSedMLFromString() will prepend it to our given
// file contents, which is not what we want. So, instead, we create a
// temporary file which contents is that of our given file contents,
// and simply call libsedml::readSedML()...
pIssues.clear();
QTemporaryFile file;
QByteArray fileContentsByteArray = pFileContents.toUtf8();
file.open();
file.write(fileContentsByteArray);
file.flush();
QByteArray fileNameByteArray = file.fileName().toUtf8();
libsedml::SedDocument *sedmlDocument = libsedml::readSedML(fileNameByteArray.constData());
libsedml::SedErrorLog *errorLog = sedmlDocument->getErrorLog();
for (unsigned int i = 0, iMax = errorLog->getNumErrors(); i < iMax; ++i) {
const libsedml::SedError *error = errorLog->getError(i);
SedmlFileIssue::Type issueType;
switch (error->getSeverity()) {
case LIBSBML_SEV_INFO:
issueType = SedmlFileIssue::Information;
break;
case LIBSBML_SEV_ERROR:
issueType = SedmlFileIssue::Error;
break;
case LIBSBML_SEV_WARNING:
issueType = SedmlFileIssue::Warning;
break;
case LIBSBML_SEV_FATAL:
issueType = SedmlFileIssue::Fatal;
break;
}
static const QRegularExpression TrailingEmptyLinesRegEx = QRegularExpression("[\\n]*$");
QString errorMessage = QString::fromStdString(error->getMessage()).remove(TrailingEmptyLinesRegEx);
pIssues << SedmlFileIssue(issueType, error->getLine(), error->getColumn(), errorMessage);
}
file.close();
// Only consider the given file contents SED-ML valid if it has no errors
return !sedmlDocument->getNumErrors(libsedml::LIBSEDML_SEV_ERROR);
}
//==============================================================================
CellMLSupport::CellmlFile * SedmlFile::cellmlFile()
{
// Return our CellML file, after loading ourselves if necessary
load();
return mCellmlFile;
}
//==============================================================================
CellMLSupport::CellmlFileRuntime * SedmlFile::runtime()
{
// Return the runtime for our CellML file, if any, after loading ourselves
// if necessary
load();
return mCellmlFile?mCellmlFile->runtime():0;
}
//==============================================================================
void SedmlFile::update()
{
//---GRY--- TO BE DONE...
}
//==============================================================================
} // namespace SEDMLSupport
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<|endoftext|> |
<commit_before><commit_msg>[code] Maked some commentary for lisibility<commit_after><|endoftext|> |
<commit_before>
#include <jni.h>
#include "Solver/Solver.h"
#include "kodkod_engine_satlab_CryptoMiniSat.h"
using namespace CMSat;
/*
* Class: kodkod_engine_satlab_CryptoMiniSat
* Method: make
* Signature: ()J
*/
JNIEXPORT jlong JNICALL Java_kodkod_engine_satlab_CryptoMiniSat_make
(JNIEnv *, jclass) {
Solver* solver = new Solver();
return ((jlong) solver);
}
/*
* Class: kodkod_engine_satlab_CryptoMiniSat
* Method: free
* Signature: (J)V
*/
JNIEXPORT void JNICALL Java_kodkod_engine_satlab_CryptoMiniSat_free
(JNIEnv *, jobject, jlong solver) {
delete ((Solver*)solver);
}
/*
* Class: kodkod_engine_satlab_CryptoMiniSat
* Method: addVariables
* Signature: (JI)V
*/
JNIEXPORT void JNICALL Java_kodkod_engine_satlab_CryptoMiniSat_addVariables
(JNIEnv *, jobject, jlong solver, jint numVars) {
Solver* solverPtr = (Solver*) solver;
for(int i = 0; i < numVars; ++i) {
solverPtr->newVar();
}
}
/*
* Class: kodkod_engine_satlab_CryptoMiniSat
* Method: addClause
* Signature: (J[I)Z
*/
JNIEXPORT jboolean JNICALL Java_kodkod_engine_satlab_CryptoMiniSat_addClause
(JNIEnv * env, jobject, jlong solver, jintArray clause) {
jsize length = env->GetArrayLength(clause);
jint* buf = env->GetIntArrayElements(clause, JNI_FALSE);
Solver* solverPtr = ((Solver*)solver);
vec<Lit> lits;
for(int i = 0; i < length; ++i) {
int var = *(buf+i);
lits.push((var > 0) ? Lit(var, false) : Lit(-var, true));
}
solverPtr->addClause(lits);
env->ReleaseIntArrayElements(clause, buf, 0);
return solverPtr->okay();
}
/*
* Class: kodkod_engine_satlab_CryptoMiniSat
* Method: solve
* Signature: (J)Z
*/
JNIEXPORT jboolean JNICALL Java_kodkod_engine_satlab_CryptoMiniSat_solve
(JNIEnv *, jobject, jlong solver) {
return ((Solver*)solver)->solve()==l_True;
}
/*
* Class: kodkod_engine_satlab_CryptoMiniSat
* Method: valueOf
* Signature: (JI)Z
*/
JNIEXPORT jboolean JNICALL Java_kodkod_engine_satlab_CryptoMiniSat_valueOf
(JNIEnv *, jobject, jlong solver, jint var) {
return ((Solver*)solver)->model[var-1]==l_True;
}
<commit_msg>*** empty log message ***<commit_after>
#include <jni.h>
#include "Solver/Solver.h"
#include "kodkod_engine_satlab_CryptoMiniSat.h"
#include <iostream>
using namespace CMSat;
using namespace std;
/*
* Class: kodkod_engine_satlab_CryptoMiniSat
* Method: make
* Signature: ()J
*/
JNIEXPORT jlong JNICALL Java_kodkod_engine_satlab_CryptoMiniSat_make
(JNIEnv *, jclass) {
/*SolverConf conf;
conf.fixRestartType = static_restart;
conf.polarity_mode = polarity_false;
conf.doFindXors= false;
conf.doPartHandler = false;
Solver* solver = new Solver(conf);
return ((jlong) solver);*/
Solver* solver = new Solver();
return ((jlong) solver);
}
/*
* Class: kodkod_engine_satlab_CryptoMiniSat
* Method: free
* Signature: (J)V
*/
JNIEXPORT void JNICALL Java_kodkod_engine_satlab_CryptoMiniSat_free
(JNIEnv *, jobject, jlong solver) {
delete ((Solver*)solver);
}
/*
* Class: kodkod_engine_satlab_CryptoMiniSat
* Method: addVariables
* Signature: (JI)V
*/
JNIEXPORT void JNICALL Java_kodkod_engine_satlab_CryptoMiniSat_addVariables
(JNIEnv *, jobject, jlong solver, jint numVars) {
Solver* solverPtr = (Solver*) solver;
SolverConf conf = solverPtr->conf;
/*std::cout << (conf.fixRestartType == static_restart);
std::cout << (conf.polarity_mode == polarity_false);
std::cout << (conf.doFindXors);
std::cout << (conf.doPartHandler);*/
for(int i = 0; i < numVars; ++i) {
solverPtr->newVar();
}
}
/*
* Class: kodkod_engine_satlab_CryptoMiniSat
* Method: addClause
* Signature: (J[I)Z
*/
JNIEXPORT jboolean JNICALL Java_kodkod_engine_satlab_CryptoMiniSat_addClause
(JNIEnv * env, jobject, jlong solver, jintArray clause) {
jsize length = env->GetArrayLength(clause);
jint* buf = env->GetIntArrayElements(clause, JNI_FALSE);
Solver* solverPtr = ((Solver*)solver);
vec<Lit> lits;
for(int i = 0; i < length; ++i) {
int var = *(buf+i);
lits.push((var > 0) ? Lit(var, false) : Lit(-var, true));
}
solverPtr->addClause(lits);
env->ReleaseIntArrayElements(clause, buf, 0);
return solverPtr->okay();
}
/*
* Class: kodkod_engine_satlab_CryptoMiniSat
* Method: solve
* Signature: (J)Z
*/
JNIEXPORT jboolean JNICALL Java_kodkod_engine_satlab_CryptoMiniSat_solve
(JNIEnv *, jobject, jlong solver) {
return ((Solver*)solver)->solve()==l_True;
}
/*
* Class: kodkod_engine_satlab_CryptoMiniSat
* Method: valueOf
* Signature: (JI)Z
*/
JNIEXPORT jboolean JNICALL Java_kodkod_engine_satlab_CryptoMiniSat_valueOf
(JNIEnv *, jobject, jlong solver, jint var) {
return ((Solver*)solver)->model[var-1]==l_True;
}
<|endoftext|> |
<commit_before>#pragma once
#include "types.hpp"
#include <mach/mach_time.h>
#include <optional>
#include <pqrs/dispatcher.hpp>
#include <pqrs/osx/iokit_hid_device.hpp>
namespace krbn {
class hid_keyboard_caps_lock_led_state_manager final : public pqrs::dispatcher::extra::dispatcher_client {
public:
hid_keyboard_caps_lock_led_state_manager(IOHIDDeviceRef device) : dispatcher_client(),
device_(device),
timer_(*this) {
if (device_) {
pqrs::osx::iokit_hid_device hid_device(*device_);
for (const auto& e : hid_device.make_elements()) {
auto usage_page = pqrs::osx::iokit_hid_usage_page(IOHIDElementGetUsagePage(*e));
auto usage = pqrs::osx::iokit_hid_usage(IOHIDElementGetUsage(*e));
if (usage_page == pqrs::osx::iokit_hid_usage_page_leds &&
usage == pqrs::osx::iokit_hid_usage_led_caps_lock) {
element_ = e;
}
}
}
}
~hid_keyboard_caps_lock_led_state_manager(void) {
detach_from_dispatcher([this] {
timer_.stop();
});
}
void set_state(std::optional<led_state> value) {
std::lock_guard<std::mutex> lock(state_mutex_);
state_ = value;
enqueue_to_dispatcher([this] {
update_caps_lock_led();
});
}
void async_start(void) {
timer_.start(
[this] {
update_caps_lock_led();
},
std::chrono::milliseconds(3000));
}
void async_stop(void) {
timer_.stop();
}
private:
void update_caps_lock_led(void) const {
// macOS 10.12 sometimes synchronize caps lock LED to internal keyboard caps lock state.
// The behavior causes LED state mismatch because
// the caps lock state of karabiner_grabber is independent from the hardware caps lock state.
// Thus, we monitor the LED state and update it if needed.
if (auto integer_value = make_integer_value()) {
if (device_ && element_) {
if (auto value = IOHIDValueCreateWithIntegerValue(kCFAllocatorDefault,
*element_,
mach_absolute_time(),
*integer_value)) {
IOHIDDeviceSetValue(*device_, *element_, value);
CFRelease(value);
}
}
}
}
std::optional<CFIndex> make_integer_value(void) const {
std::lock_guard<std::mutex> lock(state_mutex_);
if (state_ && element_) {
if (*state_ == led_state::on) {
return IOHIDElementGetLogicalMax(*element_);
} else {
return IOHIDElementGetLogicalMin(*element_);
}
}
return std::nullopt;
}
pqrs::cf::cf_ptr<IOHIDDeviceRef> device_;
pqrs::cf::cf_ptr<IOHIDElementRef> element_;
std::optional<led_state> state_;
mutable std::mutex state_mutex_;
pqrs::dispatcher::extra::timer timer_;
};
} // namespace krbn
<commit_msg>fix an issue that hid_keyboard_caps_lock_led_state_manager manipulates led before it started<commit_after>#pragma once
#include "types.hpp"
#include <mach/mach_time.h>
#include <optional>
#include <pqrs/dispatcher.hpp>
#include <pqrs/osx/iokit_hid_device.hpp>
namespace krbn {
class hid_keyboard_caps_lock_led_state_manager final : public pqrs::dispatcher::extra::dispatcher_client {
public:
hid_keyboard_caps_lock_led_state_manager(IOHIDDeviceRef device) : dispatcher_client(),
device_(device),
timer_(*this),
started_(false) {
if (device_) {
pqrs::osx::iokit_hid_device hid_device(*device_);
for (const auto& e : hid_device.make_elements()) {
auto usage_page = pqrs::osx::iokit_hid_usage_page(IOHIDElementGetUsagePage(*e));
auto usage = pqrs::osx::iokit_hid_usage(IOHIDElementGetUsage(*e));
if (usage_page == pqrs::osx::iokit_hid_usage_page_leds &&
usage == pqrs::osx::iokit_hid_usage_led_caps_lock) {
element_ = e;
}
}
}
}
~hid_keyboard_caps_lock_led_state_manager(void) {
detach_from_dispatcher([this] {
timer_.stop();
});
}
void set_state(std::optional<led_state> value) {
std::lock_guard<std::mutex> lock(state_mutex_);
state_ = value;
enqueue_to_dispatcher([this] {
update_caps_lock_led();
});
}
void async_start(void) {
enqueue_to_dispatcher([this] {
started_ = true;
timer_.start(
[this] {
update_caps_lock_led();
},
std::chrono::milliseconds(3000));
});
}
void async_stop(void) {
enqueue_to_dispatcher([this] {
started_ = false;
timer_.stop();
});
}
private:
void update_caps_lock_led(void) const {
if (!started_) {
return;
}
// macOS 10.12 sometimes synchronize caps lock LED to internal keyboard caps lock state.
// The behavior causes LED state mismatch because
// the caps lock state of karabiner_grabber is independent from the hardware caps lock state.
// Thus, we monitor the LED state and update it if needed.
if (auto integer_value = make_integer_value()) {
if (device_ && element_) {
if (auto value = IOHIDValueCreateWithIntegerValue(kCFAllocatorDefault,
*element_,
mach_absolute_time(),
*integer_value)) {
IOHIDDeviceSetValue(*device_, *element_, value);
CFRelease(value);
}
}
}
}
std::optional<CFIndex> make_integer_value(void) const {
std::lock_guard<std::mutex> lock(state_mutex_);
if (state_ && element_) {
if (*state_ == led_state::on) {
return IOHIDElementGetLogicalMax(*element_);
} else {
return IOHIDElementGetLogicalMin(*element_);
}
}
return std::nullopt;
}
pqrs::cf::cf_ptr<IOHIDDeviceRef> device_;
pqrs::cf::cf_ptr<IOHIDElementRef> element_;
std::optional<led_state> state_;
mutable std::mutex state_mutex_;
pqrs::dispatcher::extra::timer timer_;
bool started_;
};
} // namespace krbn
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
/// \ingroup macros
/// \file loadmacros.C
/// \brief Macro which loads and compiles the MUON macros:
///
/// \author I. Hrivnacova, IPN Orsay
///
/// <pre>
/// runSimulation.C - ok, comp, x; Laurent
/// runReconstruction.C - ok, comp, x; Laurent
/// fastMUONGen.C - ok, comp, x; Hermine, Alessandro
/// fastMUONSim.C - ok, comp, x; Hermine, Alessandro
/// DecodeRecoCocktail.C - ok, comp, README; Hermine, Alessandro
/// ReadRecoCocktail.C - ok, comp, README; Hermine, Alessandro
/// MergeMuonLight.C - x, comp, README; Hermine, Alessandro
/// MakeMUONFullMisAlignment.C - ok, comp, README; Javier, Ivana
/// MakeMUONResMisAlignment.C - ok, comp, README; Javier, Ivana
/// MakeMUONZeroMisAlignment.C - ok, comp, README; Javier, Ivana
/// MUONAlignment.C - ok, comp, README; Javier
/// MUONCheck.C - ok, comp, x, Frederic, in test
/// MUONCheckDI.C - x, comp, x Artur
/// MUONCheckMisAligner.C - ok, comp, x, Javier
/// MUONefficiency.C - ok, comp, README; Christophe, in test
/// MUONGenerateBusPatch.C - ok, comp, x, Christian
/// MUONGenerateGeometryData.C - ok, comp, README; Ivana
/// MUONGenerateTestGMS.C - ok, comp, READMEshuttle; Ivana
/// MUONmassPlot_ESD.C - ok, comp, README, Christian
/// MUONplotefficiency.C - ok, comp, README; Christophe
/// MUONRawStreamTracker.C - x, comp, README; Christian
/// MUONRawStreamTrigger.C - x, comp, README; Christian
/// MUONRecoCheck.C - ok, comp, README; Hermine, Alessandro
/// MUONResoEffChamber.C - ok, comp, x, Nicolas
/// MUONStatusMap.C - ok, comp, x, Laurent
/// MUONTimeRawStreamTracker.C - ok, comp, README, Artur
/// MUONTrigger.C - ok, comp, README, Philippe C.
/// MUONTriggerEfficiency.C - ok, comp, x, Philippe C., in test
/// MUONTriggerEfficiencyPt.C - x, comp, README, Philippe C.
/// MUONTriggerChamberEfficiency.C- x, comp, README, Diego
/// TestMUONPreprocessor.C - ok, comp, READMEshuttle; Laurent
/// </pre>
///
/// - 1st item: ok/fails/x - if the macro runs; x means that it was not tried either for lack
/// of documentation, or expertise
/// - 2nd item: comp/x - if the macro can be compiled
/// - 3rd item: README/x - if it is documented in README, x means no doxumentation outside the
/// macro itself
/// - 4th item: author(s) - responsible for macro maintenance
/// - eventually 5th item: - if the macro is run within test scripts
#if !defined(__CINT__) || defined(__MAKECINT__)
#include <TROOT.h>
#include <TSystem.h>
#include <TString.h>
#endif
void loadmacros ()
{
// Redefine include paths as some macros need
// to see more than what is define in rootlogon.C
//
TString includePath = "-I${ALICE_ROOT}/include ";
includePath += "-I${ALICE_ROOT}/RAW ";
includePath += "-I${ALICE_ROOT}/FASTSIM ";
includePath += "-I${ALICE_ROOT}/EVGEN ";
includePath += "-I${ALICE_ROOT}/SHUTTLE/TestShuttle ";
includePath += "-I${ALICE_ROOT}/ITS ";
includePath += "-I${ALICE_ROOT}/MUON ";
includePath += "-I${ALICE_ROOT}/MUON/mapping";
gSystem->SetIncludePath(includePath.Data());
// Load libraries not linked with aliroot
//
gSystem->Load("$ALICE_ROOT/SHUTTLE/TestShuttle/libTestShuttle.so");
gSystem->Load("libMUONshuttle.so");
gSystem->Load("libMUONevaluation.so");
// Load macros
//
gROOT->LoadMacro("$ALICE_ROOT/MUON/runSimulation.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/runReconstruction.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/fastMUONGen.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/fastMUONSim.C++");
// gROOT->LoadMacro("$ALICE_ROOT/MUON/DecodeRecoCocktail.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/ReadRecoCocktail.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MergeMuonLight.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MakeMUONFullMisAlignment.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MakeMUONResMisAlignment.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MakeMUONZeroMisAlignment.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONAlignment.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONCheck.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONCheckDI.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONCheckMisAligner.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONefficiency.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONGenerateBusPatch.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONGenerateGeometryData.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONGenerateTestGMS.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONmassPlot_ESD.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONplotefficiency.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONRawStreamTracker.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONRawStreamTrigger.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONRecoCheck.C++");
// gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONResoEffChamber.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONStatusMap.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONTrigger.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONTriggerEfficiency.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONTriggerEfficiencyPt.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONTriggerChamberEfficiency.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/TestMUONPreprocessor.C++");
}
<commit_msg>- Introducing more functions and simplified usage - Adding recently added macros<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
/// \ingroup macros
/// \file loadmacros.C
/// \brief Macro which loads and compiles the MUON macros
///
/// \author I. Hrivnacova, IPN Orsay
#if !defined(__CINT__) || defined(__MAKECINT__)
#include <TROOT.h>
#include <TSystem.h>
#include <TString.h>
#endif
void init()
{
/// Set include path and load libraries which are not
/// linked with aliroot
// Redefine include paths as some macros need
// to see more than what is define in rootlogon.C
//
TString includePath = "-I${ALICE_ROOT}/include ";
includePath += "-I${ALICE_ROOT}/RAW ";
includePath += "-I${ALICE_ROOT}/FASTSIM ";
includePath += "-I${ALICE_ROOT}/EVGEN ";
includePath += "-I${ALICE_ROOT}/SHUTTLE/TestShuttle ";
includePath += "-I${ALICE_ROOT}/ITS ";
includePath += "-I${ALICE_ROOT}/MUON ";
includePath += "-I${ALICE_ROOT}/MUON/mapping";
gSystem->SetIncludePath(includePath.Data());
// Load libraries not linked with aliroot
//
gSystem->Load("$ALICE_ROOT/SHUTTLE/TestShuttle/libTestShuttle.so");
gSystem->Load("libMUONshuttle.so");
gSystem->Load("libMUONevaluation.so");
gSystem->Load("liblhapdf.so");
gSystem->Load("libpythia6.so");
gSystem->Load("libgeant321.so");
gSystem->Load("libEG");
gSystem->Load("libEGPythia6");
gSystem->Load("libAliPythia6.so");
}
void loadmacro(const TString& macroName)
{
/// Load the macro with given name
TString path = "$ALICE_ROOT/MUON/";
path += macroName;
path += ".C++";
gROOT->LoadMacro(path.Data());
}
void loadmacros ()
{
init();
loadmacro("DecodeRecoCocktail"); // Hermine, Alessandro
loadmacro("fastMUONGen"); // Hermine, Alessandro
loadmacro("fastMUONSim"); // Hermine, Alessandro
loadmacro("MakeMUONFullMisAlignment"); // Javier, Ivana
loadmacro("MakeMUONResMisAlignment"); // Javier, Ivana
loadmacro("MakeMUONZeroMisAlignment"); // Javier, Ivana
loadmacro("MergeMuonLight"); // Hermine, Alessandro
loadmacro("MUONAlignment"); // Javier
loadmacro("MUONCheck"); // Frederic
loadmacro("MUONCheckDI"); // Artur
loadmacro("MUONCheckMisAligner"); // Javier
loadmacro("MUONClusterInfo"); // Philippe P.
loadmacro("MUONefficiency"); // Christophe
loadmacro("MUONGenerateBusPatch"); // Christian
loadmacro("MUONGenerateGeometryData"); // Ivana
loadmacro("MUONGenerateTestGMS"); // Ivana
loadmacro("MUONGeometryViewingHelper"); // Ivana
loadmacro("MUONmassPlot_ESD"); // Christian
loadmacro("MUONOfflineShift"); // Laurent
loadmacro("MUONplotefficiency"); // Christian
loadmacro("MUONRawStreamTracker"); // Christian
loadmacro("MUONRawStreamTrigger"); // Christian
loadmacro("MUONReCalcGlobalTrigger"); // Bogdan
loadmacro("MUONRecoCheck"); // Hermine, Alessandro
loadmacro("MUONRefit"); // Philippe P.
// loadmacro("MUONResoEffChamber"); // Nicolas
loadmacro("MUONStatusMap"); // Laurent
loadmacro("MUONSurveyUtil"); // Javier
loadmacro("MUONSurveyCh8L"); // Javier
loadmacro("MUONTimeRawStreamTracker"); // Artur
loadmacro("MUONTimeRawStreamTrigger"); // Artur
loadmacro("MUONTrigger"); // Bogdan
loadmacro("MUONTriggerChamberEfficiency"); // Diego
loadmacro("MUONTriggerEfficiency"); // Bogdan
loadmacro("MUONTriggerEfficiencyPt"); // Bogdan
loadmacro("ReadRecoCocktail"); // Hermine, Alessandro
loadmacro("runReconstruction"); // Laurent
loadmacro("runSimulation"); // Laurent
loadmacro("TestMUONPreprocessor"); // Laurent
loadmacro("TestRecPoints"); // Diego
}
<|endoftext|> |
<commit_before>#include "NodeThread.h"
#include "nodeblink.h"
#include "gin/v8_initializer.h"
#include "libplatform/libplatform.h"
#include "base/thread.h"
#include "common/ThreadCall.h"
#include "common/NodeBinding.h"
#include <string.h>
#include <Windows.h>
#include <process.h>
#pragma comment(lib,"openssl.lib")
#pragma comment(lib, "IPHLPAPI.lib")
#pragma comment(lib, "Userenv.lib")
#pragma comment(lib, "Psapi.lib")
namespace atom {
static void childSignalCallback(uv_async_t* signal) {
}
class ElectronFsHooks : public node::Environment::FileSystemHooks {
virtual bool internalModuleStat(const char* path, int *rc) override {
*rc = 1;
return false;
}
void open() {
}
};
class ArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
public:
ArrayBufferAllocator() : env_(nullptr) { }
inline void set_env(node::Environment* env) { env_ = env; }
virtual void* Allocate(size_t size) {
void* p = malloc(size);
memset(p, 0, size);
return p;
}
virtual void* AllocateUninitialized(size_t size) {
return malloc(size);
}
virtual void Free(void* data, size_t) { free(data); }
private:
node::Environment* env_;
};
static void gcTimerCallBack(uv_timer_t* handle) {
return;
v8::Isolate *isolate = (v8::Isolate*)(handle->data);
if (isolate)
isolate->LowMemoryNotification();
}
void nodeInitCallBack(NodeArgc* n) {
uv_timer_t gcTimer;
gcTimer.data = n->childEnv->isolate();
uv_timer_init(n->childLoop, &gcTimer);
uv_timer_start(&gcTimer, gcTimerCallBack, 1000 * 10, 1);
uv_loop_t* loop = n->childLoop;
atom::ThreadCall::init(loop);
atom::ThreadCall::messageLoop(loop, n->v8platform, v8::Isolate::GetCurrent());
}
void nodePreInitCallBack(NodeArgc* n) {
}
static v8::Isolate* initNodeEnv(NodeArgc* nodeArgc) {
v8::Isolate::CreateParams params;
ArrayBufferAllocator array_buffer_allocator;
params.array_buffer_allocator = &array_buffer_allocator;
v8::Isolate *isolate = v8::Isolate::New(params);
v8::Isolate::Scope isolateScope(isolate);
v8::HandleScope handleScope(isolate);
v8::Local<v8::Context> context = v8::Context::New(isolate);
v8::Context::Scope contextScope(context);
nodeArgc->childEnv = nodeArgc->m_nodeBinding->createEnvironment(context);
ElectronFsHooks fsHooks;
nodeArgc->childEnv->file_system_hooks(&fsHooks);
node::LoadEnvironment(nodeArgc->childEnv);
nodeInitCallBack(nodeArgc);
return isolate;
}
static void workerRun(NodeArgc* nodeArgc) {
int err = uv_loop_init(nodeArgc->childLoop);
if (err != 0)
goto loop_init_failed;
// Interruption signal handler
err = uv_async_init(nodeArgc->childLoop, &nodeArgc->async, childSignalCallback);
if (err != 0)
goto async_init_failed;
//uv_unref(reinterpret_cast<uv_handle_t*>(&nodeArgc->async)); //zero 不屏蔽此句导致loop循环退出
nodeArgc->initType = true;
::SetEvent(nodeArgc->initEvent);
nodeArgc->v8platform = (v8::Platform*)node::nodeCreateDefaultPlatform();
base::SetThreadName("NodeCore");
ThreadCall::createBlinkThread(nodeArgc->v8platform);
v8::Isolate* isolate = initNodeEnv(nodeArgc);
// Clean-up all running handles
nodeArgc->childEnv->CleanupHandles();
nodeArgc->childEnv->Dispose();
nodeArgc->childEnv = nullptr;
isolate->Dispose();
return;
async_init_failed:
err = uv_loop_close(nodeArgc->childLoop);
CHECK_EQ(err, 0);
loop_init_failed:
free(nodeArgc);
nodeArgc->initType = false;
::SetEvent(nodeArgc->initEvent);
}
NodeArgc* runNodeThread() {
NodeArgc* nodeArgc = (NodeArgc *)malloc(sizeof(NodeArgc));
memset(nodeArgc, 0, sizeof(NodeArgc));
// nodeArgc->initcall = initcall;
// nodeArgc->preInitcall = preInitcall;
nodeArgc->childLoop = (uv_loop_t *)malloc(sizeof(uv_loop_t));
nodeArgc->m_nodeBinding = new NodeBindings(true, nodeArgc->childLoop);
// nodeArgc->argv = new char*[argc + 1];
// for (int i = 0; i < argc; i++) {
// // Compute the size of the required buffer
// DWORD size = WideCharToMultiByte(CP_UTF8, 0, wargv[i], -1, nullptr, 0, nullptr, nullptr);
// if (size == 0)
// ::DebugBreak();
//
// // Do the actual conversion
// nodeArgc->argv[i] = new char[size];
// DWORD result = WideCharToMultiByte(CP_UTF8, 0, wargv[i], -1, nodeArgc->argv[i], size, nullptr, nullptr);
// if (result == 0)
// ::DebugBreak();
// }
// nodeArgc->argv[argc] = nullptr;
// nodeArgc->argc = argc;
nodeArgc->initEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL); // 创建一个对象,用来等待node环境基础环境创建成功
int err = uv_thread_create(&nodeArgc->thread, reinterpret_cast<uv_thread_cb>(workerRun), nodeArgc);
if (err != 0)
goto thread_create_failed;
::WaitForSingleObject(nodeArgc->initEvent, INFINITE);
::CloseHandle(nodeArgc->initEvent);
nodeArgc->initEvent = NULL;
if (!nodeArgc->initType)
goto thread_init_failed;
return nodeArgc;
thread_init_failed:
thread_create_failed:
free(nodeArgc);
return nullptr;
}
node::Environment* nodeGetEnvironment(NodeArgc* nodeArgc) {
if (nodeArgc)
return nodeArgc->childEnv;
return nullptr;
}
} // atom
namespace node {
namespace debugger {
Agent::~Agent(void) {
DebugBreak();
}
}
}<commit_msg>* 改下换行方式<commit_after>#include "NodeThread.h"
#include "nodeblink.h"
#include "gin/v8_initializer.h"
#include "libplatform/libplatform.h"
#include "base/thread.h"
#include "common/ThreadCall.h"
#include "common/NodeBinding.h"
#include <string.h>
#include <Windows.h>
#include <process.h>
#pragma comment(lib,"openssl.lib")
#pragma comment(lib, "IPHLPAPI.lib")
#pragma comment(lib, "Userenv.lib")
#pragma comment(lib, "Psapi.lib")
namespace atom {
static void childSignalCallback(uv_async_t* signal) {
}
class ElectronFsHooks : public node::Environment::FileSystemHooks {
virtual bool internalModuleStat(const char* path, int *rc) override {
*rc = 1;
return false;
}
void open() {
}
};
class ArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
public:
ArrayBufferAllocator() : env_(nullptr) { }
inline void set_env(node::Environment* env) { env_ = env; }
virtual void* Allocate(size_t size) {
void* p = malloc(size);
memset(p, 0, size);
return p;
}
virtual void* AllocateUninitialized(size_t size) {
return malloc(size);
}
virtual void Free(void* data, size_t) { free(data); }
private:
node::Environment* env_;
};
static void gcTimerCallBack(uv_timer_t* handle) {
return;
v8::Isolate *isolate = (v8::Isolate*)(handle->data);
if (isolate)
isolate->LowMemoryNotification();
}
void nodeInitCallBack(NodeArgc* n) {
uv_timer_t gcTimer;
gcTimer.data = n->childEnv->isolate();
uv_timer_init(n->childLoop, &gcTimer);
uv_timer_start(&gcTimer, gcTimerCallBack, 1000 * 10, 1);
uv_loop_t* loop = n->childLoop;
atom::ThreadCall::init(loop);
atom::ThreadCall::messageLoop(loop, n->v8platform, v8::Isolate::GetCurrent());
}
void nodePreInitCallBack(NodeArgc* n) {
}
static v8::Isolate* initNodeEnv(NodeArgc* nodeArgc) {
v8::Isolate::CreateParams params;
ArrayBufferAllocator array_buffer_allocator;
params.array_buffer_allocator = &array_buffer_allocator;
v8::Isolate *isolate = v8::Isolate::New(params);
v8::Isolate::Scope isolateScope(isolate);
v8::HandleScope handleScope(isolate);
v8::Local<v8::Context> context = v8::Context::New(isolate);
v8::Context::Scope contextScope(context);
nodeArgc->childEnv = nodeArgc->m_nodeBinding->createEnvironment(context);
ElectronFsHooks fsHooks;
nodeArgc->childEnv->file_system_hooks(&fsHooks);
node::LoadEnvironment(nodeArgc->childEnv);
nodeInitCallBack(nodeArgc);
return isolate;
}
static void workerRun(NodeArgc* nodeArgc) {
int err = uv_loop_init(nodeArgc->childLoop);
if (err != 0)
goto loop_init_failed;
// Interruption signal handler
err = uv_async_init(nodeArgc->childLoop, &nodeArgc->async, childSignalCallback);
if (err != 0)
goto async_init_failed;
//uv_unref(reinterpret_cast<uv_handle_t*>(&nodeArgc->async)); //zero 不屏蔽此句导致loop循环退出
nodeArgc->initType = true;
::SetEvent(nodeArgc->initEvent);
nodeArgc->v8platform = (v8::Platform*)node::nodeCreateDefaultPlatform();
base::SetThreadName("NodeCore");
ThreadCall::createBlinkThread(nodeArgc->v8platform);
v8::Isolate* isolate = initNodeEnv(nodeArgc);
// Clean-up all running handles
nodeArgc->childEnv->CleanupHandles();
nodeArgc->childEnv->Dispose();
nodeArgc->childEnv = nullptr;
isolate->Dispose();
return;
async_init_failed:
err = uv_loop_close(nodeArgc->childLoop);
CHECK_EQ(err, 0);
loop_init_failed:
free(nodeArgc);
nodeArgc->initType = false;
::SetEvent(nodeArgc->initEvent);
}
NodeArgc* runNodeThread() {
NodeArgc* nodeArgc = (NodeArgc *)malloc(sizeof(NodeArgc));
memset(nodeArgc, 0, sizeof(NodeArgc));
// nodeArgc->initcall = initcall;
// nodeArgc->preInitcall = preInitcall;
nodeArgc->childLoop = (uv_loop_t *)malloc(sizeof(uv_loop_t));
nodeArgc->m_nodeBinding = new NodeBindings(true, nodeArgc->childLoop);
// nodeArgc->argv = new char*[argc + 1];
// for (int i = 0; i < argc; i++) {
// // Compute the size of the required buffer
// DWORD size = WideCharToMultiByte(CP_UTF8, 0, wargv[i], -1, nullptr, 0, nullptr, nullptr);
// if (size == 0)
// ::DebugBreak();
//
// // Do the actual conversion
// nodeArgc->argv[i] = new char[size];
// DWORD result = WideCharToMultiByte(CP_UTF8, 0, wargv[i], -1, nodeArgc->argv[i], size, nullptr, nullptr);
// if (result == 0)
// ::DebugBreak();
// }
// nodeArgc->argv[argc] = nullptr;
// nodeArgc->argc = argc;
nodeArgc->initEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL); // 创建一个对象,用来等待node环境基础环境创建成功
int err = uv_thread_create(&nodeArgc->thread, reinterpret_cast<uv_thread_cb>(workerRun), nodeArgc);
if (err != 0)
goto thread_create_failed;
::WaitForSingleObject(nodeArgc->initEvent, INFINITE);
::CloseHandle(nodeArgc->initEvent);
nodeArgc->initEvent = NULL;
if (!nodeArgc->initType)
goto thread_init_failed;
return nodeArgc;
thread_init_failed:
thread_create_failed:
free(nodeArgc);
return nullptr;
}
node::Environment* nodeGetEnvironment(NodeArgc* nodeArgc) {
if (nodeArgc)
return nodeArgc->childEnv;
return nullptr;
}
} // atom
namespace node {
namespace debugger {
Agent::~Agent(void) {
DebugBreak();
}
}
}<|endoftext|> |
<commit_before>#include <string>
#include <vector>
#include "caffe/data_layers.hpp"
#include "caffe/util/io.hpp"
namespace caffe {
template <typename Dtype>
BaseDataLayer<Dtype>::BaseDataLayer(const LayerParameter& param)
: Layer<Dtype>(param),
transform_param_(param.transform_param()),
data_transformer_(transform_param_) {
}
template <typename Dtype>
void BaseDataLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top) {
if (top->size() == 1) {
output_labels_ = false;
} else {
output_labels_ = true;
}
DataLayerSetUp(bottom, top);
// The subclasses should setup the datum channels, height and width
CHECK_GT(datum_channels_, 0);
CHECK_GT(datum_height_, 0);
CHECK_GT(datum_width_, 0);
if (transform_param_.crop_size() > 0) {
CHECK_GE(datum_height_, transform_param_.crop_size());
CHECK_GE(datum_width_, transform_param_.crop_size());
}
// check if we want to have mean
if (transform_param_.has_mean_file()) {
const string& mean_file = transform_param_.mean_file();
LOG(INFO) << "Loading mean file from" << mean_file;
BlobProto blob_proto;
ReadProtoFromBinaryFileOrDie(mean_file.c_str(), &blob_proto);
data_mean_.FromProto(blob_proto);
CHECK_GE(data_mean_.num(), 1);
CHECK_GE(data_mean_.channels(), datum_channels_);
CHECK_GE(data_mean_.height(), datum_height_);
CHECK_GE(data_mean_.width(), datum_width_);
} else {
// Simply initialize an all-empty mean.
data_mean_.Reshape(1, datum_channels_, datum_height_, datum_width_);
}
mean_ = data_mean_.cpu_data();
}
template <typename Dtype>
void BasePrefetchingDataLayer<Dtype>::LayerSetUp(
const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) {
BaseDataLayer<Dtype>::LayerSetUp(bottom, top);
// Now, start the prefetch thread. Before calling prefetch, we make two
// cpu_data calls so that the prefetch thread does not accidentally make
// simultaneous cudaMalloc calls when the main thread is running. In some
// GPUs this seems to cause failures if we do not so.
this->prefetch_data_.mutable_cpu_data();
if (this->output_labels_) {
this->prefetch_label_.mutable_cpu_data();
}
DLOG(INFO) << "Initializing prefetch";
this->CreatePrefetchThread();
DLOG(INFO) << "Prefetch initialized.";
}
template <typename Dtype>
void BasePrefetchingDataLayer<Dtype>::CreatePrefetchThread() {
this->phase_ = Caffe::phase();
this->data_transformer_.InitRand();
CHECK(StartInternalThread()) << "Thread execution failed";
}
template <typename Dtype>
void BasePrefetchingDataLayer<Dtype>::JoinPrefetchThread() {
CHECK(WaitForInternalThreadToExit()) << "Thread joining failed";
}
template <typename Dtype>
void BasePrefetchingDataLayer<Dtype>::Forward_cpu(
const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) {
// First, join the thread
JoinPrefetchThread();
// Copy the data
caffe_copy(prefetch_data_.count(), prefetch_data_.cpu_data(),
(*top)[0]->mutable_cpu_data());
if (this->output_labels_) {
caffe_copy(prefetch_label_.count(), prefetch_label_.cpu_data(),
(*top)[1]->mutable_cpu_data());
}
// Start a new prefetch thread
CreatePrefetchThread();
}
#ifdef CPU_ONLY
STUB_GPU_FORWARD(BasePrefetchingDataLayer, Forward);
#endif
INSTANTIATE_CLASS(BaseDataLayer);
INSTANTIATE_CLASS(BasePrefetchingDataLayer);
} // namespace caffe
<commit_msg>Initialize the transformer rng in the base data layer<commit_after>#include <string>
#include <vector>
#include "caffe/data_layers.hpp"
#include "caffe/util/io.hpp"
namespace caffe {
template <typename Dtype>
BaseDataLayer<Dtype>::BaseDataLayer(const LayerParameter& param)
: Layer<Dtype>(param),
transform_param_(param.transform_param()),
data_transformer_(transform_param_) {
}
template <typename Dtype>
void BaseDataLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top) {
if (top->size() == 1) {
output_labels_ = false;
} else {
output_labels_ = true;
}
DataLayerSetUp(bottom, top);
// The subclasses should setup the datum channels, height and width
CHECK_GT(datum_channels_, 0);
CHECK_GT(datum_height_, 0);
CHECK_GT(datum_width_, 0);
if (transform_param_.crop_size() > 0) {
CHECK_GE(datum_height_, transform_param_.crop_size());
CHECK_GE(datum_width_, transform_param_.crop_size());
}
// check if we want to have mean
if (transform_param_.has_mean_file()) {
const string& mean_file = transform_param_.mean_file();
LOG(INFO) << "Loading mean file from" << mean_file;
BlobProto blob_proto;
ReadProtoFromBinaryFileOrDie(mean_file.c_str(), &blob_proto);
data_mean_.FromProto(blob_proto);
CHECK_GE(data_mean_.num(), 1);
CHECK_GE(data_mean_.channels(), datum_channels_);
CHECK_GE(data_mean_.height(), datum_height_);
CHECK_GE(data_mean_.width(), datum_width_);
} else {
// Simply initialize an all-empty mean.
data_mean_.Reshape(1, datum_channels_, datum_height_, datum_width_);
}
mean_ = data_mean_.cpu_data();
data_transformer_.InitRand();
}
template <typename Dtype>
void BasePrefetchingDataLayer<Dtype>::LayerSetUp(
const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) {
BaseDataLayer<Dtype>::LayerSetUp(bottom, top);
// Now, start the prefetch thread. Before calling prefetch, we make two
// cpu_data calls so that the prefetch thread does not accidentally make
// simultaneous cudaMalloc calls when the main thread is running. In some
// GPUs this seems to cause failures if we do not so.
this->prefetch_data_.mutable_cpu_data();
if (this->output_labels_) {
this->prefetch_label_.mutable_cpu_data();
}
DLOG(INFO) << "Initializing prefetch";
this->CreatePrefetchThread();
DLOG(INFO) << "Prefetch initialized.";
}
template <typename Dtype>
void BasePrefetchingDataLayer<Dtype>::CreatePrefetchThread() {
this->phase_ = Caffe::phase();
this->data_transformer_.InitRand();
CHECK(StartInternalThread()) << "Thread execution failed";
}
template <typename Dtype>
void BasePrefetchingDataLayer<Dtype>::JoinPrefetchThread() {
CHECK(WaitForInternalThreadToExit()) << "Thread joining failed";
}
template <typename Dtype>
void BasePrefetchingDataLayer<Dtype>::Forward_cpu(
const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) {
// First, join the thread
JoinPrefetchThread();
// Copy the data
caffe_copy(prefetch_data_.count(), prefetch_data_.cpu_data(),
(*top)[0]->mutable_cpu_data());
if (this->output_labels_) {
caffe_copy(prefetch_label_.count(), prefetch_label_.cpu_data(),
(*top)[1]->mutable_cpu_data());
}
// Start a new prefetch thread
CreatePrefetchThread();
}
#ifdef CPU_ONLY
STUB_GPU_FORWARD(BasePrefetchingDataLayer, Forward);
#endif
INSTANTIATE_CLASS(BaseDataLayer);
INSTANTIATE_CLASS(BasePrefetchingDataLayer);
} // namespace caffe
<|endoftext|> |
<commit_before><commit_msg>INTEGRATION: CWS vgbugs07 (1.12.256); FILE MERGED 2007/06/04 13:27:29 vg 1.12.256.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after><|endoftext|> |
<commit_before><commit_msg>INTEGRATION: CWS cellbreak (1.4.324); FILE MERGED 2003/11/14 10:06:55 fme 1.4.324.3: #i2109# Split table rows 2003/11/07 10:12:15 fme 1.4.324.2: RESYNC: (1.4-1.5); FILE MERGED 2003/09/08 07:46:05 fme 1.4.324.1: #i2109# Feature - Split table rows<commit_after><|endoftext|> |
<commit_before><commit_msg>fix up unit test<commit_after><|endoftext|> |
<commit_before>/*
* Copyright 2014, Nicolas Mansard, LAAS-CNRS
*
* This file is part of eigenpy.
* eigenpy 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.
* eigenpy 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 eigenpy. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __eigenpy_details_hpp__
#define __eigenpy_details_hpp__
#include "eigenpy/fwd.hpp"
#include <numpy/arrayobject.h>
#include <iostream>
#include "eigenpy/eigenpy.hpp"
#include "eigenpy/registration.hpp"
#include "eigenpy/map.hpp"
namespace eigenpy
{
template <typename SCALAR> struct NumpyEquivalentType {};
template <> struct NumpyEquivalentType<double> { enum { type_code = NPY_DOUBLE };};
template <> struct NumpyEquivalentType<int> { enum { type_code = NPY_INT };};
template <> struct NumpyEquivalentType<float> { enum { type_code = NPY_FLOAT };};
namespace bp = boost::python;
struct PyMatrixType
{
static PyMatrixType & getInstance()
{
static PyMatrixType instance;
return instance;
}
operator bp::object () { return pyMatrixType; }
bp::object make(PyArrayObject* pyArray, bool copy = false)
{ return make((PyObject*)pyArray,copy); }
bp::object make(PyObject* pyObj, bool copy = false)
{
bp::object m
= pyMatrixType(bp::object(bp::handle<>(pyObj)), bp::object(), copy);
Py_INCREF(m.ptr());
return m;
}
protected:
PyMatrixType()
{
pyModule = bp::import("numpy");
pyMatrixType = pyModule.attr("matrix");
}
bp::object pyMatrixType;
bp::object pyModule;
};
template<typename MatType>
struct EigenObjectAllocator
{
typedef MatType Type;
static void allocate(PyArrayObject * pyArray, void * storage)
{
typename MapNumpy<MatType>::EigenMap numpyMap = MapNumpy<MatType>::map(pyArray);
new(storage) MatType(numpyMap);
}
static void convert(Type const & mat , PyArrayObject * pyArray)
{
MapNumpy<MatType>::map(pyArray) = mat;
}
};
#if EIGEN_VERSION_AT_LEAST(3,2,0)
template<typename MatType>
struct EigenObjectAllocator< eigenpy::Ref<MatType> >
{
typedef eigenpy::Ref<MatType> Type;
static void allocate(PyArrayObject * pyArray, void * storage)
{
typename MapNumpy<MatType>::EigenMap numpyMap = MapNumpy<MatType>::map(pyArray);
new(storage) Type(numpyMap);
}
static void convert(Type const & mat , PyArrayObject * pyArray)
{
MapNumpy<MatType>::map(pyArray) = mat;
}
};
#endif
/* --- TO PYTHON -------------------------------------------------------------- */
template<typename MatType>
struct EigenToPy
{
static PyObject* convert(MatType const& mat)
{
typedef typename MatType::Scalar T;
assert( (mat.rows()<INT_MAX) && (mat.cols()<INT_MAX)
&& "Matrix range larger than int ... should never happen." );
const int R = (int)mat.rows(), C = (int)mat.cols();
npy_intp shape[2] = { R,C };
PyArrayObject* pyArray = (PyArrayObject*)
PyArray_SimpleNew(2, shape, NumpyEquivalentType<T>::type_code);
EigenObjectAllocator<MatType>::convert(mat,pyArray);
return PyMatrixType::getInstance().make(pyArray).ptr();
}
};
/* --- FROM PYTHON ------------------------------------------------------------ */
template<typename MatType>
struct EigenFromPy
{
EigenFromPy()
{
bp::converter::registry::push_back
(reinterpret_cast<void *(*)(_object *)>(&convertible),
&construct,bp::type_id<MatType>());
}
// Determine if obj_ptr can be converted in a Eigenvec
static void* convertible(PyArrayObject* obj_ptr)
{
if (!PyArray_Check(obj_ptr))
{
#ifndef NDEBUG
std::cerr << "The python object is not a numpy array." << std::endl;
#endif
return 0;
}
if(MatType::IsVectorAtCompileTime)
{
if(PyArray_DIMS(obj_ptr)[0] > 1 && PyArray_DIMS(obj_ptr)[1] > 1)
{
#ifndef NDEBUG
std::cerr << "The number of dimension of the object does not correspond to a vector" << std::endl;
#endif
return 0;
}
if(((PyArray_DIMS(obj_ptr)[0] == 1) && (MatType::ColsAtCompileTime == 1))
|| ((PyArray_DIMS(obj_ptr)[1] == 1) && (MatType::RowsAtCompileTime == 1)))
{
#ifndef NDEBUG
if(MatType::ColsAtCompileTime == 1)
std::cerr << "The object is not a column vector" << std::endl;
else
std::cerr << "The object is not a row vector" << std::endl;
#endif
return 0;
}
}
if (PyArray_NDIM(obj_ptr) != 2)
{
if ( (PyArray_NDIM(obj_ptr) !=1) || (! MatType::IsVectorAtCompileTime) )
{
#ifndef NDEBUG
std::cerr << "The number of dimension of the object is not correct." << std::endl;
#endif
return 0;
}
}
if ((PyArray_ObjectType(reinterpret_cast<PyObject *>(obj_ptr), 0))
!= NumpyEquivalentType<typename MatType::Scalar>::type_code)
{
#ifndef NDEBUG
std::cerr << "The internal type as no Eigen equivalent." << std::endl;
#endif
return 0;
}
#ifdef NPY_1_8_API_VERSION
if (!(PyArray_FLAGS(obj_ptr)))
#else
if (!(PyArray_FLAGS(obj_ptr) & NPY_ALIGNED))
#endif
{
#ifndef NDEBUG
std::cerr << "NPY non-aligned matrices are not implemented." << std::endl;
#endif
return 0;
}
return obj_ptr;
}
// Convert obj_ptr into a Eigenvec
static void construct(PyObject* pyObj,
bp::converter::rvalue_from_python_stage1_data* memory)
{
using namespace Eigen;
PyArrayObject * pyArray = reinterpret_cast<PyArrayObject*>(pyObj);
assert((PyArray_DIMS(pyArray)[0]<INT_MAX) && (PyArray_DIMS(pyArray)[1]<INT_MAX));
void* storage = ((bp::converter::rvalue_from_python_storage<MatType>*)
((void*)memory))->storage.bytes;
EigenObjectAllocator<MatType>::allocate(pyArray,storage);
memory->convertible = storage;
}
};
#define numpy_import_array() {if (_import_array() < 0) {PyErr_Print(); PyErr_SetString(PyExc_ImportError, "numpy.core.multiarray failed to import"); } }
template<typename MatType,typename EigenEquivalentType>
void enableEigenPySpecific()
{
enableEigenPySpecific<MatType>();
}
template<typename MatType>
void enableEigenPySpecific()
{
numpy_import_array();
if(check_registration<MatType>()) return;
bp::to_python_converter<MatType,EigenToPy<MatType> >();
EigenFromPy<MatType>();
}
} // namespace eigenpy
#endif // ifndef __eigenpy_details_hpp__
<commit_msg>[Conversion] Fix bug when converting matrix of dim 1x1<commit_after>/*
* Copyright 2014-2018, Nicolas Mansard and Justin Carpentier, LAAS-CNRS
*
* This file is part of eigenpy.
* eigenpy 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.
* eigenpy 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 eigenpy. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __eigenpy_details_hpp__
#define __eigenpy_details_hpp__
#include "eigenpy/fwd.hpp"
#include <numpy/arrayobject.h>
#include <iostream>
#include "eigenpy/eigenpy.hpp"
#include "eigenpy/registration.hpp"
#include "eigenpy/map.hpp"
namespace eigenpy
{
template <typename SCALAR> struct NumpyEquivalentType {};
template <> struct NumpyEquivalentType<double> { enum { type_code = NPY_DOUBLE };};
template <> struct NumpyEquivalentType<int> { enum { type_code = NPY_INT };};
template <> struct NumpyEquivalentType<float> { enum { type_code = NPY_FLOAT };};
namespace bp = boost::python;
struct PyMatrixType
{
static PyMatrixType & getInstance()
{
static PyMatrixType instance;
return instance;
}
operator bp::object () { return pyMatrixType; }
bp::object make(PyArrayObject* pyArray, bool copy = false)
{ return make((PyObject*)pyArray,copy); }
bp::object make(PyObject* pyObj, bool copy = false)
{
bp::object m
= pyMatrixType(bp::object(bp::handle<>(pyObj)), bp::object(), copy);
Py_INCREF(m.ptr());
return m;
}
protected:
PyMatrixType()
{
pyModule = bp::import("numpy");
pyMatrixType = pyModule.attr("matrix");
}
bp::object pyMatrixType;
bp::object pyModule;
};
template<typename MatType>
struct EigenObjectAllocator
{
typedef MatType Type;
static void allocate(PyArrayObject * pyArray, void * storage)
{
typename MapNumpy<MatType>::EigenMap numpyMap = MapNumpy<MatType>::map(pyArray);
new(storage) MatType(numpyMap);
}
static void convert(Type const & mat , PyArrayObject * pyArray)
{
MapNumpy<MatType>::map(pyArray) = mat;
}
};
#if EIGEN_VERSION_AT_LEAST(3,2,0)
template<typename MatType>
struct EigenObjectAllocator< eigenpy::Ref<MatType> >
{
typedef eigenpy::Ref<MatType> Type;
static void allocate(PyArrayObject * pyArray, void * storage)
{
typename MapNumpy<MatType>::EigenMap numpyMap = MapNumpy<MatType>::map(pyArray);
new(storage) Type(numpyMap);
}
static void convert(Type const & mat , PyArrayObject * pyArray)
{
MapNumpy<MatType>::map(pyArray) = mat;
}
};
#endif
/* --- TO PYTHON -------------------------------------------------------------- */
template<typename MatType>
struct EigenToPy
{
static PyObject* convert(MatType const& mat)
{
typedef typename MatType::Scalar T;
assert( (mat.rows()<INT_MAX) && (mat.cols()<INT_MAX)
&& "Matrix range larger than int ... should never happen." );
const int R = (int)mat.rows(), C = (int)mat.cols();
npy_intp shape[2] = { R,C };
PyArrayObject* pyArray = (PyArrayObject*)
PyArray_SimpleNew(2, shape, NumpyEquivalentType<T>::type_code);
EigenObjectAllocator<MatType>::convert(mat,pyArray);
return PyMatrixType::getInstance().make(pyArray).ptr();
}
};
/* --- FROM PYTHON ------------------------------------------------------------ */
template<typename MatType>
struct EigenFromPy
{
EigenFromPy()
{
bp::converter::registry::push_back
(reinterpret_cast<void *(*)(_object *)>(&convertible),
&construct,bp::type_id<MatType>());
}
// Determine if obj_ptr can be converted in a Eigenvec
static void* convertible(PyArrayObject* obj_ptr)
{
std::cout << "call convertible" << std::endl;
if (!PyArray_Check(obj_ptr))
{
#ifndef NDEBUG
std::cerr << "The python object is not a numpy array." << std::endl;
#endif
return 0;
}
std::cout << "PyArray_DIMS(obj_ptr)[0]: " << PyArray_DIMS(obj_ptr)[0] << std::endl;
std::cout << "PyArray_DIMS(obj_ptr)[1]: " << PyArray_DIMS(obj_ptr)[1] << std::endl;
if(MatType::IsVectorAtCompileTime)
{
// Special care of scalar matrix of dimension 1x1.
if(PyArray_DIMS(obj_ptr)[0] == 1 && PyArray_DIMS(obj_ptr)[1] == 1)
return obj_ptr;
if(PyArray_DIMS(obj_ptr)[0] > 1 && PyArray_DIMS(obj_ptr)[1] > 1)
{
#ifndef NDEBUG
std::cerr << "The number of dimension of the object does not correspond to a vector" << std::endl;
#endif
return 0;
}
if(((PyArray_DIMS(obj_ptr)[0] == 1) && (MatType::ColsAtCompileTime == 1))
|| ((PyArray_DIMS(obj_ptr)[1] == 1) && (MatType::RowsAtCompileTime == 1)))
{
#ifndef NDEBUG
std::cout << "MatType::ColsAtCompileTime: " << MatType::ColsAtCompileTime << std::endl;
if(MatType::ColsAtCompileTime == 1)
std::cerr << "The object is not a column vector" << std::endl;
else
std::cerr << "The object is not a row vector" << std::endl;
#endif
return 0;
}
}
if (PyArray_NDIM(obj_ptr) != 2)
{
if ( (PyArray_NDIM(obj_ptr) !=1) || (! MatType::IsVectorAtCompileTime) )
{
#ifndef NDEBUG
std::cerr << "The number of dimension of the object is not correct." << std::endl;
#endif
return 0;
}
}
if ((PyArray_ObjectType(reinterpret_cast<PyObject *>(obj_ptr), 0))
!= NumpyEquivalentType<typename MatType::Scalar>::type_code)
{
#ifndef NDEBUG
std::cerr << "The internal type as no Eigen equivalent." << std::endl;
#endif
return 0;
}
#ifdef NPY_1_8_API_VERSION
if (!(PyArray_FLAGS(obj_ptr)))
#else
if (!(PyArray_FLAGS(obj_ptr) & NPY_ALIGNED))
#endif
{
#ifndef NDEBUG
std::cerr << "NPY non-aligned matrices are not implemented." << std::endl;
#endif
return 0;
}
return obj_ptr;
}
// Convert obj_ptr into a Eigenvec
static void construct(PyObject* pyObj,
bp::converter::rvalue_from_python_stage1_data* memory)
{
using namespace Eigen;
PyArrayObject * pyArray = reinterpret_cast<PyArrayObject*>(pyObj);
assert((PyArray_DIMS(pyArray)[0]<INT_MAX) && (PyArray_DIMS(pyArray)[1]<INT_MAX));
void* storage = ((bp::converter::rvalue_from_python_storage<MatType>*)
((void*)memory))->storage.bytes;
EigenObjectAllocator<MatType>::allocate(pyArray,storage);
memory->convertible = storage;
}
};
#define numpy_import_array() {if (_import_array() < 0) {PyErr_Print(); PyErr_SetString(PyExc_ImportError, "numpy.core.multiarray failed to import"); } }
template<typename MatType,typename EigenEquivalentType>
void enableEigenPySpecific()
{
enableEigenPySpecific<MatType>();
}
template<typename MatType>
void enableEigenPySpecific()
{
numpy_import_array();
if(check_registration<MatType>()) return;
bp::to_python_converter<MatType,EigenToPy<MatType> >();
EigenFromPy<MatType>();
}
} // namespace eigenpy
#endif // ifndef __eigenpy_details_hpp__
<|endoftext|> |
<commit_before>//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
#include "NXUserDetectorConstruction.hh"
#include "NXUIMessenger.hh"
#include "NXChamberParameterisation.hh"
#include "NXMagneticField.hh"
#include "NXSensitiveDetector.hh"
#include "G4Material.hh"
#include "G4Box.hh"
#include "G4LogicalVolume.hh"
#include "G4PVPlacement.hh"
#include "G4PVParameterised.hh"
#include "G4SDManager.hh"
#include "G4GeometryTolerance.hh"
#include "G4GeometryManager.hh"
#include "G4UserLimits.hh"
#include "G4VisAttributes.hh"
#include "G4Colour.hh"
#include "G4ios.hh"
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
NXUserDetectorConstruction::NXUserDetectorConstruction() :
solidWorld(0), logicWorld(0), physiWorld(0),
solidTarget(0), logicTarget(0), physiTarget(0),
solidTracker(0),logicTracker(0),physiTracker(0),
solidChamber(0),logicChamber(0),physiChamber(0),
TargetMater(0), ChamberMater(0),chamberParam(0),
stepLimit(0), fpMagField(0),
fWorldLength(0.), fTargetLength(0.), fTrackerLength(0.),
NbOfChambers(0) , ChamberWidth(0.), ChamberSpacing(0.)
{
//In NXMagneticField, the constructor does everything. now there is no MagneticField, because there is no G4threevector variable in () and it mean the MagneticField is zero.
fpMagField = new NXMagneticField();
detectorMessenger = new NXUIMessenger(this);
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
NXUserDetectorConstruction::~NXUserDetectorConstruction()
{
delete fpMagField;
delete stepLimit;
delete chamberParam;
delete detectorMessenger;
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
G4VPhysicalVolume* NXUserDetectorConstruction::Construct()
{
//--------- Material definition ---------
G4double a, z;
G4double density, temperature, pressure;
G4int nel;
//Air
G4Element* N = new G4Element("Nitrogen", "N", z=7., a= 14.01*g/mole);
G4Element* O = new G4Element("Oxygen" , "O", z=8., a= 16.00*g/mole);
G4Material* Air = new G4Material("Air", density= 1.29*mg/cm3, nel=2);
Air->AddElement(N, 70*perCent);
Air->AddElement(O, 30*perCent);
//Lead
G4Material* Pb =
new G4Material("Lead", z=82., a= 207.19*g/mole, density= 11.35*g/cm3);
//Xenon gas
G4Material* Xenon =
new G4Material("XenonGas", z=54., a=131.29*g/mole, density= 5.458*mg/cm3,
kStateGas, temperature= 293.15*kelvin, pressure= 1*atmosphere);
// Print all the materials defined.
//
G4cout << G4endl << "The materials defined are : " << G4endl << G4endl;
G4cout << *(G4Material::GetMaterialTable()) << G4endl;
//--------- Sizes of the principal geometrical components (solids) ---------
NbOfChambers = 5;
ChamberWidth = 20*cm;
ChamberSpacing = 80*cm;
fTrackerLength = (NbOfChambers+1)*ChamberSpacing; // Full length of Tracker
fTargetLength = 5.0 * cm; // Full length of Target
TargetMater = Pb;
ChamberMater = Xenon;
fWorldLength= 1.2 *(fTargetLength+fTrackerLength);
G4double targetSize = 0.5*fTargetLength; // Half length of the Target
G4double trackerSize = 0.5*fTrackerLength; // Half length of the Tracker
//--------- Definitions of Solids, Logical Volumes, Physical Volumes ---------
//------------------------------
// World
//------------------------------
G4double HalfWorldLength = 0.5*fWorldLength;
G4GeometryManager::GetInstance()->SetWorldMaximumExtent(fWorldLength);
G4cout << "Computed tolerance = "
<< G4GeometryTolerance::GetInstance()->GetSurfaceTolerance()/mm
<< " mm" << G4endl;
solidWorld= new G4Box("world",HalfWorldLength,HalfWorldLength,HalfWorldLength);
logicWorld= new G4LogicalVolume( solidWorld, Air, "World", 0, 0, 0);
// Must place the World Physical volume unrotated at (0,0,0).
//
physiWorld = new G4PVPlacement(0, // no rotation
G4ThreeVector(), // at (0,0,0)
logicWorld, // its logical volume
"World", // its name
0, // its mother volume
false, // no boolean operations
0); // copy number
//------------------------------
// Target
//------------------------------
G4ThreeVector positionTarget = G4ThreeVector(0,0,-(targetSize+trackerSize));
solidTarget = new G4Box("target",targetSize,targetSize,targetSize);
logicTarget = new G4LogicalVolume(solidTarget,TargetMater,"Target",0,0,0);
physiTarget = new G4PVPlacement(0, // no rotation
positionTarget, // at (x,y,z)
logicTarget, // its logical volume
"Target", // its name
logicWorld, // its mother volume
false, // no boolean operations
0); // copy number
G4cout << "Target is " << fTargetLength/cm << " cm of "
<< TargetMater->GetName() << G4endl;
//------------------------------
// Tracker
//------------------------------
G4ThreeVector positionTracker = G4ThreeVector(0,0,0);
solidTracker = new G4Box("tracker",trackerSize,trackerSize,trackerSize);
logicTracker = new G4LogicalVolume(solidTracker , Air, "Tracker",0,0,0);
physiTracker = new G4PVPlacement(0, // no rotation
positionTracker, // at (x,y,z)
logicTracker, // its logical volume
"Tracker", // its name
logicWorld, // its mother volume
false, // no boolean operations
0); // copy number
//------------------------------
// Tracker segments
//------------------------------
//
// An example of Parameterised volumes
// dummy values for G4Box -- modified by parameterised volume
solidChamber = new G4Box("chamber", 100*cm, 100*cm, 10*cm);
logicChamber = new G4LogicalVolume(solidChamber,ChamberMater,"Chamber",0,0,0);
G4double firstPosition = -trackerSize + 0.5*ChamberWidth;
G4double firstLength = fTrackerLength/10;
G4double lastLength = fTrackerLength;
chamberParam = new NXChamberParameterisation(
NbOfChambers, // NoChambers
firstPosition, // Z of center of first
ChamberSpacing, // Z spacing of centers
ChamberWidth, // Width Chamber
firstLength, // lengthInitial
lastLength); // lengthFinal
// dummy value : kZAxis -- modified by parameterised volume
//
physiChamber = new G4PVParameterised(
"Chamber", // their name
logicChamber, // their logical volume
logicTracker, // Mother logical volume
kZAxis, // Are placed along this axis
NbOfChambers, // Number of chambers
chamberParam); // The parametrisation
G4cout << "There are " << NbOfChambers << " chambers in the tracker region. "
<< "The chambers are " << ChamberWidth/mm << " mm of "
<< ChamberMater->GetName() << "\n The distance between chamber is "
<< ChamberSpacing/cm << " cm" << G4endl;
//------------------------------------------------
// Sensitive detectors
//------------------------------------------------
G4SDManager* SDman = G4SDManager::GetSDMpointer();
G4String trackerChamberSDname = "ExN02/TrackerChamberSD";
NXSensitiveDetector* aTrackerSD = new NXSensitiveDetector( trackerChamberSDname );
SDman->AddNewDetector( aTrackerSD );
logicChamber->SetSensitiveDetector( aTrackerSD );
//--------- Visualization attributes -------------------------------
G4VisAttributes* BoxVisAtt= new G4VisAttributes(G4Colour(1.0,1.0,1.0));
logicWorld ->SetVisAttributes(BoxVisAtt);
logicTarget ->SetVisAttributes(BoxVisAtt);
logicTracker->SetVisAttributes(BoxVisAtt);
G4VisAttributes* ChamberVisAtt = new G4VisAttributes(G4Colour(1.0,1.0,0.0));
logicChamber->SetVisAttributes(ChamberVisAtt);
//--------- example of User Limits -------------------------------
// below is an example of how to set tracking constraints in a given
// logical volume(see also in NXPhysicsList how to setup the processes
// G4StepLimiter or G4UserSpecialCuts).
// Sets a max Step length in the tracker region, with G4StepLimiter
//
G4double maxStep = 0.5*ChamberWidth;
stepLimit = new G4UserLimits(maxStep);
logicTracker->SetUserLimits(stepLimit);
// Set additional contraints on the track, with G4UserSpecialCuts
//
// G4double maxLength = 2*fTrackerLength, maxTime = 0.1*ns, minEkin = 10*MeV;
// logicTracker->SetUserLimits(new G4UserLimits(maxStep,maxLength,maxTime,
// minEkin));
return physiWorld;
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void NXUserDetectorConstruction::setTargetMaterial(G4String materialName)
{
// search the material by its name
G4Material* pttoMaterial = G4Material::GetMaterial(materialName);
if (pttoMaterial)
{TargetMater = pttoMaterial;
logicTarget->SetMaterial(pttoMaterial);
G4cout << "\n----> The target is " << fTargetLength/cm << " cm of "
<< materialName << G4endl;
}
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void NXUserDetectorConstruction::setChamberMaterial(G4String materialName)
{
// search the material by its name
G4Material* pttoMaterial = G4Material::GetMaterial(materialName);
if (pttoMaterial)
{ChamberMater = pttoMaterial;
logicChamber->SetMaterial(pttoMaterial);
G4cout << "\n----> The chambers are " << ChamberWidth/cm << " cm of "
<< materialName << G4endl;
}
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void NXUserDetectorConstruction::SetMagField(G4double fieldValue)
{
fpMagField->SetFieldValue(fieldValue);
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void NXUserDetectorConstruction::SetMaxStep(G4double maxStep)
{
if ((stepLimit)&&(maxStep>0.)) stepLimit->SetMaxAllowedStep(maxStep);
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
<commit_msg>use NIST material database instead of build material by myself.<commit_after>//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
#include "NXUserDetectorConstruction.hh"
#include "NXUIMessenger.hh"
#include "NXChamberParameterisation.hh"
#include "NXMagneticField.hh"
#include "NXSensitiveDetector.hh"
#include "G4Material.hh"
#include "G4Box.hh"
#include "G4LogicalVolume.hh"
#include "G4PVPlacement.hh"
#include "G4PVParameterised.hh"
#include "G4SDManager.hh"
#include "G4GeometryTolerance.hh"
#include "G4GeometryManager.hh"
#include "G4UserLimits.hh"
#include "G4VisAttributes.hh"
#include "G4Colour.hh"
#include "G4ios.hh"
#include "G4NistManager.hh"
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
NXUserDetectorConstruction::NXUserDetectorConstruction() :
solidWorld(0), logicWorld(0), physiWorld(0),
solidTarget(0), logicTarget(0), physiTarget(0),
solidTracker(0),logicTracker(0),physiTracker(0),
solidChamber(0),logicChamber(0),physiChamber(0),
TargetMater(0), ChamberMater(0),chamberParam(0),
stepLimit(0), fpMagField(0),
fWorldLength(0.), fTargetLength(0.), fTrackerLength(0.),
NbOfChambers(0) , ChamberWidth(0.), ChamberSpacing(0.)
{
//In NXMagneticField, the constructor does everything. now there is no MagneticField, because there is no G4threevector variable in () and it mean the MagneticField is zero.
fpMagField = new NXMagneticField();
detectorMessenger = new NXUIMessenger(this);
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
NXUserDetectorConstruction::~NXUserDetectorConstruction()
{
delete fpMagField;
delete stepLimit;
delete chamberParam;
delete detectorMessenger;
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
G4VPhysicalVolume* NXUserDetectorConstruction::Construct()
{
//--------- Material definition ---------
G4double a, z;
G4double density, temperature, pressure;
G4int nel;
//Air
G4Element* N = new G4Element("Nitrogen", "N", z=7., a= 14.01*g/mole);
G4Element* O = new G4Element("Oxygen" , "O", z=8., a= 16.00*g/mole);
G4Material* Air = new G4Material("Air", density= 1.29*mg/cm3, nel=2);
Air->AddElement(N, 70*perCent);
Air->AddElement(O, 30*perCent);
//Lead
G4Material* Pb =
new G4Material("Lead", z=82., a= 207.19*g/mole, density= 11.35*g/cm3);
//Xenon gas
G4Material* Xenon =
new G4Material("XenonGas", z=54., a=131.29*g/mole, density= 5.458*mg/cm3,
kStateGas, temperature= 293.15*kelvin, pressure= 1*atmosphere);
G4NistManager* man=G4NistManager::Instance();
G4Material* PMMANist=man->FindOrBuildMaterial("G4_PLEXIGLASS");
G4Material* Fe=man->FindOrBuildMaterial("G4_Fe");
G4Material* Ta=man->FindOrBuildMaterial("G4_Ta");
// Print all the materials defined.
//
G4cout << G4endl << "The materials defined are : " << G4endl << G4endl;
G4cout << *(G4Material::GetMaterialTable()) << G4endl;
//--------- Sizes of the principal geometrical components (solids) ---------
NbOfChambers = 5;
ChamberWidth = 20*cm;
ChamberSpacing = 80*cm;
fTrackerLength = (NbOfChambers+1)*ChamberSpacing; // Full length of Tracker
fTargetLength = 5.0 * cm; // Full length of Target
TargetMater = Pb;
ChamberMater = Xenon;
fWorldLength= 1.2 *(fTargetLength+fTrackerLength);
G4double targetSize = 0.5*fTargetLength; // Half length of the Target
G4double trackerSize = 0.5*fTrackerLength; // Half length of the Tracker
//--------- Definitions of Solids, Logical Volumes, Physical Volumes ---------
//------------------------------
// World
//------------------------------
G4double HalfWorldLength = 0.5*fWorldLength;
G4GeometryManager::GetInstance()->SetWorldMaximumExtent(fWorldLength);
G4cout << "Computed tolerance = "
<< G4GeometryTolerance::GetInstance()->GetSurfaceTolerance()/mm
<< " mm" << G4endl;
solidWorld= new G4Box("world",HalfWorldLength,HalfWorldLength,HalfWorldLength);
logicWorld= new G4LogicalVolume( solidWorld, Air, "World", 0, 0, 0);
// Must place the World Physical volume unrotated at (0,0,0).
//
physiWorld = new G4PVPlacement(0, // no rotation
G4ThreeVector(), // at (0,0,0)
logicWorld, // its logical volume
"World", // its name
0, // its mother volume
false, // no boolean operations
0); // copy number
//------------------------------
// Target
//------------------------------
G4ThreeVector positionTarget = G4ThreeVector(0,0,-(targetSize+trackerSize));
solidTarget = new G4Box("target",targetSize,targetSize,targetSize);
logicTarget = new G4LogicalVolume(solidTarget,TargetMater,"Target",0,0,0);
physiTarget = new G4PVPlacement(0, // no rotation
positionTarget, // at (x,y,z)
logicTarget, // its logical volume
"Target", // its name
logicWorld, // its mother volume
false, // no boolean operations
0); // copy number
G4cout << "Target is " << fTargetLength/cm << " cm of "
<< TargetMater->GetName() << G4endl;
//------------------------------
// Tracker
//------------------------------
G4ThreeVector positionTracker = G4ThreeVector(0,0,0);
solidTracker = new G4Box("tracker",trackerSize,trackerSize,trackerSize);
logicTracker = new G4LogicalVolume(solidTracker , Air, "Tracker",0,0,0);
physiTracker = new G4PVPlacement(0, // no rotation
positionTracker, // at (x,y,z)
logicTracker, // its logical volume
"Tracker", // its name
logicWorld, // its mother volume
false, // no boolean operations
0); // copy number
//------------------------------
// Tracker segments
//------------------------------
//
// An example of Parameterised volumes
// dummy values for G4Box -- modified by parameterised volume
solidChamber = new G4Box("chamber", 100*cm, 100*cm, 10*cm);
logicChamber = new G4LogicalVolume(solidChamber,ChamberMater,"Chamber",0,0,0);
G4double firstPosition = -trackerSize + 0.5*ChamberWidth;
G4double firstLength = fTrackerLength/10;
G4double lastLength = fTrackerLength;
chamberParam = new NXChamberParameterisation(
NbOfChambers, // NoChambers
firstPosition, // Z of center of first
ChamberSpacing, // Z spacing of centers
ChamberWidth, // Width Chamber
firstLength, // lengthInitial
lastLength); // lengthFinal
// dummy value : kZAxis -- modified by parameterised volume
//
physiChamber = new G4PVParameterised(
"Chamber", // their name
logicChamber, // their logical volume
logicTracker, // Mother logical volume
kZAxis, // Are placed along this axis
NbOfChambers, // Number of chambers
chamberParam); // The parametrisation
G4cout << "There are " << NbOfChambers << " chambers in the tracker region. "
<< "The chambers are " << ChamberWidth/mm << " mm of "
<< ChamberMater->GetName() << "\n The distance between chamber is "
<< ChamberSpacing/cm << " cm" << G4endl;
//------------------------------------------------
// Sensitive detectors
//------------------------------------------------
G4SDManager* SDman = G4SDManager::GetSDMpointer();
G4String trackerChamberSDname = "ExN02/TrackerChamberSD";
NXSensitiveDetector* aTrackerSD = new NXSensitiveDetector( trackerChamberSDname );
SDman->AddNewDetector( aTrackerSD );
logicChamber->SetSensitiveDetector( aTrackerSD );
//--------- Visualization attributes -------------------------------
G4VisAttributes* BoxVisAtt= new G4VisAttributes(G4Colour(1.0,1.0,1.0));
logicWorld ->SetVisAttributes(BoxVisAtt);
logicTarget ->SetVisAttributes(BoxVisAtt);
logicTracker->SetVisAttributes(BoxVisAtt);
G4VisAttributes* ChamberVisAtt = new G4VisAttributes(G4Colour(1.0,1.0,0.0));
logicChamber->SetVisAttributes(ChamberVisAtt);
//--------- example of User Limits -------------------------------
// below is an example of how to set tracking constraints in a given
// logical volume(see also in NXPhysicsList how to setup the processes
// G4StepLimiter or G4UserSpecialCuts).
// Sets a max Step length in the tracker region, with G4StepLimiter
//
G4double maxStep = 0.5*ChamberWidth;
stepLimit = new G4UserLimits(maxStep);
logicTracker->SetUserLimits(stepLimit);
// Set additional contraints on the track, with G4UserSpecialCuts
//
// G4double maxLength = 2*fTrackerLength, maxTime = 0.1*ns, minEkin = 10*MeV;
// logicTracker->SetUserLimits(new G4UserLimits(maxStep,maxLength,maxTime,
// minEkin));
return physiWorld;
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void NXUserDetectorConstruction::setTargetMaterial(G4String materialName)
{
// search the material by its name
G4Material* pttoMaterial = G4Material::GetMaterial(materialName);
if (pttoMaterial)
{TargetMater = pttoMaterial;
logicTarget->SetMaterial(pttoMaterial);
G4cout << "\n----> The target is " << fTargetLength/cm << " cm of "
<< materialName << G4endl;
}
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void NXUserDetectorConstruction::setChamberMaterial(G4String materialName)
{
// search the material by its name
G4Material* pttoMaterial = G4Material::GetMaterial(materialName);
if (pttoMaterial)
{ChamberMater = pttoMaterial;
logicChamber->SetMaterial(pttoMaterial);
G4cout << "\n----> The chambers are " << ChamberWidth/cm << " cm of "
<< materialName << G4endl;
}
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void NXUserDetectorConstruction::SetMagField(G4double fieldValue)
{
fpMagField->SetFieldValue(fieldValue);
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void NXUserDetectorConstruction::SetMaxStep(G4double maxStep)
{
if ((stepLimit)&&(maxStep>0.)) stepLimit->SetMaxAllowedStep(maxStep);
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2007 Tommi Maekitalo
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* As a special exception, you may use this file as part of a free
* software library without restriction. Specifically, if other files
* instantiate templates or use macros or inline functions from this
* file, or you compile this file and link it with other files to
* produce an executable, this file does not by itself cause the
* resulting executable to be covered by the GNU General Public
* License. This exception does not however invalidate any other
* reasons why the executable file might be covered by the GNU Library
* General Public License.
*
* 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 <tntdb/oracle/value.h>
#include <tntdb/oracle/statement.h>
#include <tntdb/error.h>
#include <tntdb/decimal.h>
#include <sstream>
#include <cxxtools/log.h>
log_define("tntdb.oracle.value")
namespace tntdb
{
namespace oracle
{
namespace
{
template <typename T>
T getValue(const std::string& s, const char* tname)
{
std::istringstream in(s);
T ret;
in >> ret;
if (!in)
{
std::ostringstream msg;
msg << "can't convert \"" << s << "\" to " << tname;
throw TypeError(msg.str());
}
return ret;
}
template <typename T>
std::string toString(T v)
{
std::ostringstream ret;
ret << v;
return ret.str();
}
template <>
std::string toString(float v)
{
std::ostringstream ret;
ret.precision(24);
ret << v;
return ret.str();
}
template <>
std::string toString(double v)
{
std::ostringstream ret;
ret.precision(24);
ret << v;
return ret.str();
}
template <>
std::string toString(Decimal v)
{
std::ostringstream ret;
ret.precision(24);
ret << v;
return ret.str();
}
}
Value::Value(Statement* stmt, ub4 pos)
{
sword ret;
/* get parameter-info */
ret = OCIParamGet(stmt->getHandle(), OCI_HTYPE_STMT,
stmt->getErrorHandle(),
reinterpret_cast<void**>(¶mp), pos + 1);
stmt->checkError(ret, "OCIParamGet");
init(stmt, paramp, pos);
OCIDescriptorFree(paramp, OCI_DTYPE_PARAM);
paramp = 0;
}
Value::Value(Statement* stmt, OCIParam* paramp, ub4 pos)
{
init(stmt, paramp, pos);
}
void Value::init(Statement* stmt, OCIParam* paramp, ub4 pos)
{
sword ret;
/* retrieve column name */
ub4 col_name_len = 0;
text* col_name = 0;
ret = OCIAttrGet(paramp, OCI_DTYPE_PARAM, &col_name, &col_name_len,
OCI_ATTR_NAME, stmt->getErrorHandle());
stmt->checkError(ret, "OCIAttrGet(OCI_ATTR_NAME)");
colName.assign(reinterpret_cast<const char*>(col_name), col_name_len);
/* retrieve the data type attribute */
ret = OCIAttrGet(paramp, OCI_DTYPE_PARAM, &type, 0, OCI_ATTR_DATA_TYPE,
stmt->getErrorHandle());
stmt->checkError(ret, "OCIAttrGet(OCI_ATTR_DATA_TYPE)");
ret = OCIAttrGet(paramp, OCI_DTYPE_PARAM, &len, 0, OCI_ATTR_DATA_SIZE,
stmt->getErrorHandle());
stmt->checkError(ret, "OCIAttrGet(OCI_ATTR_DATA_SIZE)");
log_debug("column name=\"" << colName << "\" type=" << type << " size=" << len);
/* define outputvariable */
switch (type)
{
case SQLT_DAT:
case SQLT_TIMESTAMP:
case SQLT_TIMESTAMP_TZ:
case SQLT_TIMESTAMP_LTZ:
log_debug("OCIDefineByPos(SQLT_TIMESTAMP)");
ret = OCIDefineByPos(stmt->getHandle(), &defp,
stmt->getErrorHandle(), pos + 1, &datetime.getReference(stmt->getConnection()),
sizeof(OCIDateTime*), SQLT_TIMESTAMP, &nullind, &len, 0, OCI_DEFAULT);
break;
case SQLT_INT:
log_debug("OCIDefineByPos(SQLT_INT)");
ret = OCIDefineByPos(stmt->getHandle(), &defp,
stmt->getErrorHandle(), pos + 1, &longValue,
sizeof(longValue), SQLT_INT, &nullind, &len, 0, OCI_DEFAULT);
break;
case SQLT_UIN:
log_debug("OCIDefineByPos(SQLT_UIN)");
ret = OCIDefineByPos(stmt->getHandle(), &defp,
stmt->getErrorHandle(), pos + 1, &uint32Value,
sizeof(uint32Value), SQLT_UIN, &nullind, &len, 0, OCI_DEFAULT);
break;
case SQLT_FLT:
log_debug("OCIDefineByPos(SQLT_FLT)");
ret = OCIDefineByPos(stmt->getHandle(), &defp,
stmt->getErrorHandle(), pos + 1, &doubleValue,
sizeof(doubleValue), SQLT_FLT, &nullind, &len, 0, OCI_DEFAULT);
break;
case SQLT_NUM:
case SQLT_VNU:
log_debug("OCIDefineByPos(SQLT_VNU)");
ret = OCIDefineByPos(stmt->getHandle(), &defp,
stmt->getErrorHandle(), pos + 1, number.getHandle(),
OCI_NUMBER_SIZE, SQLT_VNU, &nullind, &len, 0, OCI_DEFAULT);
break;
case SQLT_BLOB:
log_debug("OCIDefineByPos(SQLT_LOB)");
ret = OCIDefineByPos(stmt->getHandle(), &defp,
stmt->getErrorHandle(), pos + 1, &blob.getHandle(stmt->getConnection()),
0, SQLT_BLOB, &nullind, &len, 0, OCI_DEFAULT);
break;
default:
log_debug("OCIDefineByPos(SQLT_AFC)");
data.reserve(len + 16);
ret = OCIDefineByPos(stmt->getHandle(), &defp,
stmt->getErrorHandle(), pos + 1, data.data(),
len + 16, SQLT_AFC, &nullind, &len, 0, OCI_DEFAULT);
break;
}
stmt->checkError(ret, "OCIDefineByPos");
}
Value::~Value()
{
if (defp)
OCIHandleFree(defp, OCI_HTYPE_DEFINE);
if (paramp)
OCIDescriptorFree(paramp, OCI_DTYPE_PARAM);
}
bool Value::isNull() const
{
return nullind != 0;
}
bool Value::getBool() const
{
if (isNull())
throw NullValue();
switch (type)
{
case SQLT_DAT:
case SQLT_TIMESTAMP:
case SQLT_TIMESTAMP_TZ:
case SQLT_TIMESTAMP_LTZ:
throw TypeError();
case SQLT_INT:
return longValue != 0;
case SQLT_UIN:
return uint32Value != 0;
case SQLT_FLT:
return doubleValue != 0;
case SQLT_NUM:
case SQLT_VNU:
return !number.getDecimal().isZero();
default:
return data[0] == 't' || data[0] == 'T'
|| data[0] == 'y' || data[0] == 'Y'
|| data[0] == '1';
}
}
int Value::getInt() const
{
if (isNull())
throw NullValue();
switch (type)
{
case SQLT_DAT:
case SQLT_TIMESTAMP:
case SQLT_TIMESTAMP_TZ:
case SQLT_TIMESTAMP_LTZ:
throw TypeError();
case SQLT_INT:
case SQLT_UIN:
return static_cast<int>(longValue);
case SQLT_FLT:
return static_cast<int>(doubleValue);
case SQLT_NUM:
case SQLT_VNU:
return number.getDecimal().getInt();
default:
return getValue<int>(data.data(), "int");
}
}
int32_t Value::getInt32() const
{
return getInt();
}
unsigned Value::getUnsigned() const
{
if (isNull())
throw NullValue();
switch (type)
{
case SQLT_DAT:
case SQLT_TIMESTAMP:
case SQLT_TIMESTAMP_TZ:
case SQLT_TIMESTAMP_LTZ:
throw TypeError();
case SQLT_INT:
case SQLT_UIN:
return static_cast<unsigned>(longValue);
case SQLT_FLT:
return static_cast<unsigned>(doubleValue);
case SQLT_NUM:
case SQLT_VNU:
return number.getDecimal().getUnsigned();
default:
return getValue<unsigned>(data.data(), "unsigned");
}
}
uint32_t Value::getUnsigned32() const
{
return getUnsigned();
}
int64_t Value::getInt64() const
{
if (isNull())
throw NullValue();
switch (type)
{
case SQLT_DAT:
case SQLT_TIMESTAMP:
case SQLT_TIMESTAMP_TZ:
case SQLT_TIMESTAMP_LTZ:
throw TypeError();
case SQLT_INT:
case SQLT_UIN:
return static_cast<int64_t>(longValue);
case SQLT_FLT:
return static_cast<int64_t>(doubleValue);
case SQLT_NUM:
case SQLT_VNU:
return number.getDecimal().getInt64();
default:
return getValue<int64_t>(data.data(), "int");
}
}
uint64_t Value::getUnsigned64() const
{
if (isNull())
throw NullValue();
switch (type)
{
case SQLT_DAT:
case SQLT_TIMESTAMP:
case SQLT_TIMESTAMP_TZ:
case SQLT_TIMESTAMP_LTZ:
throw TypeError();
case SQLT_INT:
case SQLT_UIN:
return static_cast<uint64_t>(longValue);
case SQLT_FLT:
return static_cast<uint64_t>(doubleValue);
case SQLT_NUM:
case SQLT_VNU:
return number.getDecimal().getUnsigned64();
default:
return getValue<uint64_t>(data.data(), "int");
}
}
Decimal Value::getDecimal() const
{
if (isNull())
throw NullValue();
switch (type)
{
case SQLT_DAT:
case SQLT_TIMESTAMP:
case SQLT_TIMESTAMP_TZ:
case SQLT_TIMESTAMP_LTZ:
throw TypeError();
case SQLT_INT:
case SQLT_UIN:
{
Decimal decimal;
decimal.setInt(longValue);
return decimal;
}
case SQLT_FLT:
{
Decimal decimal;
decimal.setDouble(doubleValue);
return decimal;
}
case SQLT_NUM:
case SQLT_VNU:
return number.getDecimal();
default:
return getValue<Decimal>(data.data(), "Decimal");
}
}
float Value::getFloat() const
{
if (isNull())
throw NullValue();
switch (type)
{
case SQLT_DAT:
case SQLT_TIMESTAMP:
case SQLT_TIMESTAMP_TZ:
case SQLT_TIMESTAMP_LTZ:
throw TypeError();
case SQLT_INT:
case SQLT_UIN:
return static_cast<float>(longValue);
case SQLT_FLT:
return static_cast<float>(doubleValue);
case SQLT_NUM:
case SQLT_VNU:
return number.getDecimal().getFloat();
default:
return getValue<float>(data.data(), "float");
}
}
double Value::getDouble() const
{
if (isNull())
throw NullValue();
switch (type)
{
case SQLT_DAT:
case SQLT_TIMESTAMP:
case SQLT_TIMESTAMP_TZ:
case SQLT_TIMESTAMP_LTZ:
throw TypeError();
case SQLT_INT:
case SQLT_UIN:
return static_cast<double>(longValue);
case SQLT_FLT:
return static_cast<double>(doubleValue);
case SQLT_NUM:
case SQLT_VNU:
return number.getDecimal().getDouble();
default:
return getValue<double>(data.data(), "double");
}
}
char Value::getChar() const
{
if (isNull())
throw NullValue();
switch (type)
{
case SQLT_DAT:
case SQLT_TIMESTAMP:
case SQLT_TIMESTAMP_TZ:
case SQLT_TIMESTAMP_LTZ:
throw TypeError();
case SQLT_INT:
case SQLT_UIN:
return static_cast<char>(longValue);
case SQLT_FLT:
return static_cast<char>(doubleValue);
case SQLT_NUM:
case SQLT_VNU:
return static_cast<char>(number.getDecimal().getInt());
default:
return *data.data();
}
}
void Value::getString(std::string& ret) const
{
log_debug("Value::getString with type=" << type << " name=" << colName
<< " size=" << len);
if (isNull())
throw NullValue();
switch (type)
{
case SQLT_DAT:
case SQLT_TIMESTAMP:
case SQLT_TIMESTAMP_TZ:
case SQLT_TIMESTAMP_LTZ:
ret = datetime.getDatetime().getIso();
break;
case SQLT_INT:
case SQLT_UIN:
ret = toString(longValue);
break;
case SQLT_FLT:
ret = toString(doubleValue);
break;
case SQLT_NUM:
case SQLT_VNU:
ret = number.getDecimal().toString();
break;
default:
ret.assign(data.data(), len > 0 ? len : 0);
}
}
void Value::getBlob(tntdb::Blob& ret) const
{
log_debug("get blob from type " << type);
if (isNull())
throw NullValue();
switch (type)
{
case SQLT_DAT:
case SQLT_TIMESTAMP:
case SQLT_TIMESTAMP_TZ:
case SQLT_TIMESTAMP_LTZ:
case SQLT_INT:
case SQLT_UIN:
case SQLT_FLT:
case SQLT_NUM:
case SQLT_VNU:
throw TypeError();
case SQLT_BLOB:
blob.getData(ret);
break;
default:
ret.assign(data.data(), len > 0 ? len - 1 : 0);
}
}
Date Value::getDate() const
{
if (isNull())
throw NullValue();
switch (type)
{
case SQLT_DAT:
case SQLT_TIMESTAMP:
case SQLT_TIMESTAMP_TZ:
case SQLT_TIMESTAMP_LTZ:
return datetime.getDate();
default:
throw TypeError();
}
}
Time Value::getTime() const
{
if (isNull())
throw NullValue();
switch (type)
{
case SQLT_DAT:
case SQLT_TIMESTAMP:
case SQLT_TIMESTAMP_TZ:
case SQLT_TIMESTAMP_LTZ:
return datetime.getTime();
default:
throw TypeError();
}
}
tntdb::Datetime Value::getDatetime() const
{
if (isNull())
throw NullValue();
switch (type)
{
case SQLT_DAT:
case SQLT_TIMESTAMP:
case SQLT_TIMESTAMP_TZ:
case SQLT_TIMESTAMP_LTZ:
return datetime.getDatetime();
default:
throw TypeError();
}
}
}
}
<commit_msg>fix sporadic error in string to number conversion in oracle driver<commit_after>/*
* Copyright (C) 2007 Tommi Maekitalo
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* As a special exception, you may use this file as part of a free
* software library without restriction. Specifically, if other files
* instantiate templates or use macros or inline functions from this
* file, or you compile this file and link it with other files to
* produce an executable, this file does not by itself cause the
* resulting executable to be covered by the GNU General Public
* License. This exception does not however invalidate any other
* reasons why the executable file might be covered by the GNU Library
* General Public License.
*
* 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 <tntdb/oracle/value.h>
#include <tntdb/oracle/statement.h>
#include <tntdb/error.h>
#include <tntdb/decimal.h>
#include <sstream>
#include <cxxtools/log.h>
log_define("tntdb.oracle.value")
namespace tntdb
{
namespace oracle
{
namespace
{
template <typename T>
T getValue(const std::string& s, const char* tname)
{
std::istringstream in(s);
T ret;
in >> ret;
if (!in)
{
std::ostringstream msg;
msg << "can't convert \"" << s << "\" to " << tname;
throw TypeError(msg.str());
}
return ret;
}
template <typename T>
std::string toString(T v)
{
std::ostringstream ret;
ret << v;
return ret.str();
}
template <>
std::string toString(float v)
{
std::ostringstream ret;
ret.precision(24);
ret << v;
return ret.str();
}
template <>
std::string toString(double v)
{
std::ostringstream ret;
ret.precision(24);
ret << v;
return ret.str();
}
template <>
std::string toString(Decimal v)
{
std::ostringstream ret;
ret.precision(24);
ret << v;
return ret.str();
}
}
Value::Value(Statement* stmt, ub4 pos)
{
sword ret;
/* get parameter-info */
ret = OCIParamGet(stmt->getHandle(), OCI_HTYPE_STMT,
stmt->getErrorHandle(),
reinterpret_cast<void**>(¶mp), pos + 1);
stmt->checkError(ret, "OCIParamGet");
init(stmt, paramp, pos);
OCIDescriptorFree(paramp, OCI_DTYPE_PARAM);
paramp = 0;
}
Value::Value(Statement* stmt, OCIParam* paramp, ub4 pos)
{
init(stmt, paramp, pos);
}
void Value::init(Statement* stmt, OCIParam* paramp, ub4 pos)
{
sword ret;
/* retrieve column name */
ub4 col_name_len = 0;
text* col_name = 0;
ret = OCIAttrGet(paramp, OCI_DTYPE_PARAM, &col_name, &col_name_len,
OCI_ATTR_NAME, stmt->getErrorHandle());
stmt->checkError(ret, "OCIAttrGet(OCI_ATTR_NAME)");
colName.assign(reinterpret_cast<const char*>(col_name), col_name_len);
/* retrieve the data type attribute */
ret = OCIAttrGet(paramp, OCI_DTYPE_PARAM, &type, 0, OCI_ATTR_DATA_TYPE,
stmt->getErrorHandle());
stmt->checkError(ret, "OCIAttrGet(OCI_ATTR_DATA_TYPE)");
ret = OCIAttrGet(paramp, OCI_DTYPE_PARAM, &len, 0, OCI_ATTR_DATA_SIZE,
stmt->getErrorHandle());
stmt->checkError(ret, "OCIAttrGet(OCI_ATTR_DATA_SIZE)");
log_debug("column name=\"" << colName << "\" type=" << type << " size=" << len);
/* define outputvariable */
switch (type)
{
case SQLT_DAT:
case SQLT_TIMESTAMP:
case SQLT_TIMESTAMP_TZ:
case SQLT_TIMESTAMP_LTZ:
log_debug("OCIDefineByPos(SQLT_TIMESTAMP)");
ret = OCIDefineByPos(stmt->getHandle(), &defp,
stmt->getErrorHandle(), pos + 1, &datetime.getReference(stmt->getConnection()),
sizeof(OCIDateTime*), SQLT_TIMESTAMP, &nullind, &len, 0, OCI_DEFAULT);
break;
case SQLT_INT:
log_debug("OCIDefineByPos(SQLT_INT)");
ret = OCIDefineByPos(stmt->getHandle(), &defp,
stmt->getErrorHandle(), pos + 1, &longValue,
sizeof(longValue), SQLT_INT, &nullind, &len, 0, OCI_DEFAULT);
break;
case SQLT_UIN:
log_debug("OCIDefineByPos(SQLT_UIN)");
ret = OCIDefineByPos(stmt->getHandle(), &defp,
stmt->getErrorHandle(), pos + 1, &uint32Value,
sizeof(uint32Value), SQLT_UIN, &nullind, &len, 0, OCI_DEFAULT);
break;
case SQLT_FLT:
log_debug("OCIDefineByPos(SQLT_FLT)");
ret = OCIDefineByPos(stmt->getHandle(), &defp,
stmt->getErrorHandle(), pos + 1, &doubleValue,
sizeof(doubleValue), SQLT_FLT, &nullind, &len, 0, OCI_DEFAULT);
break;
case SQLT_NUM:
case SQLT_VNU:
log_debug("OCIDefineByPos(SQLT_VNU)");
ret = OCIDefineByPos(stmt->getHandle(), &defp,
stmt->getErrorHandle(), pos + 1, number.getHandle(),
OCI_NUMBER_SIZE, SQLT_VNU, &nullind, &len, 0, OCI_DEFAULT);
break;
case SQLT_BLOB:
log_debug("OCIDefineByPos(SQLT_LOB)");
ret = OCIDefineByPos(stmt->getHandle(), &defp,
stmt->getErrorHandle(), pos + 1, &blob.getHandle(stmt->getConnection()),
0, SQLT_BLOB, &nullind, &len, 0, OCI_DEFAULT);
break;
default:
log_debug("OCIDefineByPos(SQLT_AFC)");
data.reserve(len + 16);
ret = OCIDefineByPos(stmt->getHandle(), &defp,
stmt->getErrorHandle(), pos + 1, data.data(),
len + 16, SQLT_AFC, &nullind, &len, 0, OCI_DEFAULT);
break;
}
stmt->checkError(ret, "OCIDefineByPos");
}
Value::~Value()
{
if (defp)
OCIHandleFree(defp, OCI_HTYPE_DEFINE);
if (paramp)
OCIDescriptorFree(paramp, OCI_DTYPE_PARAM);
}
bool Value::isNull() const
{
return nullind != 0;
}
bool Value::getBool() const
{
if (isNull())
throw NullValue();
switch (type)
{
case SQLT_DAT:
case SQLT_TIMESTAMP:
case SQLT_TIMESTAMP_TZ:
case SQLT_TIMESTAMP_LTZ:
throw TypeError();
case SQLT_INT:
return longValue != 0;
case SQLT_UIN:
return uint32Value != 0;
case SQLT_FLT:
return doubleValue != 0;
case SQLT_NUM:
case SQLT_VNU:
return !number.getDecimal().isZero();
default:
return data[0] == 't' || data[0] == 'T'
|| data[0] == 'y' || data[0] == 'Y'
|| data[0] == '1';
}
}
int Value::getInt() const
{
if (isNull())
throw NullValue();
switch (type)
{
case SQLT_DAT:
case SQLT_TIMESTAMP:
case SQLT_TIMESTAMP_TZ:
case SQLT_TIMESTAMP_LTZ:
throw TypeError();
case SQLT_INT:
case SQLT_UIN:
return static_cast<int>(longValue);
case SQLT_FLT:
return static_cast<int>(doubleValue);
case SQLT_NUM:
case SQLT_VNU:
return number.getDecimal().getInt();
default:
return getValue<int>(std::string(data.data(), len), "int");
}
}
int32_t Value::getInt32() const
{
return getInt();
}
unsigned Value::getUnsigned() const
{
if (isNull())
throw NullValue();
switch (type)
{
case SQLT_DAT:
case SQLT_TIMESTAMP:
case SQLT_TIMESTAMP_TZ:
case SQLT_TIMESTAMP_LTZ:
throw TypeError();
case SQLT_INT:
case SQLT_UIN:
return static_cast<unsigned>(longValue);
case SQLT_FLT:
return static_cast<unsigned>(doubleValue);
case SQLT_NUM:
case SQLT_VNU:
return number.getDecimal().getUnsigned();
default:
return getValue<unsigned>(std::string(data.data(), len), "unsigned");
}
}
uint32_t Value::getUnsigned32() const
{
return getUnsigned();
}
int64_t Value::getInt64() const
{
if (isNull())
throw NullValue();
switch (type)
{
case SQLT_DAT:
case SQLT_TIMESTAMP:
case SQLT_TIMESTAMP_TZ:
case SQLT_TIMESTAMP_LTZ:
throw TypeError();
case SQLT_INT:
case SQLT_UIN:
return static_cast<int64_t>(longValue);
case SQLT_FLT:
return static_cast<int64_t>(doubleValue);
case SQLT_NUM:
case SQLT_VNU:
return number.getDecimal().getInt64();
default:
return getValue<int64_t>(std::string(data.data(), len), "int64_t");
}
}
uint64_t Value::getUnsigned64() const
{
if (isNull())
throw NullValue();
switch (type)
{
case SQLT_DAT:
case SQLT_TIMESTAMP:
case SQLT_TIMESTAMP_TZ:
case SQLT_TIMESTAMP_LTZ:
throw TypeError();
case SQLT_INT:
case SQLT_UIN:
return static_cast<uint64_t>(longValue);
case SQLT_FLT:
return static_cast<uint64_t>(doubleValue);
case SQLT_NUM:
case SQLT_VNU:
return number.getDecimal().getUnsigned64();
default:
return getValue<uint64_t>(std::string(data.data(), len), "uint64_t");
}
}
Decimal Value::getDecimal() const
{
if (isNull())
throw NullValue();
switch (type)
{
case SQLT_DAT:
case SQLT_TIMESTAMP:
case SQLT_TIMESTAMP_TZ:
case SQLT_TIMESTAMP_LTZ:
throw TypeError();
case SQLT_INT:
case SQLT_UIN:
{
Decimal decimal;
decimal.setInt(longValue);
return decimal;
}
case SQLT_FLT:
{
Decimal decimal;
decimal.setDouble(doubleValue);
return decimal;
}
case SQLT_NUM:
case SQLT_VNU:
return number.getDecimal();
default:
return getValue<Decimal>(std::string(data.data(), len), "Decimal");
}
}
float Value::getFloat() const
{
if (isNull())
throw NullValue();
switch (type)
{
case SQLT_DAT:
case SQLT_TIMESTAMP:
case SQLT_TIMESTAMP_TZ:
case SQLT_TIMESTAMP_LTZ:
throw TypeError();
case SQLT_INT:
case SQLT_UIN:
return static_cast<float>(longValue);
case SQLT_FLT:
return static_cast<float>(doubleValue);
case SQLT_NUM:
case SQLT_VNU:
return number.getDecimal().getFloat();
default:
return getValue<float>(std::string(data.data(), len), "float");
}
}
double Value::getDouble() const
{
if (isNull())
throw NullValue();
switch (type)
{
case SQLT_DAT:
case SQLT_TIMESTAMP:
case SQLT_TIMESTAMP_TZ:
case SQLT_TIMESTAMP_LTZ:
throw TypeError();
case SQLT_INT:
case SQLT_UIN:
return static_cast<double>(longValue);
case SQLT_FLT:
return static_cast<double>(doubleValue);
case SQLT_NUM:
case SQLT_VNU:
return number.getDecimal().getDouble();
default:
return getValue<double>(std::string(data.data(), len), "double");
}
}
char Value::getChar() const
{
if (isNull())
throw NullValue();
switch (type)
{
case SQLT_DAT:
case SQLT_TIMESTAMP:
case SQLT_TIMESTAMP_TZ:
case SQLT_TIMESTAMP_LTZ:
throw TypeError();
case SQLT_INT:
case SQLT_UIN:
return static_cast<char>(longValue);
case SQLT_FLT:
return static_cast<char>(doubleValue);
case SQLT_NUM:
case SQLT_VNU:
return static_cast<char>(number.getDecimal().getInt());
default:
return *data.data();
}
}
void Value::getString(std::string& ret) const
{
log_debug("Value::getString with type=" << type << " name=" << colName
<< " size=" << len);
if (isNull())
throw NullValue();
switch (type)
{
case SQLT_DAT:
case SQLT_TIMESTAMP:
case SQLT_TIMESTAMP_TZ:
case SQLT_TIMESTAMP_LTZ:
ret = datetime.getDatetime().getIso();
break;
case SQLT_INT:
case SQLT_UIN:
ret = toString(longValue);
break;
case SQLT_FLT:
ret = toString(doubleValue);
break;
case SQLT_NUM:
case SQLT_VNU:
ret = number.getDecimal().toString();
break;
default:
ret.assign(data.data(), len > 0 ? len : 0);
}
}
void Value::getBlob(tntdb::Blob& ret) const
{
log_debug("get blob from type " << type);
if (isNull())
throw NullValue();
switch (type)
{
case SQLT_DAT:
case SQLT_TIMESTAMP:
case SQLT_TIMESTAMP_TZ:
case SQLT_TIMESTAMP_LTZ:
case SQLT_INT:
case SQLT_UIN:
case SQLT_FLT:
case SQLT_NUM:
case SQLT_VNU:
throw TypeError();
case SQLT_BLOB:
blob.getData(ret);
break;
default:
ret.assign(data.data(), len > 0 ? len - 1 : 0);
}
}
Date Value::getDate() const
{
if (isNull())
throw NullValue();
switch (type)
{
case SQLT_DAT:
case SQLT_TIMESTAMP:
case SQLT_TIMESTAMP_TZ:
case SQLT_TIMESTAMP_LTZ:
return datetime.getDate();
default:
throw TypeError();
}
}
Time Value::getTime() const
{
if (isNull())
throw NullValue();
switch (type)
{
case SQLT_DAT:
case SQLT_TIMESTAMP:
case SQLT_TIMESTAMP_TZ:
case SQLT_TIMESTAMP_LTZ:
return datetime.getTime();
default:
throw TypeError();
}
}
tntdb::Datetime Value::getDatetime() const
{
if (isNull())
throw NullValue();
switch (type)
{
case SQLT_DAT:
case SQLT_TIMESTAMP:
case SQLT_TIMESTAMP_TZ:
case SQLT_TIMESTAMP_LTZ:
return datetime.getDatetime();
default:
throw TypeError();
}
}
}
}
<|endoftext|> |
<commit_before>#include "core.h"
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <fstream>
#include <QDebug>
#include "cpuregisters.h"
#include "keyboard.h"
#include "memory.h"
#include "screen.h"
#include "timer.h"
namespace gameboy {
Core::Core() :
registers(new CPURegisters),
memory(new Memory),
breakpoint(-1),
screen(new Screen(memory)),
timer(new Timer(memory)),
keyboard(new Keyboard) {
reset();
}
Core::~Core() {
delete keyboard;
delete screen;
delete memory;
delete registers;
}
void Core::loadROM(const std::string &file) {
memory->loadROM(file);
}
void Core::reset() {
registers->reset();
memory->reset();
screen->reset();
conditional = false;
clock = 0;
}
Keyboard* Core::getKeyboard() {
return keyboard;
}
util::Color* Core::getFramebuffer() {
return screen->getFramebuffer();
}
bool Core::drawFlagSet() {
return screen->drawFlagSet();
}
void Core::emulateCycle() {
uint8_t interrupt = memory->read(0xFF0F) & memory->read(0xFFFF) & 0x1F;
uint8_t lastClocks = 0;
if (interrupt && memory->read(registers->pc) == 0x76) { // HALT
registers->pc++;
}
if ((registers->getIME()) && interrupt) {
if (interrupt & 0x01) { // V-BLANK
memory->write(0xFF0F, memory->read(0xFF0F) & 0xFE); // Disable Flag
INT40();
} else if (interrupt & 0x02) { // LCD-STAT
memory->write(0xFF0F, memory->read(0xFF0F) & 0xFD); // Disable Flag
INT48();
} else if (interrupt & 0x04) { // TIMER
memory->write(0xFF0F, memory->read(0xFF0F) & 0xFB); // Disable Flag
INT50();
} else if (interrupt & 0x08) { // SERIAL
memory->write(0xFF0F, memory->read(0xFF0F) & 0xF7); // Disable Flag
INT58();
} else if (interrupt & 0x10) { // JOYPAD
memory->write(0xFF0F, memory->read(0xFF0F) & 0xEF); // Disable Flag
INT60();
}
lastClocks = 3;
} else {
uint8_t opCode = memory->read(registers->pc++);
uint8_t cb = memory->read(registers->pc);
(this->*opCodes[opCode])();
if (opCode == 0xCB) {
lastClocks = opCodeCBCycles[cb];
} else if (conditional) {
conditional = false;
lastClocks = opCodeCondCycles[opCode];
} else {
lastClocks = opCodeCycles[opCode];
}
}
clock += lastClocks;
screen->step(lastClocks);
timer->step(lastClocks);
updateKeyRegister();
}
void Core::handleCB() {
(this->*opCodesCB[memory->read(registers->pc++)])();
}
void Core::xx() {
qDebug() << "Unknown opcode: " << QString("%1").arg(memory->read(registers->pc-1), 0, 16);
exit(EXIT_FAILURE);
}
void Core::CBxx() {
qDebug() << "Unknown opcode: cb" << QString("%1").arg(memory->read(registers->pc-1), 0, 16);
exit(EXIT_FAILURE);
}
void Core::emulateUntilVBlank() throw (exceptions::Breakpoint) {
do {
if (breakpoint == (int32_t)registers->pc) {
throw exceptions::Breakpoint();
}
emulateCycle();
} while (!screen->drawFlagSet());
}
void Core::updateKeyRegister() { //Keys are active-low
if ((memory->read(0xFF00) & 0x20) == 0) { //Bit 5
if (keyboard->start) {
if (memory->read(0xFF00) & 0x08) {
memory->write(0xFF0F, memory->read(0xFF0F) | 0x10);
}
memory->write(0xFF00, memory->read(0xFF00) & 0xF7);
} else {
memory->write(0xFF00, memory->read(0xFF00) | 0x08);
}
if (keyboard->select) {
if (memory->read(0xFF00) & 0x04) {
memory->write(0xFF0F, memory->read(0xFF0F) | 0x10);
}
memory->write(0xFF00, memory->read(0xFF00) & 0xFB);
} else {
memory->write(0xFF00, memory->read(0xFF00) | 0x04);
}
if (keyboard->b) {
if (memory->read(0xFF00) & 0x02) {
memory->write(0xFF0F, memory->read(0xFF0F) | 0x10);
}
memory->write(0xFF00, memory->read(0xFF00) & 0xFD);
} else {
memory->write(0xFF00, memory->read(0xFF00) | 0x02);
}
if (keyboard->a) {
if (memory->read(0xFF00) & 0x01) {
memory->write(0xFF0F, memory->read(0xFF0F) | 0x10);
}
memory->write(0xFF00, memory->read(0xFF00) & 0xFE);
} else {
memory->write(0xFF00, memory->read(0xFF00) | 0x01);
}
} else if ((memory->read(0xFF00) & 0x10) == 0) { //Bit 4
if (keyboard->down) {
if (memory->read(0xFF00) & 0x08) {
memory->write(0xFF0F, memory->read(0xFF0F) | 0x10);
}
memory->write(0xFF00, memory->read(0xFF00) & 0xF7);
} else {
memory->write(0xFF00, memory->read(0xFF00) | 0x08);
}
if (keyboard->up) {
if (memory->read(0xFF00) & 0x04) {
memory->write(0xFF0F, memory->read(0xFF0F) | 0x10);
}
memory->write(0xFF00, memory->read(0xFF00) & 0xFB);
} else {
memory->write(0xFF00, memory->read(0xFF00) | 0x04);
}
if (keyboard->left) {
if (memory->read(0xFF00) & 0x02) {
memory->write(0xFF0F, memory->read(0xFF0F) | 0x10);
}
memory->write(0xFF00, memory->read(0xFF00) & 0xFD);
} else {
memory->write(0xFF00, memory->read(0xFF00) | 0x02);
}
if (keyboard->right) {
if (memory->read(0xFF01) & 0x08) {
memory->write(0xFF0F, memory->read(0xFF0F) | 0x10);
}
memory->write(0xFF00, memory->read(0xFF00) & 0xFE);
} else {
memory->write(0xFF00, memory->read(0xFF00) | 0x01);
}
}
}
}<commit_msg>Fixed SGB roms<commit_after>#include "core.h"
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <fstream>
#include <QDebug>
#include "cpuregisters.h"
#include "keyboard.h"
#include "memory.h"
#include "screen.h"
#include "timer.h"
namespace gameboy {
Core::Core() :
registers(new CPURegisters),
memory(new Memory),
breakpoint(-1),
screen(new Screen(memory)),
timer(new Timer(memory)),
keyboard(new Keyboard) {
reset();
}
Core::~Core() {
delete keyboard;
delete screen;
delete memory;
delete registers;
}
void Core::loadROM(const std::string &file) {
memory->loadROM(file);
}
void Core::reset() {
registers->reset();
memory->reset();
screen->reset();
conditional = false;
clock = 0;
}
Keyboard* Core::getKeyboard() {
return keyboard;
}
util::Color* Core::getFramebuffer() {
return screen->getFramebuffer();
}
bool Core::drawFlagSet() {
return screen->drawFlagSet();
}
void Core::emulateCycle() {
uint8_t interrupt = memory->read(0xFF0F) & memory->read(0xFFFF) & 0x1F;
uint8_t lastClocks = 0;
if (interrupt && memory->read(registers->pc) == 0x76) { // HALT
registers->pc++;
}
if ((registers->getIME()) && interrupt) {
if (interrupt & 0x01) { // V-BLANK
memory->write(0xFF0F, memory->read(0xFF0F) & 0xFE); // Disable Flag
INT40();
} else if (interrupt & 0x02) { // LCD-STAT
memory->write(0xFF0F, memory->read(0xFF0F) & 0xFD); // Disable Flag
INT48();
} else if (interrupt & 0x04) { // TIMER
memory->write(0xFF0F, memory->read(0xFF0F) & 0xFB); // Disable Flag
INT50();
} else if (interrupt & 0x08) { // SERIAL
memory->write(0xFF0F, memory->read(0xFF0F) & 0xF7); // Disable Flag
INT58();
} else if (interrupt & 0x10) { // JOYPAD
memory->write(0xFF0F, memory->read(0xFF0F) & 0xEF); // Disable Flag
INT60();
}
lastClocks = 3;
} else {
uint8_t opCode = memory->read(registers->pc++);
uint8_t cb = memory->read(registers->pc);
(this->*opCodes[opCode])();
if (opCode == 0xCB) {
lastClocks = opCodeCBCycles[cb];
} else if (conditional) {
conditional = false;
lastClocks = opCodeCondCycles[opCode];
} else {
lastClocks = opCodeCycles[opCode];
}
}
clock += lastClocks;
screen->step(lastClocks);
timer->step(lastClocks);
updateKeyRegister();
}
void Core::handleCB() {
(this->*opCodesCB[memory->read(registers->pc++)])();
}
void Core::xx() {
qDebug() << "Unknown opcode: " << QString("%1").arg(memory->read(registers->pc-1), 0, 16);
exit(EXIT_FAILURE);
}
void Core::CBxx() {
qDebug() << "Unknown opcode: cb" << QString("%1").arg(memory->read(registers->pc-1), 0, 16);
exit(EXIT_FAILURE);
}
void Core::emulateUntilVBlank() throw (exceptions::Breakpoint) {
do {
if (breakpoint == (int32_t)registers->pc) {
throw exceptions::Breakpoint();
}
emulateCycle();
} while (!screen->drawFlagSet());
}
void Core::updateKeyRegister() { //Keys are active-low
if ((memory->read(0xFF00) & 0x20) == 0) { //Bit 5
if (keyboard->start) {
if (memory->read(0xFF00) & 0x08) {
memory->write(0xFF0F, memory->read(0xFF0F) | 0x10);
}
memory->write(0xFF00, memory->read(0xFF00) & 0xF7);
} else {
memory->write(0xFF00, memory->read(0xFF00) | 0x08);
}
if (keyboard->select) {
if (memory->read(0xFF00) & 0x04) {
memory->write(0xFF0F, memory->read(0xFF0F) | 0x10);
}
memory->write(0xFF00, memory->read(0xFF00) & 0xFB);
} else {
memory->write(0xFF00, memory->read(0xFF00) | 0x04);
}
if (keyboard->b) {
if (memory->read(0xFF00) & 0x02) {
memory->write(0xFF0F, memory->read(0xFF0F) | 0x10);
}
memory->write(0xFF00, memory->read(0xFF00) & 0xFD);
} else {
memory->write(0xFF00, memory->read(0xFF00) | 0x02);
}
if (keyboard->a) {
if (memory->read(0xFF00) & 0x01) {
memory->write(0xFF0F, memory->read(0xFF0F) | 0x10);
}
memory->write(0xFF00, memory->read(0xFF00) & 0xFE);
} else {
memory->write(0xFF00, memory->read(0xFF00) | 0x01);
}
} else if ((memory->read(0xFF00) & 0x10) == 0) { //Bit 4
if (keyboard->down) {
if (memory->read(0xFF00) & 0x08) {
memory->write(0xFF0F, memory->read(0xFF0F) | 0x10);
}
memory->write(0xFF00, memory->read(0xFF00) & 0xF7);
} else {
memory->write(0xFF00, memory->read(0xFF00) | 0x08);
}
if (keyboard->up) {
if (memory->read(0xFF00) & 0x04) {
memory->write(0xFF0F, memory->read(0xFF0F) | 0x10);
}
memory->write(0xFF00, memory->read(0xFF00) & 0xFB);
} else {
memory->write(0xFF00, memory->read(0xFF00) | 0x04);
}
if (keyboard->left) {
if (memory->read(0xFF00) & 0x02) {
memory->write(0xFF0F, memory->read(0xFF0F) | 0x10);
}
memory->write(0xFF00, memory->read(0xFF00) & 0xFD);
} else {
memory->write(0xFF00, memory->read(0xFF00) | 0x02);
}
if (keyboard->right) {
if (memory->read(0xFF01) & 0x08) {
memory->write(0xFF0F, memory->read(0xFF0F) | 0x10);
}
memory->write(0xFF00, memory->read(0xFF00) & 0xFE);
} else {
memory->write(0xFF00, memory->read(0xFF00) | 0x01);
}
}
// Disable SNES Communication
if ((memory->read(0xFF00) & 0x30) == 0x30) {
memory->write(0xFF00, memory->read(0xFF00) | 0x0F); // Joypad 1
}
}
}<|endoftext|> |
<commit_before>// 0 = all
// 1 = not pion
// 2 = not kaon
// 3 = not proton
// 4 = not muon
// 5 = not electron
// 6 = not neutron
Int_t particle_type=0;
#include "iostream.h"
void RICHMerger (Int_t evNumber1=0,Int_t evNumber2=0)
{
/////////////////////////////////////////////////////////////////////////
// This macro is a small example of a ROOT macro
// illustrating how to read the output of GALICE
// and do some analysis.
//
/////////////////////////////////////////////////////////////////////////
// Dynamically link some shared libs
if (gClassTable->GetID("AliRun") < 0) {
gROOT->LoadMacro("loadlibs.C");
loadlibs();
}else {
delete gAlice;
gAlice = 0;
}
galice=0;
// Connect the Root Galice file containing Geometry, Kine and Hits
TFile *file = (TFile*)gROOT->GetListOfFiles()->FindObject("galice.root");
if (file) file->Close();
file = new TFile("galice.root","UPDATE");
// file->ls();
// Get AliRun object from file or create it if not on file
if (gClassTable->GetID("AliRun") < 0) {
gROOT->LoadMacro("loadlibs.C");
loadlibs();
}
if (!gAlice) {
gAlice = (AliRun*)file->Get("gAlice");
if (gAlice) printf("AliRun object found on file\n");
if (!gAlice) gAlice = new AliRun("gAlice","Alice test program");
} else {
delete gAlice;
gAlice = (AliRun*)file->Get("gAlice");
if (gAlice) printf("AliRun object found on file\n");
if (!gAlice) gAlice = new AliRun("gAlice","Alice test program");
}
AliRICH *RICH = (AliRICH*) gAlice->GetDetector("RICH");
AliRICHChamber* iChamber;
printf("Generating tresholds...\n");
for(Int_t i=0;i<7;i++)
{
iChamber = &(RICH->Chamber(i));
iChamber->GenerateTresholds();
}
// creation
AliRICHMerger* merger = new AliRICHMerger();
// configuration
merger->SetMode(1);
merger->SetSignalEventNumber(0);
merger->SetBackgroundEventNumber(0);
merger->SetBackgroundFileName("bg.root");
// pass
RICH->SetMerger(merger);
merger->Init();
//
// Event Loop
//
for (int nev=0; nev<= evNumber2; nev++) {
Int_t nparticles = gAlice->GetEvent(nev);
cout <<endl<< "Processing event:" <<nev<<endl;
cout << "Particles :" <<nparticles<<endl;
if (nev < evNumber1) continue;
if (nparticles <= 0) return;
if (RICH)
{
//gAlice->MakeTree("D");
//RICH->MakeBranch("D");
merger->Digitise(nev, particle_type);
}
//if (RICH) gAlice->SDigits2Digits("RICH");
//char hname[30];
//sprintf(hname,"TreeD%d",nev);
//gAlice->TreeD()->Write(hname);
//gAlice->TreeD()->Reset();
} // event loop
file->Close();
//delete gAlice;
printf("\nEnd of Macro *************************************\n");
}
<commit_msg>Obsolete.<commit_after><|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.