text
stringlengths 54
60.6k
|
|---|
<commit_before>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <string>
#include <vector>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "sandbox.h"
using namespace std;
static const uint32_t STACK_SIZE = 64 * 1024;
bool loadRawData(machine& mach, const string& filename)
{
// open and mmap input file
mfile pf(filename);
if (!pf.open(O_RDONLY))
return false;
static unsigned int dataCount = 0;
char tmpstr[32];
// alloc new data memory range
sprintf(tmpstr, "data%u", dataCount++);
size_t sz = pf.st.st_size;
addressRange *rdr = new addressRange(tmpstr, sz);
// copy mmap'd data into local buffer
rdr->buf.assign((char *) pf.data, sz);
rdr->updateRoot();
// add to global memory map
return mach.mapInsert(rdr);
}
static void usage(const char *progname)
{
fprintf(stderr,
"Usage: %s [options]\n"
"\n"
"options:\n"
"-E <directory>\t\tAdd to executable hash search path list\n"
"-e <hash|pathname>\tLoad specified Moxie executable into address space\n"
"-D <directory>\t\tAdd to data hash search path list\n"
"-d <file>\t\tLoad data into address space\n"
"-o <file>\t\tOutput data to <file>. \"-\" for stdout\n"
"-t\t\t\tEnabling simulator tracing\n"
,
progname);
}
static void printMemMap(machine &mach)
{
for (unsigned int i = 0; i < mach.memmap.size(); i++) {
addressRange *ar = mach.memmap[i];
fprintf(stderr, "%s %08x-%08x %s\n",
ar->readOnly ? "ro" : "rw", ar->start, ar->end,
ar->name.c_str());
}
}
static void addStackMem(machine& mach)
{
// alloc r/w memory range
addressRange *rdr = new addressRange("stack", STACK_SIZE);
rdr->buf.resize(STACK_SIZE);
rdr->updateRoot();
rdr->readOnly = false;
// add memory range to global memory map
mach.mapInsert(rdr);
// set SR #7 to now-initialized stack vaddr
mach.cpu.asregs.sregs[7] = rdr->end;
}
static void addMapDescriptor(machine& mach)
{
// fill list from existing memory map
vector<struct mach_memmap_ent> desc;
mach.fillDescriptors(desc);
// add entry for the mapdesc range to be added to memory map
struct mach_memmap_ent mme_self;
memset(&mme_self, 0, sizeof(mme_self));
desc.push_back(mme_self);
// add blank entry for list terminator
struct mach_memmap_ent mme_end;
memset(&mme_end, 0, sizeof(mme_end));
desc.push_back(mme_end);
// calc total region size
size_t sz = sizeof(mme_end) * desc.size();
// manually fill in mapdesc range descriptor
mme_self.length = sz;
strcpy(mme_self.tags, "ro,mapdesc,");
// build entry for global memory map
addressRange *ar = new addressRange("mapdesc", sz);
// allocate space for descriptor array
ar->buf.resize(sz);
ar->updateRoot();
// copy 'desc' array into allocated memory space
unsigned int i = 0;
for (vector<struct mach_memmap_ent>::iterator it = desc.begin();
it != desc.end(); it++, i++) {
struct mach_memmap_ent& mme = (*it);
memcpy(&ar->buf[i * sizeof(mme)], &mme, sizeof(mme));
}
// add memory range to global memory map
mach.mapInsert(ar);
// set SR #6 to now-initialized mapdesc start vaddr
mach.cpu.asregs.sregs[6] = ar->start;
}
static void gatherOutput(machine& mach, const string& outFilename)
{
if (!outFilename.size())
return;
uint32_t vaddr = mach.cpu.asregs.sregs[6];
uint32_t length = mach.cpu.asregs.sregs[7];
if (!vaddr || !length)
return;
char *p = (char *) mach.physaddr(vaddr, length);
if (!p) {
fprintf(stderr, "Sim exception %d (%s) upon output\n",
SIGBUS,
strsignal(SIGBUS));
exit(EXIT_FAILURE);
}
int fd;
if (outFilename == "-") {
fd = STDOUT_FILENO;
} else {
fd = open(outFilename.c_str(),
O_WRONLY | O_CREAT | O_TRUNC, 0666);
if (fd < 0) {
perror(outFilename.c_str());
exit(EXIT_FAILURE);
}
}
while (length > 0) {
ssize_t bytes = write(fd, p, length);
if (bytes < 0) {
perror(outFilename.c_str());
exit(EXIT_FAILURE);
}
length -= bytes;
p += bytes;
}
close(fd);
}
static bool isDir(const char *pathname)
{
struct stat st;
if (stat(pathname, &st) < 0)
return false;
return S_ISDIR(st.st_mode);
}
int main (int argc, char *argv[])
{
machine mach;
vector<string> pathExec;
vector<string> pathData;
bool progLoaded = false;
string outFilename;
int opt;
while ((opt = getopt(argc, argv, "E:e:D:d:o:t")) != -1) {
switch(opt) {
case 'E':
if (!isDir(optarg)) {
fprintf(stderr, "%s not a directory\n", optarg);
exit(EXIT_FAILURE);
}
pathExec.push_back(optarg);
break;
case 'e':
bool rc;
if (IsHex(optarg))
rc = loadElfHash(mach, optarg, pathExec);
else
rc = loadElfProgram(mach, optarg);
if (!rc) {
fprintf(stderr, "ELF load failed for %s\n",
optarg);
exit(EXIT_FAILURE);
}
progLoaded = true;
break;
case 'D':
if (!isDir(optarg)) {
fprintf(stderr, "%s not a directory\n", optarg);
exit(EXIT_FAILURE);
}
pathExec.push_back(optarg);
break;
case 'd':
if (!loadRawData(mach, optarg)) {
fprintf(stderr, "Data load failed for %s\n",
optarg);
exit(EXIT_FAILURE);
}
break;
case 'o':
outFilename = optarg;
break;
case 't':
mach.tracing = true;
break;
default:
usage(argv[0]);
exit(EXIT_FAILURE);
}
}
if (!progLoaded) {
fprintf(stderr, "No Moxie program loaded.\n");
usage(argv[0]);
exit(EXIT_FAILURE);
}
addStackMem(mach);
addMapDescriptor(mach);
printMemMap(mach);
mach.cpu.asregs.regs[PC_REGNO] = mach.startAddr;
// create new child process
pid_t child = fork();
if (child == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
// child executes sandbox
if (child == 0) {
sim_resume(mach);
if (mach.cpu.asregs.exception != SIGQUIT) {
fprintf(stderr, "Sim exception %d (%s)\n",
mach.cpu.asregs.exception,
strsignal(mach.cpu.asregs.exception));
exit(EXIT_FAILURE);
}
gatherOutput(mach, outFilename);
// return $r0, the exit status passed to _exit()
exit(mach.cpu.asregs.regs[2] & 0xff);
// parent waits
} else {
int status = 0;
pid_t res = wait(&status);
if (res == -1)
perror("wait");
return WEXITSTATUS(status);
}
return EXIT_FAILURE; // not reached
}
<commit_msg>Revert "execute simulator in child process"<commit_after>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <string>
#include <vector>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "sandbox.h"
using namespace std;
static const uint32_t STACK_SIZE = 64 * 1024;
bool loadRawData(machine& mach, const string& filename)
{
// open and mmap input file
mfile pf(filename);
if (!pf.open(O_RDONLY))
return false;
static unsigned int dataCount = 0;
char tmpstr[32];
// alloc new data memory range
sprintf(tmpstr, "data%u", dataCount++);
size_t sz = pf.st.st_size;
addressRange *rdr = new addressRange(tmpstr, sz);
// copy mmap'd data into local buffer
rdr->buf.assign((char *) pf.data, sz);
rdr->updateRoot();
// add to global memory map
return mach.mapInsert(rdr);
}
static void usage(const char *progname)
{
fprintf(stderr,
"Usage: %s [options]\n"
"\n"
"options:\n"
"-E <directory>\t\tAdd to executable hash search path list\n"
"-e <hash|pathname>\tLoad specified Moxie executable into address space\n"
"-D <directory>\t\tAdd to data hash search path list\n"
"-d <file>\t\tLoad data into address space\n"
"-o <file>\t\tOutput data to <file>. \"-\" for stdout\n"
"-t\t\t\tEnabling simulator tracing\n"
,
progname);
}
static void printMemMap(machine &mach)
{
for (unsigned int i = 0; i < mach.memmap.size(); i++) {
addressRange *ar = mach.memmap[i];
fprintf(stderr, "%s %08x-%08x %s\n",
ar->readOnly ? "ro" : "rw", ar->start, ar->end,
ar->name.c_str());
}
}
static void addStackMem(machine& mach)
{
// alloc r/w memory range
addressRange *rdr = new addressRange("stack", STACK_SIZE);
rdr->buf.resize(STACK_SIZE);
rdr->updateRoot();
rdr->readOnly = false;
// add memory range to global memory map
mach.mapInsert(rdr);
// set SR #7 to now-initialized stack vaddr
mach.cpu.asregs.sregs[7] = rdr->end;
}
static void addMapDescriptor(machine& mach)
{
// fill list from existing memory map
vector<struct mach_memmap_ent> desc;
mach.fillDescriptors(desc);
// add entry for the mapdesc range to be added to memory map
struct mach_memmap_ent mme_self;
memset(&mme_self, 0, sizeof(mme_self));
desc.push_back(mme_self);
// add blank entry for list terminator
struct mach_memmap_ent mme_end;
memset(&mme_end, 0, sizeof(mme_end));
desc.push_back(mme_end);
// calc total region size
size_t sz = sizeof(mme_end) * desc.size();
// manually fill in mapdesc range descriptor
mme_self.length = sz;
strcpy(mme_self.tags, "ro,mapdesc,");
// build entry for global memory map
addressRange *ar = new addressRange("mapdesc", sz);
// allocate space for descriptor array
ar->buf.resize(sz);
ar->updateRoot();
// copy 'desc' array into allocated memory space
unsigned int i = 0;
for (vector<struct mach_memmap_ent>::iterator it = desc.begin();
it != desc.end(); it++, i++) {
struct mach_memmap_ent& mme = (*it);
memcpy(&ar->buf[i * sizeof(mme)], &mme, sizeof(mme));
}
// add memory range to global memory map
mach.mapInsert(ar);
// set SR #6 to now-initialized mapdesc start vaddr
mach.cpu.asregs.sregs[6] = ar->start;
}
static void gatherOutput(machine& mach, const string& outFilename)
{
if (!outFilename.size())
return;
uint32_t vaddr = mach.cpu.asregs.sregs[6];
uint32_t length = mach.cpu.asregs.sregs[7];
if (!vaddr || !length)
return;
char *p = (char *) mach.physaddr(vaddr, length);
if (!p) {
fprintf(stderr, "Sim exception %d (%s) upon output\n",
SIGBUS,
strsignal(SIGBUS));
exit(EXIT_FAILURE);
}
int fd;
if (outFilename == "-") {
fd = STDOUT_FILENO;
} else {
fd = open(outFilename.c_str(),
O_WRONLY | O_CREAT | O_TRUNC, 0666);
if (fd < 0) {
perror(outFilename.c_str());
exit(EXIT_FAILURE);
}
}
while (length > 0) {
ssize_t bytes = write(fd, p, length);
if (bytes < 0) {
perror(outFilename.c_str());
exit(EXIT_FAILURE);
}
length -= bytes;
p += bytes;
}
close(fd);
}
static bool isDir(const char *pathname)
{
struct stat st;
if (stat(pathname, &st) < 0)
return false;
return S_ISDIR(st.st_mode);
}
int main (int argc, char *argv[])
{
machine mach;
vector<string> pathExec;
vector<string> pathData;
bool progLoaded = false;
string outFilename;
int opt;
while ((opt = getopt(argc, argv, "E:e:D:d:o:t")) != -1) {
switch(opt) {
case 'E':
if (!isDir(optarg)) {
fprintf(stderr, "%s not a directory\n", optarg);
exit(EXIT_FAILURE);
}
pathExec.push_back(optarg);
break;
case 'e':
bool rc;
if (IsHex(optarg))
rc = loadElfHash(mach, optarg, pathExec);
else
rc = loadElfProgram(mach, optarg);
if (!rc) {
fprintf(stderr, "ELF load failed for %s\n",
optarg);
exit(EXIT_FAILURE);
}
progLoaded = true;
break;
case 'D':
if (!isDir(optarg)) {
fprintf(stderr, "%s not a directory\n", optarg);
exit(EXIT_FAILURE);
}
pathExec.push_back(optarg);
break;
case 'd':
if (!loadRawData(mach, optarg)) {
fprintf(stderr, "Data load failed for %s\n",
optarg);
exit(EXIT_FAILURE);
}
break;
case 'o':
outFilename = optarg;
break;
case 't':
mach.tracing = true;
break;
default:
usage(argv[0]);
exit(EXIT_FAILURE);
}
}
if (!progLoaded) {
fprintf(stderr, "No Moxie program loaded.\n");
usage(argv[0]);
exit(EXIT_FAILURE);
}
addStackMem(mach);
addMapDescriptor(mach);
printMemMap(mach);
mach.cpu.asregs.regs[PC_REGNO] = mach.startAddr;
sim_resume(mach);
if (mach.cpu.asregs.exception != SIGQUIT) {
fprintf(stderr, "Sim exception %d (%s)\n",
mach.cpu.asregs.exception,
strsignal(mach.cpu.asregs.exception));
exit(EXIT_FAILURE);
}
gatherOutput(mach, outFilename);
// return $r0, the exit status passed to _exit()
return mach.cpu.asregs.regs[2];
}
<|endoftext|>
|
<commit_before>//
// 1770.cpp
// Clock Signal
//
// Created by Thomas Harte on 17/09/2016.
// Copyright © 2016 Thomas Harte. All rights reserved.
//
#include "1770.hpp"
#include "../../Storage/Disk/Encodings/MFM.hpp"
using namespace WD;
WD1770::WD1770() :
Storage::Disk::Drive(8000000, 1, 300),
status_(0),
interesting_event_mask_(Event::Command),
resume_point_(0),
delay_time_(0)
{
set_is_double_density(false);
posit_event(Event::Command);
}
void WD1770::set_is_double_density(bool is_double_density)
{
is_double_density_ = is_double_density;
Storage::Time bit_length;
bit_length.length = 1;
bit_length.clock_rate = is_double_density ? 500000 : 250000;
set_expected_bit_length(bit_length);
}
void WD1770::set_register(int address, uint8_t value)
{
switch(address&3)
{
case 0:
command_ = value;
posit_event(Event::Command);
// TODO: is this force interrupt?
break;
case 1: track_ = value; break;
case 2: sector_ = value; break;
case 3: data_ = value; break;
}
}
uint8_t WD1770::get_register(int address)
{
switch(address&3)
{
default: return status_;
case 1: return track_;
case 2: return sector_;
case 3: status_ &= ~Flag::DataRequest; return data_;
}
}
void WD1770::run_for_cycles(unsigned int number_of_cycles)
{
if(status_ & Flag::MotorOn) Storage::Disk::Drive::run_for_cycles((int)number_of_cycles);
if(delay_time_)
{
if(delay_time_ <= number_of_cycles)
{
delay_time_ = 0;
posit_event(Event::Timer);
}
else
{
delay_time_ -= number_of_cycles;
}
}
}
void WD1770::process_input_bit(int value, unsigned int cycles_since_index_hole)
{
shift_register_ = (shift_register_ << 1) | value;
bits_since_token_++;
Token::Type token_type = Token::Byte;
if(!is_double_density_)
{
switch(shift_register_ & 0xffff)
{
case Storage::Encodings::MFM::FMIndexAddressMark:
token_type = Token::Index;
break;
case Storage::Encodings::MFM::FMIDAddressMark:
token_type = Token::ID;
break;
case Storage::Encodings::MFM::FMDataAddressMark:
token_type = Token::Data;
break;
case Storage::Encodings::MFM::FMDeletedDataAddressMark:
token_type = Token::DeletedData;
break;
default:
break;
}
}
else
{
// TODO: MFM
}
if(token_type != Token::Byte)
{
latest_token_.type = token_type;
bits_since_token_ = 0;
posit_event(Event::Token);
return;
}
if(bits_since_token_ == 16)
{
latest_token_.type = Token::Byte;
latest_token_.byte_value = (uint8_t)(
((shift_register_ & 0x0001) >> 0) |
((shift_register_ & 0x0004) >> 1) |
((shift_register_ & 0x0010) >> 2) |
((shift_register_ & 0x0040) >> 3) |
((shift_register_ & 0x0100) >> 4) |
((shift_register_ & 0x0400) >> 5) |
((shift_register_ & 0x1000) >> 6) |
((shift_register_ & 0x4000) >> 7));
bits_since_token_ = 0;
posit_event(Event::Token);
return;
}
}
void WD1770::process_index_hole()
{
index_hole_count_++;
posit_event(Event::IndexHole);
// motor power-down
// if(index_hole_count_ == 9 && !(status_&Flag::Busy)) status_ &= ~Flag::MotorOn;
}
// +------+----------+-------------------------+
// ! ! ! BITS !
// ! TYPE ! COMMAND ! 7 6 5 4 3 2 1 0 !
// +------+----------+-------------------------+
// ! 1 ! Restore ! 0 0 0 0 h v r1 r0 !
// ! 1 ! Seek ! 0 0 0 1 h v r1 r0 !
// ! 1 ! Step ! 0 0 1 u h v r1 r0 !
// ! 1 ! Step-in ! 0 1 0 u h v r1 r0 !
// ! 1 ! Step-out ! 0 1 1 u h v r1 r0 !
// ! 2 ! Rd sectr ! 1 0 0 m h E 0 0 !
// ! 2 ! Wt sectr ! 1 0 1 m h E P a0 !
// ! 3 ! Rd addr ! 1 1 0 0 h E 0 0 !
// ! 3 ! Rd track ! 1 1 1 0 h E 0 0 !
// ! 3 ! Wt track ! 1 1 1 1 h E P 0 !
// ! 4 ! Forc int ! 1 1 0 1 i3 i2 i1 i0 !
// +------+----------+-------------------------+
#define WAIT_FOR_EVENT(mask) resume_point_ = __LINE__; interesting_event_mask_ = mask; return; case __LINE__:
#define WAIT_FOR_TIME(ms) resume_point_ = __LINE__; interesting_event_mask_ = Event::Timer; delay_time_ = ms * 8000; if(delay_time_) return; case __LINE__:
#define BEGIN_SECTION() switch(resume_point_) { default:
#define END_SECTION() 0; }
void WD1770::posit_event(Event new_event_type)
{
if(!(interesting_event_mask_ & (int)new_event_type)) return;
interesting_event_mask_ &= ~new_event_type;
BEGIN_SECTION()
// Wait for a new command, branch to the appropriate handler.
wait_for_command:
printf("Idle...\n");
status_ &= ~Flag::Busy;
index_hole_count_ = 0;
WAIT_FOR_EVENT(Event::Command);
printf("Starting %02x\n", command_);
status_ |= Flag::Busy;
if(!(command_ & 0x80)) goto begin_type_1;
if(!(command_ & 0x40)) goto begin_type_2;
goto begin_type_3;
/*
Type 1 entry point.
*/
begin_type_1:
// Set initial flags, skip spin-up if possible.
status_ &= ~(Flag::DataRequest | Flag::DataRequest | Flag::SeekError);
set_interrupt_request(false);
if((command_&0x08) || (status_ & Flag::MotorOn)) goto test_type1_type;
// Perform spin up.
status_ |= Flag::MotorOn;
WAIT_FOR_EVENT(Event::IndexHole);
WAIT_FOR_EVENT(Event::IndexHole);
WAIT_FOR_EVENT(Event::IndexHole);
WAIT_FOR_EVENT(Event::IndexHole);
WAIT_FOR_EVENT(Event::IndexHole);
WAIT_FOR_EVENT(Event::IndexHole);
status_ |= Flag::SpinUp;
test_type1_type:
// Set step direction if this is a step in or out.
if((command_ >> 5) == 2) step_direction_ = 1;
if((command_ >> 5) == 3) step_direction_ = 0;
if((command_ >> 5) != 0) goto perform_step_command;
// This is now definitely either a seek or a restore; if it's a restore then set track to 0xff and data to 0x00.
if(!(command_ & 0x10))
{
track_ = 0xff;
data_ = 0;
}
perform_seek_or_restore_command:
if(track_ == data_) goto verify;
step_direction_ = (data_ > track_);
adjust_track:
if(step_direction_) track_++; else track_--;
perform_step:
if(!step_direction_ && get_is_track_zero())
{
track_ = 0;
goto verify;
}
step(step_direction_ ? 1 : -1);
int time_to_wait;
switch(command_ & 3)
{
default:
case 0: time_to_wait = 6; break; // 2 on a 1772
case 1: time_to_wait = 12; break; // 3 on a 1772
case 2: time_to_wait = 20; break; // 5 on a 1772
case 3: time_to_wait = 30; break; // 6 on a 1772
}
WAIT_FOR_TIME(time_to_wait);
if(command_ >> 5) goto verify;
goto perform_seek_or_restore_command;
perform_step_command:
if(command_ & 0x10) goto adjust_track;
goto perform_step;
verify:
if(!(command_ & 0x04))
{
set_interrupt_request(true);
goto wait_for_command;
}
printf("!!!TODO: verify a type 1!!!\n");
/*
Type 2 entry point.
*/
begin_type_2:
status_ &= ~(Flag::DataRequest | Flag::LostData | Flag::RecordNotFound | Flag::WriteProtect | Flag::RecordType);
set_interrupt_request(false);
distance_into_section_ = 0;
if((command_&0x08) || (status_ & Flag::MotorOn)) goto test_type2_delay;
// Perform spin up.
status_ |= Flag::MotorOn;
WAIT_FOR_EVENT(Event::IndexHole);
WAIT_FOR_EVENT(Event::IndexHole);
WAIT_FOR_EVENT(Event::IndexHole);
WAIT_FOR_EVENT(Event::IndexHole);
WAIT_FOR_EVENT(Event::IndexHole);
WAIT_FOR_EVENT(Event::IndexHole);
test_type2_delay:
index_hole_count_ = 0;
if(!(command_ & 0x04)) goto test_type2_write_protection;
WAIT_FOR_TIME(30);
test_type2_write_protection:
if(command_&0x20) // TODO:: && is_write_protected
{
set_interrupt_request(true);
status_ |= Flag::WriteProtect;
goto wait_for_command;
}
type2_get_header:
WAIT_FOR_EVENT(Event::IndexHole | Event::Token);
if(new_event_type == Event::Token)
{
if(!distance_into_section_ && latest_token_.type == Token::ID) distance_into_section_++;
else if(distance_into_section_ && latest_token_.type == Token::Byte)
{
header[distance_into_section_ - 1] = latest_token_.byte_value;
distance_into_section_++;
if(distance_into_section_ == 6)
{
if(header[0] == track_ && header[2] == sector_)
{
// TODO: test CRC
goto type2_read_or_write_data;
}
else
{
distance_into_section_ = 0;
}
}
}
}
else if(index_hole_count_ == 5)
{
set_interrupt_request(true);
status_ |= Flag::RecordNotFound;
goto wait_for_command;
}
goto type2_get_header;
type2_read_or_write_data:
if(command_&0x20) goto type2_write_data;
goto type2_read_data;
type2_read_data:
WAIT_FOR_EVENT(Event::Token);
// TODO: timeout
if(latest_token_.type == Token::Data || latest_token_.type == Token::DeletedData)
{
status_ |= (latest_token_.type == Token::DeletedData) ? Flag::RecordType : 0;
distance_into_section_ = 0;
goto type2_read_byte;
}
goto type2_read_data;
type2_read_byte:
WAIT_FOR_EVENT(Event::Token);
if(latest_token_.type != Token::Byte) goto type2_read_byte;
if(status_ & Flag::DataRequest) status_ |= Flag::LostData;
data_ = latest_token_.byte_value;
status_ |= Flag::DataRequest;
distance_into_section_++;
if(distance_into_section_ == 128 << header[3])
{
distance_into_section_ = 0;
goto type2_check_crc;
}
goto type2_read_byte;
type2_check_crc:
WAIT_FOR_EVENT(Event::Token);
if(latest_token_.type != Token::Byte) goto type2_read_byte;
header[distance_into_section_] = latest_token_.byte_value;
distance_into_section_++;
if(distance_into_section_ == 2)
{
// TODO: check CRC
if(command_ & 0x10)
{
sector_++;
goto test_type2_write_protection;
}
set_interrupt_request(true);
goto wait_for_command;
}
goto type2_check_crc;
type2_write_data:
printf("!!!TODO: data portion of sector!!!\n");
begin_type_3:
printf("!!!TODO: type 3 commands!!!\n");
END_SECTION()
}
<commit_msg>Sought to implement the verify step of type 1 commands.<commit_after>//
// 1770.cpp
// Clock Signal
//
// Created by Thomas Harte on 17/09/2016.
// Copyright © 2016 Thomas Harte. All rights reserved.
//
#include "1770.hpp"
#include "../../Storage/Disk/Encodings/MFM.hpp"
using namespace WD;
WD1770::WD1770() :
Storage::Disk::Drive(8000000, 1, 300),
status_(0),
interesting_event_mask_(Event::Command),
resume_point_(0),
delay_time_(0)
{
set_is_double_density(false);
posit_event(Event::Command);
}
void WD1770::set_is_double_density(bool is_double_density)
{
is_double_density_ = is_double_density;
Storage::Time bit_length;
bit_length.length = 1;
bit_length.clock_rate = is_double_density ? 500000 : 250000;
set_expected_bit_length(bit_length);
}
void WD1770::set_register(int address, uint8_t value)
{
switch(address&3)
{
case 0:
command_ = value;
posit_event(Event::Command);
// TODO: is this force interrupt?
break;
case 1: track_ = value; break;
case 2: sector_ = value; break;
case 3: data_ = value; break;
}
}
uint8_t WD1770::get_register(int address)
{
switch(address&3)
{
default: return status_;
case 1: return track_;
case 2: return sector_;
case 3: status_ &= ~Flag::DataRequest; return data_;
}
}
void WD1770::run_for_cycles(unsigned int number_of_cycles)
{
if(status_ & Flag::MotorOn) Storage::Disk::Drive::run_for_cycles((int)number_of_cycles);
if(delay_time_)
{
if(delay_time_ <= number_of_cycles)
{
delay_time_ = 0;
posit_event(Event::Timer);
}
else
{
delay_time_ -= number_of_cycles;
}
}
}
void WD1770::process_input_bit(int value, unsigned int cycles_since_index_hole)
{
shift_register_ = (shift_register_ << 1) | value;
bits_since_token_++;
Token::Type token_type = Token::Byte;
if(!is_double_density_)
{
switch(shift_register_ & 0xffff)
{
case Storage::Encodings::MFM::FMIndexAddressMark:
token_type = Token::Index;
break;
case Storage::Encodings::MFM::FMIDAddressMark:
token_type = Token::ID;
break;
case Storage::Encodings::MFM::FMDataAddressMark:
token_type = Token::Data;
break;
case Storage::Encodings::MFM::FMDeletedDataAddressMark:
token_type = Token::DeletedData;
break;
default:
break;
}
}
else
{
// TODO: MFM
}
if(token_type != Token::Byte)
{
latest_token_.type = token_type;
bits_since_token_ = 0;
posit_event(Event::Token);
return;
}
if(bits_since_token_ == 16)
{
latest_token_.type = Token::Byte;
latest_token_.byte_value = (uint8_t)(
((shift_register_ & 0x0001) >> 0) |
((shift_register_ & 0x0004) >> 1) |
((shift_register_ & 0x0010) >> 2) |
((shift_register_ & 0x0040) >> 3) |
((shift_register_ & 0x0100) >> 4) |
((shift_register_ & 0x0400) >> 5) |
((shift_register_ & 0x1000) >> 6) |
((shift_register_ & 0x4000) >> 7));
bits_since_token_ = 0;
posit_event(Event::Token);
return;
}
}
void WD1770::process_index_hole()
{
index_hole_count_++;
posit_event(Event::IndexHole);
// motor power-down
// if(index_hole_count_ == 9 && !(status_&Flag::Busy)) status_ &= ~Flag::MotorOn;
}
// +------+----------+-------------------------+
// ! ! ! BITS !
// ! TYPE ! COMMAND ! 7 6 5 4 3 2 1 0 !
// +------+----------+-------------------------+
// ! 1 ! Restore ! 0 0 0 0 h v r1 r0 !
// ! 1 ! Seek ! 0 0 0 1 h v r1 r0 !
// ! 1 ! Step ! 0 0 1 u h v r1 r0 !
// ! 1 ! Step-in ! 0 1 0 u h v r1 r0 !
// ! 1 ! Step-out ! 0 1 1 u h v r1 r0 !
// ! 2 ! Rd sectr ! 1 0 0 m h E 0 0 !
// ! 2 ! Wt sectr ! 1 0 1 m h E P a0 !
// ! 3 ! Rd addr ! 1 1 0 0 h E 0 0 !
// ! 3 ! Rd track ! 1 1 1 0 h E 0 0 !
// ! 3 ! Wt track ! 1 1 1 1 h E P 0 !
// ! 4 ! Forc int ! 1 1 0 1 i3 i2 i1 i0 !
// +------+----------+-------------------------+
#define WAIT_FOR_EVENT(mask) resume_point_ = __LINE__; interesting_event_mask_ = mask; return; case __LINE__:
#define WAIT_FOR_TIME(ms) resume_point_ = __LINE__; interesting_event_mask_ = Event::Timer; delay_time_ = ms * 8000; if(delay_time_) return; case __LINE__:
#define BEGIN_SECTION() switch(resume_point_) { default:
#define END_SECTION() 0; }
#define READ_ID() \
if(new_event_type == Event::Token) \
{ \
if(!distance_into_section_ && latest_token_.type == Token::ID) distance_into_section_++; \
else if(distance_into_section_ && distance_into_section_ < 7 && latest_token_.type == Token::Byte) \
{ \
header[distance_into_section_ - 1] = latest_token_.byte_value; \
distance_into_section_++; \
} \
}
void WD1770::posit_event(Event new_event_type)
{
if(!(interesting_event_mask_ & (int)new_event_type)) return;
interesting_event_mask_ &= ~new_event_type;
BEGIN_SECTION()
// Wait for a new command, branch to the appropriate handler.
wait_for_command:
printf("Idle...\n");
status_ &= ~Flag::Busy;
index_hole_count_ = 0;
WAIT_FOR_EVENT(Event::Command);
printf("Starting %02x\n", command_);
status_ |= Flag::Busy;
if(!(command_ & 0x80)) goto begin_type_1;
if(!(command_ & 0x40)) goto begin_type_2;
goto begin_type_3;
/*
Type 1 entry point.
*/
begin_type_1:
// Set initial flags, skip spin-up if possible.
status_ &= ~(Flag::DataRequest | Flag::DataRequest | Flag::SeekError);
set_interrupt_request(false);
if((command_&0x08) || (status_ & Flag::MotorOn)) goto test_type1_type;
// Perform spin up.
status_ |= Flag::MotorOn;
WAIT_FOR_EVENT(Event::IndexHole);
WAIT_FOR_EVENT(Event::IndexHole);
WAIT_FOR_EVENT(Event::IndexHole);
WAIT_FOR_EVENT(Event::IndexHole);
WAIT_FOR_EVENT(Event::IndexHole);
WAIT_FOR_EVENT(Event::IndexHole);
status_ |= Flag::SpinUp;
test_type1_type:
// Set step direction if this is a step in or out.
if((command_ >> 5) == 2) step_direction_ = 1;
if((command_ >> 5) == 3) step_direction_ = 0;
if((command_ >> 5) != 0) goto perform_step_command;
// This is now definitely either a seek or a restore; if it's a restore then set track to 0xff and data to 0x00.
if(!(command_ & 0x10))
{
track_ = 0xff;
data_ = 0;
}
perform_seek_or_restore_command:
if(track_ == data_) goto verify;
step_direction_ = (data_ > track_);
adjust_track:
if(step_direction_) track_++; else track_--;
perform_step:
if(!step_direction_ && get_is_track_zero())
{
track_ = 0;
goto verify;
}
step(step_direction_ ? 1 : -1);
int time_to_wait;
switch(command_ & 3)
{
default:
case 0: time_to_wait = 6; break; // 2 on a 1772
case 1: time_to_wait = 12; break; // 3 on a 1772
case 2: time_to_wait = 20; break; // 5 on a 1772
case 3: time_to_wait = 30; break; // 6 on a 1772
}
WAIT_FOR_TIME(time_to_wait);
if(command_ >> 5) goto verify;
goto perform_seek_or_restore_command;
perform_step_command:
if(command_ & 0x10) goto adjust_track;
goto perform_step;
verify:
if(!(command_ & 0x04))
{
set_interrupt_request(true);
goto wait_for_command;
}
index_hole_count_ = 0;
verify_read_data:
WAIT_FOR_EVENT(Event::IndexHole | Event::Token);
READ_ID();
if(index_hole_count_ == 6)
{
set_interrupt_request(true);
status_ |= Flag::SeekError;
goto wait_for_command;
}
if(distance_into_section_ == 7)
{
// TODO: CRC check
if(header[0] == track_)
{
status_ &= ~Flag::CRCError;
set_interrupt_request(true);
goto wait_for_command;
}
distance_into_section_ = 0;
}
goto verify_read_data;
/*
Type 2 entry point.
*/
begin_type_2:
status_ &= ~(Flag::DataRequest | Flag::LostData | Flag::RecordNotFound | Flag::WriteProtect | Flag::RecordType);
set_interrupt_request(false);
distance_into_section_ = 0;
if((command_&0x08) || (status_ & Flag::MotorOn)) goto test_type2_delay;
// Perform spin up.
status_ |= Flag::MotorOn;
WAIT_FOR_EVENT(Event::IndexHole);
WAIT_FOR_EVENT(Event::IndexHole);
WAIT_FOR_EVENT(Event::IndexHole);
WAIT_FOR_EVENT(Event::IndexHole);
WAIT_FOR_EVENT(Event::IndexHole);
WAIT_FOR_EVENT(Event::IndexHole);
test_type2_delay:
index_hole_count_ = 0;
if(!(command_ & 0x04)) goto test_type2_write_protection;
WAIT_FOR_TIME(30);
test_type2_write_protection:
if(command_&0x20) // TODO:: && is_write_protected
{
set_interrupt_request(true);
status_ |= Flag::WriteProtect;
goto wait_for_command;
}
type2_get_header:
WAIT_FOR_EVENT(Event::IndexHole | Event::Token);
READ_ID();
if(index_hole_count_ == 5)
{
set_interrupt_request(true);
status_ |= Flag::RecordNotFound;
goto wait_for_command;
}
if(distance_into_section_ == 7)
{
if(header[0] == track_ && header[2] == sector_)
{
// TODO: test CRC
goto type2_read_or_write_data;
}
distance_into_section_ = 0;
}
goto type2_get_header;
type2_read_or_write_data:
if(command_&0x20) goto type2_write_data;
goto type2_read_data;
type2_read_data:
WAIT_FOR_EVENT(Event::Token);
// TODO: timeout
if(latest_token_.type == Token::Data || latest_token_.type == Token::DeletedData)
{
status_ |= (latest_token_.type == Token::DeletedData) ? Flag::RecordType : 0;
distance_into_section_ = 0;
goto type2_read_byte;
}
goto type2_read_data;
type2_read_byte:
WAIT_FOR_EVENT(Event::Token);
if(latest_token_.type != Token::Byte) goto type2_read_byte;
if(status_ & Flag::DataRequest) status_ |= Flag::LostData;
data_ = latest_token_.byte_value;
status_ |= Flag::DataRequest;
distance_into_section_++;
if(distance_into_section_ == 128 << header[3])
{
distance_into_section_ = 0;
goto type2_check_crc;
}
goto type2_read_byte;
type2_check_crc:
WAIT_FOR_EVENT(Event::Token);
if(latest_token_.type != Token::Byte) goto type2_read_byte;
header[distance_into_section_] = latest_token_.byte_value;
distance_into_section_++;
if(distance_into_section_ == 2)
{
// TODO: check CRC
if(command_ & 0x10)
{
sector_++;
goto test_type2_write_protection;
}
set_interrupt_request(true);
goto wait_for_command;
}
goto type2_check_crc;
type2_write_data:
printf("!!!TODO: data portion of sector!!!\n");
begin_type_3:
printf("!!!TODO: type 3 commands!!!\n");
END_SECTION()
}
<|endoftext|>
|
<commit_before>/**
* Process control - running other tasks and manipulating their input/output
*/
#include <v8.h>
#include <string>
#include "macros.h"
#include "common.h"
#include <stdlib.h>
#include <paths.h> // for _PATH_BSHELL
namespace {
JS_METHOD(_process) {
ASSERT_CONSTRUCTOR;
SAVE_PTR(0, NULL);
return args.This();
}
JS_METHOD(_system) {
if (args.Length() != 1) {
return JS_EXCEPTION("Wrong argument count. Use new Process().system(\"command\")");
}
v8::String::Utf8Value cmd(args[0]);
int result = system(*cmd);
return JS_INT(result);
}
/**
* The initial .exec method for stream buffering system commands
*/
JS_METHOD(_exec) {
if (args.Length() != 1) {
return JS_EXCEPTION("Wrong argument count. Use new Process().exec(\"command\")");
}
std::string data;
FILE *stream;
const int MAX_BUFFER = 256;
char buffer[MAX_BUFFER];
v8::String::Utf8Value cmd(args[0]);
stream = popen(*cmd, "r");
while ( fgets(buffer, MAX_BUFFER, stream) != NULL ) {
data.append(buffer);
}
pclose(stream);
if(data.c_str() != NULL) {
return JS_STR(data.c_str());
} else {
return JS_NULL;
}
}
/**
* Execute the given command, and return exit code and stdout/stderr data
*
* TODO: any reason to keep exec? Either remove exec and rename exec2 to exec,
* or rename exec2 to something else.
*
* @param command {String} bash command
* @param input {String} optional; text to send to process as stdin
*
* @return a JavaScript object like: {
* status: {Integer} the return code from the process
* out: {String} contents of stdout
* err: {String} contents of stderr
* }
*/
JS_METHOD(_exec2) {
int arg_count = args.Length();
if (arg_count < 1 || arg_count > 2) {
return JS_EXCEPTION("Wrong argument count. Use new Process().exec2(\"command\", [\"standard input\"])");
}
const int MAX_BUFFER = 256;
char buffer[MAX_BUFFER + 1];
v8::String::Utf8Value command_arg(args[0]);
// File descriptors all named from perspective of child process.
int input_fd[2];
int out_fd[2];
int err_fd[2];
pipe(input_fd); // Where the parent is going to write to
pipe(out_fd); // From where parent is going to read
pipe(err_fd);
int pid = fork();
switch (pid) {
case -1: // Error case.
return JS_EXCEPTION("Failed to fork process");
case 0: // Child process.
close(STDOUT_FILENO);
close(STDERR_FILENO);
close(STDIN_FILENO);
dup2(input_fd[0], STDIN_FILENO);
dup2(out_fd[1], STDOUT_FILENO);
dup2(err_fd[1], STDERR_FILENO);
close(input_fd[0]); // Not required for the child
close(input_fd[1]);
close(out_fd[0]);
close(out_fd[1]);
close(err_fd[0]);
close(err_fd[1]);
execl(_PATH_BSHELL, "sh", "-c", *command_arg, NULL);
#if defined(__CYGWIN__) || defined(__MSYS__)
// On cygwin or msys, we may not have /bin/sh. In that case,
// try to find sh on PATH.
execlp("sh", "sh", "-c", *command_arg, NULL);
#endif
exit(127); // "command not found"
return JS_NULL; // unreachable
default: // Parent process.
close(input_fd[0]); // These are being used by the child
close(out_fd[1]);
close(err_fd[1]);
if (arg_count >= 2) {
v8::String::Utf8Value input_arg(args[1]);
write(input_fd[1], *input_arg, input_arg.length()); // Write to child’s stdin
}
close(input_fd[1]);
std::string ret_out;
while (true) {
int bytes_read = read(out_fd[0], buffer, MAX_BUFFER);
if (bytes_read == 0) {
break;
} else if (bytes_read < 0) {
return JS_NULL; // TODO: throw JavaScript exception
}
buffer[bytes_read] = 0;
ret_out.append(buffer);
}
close(out_fd[0]);
std::string ret_err;
while (true) {
int bytes_read = read(err_fd[0], buffer, MAX_BUFFER);
if (bytes_read == 0) {
break;
} else if (bytes_read < 0) {
return JS_NULL; // TODO: throw JavaScript exception
}
buffer[bytes_read] = 0;
ret_err.append(buffer);
}
close(err_fd[0]);
int status;
waitpid(pid, &status, 0);
v8::Handle<v8::Object> ret = v8::Object::New();
ret->Set(JS_STR("status"), JS_INT(status));
ret->Set(JS_STR("out"), JS_STR(ret_out.c_str()));
ret->Set(JS_STR("err"), JS_STR(ret_err.c_str()));
return ret;
}
}
/**
* Execute the given command as a background process.
*
* @param command {String} bash command
* @param input {String} optional; text to send to process as stdin
* @return undefined
*/
JS_METHOD(_fork) {
int arg_count = args.Length();
if (arg_count < 1 || arg_count > 2) {
return JS_EXCEPTION("Wrong argument count. Use new Process().exec2(\"command\", [\"standard input\"])");
}
v8::String::Utf8Value command_arg(args[0]);
int input_fd[2];
pipe(input_fd); // Where the parent is going to write to
int pid = fork();
switch (pid) {
case -1: // Error case.
return JS_EXCEPTION("Failed to fork process");
case 0: // Child process.
close(STDIN_FILENO);
dup2(input_fd[0], STDIN_FILENO);
close(input_fd[0]); // Not required for the child
close(input_fd[1]);
execl(_PATH_BSHELL, "sh", "-c", *command_arg, NULL);
#if defined(__CYGWIN__) || defined(__MSYS__)
// On cygwin or msys, we may not have /bin/sh. In that case,
// try to find sh on PATH.
execlp("sh", "sh", "-c", *command_arg, NULL);
#endif
exit(127); // "command not found"
return JS_NULL; // unreachable
default: // Parent process.
close(input_fd[0]); // These are being used by the child
if (arg_count >= 2) {
v8::String::Utf8Value input_arg(args[1]);
write(input_fd[1], *input_arg, input_arg.length()); // Write to child’s stdin
}
close(input_fd[1]);
return JS_UNDEFINED;
}
}
}
SHARED_INIT() {
v8::HandleScope handle_scope;
v8::Handle<v8::FunctionTemplate> funct = v8::FunctionTemplate::New(_process);
funct->SetClassName(JS_STR("Process"));
v8::Handle<v8::ObjectTemplate> ot = funct->InstanceTemplate();
ot->SetInternalFieldCount(1);
v8::Handle<v8::ObjectTemplate> process = funct->PrototypeTemplate();
/* this module provides a set of (static) functions */
process->Set(JS_STR("system"), v8::FunctionTemplate::New(_system)->GetFunction());
process->Set(JS_STR("exec"), v8::FunctionTemplate::New(_exec)->GetFunction());
process->Set(JS_STR("exec2"), v8::FunctionTemplate::New(_exec2)->GetFunction());
process->Set(JS_STR("fork"), v8::FunctionTemplate::New(_fork)->GetFunction());
exports->Set(JS_STR("Process"), funct->GetFunction());
}
<commit_msg>include sys/wait.h in process module<commit_after>/**
* Process control - running other tasks and manipulating their input/output
*/
#include <v8.h>
#include <string>
#include "macros.h"
#include "common.h"
#include <stdlib.h>
#include <sys/wait.h>
#include <paths.h> // for _PATH_BSHELL
namespace {
JS_METHOD(_process) {
ASSERT_CONSTRUCTOR;
SAVE_PTR(0, NULL);
return args.This();
}
JS_METHOD(_system) {
if (args.Length() != 1) {
return JS_EXCEPTION("Wrong argument count. Use new Process().system(\"command\")");
}
v8::String::Utf8Value cmd(args[0]);
int result = system(*cmd);
return JS_INT(result);
}
/**
* The initial .exec method for stream buffering system commands
*/
JS_METHOD(_exec) {
if (args.Length() != 1) {
return JS_EXCEPTION("Wrong argument count. Use new Process().exec(\"command\")");
}
std::string data;
FILE *stream;
const int MAX_BUFFER = 256;
char buffer[MAX_BUFFER];
v8::String::Utf8Value cmd(args[0]);
stream = popen(*cmd, "r");
while ( fgets(buffer, MAX_BUFFER, stream) != NULL ) {
data.append(buffer);
}
pclose(stream);
if(data.c_str() != NULL) {
return JS_STR(data.c_str());
} else {
return JS_NULL;
}
}
/**
* Execute the given command, and return exit code and stdout/stderr data
*
* TODO: any reason to keep exec? Either remove exec and rename exec2 to exec,
* or rename exec2 to something else.
*
* @param command {String} bash command
* @param input {String} optional; text to send to process as stdin
*
* @return a JavaScript object like: {
* status: {Integer} the return code from the process
* out: {String} contents of stdout
* err: {String} contents of stderr
* }
*/
JS_METHOD(_exec2) {
int arg_count = args.Length();
if (arg_count < 1 || arg_count > 2) {
return JS_EXCEPTION("Wrong argument count. Use new Process().exec2(\"command\", [\"standard input\"])");
}
const int MAX_BUFFER = 256;
char buffer[MAX_BUFFER + 1];
v8::String::Utf8Value command_arg(args[0]);
// File descriptors all named from perspective of child process.
int input_fd[2];
int out_fd[2];
int err_fd[2];
pipe(input_fd); // Where the parent is going to write to
pipe(out_fd); // From where parent is going to read
pipe(err_fd);
int pid = fork();
switch (pid) {
case -1: // Error case.
return JS_EXCEPTION("Failed to fork process");
case 0: // Child process.
close(STDOUT_FILENO);
close(STDERR_FILENO);
close(STDIN_FILENO);
dup2(input_fd[0], STDIN_FILENO);
dup2(out_fd[1], STDOUT_FILENO);
dup2(err_fd[1], STDERR_FILENO);
close(input_fd[0]); // Not required for the child
close(input_fd[1]);
close(out_fd[0]);
close(out_fd[1]);
close(err_fd[0]);
close(err_fd[1]);
execl(_PATH_BSHELL, "sh", "-c", *command_arg, NULL);
#if defined(__CYGWIN__) || defined(__MSYS__)
// On cygwin or msys, we may not have /bin/sh. In that case,
// try to find sh on PATH.
execlp("sh", "sh", "-c", *command_arg, NULL);
#endif
exit(127); // "command not found"
return JS_NULL; // unreachable
default: // Parent process.
close(input_fd[0]); // These are being used by the child
close(out_fd[1]);
close(err_fd[1]);
if (arg_count >= 2) {
v8::String::Utf8Value input_arg(args[1]);
write(input_fd[1], *input_arg, input_arg.length()); // Write to child’s stdin
}
close(input_fd[1]);
std::string ret_out;
while (true) {
int bytes_read = read(out_fd[0], buffer, MAX_BUFFER);
if (bytes_read == 0) {
break;
} else if (bytes_read < 0) {
return JS_NULL; // TODO: throw JavaScript exception
}
buffer[bytes_read] = 0;
ret_out.append(buffer);
}
close(out_fd[0]);
std::string ret_err;
while (true) {
int bytes_read = read(err_fd[0], buffer, MAX_BUFFER);
if (bytes_read == 0) {
break;
} else if (bytes_read < 0) {
return JS_NULL; // TODO: throw JavaScript exception
}
buffer[bytes_read] = 0;
ret_err.append(buffer);
}
close(err_fd[0]);
int status;
waitpid(pid, &status, 0);
v8::Handle<v8::Object> ret = v8::Object::New();
ret->Set(JS_STR("status"), JS_INT(status));
ret->Set(JS_STR("out"), JS_STR(ret_out.c_str()));
ret->Set(JS_STR("err"), JS_STR(ret_err.c_str()));
return ret;
}
}
/**
* Execute the given command as a background process.
*
* @param command {String} bash command
* @param input {String} optional; text to send to process as stdin
* @return undefined
*/
JS_METHOD(_fork) {
int arg_count = args.Length();
if (arg_count < 1 || arg_count > 2) {
return JS_EXCEPTION("Wrong argument count. Use new Process().exec2(\"command\", [\"standard input\"])");
}
v8::String::Utf8Value command_arg(args[0]);
int input_fd[2];
pipe(input_fd); // Where the parent is going to write to
int pid = fork();
switch (pid) {
case -1: // Error case.
return JS_EXCEPTION("Failed to fork process");
case 0: // Child process.
close(STDIN_FILENO);
dup2(input_fd[0], STDIN_FILENO);
close(input_fd[0]); // Not required for the child
close(input_fd[1]);
execl(_PATH_BSHELL, "sh", "-c", *command_arg, NULL);
#if defined(__CYGWIN__) || defined(__MSYS__)
// On cygwin or msys, we may not have /bin/sh. In that case,
// try to find sh on PATH.
execlp("sh", "sh", "-c", *command_arg, NULL);
#endif
exit(127); // "command not found"
return JS_NULL; // unreachable
default: // Parent process.
close(input_fd[0]); // These are being used by the child
if (arg_count >= 2) {
v8::String::Utf8Value input_arg(args[1]);
write(input_fd[1], *input_arg, input_arg.length()); // Write to child’s stdin
}
close(input_fd[1]);
return JS_UNDEFINED;
}
}
}
SHARED_INIT() {
v8::HandleScope handle_scope;
v8::Handle<v8::FunctionTemplate> funct = v8::FunctionTemplate::New(_process);
funct->SetClassName(JS_STR("Process"));
v8::Handle<v8::ObjectTemplate> ot = funct->InstanceTemplate();
ot->SetInternalFieldCount(1);
v8::Handle<v8::ObjectTemplate> process = funct->PrototypeTemplate();
/* this module provides a set of (static) functions */
process->Set(JS_STR("system"), v8::FunctionTemplate::New(_system)->GetFunction());
process->Set(JS_STR("exec"), v8::FunctionTemplate::New(_exec)->GetFunction());
process->Set(JS_STR("exec2"), v8::FunctionTemplate::New(_exec2)->GetFunction());
process->Set(JS_STR("fork"), v8::FunctionTemplate::New(_fork)->GetFunction());
exports->Set(JS_STR("Process"), funct->GetFunction());
}
<|endoftext|>
|
<commit_before>//
// 6850.cpp
// Clock Signal
//
// Created by Thomas Harte on 10/10/2019.
// Copyright © 2019 Thomas Harte. All rights reserved.
//
#include "6850.hpp"
#include <cassert>
using namespace Motorola::ACIA;
const HalfCycles ACIA::SameAsTransmit;
ACIA::ACIA(HalfCycles transmit_clock_rate, HalfCycles receive_clock_rate) :
transmit_clock_rate_(transmit_clock_rate),
receive_clock_rate_((receive_clock_rate != SameAsTransmit) ? receive_clock_rate : transmit_clock_rate) {
transmit.set_writer_clock_rate(transmit_clock_rate);
request_to_send.set_writer_clock_rate(transmit_clock_rate);
}
uint8_t ACIA::read(int address) {
if(address&1) {
overran_ = false;
received_data_ |= NoValueMask;
update_interrupt_line();
return uint8_t(received_data_);
} else {
return get_status();
}
}
void ACIA::reset() {
transmit.reset_writing();
transmit.write(true);
request_to_send.reset_writing();
bits_received_ = bits_incoming_ = 0;
receive_interrupt_enabled_ = transmit_interrupt_enabled_ = false;
overran_ = false;
next_transmission_ = received_data_ = NoValueMask;
update_interrupt_line();
assert(!interrupt_line_);
}
void ACIA::write(int address, uint8_t value) {
if(address&1) {
next_transmission_ = value;
consider_transmission();
update_interrupt_line();
} else {
if((value&3) == 3) {
reset();
} else {
switch(value & 3) {
default:
case 0: divider_ = 1; break;
case 1: divider_ = 16; break;
case 2: divider_ = 64; break;
}
switch((value >> 2) & 7) {
default:
case 0: data_bits_ = 7; stop_bits_ = 2; parity_ = Parity::Even; break;
case 1: data_bits_ = 7; stop_bits_ = 2; parity_ = Parity::Odd; break;
case 2: data_bits_ = 7; stop_bits_ = 1; parity_ = Parity::Even; break;
case 3: data_bits_ = 7; stop_bits_ = 1; parity_ = Parity::Odd; break;
case 4: data_bits_ = 8; stop_bits_ = 2; parity_ = Parity::None; break;
case 5: data_bits_ = 8; stop_bits_ = 1; parity_ = Parity::None; break;
case 6: data_bits_ = 8; stop_bits_ = 1; parity_ = Parity::Even; break;
case 7: data_bits_ = 8; stop_bits_ = 1; parity_ = Parity::Odd; break;
}
switch((value >> 5) & 3) {
case 0: request_to_send.write(false); transmit_interrupt_enabled_ = false; break;
case 1: request_to_send.write(false); transmit_interrupt_enabled_ = true; break;
case 2: request_to_send.write(true); transmit_interrupt_enabled_ = false; break;
case 3:
request_to_send.write(false);
transmit_interrupt_enabled_ = false;
transmit.reset_writing();
transmit.write(false);
break;
}
receive.set_read_delegate(this, Storage::Time(divider_ * 2, int(receive_clock_rate_.as_integral())));
receive_interrupt_enabled_ = value & 0x80;
update_interrupt_line();
}
}
update_clocking_observer();
}
void ACIA::consider_transmission() {
if(next_transmission_ != NoValueMask && !transmit.write_data_time_remaining()) {
// Establish start bit and [7 or 8] data bits.
if(data_bits_ == 7) next_transmission_ &= 0x7f;
int transmission = next_transmission_ << 1;
// Add a parity bit, if any.
int mask = 0x2 << data_bits_;
if(parity_ != Parity::None) {
transmission |= parity(uint8_t(next_transmission_)) ? mask : 0;
mask <<= 1;
}
// Add stop bits.
for(int c = 0; c < stop_bits_; ++c) {
transmission |= mask;
mask <<= 1;
}
// Output all that.
const int total_bits = expected_bits();
transmit.write(divider_ * 2, total_bits, transmission);
// Mark the transmit register as empty again.
next_transmission_ = NoValueMask;
}
}
ClockingHint::Preference ACIA::preferred_clocking() const {
// Real-time clocking is required if a transmission is ongoing; this is a courtesy for whomever
// is on the receiving end.
if(transmit.transmission_data_time_remaining() > 0) return ClockingHint::Preference::RealTime;
// If a bit reception is ongoing that might lead to an interrupt, ask for real-time clocking
// because it's unclear when the interrupt might come.
if(bits_incoming_ && receive_interrupt_enabled_) return ClockingHint::Preference::RealTime;
// No clocking required then.
return ClockingHint::Preference::None;
}
bool ACIA::get_interrupt_line() const {
return interrupt_line_;
}
int ACIA::expected_bits() {
return 1 + data_bits_ + stop_bits_ + (parity_ != Parity::None);
}
uint8_t ACIA::parity(uint8_t value) {
value ^= value >> 4;
value ^= value >> 2;
value ^= value >> 1;
return value ^ (parity_ == Parity::Even);
}
bool ACIA::serial_line_did_produce_bit(Serial::Line *, int bit) {
// Shift this bit into the 11-bit input register; this is big enough to hold
// the largest transmission symbol.
++bits_received_;
bits_incoming_ = (bits_incoming_ >> 1) | (bit << 10);
// If that's the now-expected number of bits, update.
const int bit_target = expected_bits();
if(bits_received_ >= bit_target) {
bits_received_ = 0;
overran_ |= get_status() & 1;
received_data_ = uint8_t(bits_incoming_ >> (12 - bit_target));
update_interrupt_line();
update_clocking_observer();
return false;
}
// TODO: overrun, and parity.
// Keep receiving, and consider a potential clocking change.
if(bits_received_ == 1) update_clocking_observer();
return true;
}
void ACIA::set_interrupt_delegate(InterruptDelegate *delegate) {
interrupt_delegate_ = delegate;
}
void ACIA::update_interrupt_line() {
const bool old_line = interrupt_line_;
/*
"Bit 7 of the control register is the rie bit. When the rie bit is high, the rdrf, ndcd,
and ovr bits will assert the nirq output. When the rie bit is low, nirq generation is disabled."
rie = read interrupt enable
rdrf = receive data register full (status word bit 0)
ndcd = data carrier detect (status word bit 2)
over = receiver overrun (status word bit 5)
"Bit 1 of the status register is the tdre bit. When high, the tdre bit indicates that data has been
transferred from the transmitter data register to the output shift register. At this point, the a6850
is ready to accept a new transmit data byte. However, if the ncts signal is high, the tdre bit remains
low regardless of the status of the transmitter data register. Also, if transmit interrupt is enabled,
the nirq output is asserted."
tdre = transmitter data register empty
ncts = clear to send
*/
const auto status = get_status();
interrupt_line_ =
(receive_interrupt_enabled_ && (status & 0x25)) ||
(transmit_interrupt_enabled_ && (status & 0x02));
if(interrupt_delegate_ && old_line != interrupt_line_) {
interrupt_delegate_->acia6850_did_change_interrupt_status(this);
}
}
uint8_t ACIA::get_status() {
return
((received_data_ & NoValueMask) ? 0x00 : 0x01) |
((next_transmission_ == NoValueMask) ? 0x02 : 0x00) |
// (data_carrier_detect.read() ? 0x04 : 0x00) |
// (clear_to_send.read() ? 0x08 : 0x00) |
(overran_ ? 0x20 : 0x00) |
(interrupt_line_ ? 0x80 : 0x00)
;
// b0: receive data full.
// b1: transmit data empty.
// b2: DCD.
// b3: CTS.
// b4: framing error (i.e. no first stop bit where expected).
// b5: receiver overran.
// b6: parity error.
// b7: IRQ state.
}
<commit_msg>Retain 6850 time tracking at all times.<commit_after>//
// 6850.cpp
// Clock Signal
//
// Created by Thomas Harte on 10/10/2019.
// Copyright © 2019 Thomas Harte. All rights reserved.
//
#include "6850.hpp"
#include <cassert>
using namespace Motorola::ACIA;
const HalfCycles ACIA::SameAsTransmit;
ACIA::ACIA(HalfCycles transmit_clock_rate, HalfCycles receive_clock_rate) :
transmit_clock_rate_(transmit_clock_rate),
receive_clock_rate_((receive_clock_rate != SameAsTransmit) ? receive_clock_rate : transmit_clock_rate) {
transmit.set_writer_clock_rate(transmit_clock_rate);
request_to_send.set_writer_clock_rate(transmit_clock_rate);
}
uint8_t ACIA::read(int address) {
if(address&1) {
overran_ = false;
received_data_ |= NoValueMask;
update_interrupt_line();
return uint8_t(received_data_);
} else {
return get_status();
}
}
void ACIA::reset() {
transmit.reset_writing();
transmit.write(true);
request_to_send.reset_writing();
bits_received_ = bits_incoming_ = 0;
receive_interrupt_enabled_ = transmit_interrupt_enabled_ = false;
overran_ = false;
next_transmission_ = received_data_ = NoValueMask;
update_interrupt_line();
assert(!interrupt_line_);
}
void ACIA::write(int address, uint8_t value) {
if(address&1) {
next_transmission_ = value;
consider_transmission();
update_interrupt_line();
} else {
if((value&3) == 3) {
reset();
} else {
switch(value & 3) {
default:
case 0: divider_ = 1; break;
case 1: divider_ = 16; break;
case 2: divider_ = 64; break;
}
switch((value >> 2) & 7) {
default:
case 0: data_bits_ = 7; stop_bits_ = 2; parity_ = Parity::Even; break;
case 1: data_bits_ = 7; stop_bits_ = 2; parity_ = Parity::Odd; break;
case 2: data_bits_ = 7; stop_bits_ = 1; parity_ = Parity::Even; break;
case 3: data_bits_ = 7; stop_bits_ = 1; parity_ = Parity::Odd; break;
case 4: data_bits_ = 8; stop_bits_ = 2; parity_ = Parity::None; break;
case 5: data_bits_ = 8; stop_bits_ = 1; parity_ = Parity::None; break;
case 6: data_bits_ = 8; stop_bits_ = 1; parity_ = Parity::Even; break;
case 7: data_bits_ = 8; stop_bits_ = 1; parity_ = Parity::Odd; break;
}
switch((value >> 5) & 3) {
case 0: request_to_send.write(false); transmit_interrupt_enabled_ = false; break;
case 1: request_to_send.write(false); transmit_interrupt_enabled_ = true; break;
case 2: request_to_send.write(true); transmit_interrupt_enabled_ = false; break;
case 3:
request_to_send.write(false);
transmit_interrupt_enabled_ = false;
transmit.reset_writing();
transmit.write(false);
break;
}
receive.set_read_delegate(this, Storage::Time(divider_ * 2, int(receive_clock_rate_.as_integral())));
receive_interrupt_enabled_ = value & 0x80;
update_interrupt_line();
}
}
update_clocking_observer();
}
void ACIA::consider_transmission() {
if(next_transmission_ != NoValueMask && !transmit.write_data_time_remaining()) {
// Establish start bit and [7 or 8] data bits.
if(data_bits_ == 7) next_transmission_ &= 0x7f;
int transmission = next_transmission_ << 1;
// Add a parity bit, if any.
int mask = 0x2 << data_bits_;
if(parity_ != Parity::None) {
transmission |= parity(uint8_t(next_transmission_)) ? mask : 0;
mask <<= 1;
}
// Add stop bits.
for(int c = 0; c < stop_bits_; ++c) {
transmission |= mask;
mask <<= 1;
}
// Output all that.
const int total_bits = expected_bits();
transmit.write(divider_ * 2, total_bits, transmission);
// Mark the transmit register as empty again.
next_transmission_ = NoValueMask;
}
}
ClockingHint::Preference ACIA::preferred_clocking() const {
// Real-time clocking is required if a transmission is ongoing; this is a courtesy for whomever
// is on the receiving end.
if(transmit.transmission_data_time_remaining() > 0) return ClockingHint::Preference::RealTime;
// If a bit reception is ongoing that might lead to an interrupt, ask for real-time clocking
// because it's unclear when the interrupt might come.
if(bits_incoming_ && receive_interrupt_enabled_) return ClockingHint::Preference::RealTime;
// Real-time clocking not required then.
return ClockingHint::Preference::JustInTime;
}
bool ACIA::get_interrupt_line() const {
return interrupt_line_;
}
int ACIA::expected_bits() {
return 1 + data_bits_ + stop_bits_ + (parity_ != Parity::None);
}
uint8_t ACIA::parity(uint8_t value) {
value ^= value >> 4;
value ^= value >> 2;
value ^= value >> 1;
return value ^ (parity_ == Parity::Even);
}
bool ACIA::serial_line_did_produce_bit(Serial::Line *, int bit) {
// Shift this bit into the 11-bit input register; this is big enough to hold
// the largest transmission symbol.
++bits_received_;
bits_incoming_ = (bits_incoming_ >> 1) | (bit << 10);
// If that's the now-expected number of bits, update.
const int bit_target = expected_bits();
if(bits_received_ >= bit_target) {
bits_received_ = 0;
overran_ |= get_status() & 1;
received_data_ = uint8_t(bits_incoming_ >> (12 - bit_target));
update_interrupt_line();
update_clocking_observer();
return false;
}
// TODO: overrun, and parity.
// Keep receiving, and consider a potential clocking change.
if(bits_received_ == 1) update_clocking_observer();
return true;
}
void ACIA::set_interrupt_delegate(InterruptDelegate *delegate) {
interrupt_delegate_ = delegate;
}
void ACIA::update_interrupt_line() {
const bool old_line = interrupt_line_;
/*
"Bit 7 of the control register is the rie bit. When the rie bit is high, the rdrf, ndcd,
and ovr bits will assert the nirq output. When the rie bit is low, nirq generation is disabled."
rie = read interrupt enable
rdrf = receive data register full (status word bit 0)
ndcd = data carrier detect (status word bit 2)
over = receiver overrun (status word bit 5)
"Bit 1 of the status register is the tdre bit. When high, the tdre bit indicates that data has been
transferred from the transmitter data register to the output shift register. At this point, the a6850
is ready to accept a new transmit data byte. However, if the ncts signal is high, the tdre bit remains
low regardless of the status of the transmitter data register. Also, if transmit interrupt is enabled,
the nirq output is asserted."
tdre = transmitter data register empty
ncts = clear to send
*/
const auto status = get_status();
interrupt_line_ =
(receive_interrupt_enabled_ && (status & 0x25)) ||
(transmit_interrupt_enabled_ && (status & 0x02));
if(interrupt_delegate_ && old_line != interrupt_line_) {
interrupt_delegate_->acia6850_did_change_interrupt_status(this);
}
}
uint8_t ACIA::get_status() {
return
((received_data_ & NoValueMask) ? 0x00 : 0x01) |
((next_transmission_ == NoValueMask) ? 0x02 : 0x00) |
// (data_carrier_detect.read() ? 0x04 : 0x00) |
// (clear_to_send.read() ? 0x08 : 0x00) |
(overran_ ? 0x20 : 0x00) |
(interrupt_line_ ? 0x80 : 0x00)
;
// b0: receive data full.
// b1: transmit data empty.
// b2: DCD.
// b3: CTS.
// b4: framing error (i.e. no first stop bit where expected).
// b5: receiver overran.
// b6: parity error.
// b7: IRQ state.
}
<|endoftext|>
|
<commit_before>/**************************************************************************
* Copyright(c) 1998-2016, 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. *
**************************************************************************/
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
#include <TSystem.h>
#include <TString.h>
#include <TError.h>
#include "AliPWGJETrainHelpers.h"
std::vector<std::string> AliPWGJETrainHelpers::ExtractAliEnProductionValuesForLEGOTrain()
{
// Automatically set shared common variables
// The run period (ex. "LHC15o")
std::string period = gSystem->Getenv("ALIEN_JDL_LPMPRODUCTIONTAG");
// either "pp", "pPb" or "PbPb"
std::string collType = gSystem->Getenv("ALIEN_JDL_LPMINTERACTIONTYPE");
// Used to get mc
std::string prodType = gSystem->Getenv("ALIEN_JDL_LPMPRODUCTIONTYPE");
// In the case of the metadataset, the standard environment variables above will not be set.
// Instead, we attempt to retrieve the variable from the first enabled metadataset. This requires looping
// over the available metadatasets untils we find a non-null value.
// We assume that all children in the metadataset should have the same collision system and production type.
// Although this isn't the case for the period, since the variables are supposed to be the same
// in all metadatasets (according to Markus Z.), the track cuts presumably must all be the same for
// all periods in a metadataset.
const std::string childDatasets = gSystem->Getenv("CHILD_DATASETS"); // Used to get mc
const int nChildDatasets = std::atoi(childDatasets.c_str());
for (int i = 1; i <= nChildDatasets; i++) {
if (period == "") {
period = gSystem->Getenv(TString::Format("ALIEN_JDL_child_%i_LPMPRODUCTIONTAG", i));
}
if (collType == "") {
collType = gSystem->Getenv(TString::Format("ALIEN_JDL_child_%i_LPMINTERACTIONTYPE", i));
}
if (prodType == "") {
prodType = gSystem->Getenv(TString::Format("ALIEN_JDL_child_%i_LPMPRODUCTIONTYPE", i));
}
}
// Validate the extract variables. Each one must be set at this point.
if (period == "" || collType == "" || prodType == "") {
// Somehow failed to extract the variables which should always be available.
::Fatal("AliPWGJETrainHelpers", "Somehow failed to extract the period, collision type, or production type.\n");
}
// Determine if it's an MC production.
const bool mc = (prodType == "MC");
// Determine if it's Run2
std::string yearString = period.substr(3, 2);
int productionYear = std::atoi(yearString.c_str());
const bool isRun2 = productionYear > 14;
// We need to return multiple values, so we use a vector and convert the bools to strings temporarily.
// They should be converted back after returning.
// (Not that the bool text doesn't really matter as long as it's non-zero, but we select "true" as it
// corresponds to the variables being true).
return std::vector<std::string>{period, collType, mc ? "true" : "", isRun2 ? "true" : ""};
}
<commit_msg>Fix handling of Getenv<commit_after>/**************************************************************************
* Copyright(c) 1998-2016, 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. *
**************************************************************************/
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
#include <TSystem.h>
#include <TString.h>
#include <TError.h>
#include "AliPWGJETrainHelpers.h"
std::vector<std::string> AliPWGJETrainHelpers::ExtractAliEnProductionValuesForLEGOTrain()
{
// NOTE: `Getenv(...)` returns `nullptr` if the environment variable isn't available.
// std::string _cannot_ be set to `nullptr`, so we retrieve the result as a `const char*`
// and then convert it to a `std::string` if it is not null. We use std::string for
// convenience and to simplify string comparison.
// Automatically set shared common variables
// The run period (ex. "LHC15o")
const char * tempPeriod = gSystem->Getenv("ALIEN_JDL_LPMPRODUCTIONTAG");
std::string period = tempPeriod ? tempPeriod : "";
// Either "pp", "pPb" or "PbPb"
const char * tempCollType = gSystem->Getenv("ALIEN_JDL_LPMINTERACTIONTYPE");
std::string collType = tempCollType ? tempCollType : "";
// Used to get MC.
const char * tempProdType = gSystem->Getenv("ALIEN_JDL_LPMPRODUCTIONTYPE");
std::string prodType = tempProdType ? tempProdType : "";
// In the case of the metadataset, the standard environment variables above will not be set.
// Instead, we attempt to retrieve the variable from the first enabled metadataset. This requires looping
// over the available metadatasets until we find a non-null value.
// We assume that all children in the metadataset should have the same collision system and production type.
// Although this isn't the case for the period, since the variables are supposed to be the same
// in all metadatasets (according to Markus Z.), the track cuts presumably must all be the same for
// all periods in a metadataset.
const char * tempChildDatasets = gSystem->Getenv("CHILD_DATASETS");
// Used to get MC.
const std::string childDatasets = tempChildDatasets ? tempChildDatasets : "";
const int nChildDatasets = std::atoi(childDatasets.c_str());
for (int i = 1; i <= nChildDatasets; i++) {
if (period == "") {
tempPeriod = gSystem->Getenv(TString::Format("ALIEN_JDL_child_%i_LPMPRODUCTIONTAG", i));
period = tempPeriod ? tempPeriod : "";
}
if (collType == "") {
tempCollType = gSystem->Getenv(TString::Format("ALIEN_JDL_child_%i_LPMINTERACTIONTYPE", i));
collType = tempCollType ? tempCollType : "";
}
if (prodType == "") {
tempProdType = gSystem->Getenv(TString::Format("ALIEN_JDL_child_%i_LPMPRODUCTIONTYPE", i));
prodType = tempProdType ? tempProdType : "";
}
}
// Validate the extract variables. Each one must be set at this point.
if (period == "" || collType == "" || prodType == "") {
// Somehow failed to extract the variables which should always be available.
::Fatal("AliPWGJETrainHelpers", "Somehow failed to extract the period, collision type, or production type.\n");
}
// Determine if it's an MC production.
const bool mc = (prodType == "MC");
// Determine if it's Run 2
std::string yearString = period.substr(3, 2);
int productionYear = std::atoi(yearString.c_str());
const bool isRun2 = productionYear > 14;
// We need to return multiple values, so we use a vector and convert the bools to strings temporarily.
// They should be converted back after returning.
// (Not that the bool text doesn't really matter as long as it's non-zero, but we select "true" as it
// corresponds to the variables being true).
return std::vector<std::string>{period, collType, mc ? "true" : "", isRun2 ? "true" : ""};
}
<|endoftext|>
|
<commit_before>#include "qmtopology.h"
#include "qmnblist.h"
QMTopology::QMTopology()
{}
QMTopology::~QMTopology()
{}
void QMTopology::Initialize(Topology& cg_top)
{
CopyTopologyData(&cg_top);
this->InitChargeUnits();
}
void QMTopology::Cleanup()
{
vector<CrgUnit *>::iterator iter;
for(iter=_crgunits.begin(); iter!=_crgunits.end(); ++iter)
delete *iter;
_crgunits.clear();
_mcharges.clear();
Topology::Cleanup();
}
void QMTopology::Update(Topology& cg_top)
{
BeadContainer::iterator iter;
BeadContainer::iterator iter_cg;
assert(cg_top.Beads().size() == _beads.size());
_box = cg_top.getBox();
_time = cg_top.getTime();
_step = cg_top.getStep();
iter_cg = cg_top.Beads().begin();
for(iter=_beads.begin(); iter!=_beads.end(); ++iter, ++iter_cg) {
(*iter)->setPos((*iter_cg)->getPos());
if((*iter_cg)->HasU())
(*iter)->setU((*iter_cg)->getU());
if((*iter_cg)->HasV())
(*iter)->setV((*iter_cg)->getV());
if((*iter_cg)->HasW())
(*iter)->setW((*iter_cg)->getW());
QMBead * b = (QMBead*)(*iter);
if(!(*iter_cg)->HasU()) {
(*iter)->setU(vec(1,0,0));
(*iter)->setV(vec(0,1,0));
(*iter)->setW(vec(0,0,1));
}
b->UpdateCrg();
}
}
void QMTopology::LoadListCharges(const string &file)
{
_jcalc.Initialize(file);
}
void QMTopology::AddAtomisticBeads(CrgUnit *crg, Topology * totop){
mol_and_orb * atoms = crg->rotate_translate_beads();
totop->CreateResidue("DUM");
Molecule *mi = totop->CreateMolecule((crg)->getName());
mi->setUserData(crg); //mi->getUserData<CrgUnit>();
for (int i=0;i<atoms->getN();i++){
vec pos = unit<bohr,nm>::to(atoms->GetPos(i));
string atomtype = string( atoms->gettype(i) )+ string("-") + lexical_cast<string>(crg->getId());
BeadType * bt= totop->GetOrCreateBeadType(atomtype);
Bead * bead = totop ->CreateBead(1, atomtype,bt,0, 0, 0.);
bead->setPos(pos);
mi->AddBead(bead,"???");
if(crg->getType()->GetCrgUnit().getChargesNeutr()) {
double charge_of_bead_neutral=crg->getType()->GetCrgUnit().getChargesNeutr()->mpls[i];
bead->setQ(charge_of_bead_neutral);
}
}
delete atoms->getorbs();
delete atoms;
}
Bead *QMTopology::CreateBead(byte_t symmetry, string name, BeadType *type, int resnr, double m, double q)
{
QMBead *bead = new QMBead(this, _beads.size(), type, symmetry, name, resnr, m, q);
_beads.push_back(bead);
return bead;
}
void QMTopology::InitChargeUnits(){
BeadContainer::iterator itb;
for (itb = _beads.begin() ; itb< _beads.end(); ++itb){
QMBead * bead = dynamic_cast<QMBead *>(*itb);
//initialise the crgunit * only if appropriate extra info is in the cg.xml file
if ( (bead->Options()).exists("qm.crgunitname")){
string namecrgunittype = bead->getType()->getName();
int intpos = (bead->Options()).get("qm.position").as<int>();
string namecrgunit = (bead->Options()).get("qm.crgunitname").as<string>();
//determine whether it has been created already
int molid= bead->getMolecule()->getId();
string molandtype = lexical_cast<string>(molid)+":"+namecrgunit;
CrgUnit * acrg = GetCrgUnitByName(molandtype);
if(acrg == NULL)
acrg = CreateCrgUnit(molandtype, namecrgunittype, molid);
bead->setCrg(acrg);
bead->setiPos(intpos);
}
else{
bead->setCrg(NULL);
}
}
}
// TODO: this function should not be in qmtopology!
void QMTopology::ComputeAllTransferIntegrals(){
for(QMNBList::iterator iter = _nblist.begin();
iter!=_nblist.end();++iter) {
CrgUnit *crg1 = (*iter)->Crg1();
CrgUnit *crg2 = (*iter)->Crg2();
vector <double> Js = GetJCalc().CalcJ(*crg1, *crg2);
(*iter)->setJs(Js);
}
}
// In topology.cc???
//Copy charges to either charged or neutral case
void QMTopology::CopyCharges(CrgUnit *crg, Molecule *mol)
{
if(mol->BeadCount() != crg->getType()->GetCrgUnit().getN())
throw std::runtime_error("QMTopology::CopyCharges: number of atoms in crgunit does not match number of beads in molecule");
if(!crg->getType()->GetCrgUnit().getChargesNeutr())
throw std::runtime_error("QMTopology::CopyCharges: no charges defined");
//loop over all beads in that molecule
for (int i = 0; i < mol->BeadCount(); i++) {
//get charge
double charge_of_bead_i_neutral = crg->getType()->GetCrgUnit().getChargesNeutr()->mpls[i];
//set charge
mol->getBead(i)->setQ(charge_of_bead_i_neutral);
}
}
//Copy charges to either charged or neutral case
void QMTopology::CopyChargesOccupied(CrgUnit *crg, Molecule *mol)
{
if(mol->BeadCount() != crg->getType()->GetCrgUnit().getN())
throw std::runtime_error("QMTopology::CopyCharges: number of atoms in crgunit does not match number of beads in molecule");
if(!crg->getType()->GetCrgUnit().getChargesCrged())
throw std::runtime_error("QMTopology::CopyCharges: no charges defined");
//loop over all beads in that molecule
for (int i = 0; i < mol->BeadCount(); i++) {
//get charge
double charge_of_bead_i_charged = crg->getType()->GetCrgUnit().getChargesCrged()->mpls[i];
//set charge
mol->getBead(i)->setQ(charge_of_bead_i_charged);
}
}
<commit_msg>better check for bead symmetry + positions<commit_after>#include "qmtopology.h"
#include "qmnblist.h"
QMTopology::QMTopology()
{}
QMTopology::~QMTopology()
{}
void QMTopology::Initialize(Topology& cg_top)
{
CopyTopologyData(&cg_top);
this->InitChargeUnits();
}
void QMTopology::Cleanup()
{
vector<CrgUnit *>::iterator iter;
for(iter=_crgunits.begin(); iter!=_crgunits.end(); ++iter)
delete *iter;
_crgunits.clear();
_mcharges.clear();
Topology::Cleanup();
}
void QMTopology::Update(Topology& cg_top)
{
BeadContainer::iterator iter;
BeadContainer::iterator iter_cg;
assert(cg_top.Beads().size() == _beads.size());
_box = cg_top.getBox();
_time = cg_top.getTime();
_step = cg_top.getStep();
iter_cg = cg_top.Beads().begin();
for(iter=_beads.begin(); iter!=_beads.end(); ++iter, ++iter_cg) {
(*iter)->setPos((*iter_cg)->getPos());
if((*iter_cg)->HasU())
(*iter)->setU((*iter_cg)->getU());
if((*iter_cg)->HasV())
(*iter)->setV((*iter_cg)->getV());
if((*iter_cg)->HasW())
(*iter)->setW((*iter_cg)->getW());
QMBead * b = (QMBead*)(*iter);
if((*iter_cg)->getSymmetry() == 1) {
(*iter)->setU(vec(1,0,0));
(*iter)->setV(vec(0,1,0));
(*iter)->setW(vec(0,0,1));
}
b->UpdateCrg();
}
}
void QMTopology::LoadListCharges(const string &file)
{
_jcalc.Initialize(file);
}
void QMTopology::AddAtomisticBeads(CrgUnit *crg, Topology * totop){
mol_and_orb * atoms = crg->rotate_translate_beads();
totop->CreateResidue("DUM");
Molecule *mi = totop->CreateMolecule((crg)->getName());
mi->setUserData(crg); //mi->getUserData<CrgUnit>();
for (int i=0;i<atoms->getN();i++){
vec pos = unit<bohr,nm>::to(atoms->GetPos(i));
string atomtype = string( atoms->gettype(i) )+ string("-") + lexical_cast<string>(crg->getId());
BeadType * bt= totop->GetOrCreateBeadType(atomtype);
Bead * bead = totop ->CreateBead(1, atomtype,bt,0, 0, 0.);
bead->setPos(pos);
mi->AddBead(bead,"???");
if(crg->getType()->GetCrgUnit().getChargesNeutr()) {
double charge_of_bead_neutral=crg->getType()->GetCrgUnit().getChargesNeutr()->mpls[i];
bead->setQ(charge_of_bead_neutral);
}
}
delete atoms->getorbs();
delete atoms;
}
Bead *QMTopology::CreateBead(byte_t symmetry, string name, BeadType *type, int resnr, double m, double q)
{
QMBead *bead = new QMBead(this, _beads.size(), type, symmetry, name, resnr, m, q);
_beads.push_back(bead);
return bead;
}
void QMTopology::InitChargeUnits(){
BeadContainer::iterator itb;
for (itb = _beads.begin() ; itb< _beads.end(); ++itb){
QMBead * bead = dynamic_cast<QMBead *>(*itb);
//initialise the crgunit * only if appropriate extra info is in the cg.xml file
if ( (bead->Options()).exists("qm.crgunitname")){
string namecrgunittype = bead->getType()->getName();
int intpos = (bead->Options()).get("qm.position").as<int>();
string namecrgunit = (bead->Options()).get("qm.crgunitname").as<string>();
//determine whether it has been created already
int molid= bead->getMolecule()->getId();
string molandtype = lexical_cast<string>(molid)+":"+namecrgunit;
CrgUnit * acrg = GetCrgUnitByName(molandtype);
if(acrg == NULL)
acrg = CreateCrgUnit(molandtype, namecrgunittype, molid);
bead->setCrg(acrg);
bead->setiPos(intpos);
}
else{
bead->setCrg(NULL);
}
}
}
// TODO: this function should not be in qmtopology!
void QMTopology::ComputeAllTransferIntegrals(){
for(QMNBList::iterator iter = _nblist.begin();
iter!=_nblist.end();++iter) {
CrgUnit *crg1 = (*iter)->Crg1();
CrgUnit *crg2 = (*iter)->Crg2();
vector <double> Js = GetJCalc().CalcJ(*crg1, *crg2);
(*iter)->setJs(Js);
}
}
// In topology.cc???
//Copy charges to either charged or neutral case
void QMTopology::CopyCharges(CrgUnit *crg, Molecule *mol)
{
if(mol->BeadCount() != crg->getType()->GetCrgUnit().getN())
throw std::runtime_error("QMTopology::CopyCharges: number of atoms in crgunit does not match number of beads in molecule");
if(!crg->getType()->GetCrgUnit().getChargesNeutr())
throw std::runtime_error("QMTopology::CopyCharges: no charges defined");
//loop over all beads in that molecule
for (int i = 0; i < mol->BeadCount(); i++) {
//get charge
double charge_of_bead_i_neutral = crg->getType()->GetCrgUnit().getChargesNeutr()->mpls[i];
//set charge
mol->getBead(i)->setQ(charge_of_bead_i_neutral);
}
}
//Copy charges to either charged or neutral case
void QMTopology::CopyChargesOccupied(CrgUnit *crg, Molecule *mol)
{
if(mol->BeadCount() != crg->getType()->GetCrgUnit().getN())
throw std::runtime_error("QMTopology::CopyCharges: number of atoms in crgunit does not match number of beads in molecule");
if(!crg->getType()->GetCrgUnit().getChargesCrged())
throw std::runtime_error("QMTopology::CopyCharges: no charges defined");
//loop over all beads in that molecule
for (int i = 0; i < mol->BeadCount(); i++) {
//get charge
double charge_of_bead_i_charged = crg->getType()->GetCrgUnit().getChargesCrged()->mpls[i];
//set charge
mol->getBead(i)->setQ(charge_of_bead_i_charged);
}
}
<|endoftext|>
|
<commit_before>#include <AnimationComponent.hpp>
#include <queue>
#include <iostream>
#include <assimp/scene.h>
#include <Core/Containers/AlignedStdVector.hpp>
#include <Core/Utils/Graph/AdjacencyListOperation.hpp>
#include <Core/Animation/Pose/Pose.hpp>
#include <Core/Animation/Handle/HandleWeightOperation.hpp>
#include <Core/Animation/Handle/SkeletonUtils.hpp>
#include <Engine/Assets/KeyFrame/KeyTransform.hpp>
#include <Engine/Assets/KeyFrame/KeyPose.hpp>
#include <Engine/Managers/ComponentMessenger/ComponentMessenger.hpp>
#include <Drawing/SkeletonBoneDrawable.hpp>
#include "Core/Mesh/TriangleMesh.hpp"
using Ra::Engine::ComponentMessenger;
using Ra::Core::Animation::RefPose;
using Ra::Core::Animation::Skeleton;
using Ra::Core::Animation::WeightMatrix;
namespace AnimationPlugin
{
bool AnimationComponent::picked(uint drawableIdx)
{
for (const auto& dr: m_boneDrawables)
{
if ( dr->getRenderObjectIndex() == int( drawableIdx ) )
{
m_selectedBone = dr->getBoneIndex();
return true;
}
}
return false;
}
void AnimationComponent::getProperties(Ra::Core::AlignedStdVector<Ra::Engine::EditableProperty> &propsOut) const
{
if ( m_selectedBone < 0 || uint(m_selectedBone) >= m_skel.size() )
{
return;
}
CORE_ASSERT(m_selectedBone >= 0 && uint(m_selectedBone) < m_skel.size(), "Oops");
uint i = m_selectedBone;
{
const Ra::Core::Transform& tr = m_skel.getPose( Ra::Core::Animation::Handle::SpaceType::MODEL)[i];
propsOut.push_back(Ra::Engine::EditableProperty(tr, std::string("Transform ") + std::to_string(i) + "-" + m_skel.getLabel(i)));
}
}
void AnimationComponent::setProperty(const Ra::Engine::EditableProperty &prop)
{
int boneIdx = -1;
CORE_ASSERT(prop.type == Ra::Engine::EditableProperty::TRANSFORM, "Only bones transforms are editable");
for (uint i =0; i < m_skel.size(); ++i)
{
if (prop.name == std::string("Transform ") + std::to_string(i) + "-" + m_skel.getLabel(i))
{
boneIdx = i;
break;
}
}
CORE_ASSERT(boneIdx >=0 , "Property not found in skeleton");
Ra::Core::Transform tr = m_skel.getPose( Ra::Core::Animation::Handle::SpaceType::MODEL)[boneIdx];
// TODO (val) this code is copied from entity.cpp and could be factored.
for(const auto& entry: prop.primitives)
{
const Ra::Engine::EditablePrimitive& prim = entry.primitive;
switch (prim.getType())
{
case Ra::Engine::EditablePrimitive::POSITION:
{
CORE_ASSERT(prim.getName() == "Position", "Inconsistent primitive");
// Val : ignore translation for now (todo : use the flags in primitive).
// tr.translation() = prim.asPosition();
}
break;
case Ra::Engine::EditablePrimitive::ROTATION:
{
CORE_ASSERT(prim.getName() == "Rotation", "Inconsistent primitive");
tr.linear() = prim.asRotation().toRotationMatrix();
}
break;
default:
{
CORE_ASSERT(false, "Wrong primitive type in property");
}
break;
}
}
// Transforms are edited in model space but applied to local space.
const Ra::Core::Transform& TBoneModel = m_skel.getTransform(boneIdx, Ra::Core::Animation::Handle::SpaceType::MODEL);
const Ra::Core::Transform& TBoneLocal = m_skel.getTransform(boneIdx, Ra::Core::Animation::Handle::SpaceType::LOCAL);
auto diff = TBoneModel.inverse() * tr;
m_skel.setTransform(boneIdx,TBoneLocal * diff, Ra::Core::Animation::Handle::SpaceType::LOCAL);
}
void AnimationComponent::setSkeleton(const Ra::Core::Animation::Skeleton& skel)
{
m_skel = skel;
m_refPose = skel.getPose( Ra::Core::Animation::Handle::SpaceType::MODEL);
}
void AnimationComponent::update(Scalar dt)
{
if( dt != 0.0 ) {
const Scalar factor = ( m_slowMo ? 0.1 : 1.0 ) * m_speed;
dt = factor * ( ( m_animationTimeStep ) ? m_dt[m_animationID] : dt );
}
// Ignore large dt that appear when the engine is paused (while loading a file for instance)
if( !m_animationTimeStep && ( dt > 0.5 ) )
{
dt = 0;
}
// Compute the elapsed time
m_animationTime += dt;
// get the current pose from the animation
if ( dt > 0 && m_animations.size() > 0)
{
m_wasReset = false;
Ra::Core::Animation::Pose currentPose = m_animations[m_animationID].getPose(m_animationTime);
// update the pose of the skeleton
m_skel.setPose(currentPose, Ra::Core::Animation::Handle::SpaceType::LOCAL);
}
// update the render objects
for (SkeletonBoneRenderObject* bone : m_boneDrawables)
{
bone->update();
}
}
void AnimationComponent::setupSkeletonDisplay()
{
for( uint i = 0; i < m_skel.size(); ++i ) {
if( !m_skel.m_graph.isLeaf( i ) ) {
SkeletonBoneRenderObject* boneRenderObject = new SkeletonBoneRenderObject( m_skel.getLabel( i ), this, i, getRoMgr());
m_boneDrawables.push_back(boneRenderObject);
m_renderObjects.push_back( boneRenderObject->getRenderObjectIndex());
} else {
LOG( logDEBUG ) << "Bone " << m_skel.getLabel( i ) << " not displayed.";
}
}
}
void AnimationComponent::printSkeleton(const Ra::Core::Animation::Skeleton& skeleton)
{
std::deque<int> queue;
std::deque<int> levels;
queue.push_back(0);
levels.push_back(0);
while (!queue.empty())
{
int i = queue.front();
queue.pop_front();
int level = levels.front();
levels.pop_front();
std::cout<<i<<" "<<skeleton.getLabel(i)<<"\t";
for(auto c : skeleton.m_graph.m_child[i] )
{
queue.push_back(c);
levels.push_back(level+1);
}
if( levels.front() != level)
{
std::cout<<std::endl;
}
}
}
void AnimationComponent::reset()
{
m_animationTime = 0;
m_skel.setPose(m_refPose, Ra::Core::Animation::Handle::SpaceType::MODEL);
for (SkeletonBoneRenderObject* bone : m_boneDrawables)
{
bone->update();
}
m_wasReset = true;
}
Ra::Core::Animation::Pose AnimationComponent::getRefPose() const
{
return m_refPose;
}
Ra::Core::Animation::WeightMatrix AnimationComponent::getWeights() const
{
return m_weights;
}
void AnimationComponent::handleSkeletonLoading( const Ra::Asset::HandleData* data, const std::map< uint, uint >& duplicateTable ) {
std::string name( m_name );
name.append( "_" + data->getName() );
std::string skelName = name;
skelName.append( "_SKEL" );
m_skel.setName( name );
m_contentName = data->getName();
std::map< uint, uint > indexTable;
createSkeleton( data, indexTable );
createWeightMatrix( data, indexTable, duplicateTable );
m_refPose = m_skel.getPose( Ra::Core::Animation::Handle::SpaceType::MODEL);
setupSkeletonDisplay();
setupIO(m_contentName);
}
void AnimationComponent::handleAnimationLoading( const std::vector< Ra::Asset::AnimationData* > data ) {
m_animations.clear();
CORE_ASSERT( ( m_skel.size() != 0 ), "At least a skeleton should be loaded first.");
if( data.empty() ) return;
std::map< uint, uint > table;
std::set< Ra::Asset::Time > keyTime;
for( uint n = 0; n < data.size(); ++n ) {
auto handleAnim = data[n]->getFrames();
for( uint i = 0; i < m_skel.size(); ++i ) {
for( uint j = 0; j < handleAnim.size(); ++j ) {
if( m_skel.getLabel( i ) == handleAnim[j].m_name ) {
table[j] = i;
auto set = handleAnim[j].m_anim.timeSchedule();
keyTime.insert( set.begin(), set.end() );
}
}
}
Ra::Asset::KeyPose keypose;
Ra::Core::Animation::Pose pose = m_skel.m_pose;
m_animations.push_back( Ra::Core::Animation::Animation() );
for( const auto& t : keyTime ) {
for( const auto& it : table ) {
pose[it.second] = ( m_skel.m_graph.isRoot( it.second ) ) ? m_skel.m_pose[it.second] : handleAnim[it.first].m_anim.at( t );
}
m_animations.back().addKeyPose( pose, t );
keypose.insertKeyFrame( t, pose );
}
m_dt.push_back( data[n]->getTimeStep() );
}
m_animationID = 0;
m_animationTime = 0.0;
}
void AnimationComponent::createSkeleton( const Ra::Asset::HandleData* data, std::map< uint, uint >& indexTable ) {
const uint size = data->getComponentDataSize();
auto component = data->getComponentData();
std::set< uint > root;
for( uint i = 0; i < size; ++i ) {
root.insert( i );
}
auto edgeList = data->getEdgeData();
for( const auto& edge : edgeList ) {
root.erase( edge[1] );
}
std::vector< bool > processed( size, false );
for( const auto& r : root ) {
addBone( -1, r, component, edgeList, processed, indexTable );
}
}
void AnimationComponent::addBone( const int parent,
const uint dataID,
const Ra::Core::AlignedStdVector< Ra::Asset::HandleComponentData >& data,
const Ra::Core::AlignedStdVector< Ra::Core::Vector2i >& edgeList,
std::vector< bool >& processed,
std::map< uint, uint >& indexTable ) {
if( !processed[dataID] ) {
processed[dataID] = true;
uint index = m_skel.addBone( parent, data.at( dataID ).m_frame, Ra::Core::Animation::Handle::SpaceType::MODEL, data.at( dataID ).m_name );
indexTable[dataID] = index;
for( const auto& edge : edgeList ) {
if( edge[0] == dataID ) {
addBone( index, edge[1], data, edgeList, processed, indexTable );
}
}
}
}
void AnimationComponent::createWeightMatrix( const Ra::Asset::HandleData* data, const std::map< uint, uint >& indexTable, const std::map< uint, uint >& duplicateTable ) {
// Bad bad bad hack
// Fails eventually with a 1 vertex mesh
uint vertexSize = 0;
for( const auto& item : duplicateTable ) {
if( item.second > vertexSize ) {
vertexSize = ( item.second > vertexSize ) ? item.second : vertexSize;
}
}
vertexSize++;
m_weights.resize( vertexSize, data->getComponentDataSize() );
//m_weights.resize( data->getVertexSize(), data->getComponentDataSize() );
//m_weights.setZero();
for( const auto& it : indexTable ) {
const uint idx = it.first;
const uint col = it.second;
const uint size = data->getComponent( idx ).m_weight.size();
for( uint i = 0; i < size; ++i ) {
const uint row = duplicateTable.at( data->getComponent( idx ).m_weight[i].first );
const Scalar w = data->getComponent( idx ).m_weight[i].second;
m_weights.coeffRef( row, col ) = w;
}
}
Ra::Core::Animation::checkWeightMatrix( m_weights, false );
}
void AnimationComponent::setupIO(const std::string &id)
{
ComponentMessenger::CallbackTypes<Skeleton>::Getter skelOut = std::bind( &AnimationComponent::getSkeletonOutput, this );
ComponentMessenger::getInstance()->registerOutput<Skeleton>( getEntity(), this, id, skelOut);
ComponentMessenger::CallbackTypes<RefPose>::Getter refpOut = std::bind( &AnimationComponent::getRefPoseOutput, this );
ComponentMessenger::getInstance()->registerOutput<Ra::Core::Animation::Pose>( getEntity(), this, id, refpOut);
ComponentMessenger::CallbackTypes<WeightMatrix>::Getter wOut = std::bind( &AnimationComponent::getWeightsOutput, this );
ComponentMessenger::getInstance()->registerOutput<Ra::Core::Animation::WeightMatrix>( getEntity(), this, id, wOut);
ComponentMessenger::CallbackTypes<bool>::Getter resetOut = std::bind( &AnimationComponent::getWasReset, this );
ComponentMessenger::getInstance()->registerOutput<bool>( getEntity(), this, id, resetOut);
}
const Ra::Core::Animation::Skeleton* AnimationComponent::getSkeletonOutput() const
{
return &m_skel;
}
const Ra::Core::Animation::WeightMatrix* AnimationComponent::getWeightsOutput() const
{
return &m_weights;
}
const Ra::Core::Animation::RefPose* AnimationComponent::getRefPoseOutput() const
{
return &m_refPose;
}
const bool* AnimationComponent::getWasReset() const
{
return &m_wasReset;
}
void AnimationComponent::toggleXray(bool on) const
{
for (const auto& b : m_boneDrawables)
{
b->toggleXray(on);
}
}
void AnimationComponent::toggleSkeleton( const bool status ) {
for (const auto& b : m_boneDrawables)
{
const auto id = b->getRenderObjectIndex();
getRoMgr()->getRenderObject( id )->setVisible( status );
}
}
void AnimationComponent::toggleAnimationTimeStep( const bool status ) {
m_animationTimeStep = status;
}
void AnimationComponent::setSpeed( const Scalar value ) {
m_speed = value;
}
void AnimationComponent::toggleSlowMotion( const bool status ) {
m_slowMo = status;
}
void AnimationComponent::setAnimation( const uint i ) {
if( i < m_animations.size() ) {
m_animationID = i;
}
}
}
<commit_msg>Enabled the animation of the root bone from the files<commit_after>#include <AnimationComponent.hpp>
#include <queue>
#include <iostream>
#include <assimp/scene.h>
#include <Core/Containers/AlignedStdVector.hpp>
#include <Core/Utils/Graph/AdjacencyListOperation.hpp>
#include <Core/Animation/Pose/Pose.hpp>
#include <Core/Animation/Handle/HandleWeightOperation.hpp>
#include <Core/Animation/Handle/SkeletonUtils.hpp>
#include <Engine/Assets/KeyFrame/KeyTransform.hpp>
#include <Engine/Assets/KeyFrame/KeyPose.hpp>
#include <Engine/Managers/ComponentMessenger/ComponentMessenger.hpp>
#include <Drawing/SkeletonBoneDrawable.hpp>
#include "Core/Mesh/TriangleMesh.hpp"
using Ra::Engine::ComponentMessenger;
using Ra::Core::Animation::RefPose;
using Ra::Core::Animation::Skeleton;
using Ra::Core::Animation::WeightMatrix;
namespace AnimationPlugin
{
bool AnimationComponent::picked(uint drawableIdx)
{
for (const auto& dr: m_boneDrawables)
{
if ( dr->getRenderObjectIndex() == int( drawableIdx ) )
{
m_selectedBone = dr->getBoneIndex();
return true;
}
}
return false;
}
void AnimationComponent::getProperties(Ra::Core::AlignedStdVector<Ra::Engine::EditableProperty> &propsOut) const
{
if ( m_selectedBone < 0 || uint(m_selectedBone) >= m_skel.size() )
{
return;
}
CORE_ASSERT(m_selectedBone >= 0 && uint(m_selectedBone) < m_skel.size(), "Oops");
uint i = m_selectedBone;
{
const Ra::Core::Transform& tr = m_skel.getPose( Ra::Core::Animation::Handle::SpaceType::MODEL)[i];
propsOut.push_back(Ra::Engine::EditableProperty(tr, std::string("Transform ") + std::to_string(i) + "-" + m_skel.getLabel(i)));
}
}
void AnimationComponent::setProperty(const Ra::Engine::EditableProperty &prop)
{
int boneIdx = -1;
CORE_ASSERT(prop.type == Ra::Engine::EditableProperty::TRANSFORM, "Only bones transforms are editable");
for (uint i =0; i < m_skel.size(); ++i)
{
if (prop.name == std::string("Transform ") + std::to_string(i) + "-" + m_skel.getLabel(i))
{
boneIdx = i;
break;
}
}
CORE_ASSERT(boneIdx >=0 , "Property not found in skeleton");
Ra::Core::Transform tr = m_skel.getPose( Ra::Core::Animation::Handle::SpaceType::MODEL)[boneIdx];
// TODO (val) this code is copied from entity.cpp and could be factored.
for(const auto& entry: prop.primitives)
{
const Ra::Engine::EditablePrimitive& prim = entry.primitive;
switch (prim.getType())
{
case Ra::Engine::EditablePrimitive::POSITION:
{
CORE_ASSERT(prim.getName() == "Position", "Inconsistent primitive");
// Val : ignore translation for now (todo : use the flags in primitive).
// tr.translation() = prim.asPosition();
}
break;
case Ra::Engine::EditablePrimitive::ROTATION:
{
CORE_ASSERT(prim.getName() == "Rotation", "Inconsistent primitive");
tr.linear() = prim.asRotation().toRotationMatrix();
}
break;
default:
{
CORE_ASSERT(false, "Wrong primitive type in property");
}
break;
}
}
// Transforms are edited in model space but applied to local space.
const Ra::Core::Transform& TBoneModel = m_skel.getTransform(boneIdx, Ra::Core::Animation::Handle::SpaceType::MODEL);
const Ra::Core::Transform& TBoneLocal = m_skel.getTransform(boneIdx, Ra::Core::Animation::Handle::SpaceType::LOCAL);
auto diff = TBoneModel.inverse() * tr;
m_skel.setTransform(boneIdx,TBoneLocal * diff, Ra::Core::Animation::Handle::SpaceType::LOCAL);
}
void AnimationComponent::setSkeleton(const Ra::Core::Animation::Skeleton& skel)
{
m_skel = skel;
m_refPose = skel.getPose( Ra::Core::Animation::Handle::SpaceType::MODEL);
}
void AnimationComponent::update(Scalar dt)
{
if( dt != 0.0 ) {
const Scalar factor = ( m_slowMo ? 0.1 : 1.0 ) * m_speed;
dt = factor * ( ( m_animationTimeStep ) ? m_dt[m_animationID] : dt );
}
// Ignore large dt that appear when the engine is paused (while loading a file for instance)
if( !m_animationTimeStep && ( dt > 0.5 ) )
{
dt = 0;
}
// Compute the elapsed time
m_animationTime += dt;
// get the current pose from the animation
if ( dt > 0 && m_animations.size() > 0)
{
m_wasReset = false;
Ra::Core::Animation::Pose currentPose = m_animations[m_animationID].getPose(m_animationTime);
// update the pose of the skeleton
m_skel.setPose(currentPose, Ra::Core::Animation::Handle::SpaceType::LOCAL);
}
// update the render objects
for (SkeletonBoneRenderObject* bone : m_boneDrawables)
{
bone->update();
}
}
void AnimationComponent::setupSkeletonDisplay()
{
for( uint i = 0; i < m_skel.size(); ++i ) {
if( !m_skel.m_graph.isLeaf( i ) ) {
SkeletonBoneRenderObject* boneRenderObject = new SkeletonBoneRenderObject( m_skel.getLabel( i ), this, i, getRoMgr());
m_boneDrawables.push_back(boneRenderObject);
m_renderObjects.push_back( boneRenderObject->getRenderObjectIndex());
} else {
LOG( logDEBUG ) << "Bone " << m_skel.getLabel( i ) << " not displayed.";
}
}
}
void AnimationComponent::printSkeleton(const Ra::Core::Animation::Skeleton& skeleton)
{
std::deque<int> queue;
std::deque<int> levels;
queue.push_back(0);
levels.push_back(0);
while (!queue.empty())
{
int i = queue.front();
queue.pop_front();
int level = levels.front();
levels.pop_front();
std::cout<<i<<" "<<skeleton.getLabel(i)<<"\t";
for(auto c : skeleton.m_graph.m_child[i] )
{
queue.push_back(c);
levels.push_back(level+1);
}
if( levels.front() != level)
{
std::cout<<std::endl;
}
}
}
void AnimationComponent::reset()
{
m_animationTime = 0;
m_skel.setPose(m_refPose, Ra::Core::Animation::Handle::SpaceType::MODEL);
for (SkeletonBoneRenderObject* bone : m_boneDrawables)
{
bone->update();
}
m_wasReset = true;
}
Ra::Core::Animation::Pose AnimationComponent::getRefPose() const
{
return m_refPose;
}
Ra::Core::Animation::WeightMatrix AnimationComponent::getWeights() const
{
return m_weights;
}
void AnimationComponent::handleSkeletonLoading( const Ra::Asset::HandleData* data, const std::map< uint, uint >& duplicateTable ) {
std::string name( m_name );
name.append( "_" + data->getName() );
std::string skelName = name;
skelName.append( "_SKEL" );
m_skel.setName( name );
m_contentName = data->getName();
std::map< uint, uint > indexTable;
createSkeleton( data, indexTable );
createWeightMatrix( data, indexTable, duplicateTable );
m_refPose = m_skel.getPose( Ra::Core::Animation::Handle::SpaceType::MODEL);
setupSkeletonDisplay();
setupIO(m_contentName);
}
void AnimationComponent::handleAnimationLoading( const std::vector< Ra::Asset::AnimationData* > data ) {
m_animations.clear();
CORE_ASSERT( ( m_skel.size() != 0 ), "At least a skeleton should be loaded first.");
if( data.empty() ) return;
std::map< uint, uint > table;
std::set< Ra::Asset::Time > keyTime;
for( uint n = 0; n < data.size(); ++n ) {
auto handleAnim = data[n]->getFrames();
for( uint i = 0; i < m_skel.size(); ++i ) {
for( uint j = 0; j < handleAnim.size(); ++j ) {
if( m_skel.getLabel( i ) == handleAnim[j].m_name ) {
table[j] = i;
auto set = handleAnim[j].m_anim.timeSchedule();
keyTime.insert( set.begin(), set.end() );
}
}
}
Ra::Asset::KeyPose keypose;
Ra::Core::Animation::Pose pose = m_skel.m_pose;
m_animations.push_back( Ra::Core::Animation::Animation() );
for( const auto& t : keyTime ) {
for( const auto& it : table ) {
//pose[it.second] = ( m_skel.m_graph.isRoot( it.second ) ) ? m_skel.m_pose[it.second] : handleAnim[it.first].m_anim.at( t );
pose[it.second] = handleAnim[it.first].m_anim.at( t );
}
m_animations.back().addKeyPose( pose, t );
keypose.insertKeyFrame( t, pose );
}
m_dt.push_back( data[n]->getTimeStep() );
}
m_animationID = 0;
m_animationTime = 0.0;
}
void AnimationComponent::createSkeleton( const Ra::Asset::HandleData* data, std::map< uint, uint >& indexTable ) {
const uint size = data->getComponentDataSize();
auto component = data->getComponentData();
std::set< uint > root;
for( uint i = 0; i < size; ++i ) {
root.insert( i );
}
auto edgeList = data->getEdgeData();
for( const auto& edge : edgeList ) {
root.erase( edge[1] );
}
std::vector< bool > processed( size, false );
for( const auto& r : root ) {
addBone( -1, r, component, edgeList, processed, indexTable );
}
}
void AnimationComponent::addBone( const int parent,
const uint dataID,
const Ra::Core::AlignedStdVector< Ra::Asset::HandleComponentData >& data,
const Ra::Core::AlignedStdVector< Ra::Core::Vector2i >& edgeList,
std::vector< bool >& processed,
std::map< uint, uint >& indexTable ) {
if( !processed[dataID] ) {
processed[dataID] = true;
uint index = m_skel.addBone( parent, data.at( dataID ).m_frame, Ra::Core::Animation::Handle::SpaceType::MODEL, data.at( dataID ).m_name );
indexTable[dataID] = index;
for( const auto& edge : edgeList ) {
if( edge[0] == dataID ) {
addBone( index, edge[1], data, edgeList, processed, indexTable );
}
}
}
}
void AnimationComponent::createWeightMatrix( const Ra::Asset::HandleData* data, const std::map< uint, uint >& indexTable, const std::map< uint, uint >& duplicateTable ) {
// Bad bad bad hack
// Fails eventually with a 1 vertex mesh
uint vertexSize = 0;
for( const auto& item : duplicateTable ) {
if( item.second > vertexSize ) {
vertexSize = ( item.second > vertexSize ) ? item.second : vertexSize;
}
}
vertexSize++;
m_weights.resize( vertexSize, data->getComponentDataSize() );
//m_weights.resize( data->getVertexSize(), data->getComponentDataSize() );
//m_weights.setZero();
for( const auto& it : indexTable ) {
const uint idx = it.first;
const uint col = it.second;
const uint size = data->getComponent( idx ).m_weight.size();
for( uint i = 0; i < size; ++i ) {
const uint row = duplicateTable.at( data->getComponent( idx ).m_weight[i].first );
const Scalar w = data->getComponent( idx ).m_weight[i].second;
m_weights.coeffRef( row, col ) = w;
}
}
Ra::Core::Animation::checkWeightMatrix( m_weights, false );
}
void AnimationComponent::setupIO(const std::string &id)
{
ComponentMessenger::CallbackTypes<Skeleton>::Getter skelOut = std::bind( &AnimationComponent::getSkeletonOutput, this );
ComponentMessenger::getInstance()->registerOutput<Skeleton>( getEntity(), this, id, skelOut);
ComponentMessenger::CallbackTypes<RefPose>::Getter refpOut = std::bind( &AnimationComponent::getRefPoseOutput, this );
ComponentMessenger::getInstance()->registerOutput<Ra::Core::Animation::Pose>( getEntity(), this, id, refpOut);
ComponentMessenger::CallbackTypes<WeightMatrix>::Getter wOut = std::bind( &AnimationComponent::getWeightsOutput, this );
ComponentMessenger::getInstance()->registerOutput<Ra::Core::Animation::WeightMatrix>( getEntity(), this, id, wOut);
ComponentMessenger::CallbackTypes<bool>::Getter resetOut = std::bind( &AnimationComponent::getWasReset, this );
ComponentMessenger::getInstance()->registerOutput<bool>( getEntity(), this, id, resetOut);
}
const Ra::Core::Animation::Skeleton* AnimationComponent::getSkeletonOutput() const
{
return &m_skel;
}
const Ra::Core::Animation::WeightMatrix* AnimationComponent::getWeightsOutput() const
{
return &m_weights;
}
const Ra::Core::Animation::RefPose* AnimationComponent::getRefPoseOutput() const
{
return &m_refPose;
}
const bool* AnimationComponent::getWasReset() const
{
return &m_wasReset;
}
void AnimationComponent::toggleXray(bool on) const
{
for (const auto& b : m_boneDrawables)
{
b->toggleXray(on);
}
}
void AnimationComponent::toggleSkeleton( const bool status ) {
for (const auto& b : m_boneDrawables)
{
const auto id = b->getRenderObjectIndex();
getRoMgr()->getRenderObject( id )->setVisible( status );
}
}
void AnimationComponent::toggleAnimationTimeStep( const bool status ) {
m_animationTimeStep = status;
}
void AnimationComponent::setSpeed( const Scalar value ) {
m_speed = value;
}
void AnimationComponent::toggleSlowMotion( const bool status ) {
m_slowMo = status;
}
void AnimationComponent::setAnimation( const uint i ) {
if( i < m_animations.size() ) {
m_animationID = i;
}
}
}
<|endoftext|>
|
<commit_before>#ifndef ANIMPLUGIN_ANIMATION_COMPONENT_HPP_
#define ANIMPLUGIN_ANIMATION_COMPONENT_HPP_
#include <AnimationPluginMacros.hpp>
#include <Core/Animation/Animation.hpp>
#include <Core/Animation/Handle/Skeleton.hpp>
#include <Core/Animation/Handle/HandleWeight.hpp>
#include <Core/Animation/Pose/Pose.hpp>
#include <Core/File/AnimationData.hpp>
#include <Core/File/HandleData.hpp>
#include <Engine/Component/Component.hpp>
#include <memory>
namespace AnimationPlugin
{
class SkeletonBoneRenderObject;
class AnimationComponent : public Ra::Engine::Component
{
public:
AnimationComponent(const std::string& name);
virtual ~AnimationComponent();
virtual void initialize() override{}
void setSkeleton(const Ra::Core::Animation::Skeleton& skel);
inline Ra::Core::Animation::Skeleton& getSkeleton() { return m_skel; }
ANIM_PLUGIN_API Ra::Core::Animation::WeightMatrix getWeights() const;
ANIM_PLUGIN_API Ra::Core::Animation::Pose getRefPose() const;
/// Update the skeleton with an animation.
void update(Scalar dt);
void reset();
ANIM_PLUGIN_API void setXray(bool on) const;
void toggleSkeleton( const bool status );
void toggleAnimationTimeStep( const bool status );
void setSpeed( const Scalar value );
void toggleSlowMotion( const bool status );
void setAnimation( const uint i );
uint getBoneIdx(Ra::Core::Index index) const ;
Scalar getTime() const;
void handleSkeletonLoading( const Ra::Asset::HandleData* data, const std::vector<uint>& duplicateTable, uint nbMeshVertices );
void handleAnimationLoading( const std::vector< Ra::Asset::AnimationData* > data );
//
// Editable interface
//
virtual bool canEdit(Ra::Core::Index roIdx) const override;
virtual Ra::Core::Transform getTransform(Ra::Core::Index roIdx) const override;
virtual void setTransform(Ra::Core::Index roIdx, const Ra::Core::Transform& transform) override;
public:
// debug function to display the hierarchy
void printSkeleton(const Ra::Core::Animation::Skeleton& skeleton);
//
// Loading data functions
//
void setWeights (Ra::Core::Animation::WeightMatrix m);
// Component communication
void setContentName (const std::string name);
void setupIO( const std::string& id );
const Ra::Core::Animation::Skeleton* getSkeletonOutput() const;
const Ra::Core::Animation::RefPose* getRefPoseOutput() const;
const Ra::Core::Animation::WeightMatrix* getWeightsOutput() const;
const bool* getWasReset() const;
const Ra::Core::Animation::Animation* getAnimation() const;
const Scalar* getTimeOutput() const;
private:
// Internal function to create the skinning weights.
void createWeightMatrix( const Ra::Asset::HandleData* data, const std::map< uint, uint >& indexTable,
const std::vector<uint>& duplicateTable, uint nbMeshVertices );
// Internal function to create the bone display objects.
void setupSkeletonDisplay();
private:
std::string m_contentName;
Ra::Core::Animation::Skeleton m_skel; // Skeleton
Ra::Core::Animation::RefPose m_refPose; // Ref pose in model space.
std::vector<Ra::Core::Animation::Animation> m_animations;
Ra::Core::Animation::WeightMatrix m_weights; // Skinning weights ( should go in skinning )
std::vector< std::unique_ptr<SkeletonBoneRenderObject> > m_boneDrawables ; // Vector of bone display objects
uint m_animationID;
bool m_animationTimeStep;
Scalar m_animationTime;
std::vector< Scalar > m_dt;
Scalar m_speed;
bool m_slowMo;
bool m_wasReset;
bool m_resetDone;
};
}
#endif //ANIMPLUGIN_ANIMATION_COMPONENT_HPP_
<commit_msg>Add missing ANIM_PLUGIN_API macro on AnimationComponent class<commit_after>#ifndef ANIMPLUGIN_ANIMATION_COMPONENT_HPP_
#define ANIMPLUGIN_ANIMATION_COMPONENT_HPP_
#include <AnimationPluginMacros.hpp>
#include <Core/Animation/Animation.hpp>
#include <Core/Animation/Handle/Skeleton.hpp>
#include <Core/Animation/Handle/HandleWeight.hpp>
#include <Core/Animation/Pose/Pose.hpp>
#include <Core/File/AnimationData.hpp>
#include <Core/File/HandleData.hpp>
#include <Engine/Component/Component.hpp>
#include <memory>
namespace AnimationPlugin
{
class SkeletonBoneRenderObject;
class ANIM_PLUGIN_API AnimationComponent : public Ra::Engine::Component
{
public:
AnimationComponent(const std::string& name);
virtual ~AnimationComponent();
virtual void initialize() override{}
void setSkeleton(const Ra::Core::Animation::Skeleton& skel);
inline Ra::Core::Animation::Skeleton& getSkeleton() { return m_skel; }
Ra::Core::Animation::WeightMatrix getWeights() const;
Ra::Core::Animation::Pose getRefPose() const;
/// Update the skeleton with an animation.
void update(Scalar dt);
void reset();
void setXray(bool on) const;
void toggleSkeleton( const bool status );
void toggleAnimationTimeStep( const bool status );
void setSpeed( const Scalar value );
void toggleSlowMotion( const bool status );
void setAnimation( const uint i );
uint getBoneIdx(Ra::Core::Index index) const ;
Scalar getTime() const;
void handleSkeletonLoading( const Ra::Asset::HandleData* data, const std::vector<uint>& duplicateTable, uint nbMeshVertices );
void handleAnimationLoading( const std::vector< Ra::Asset::AnimationData* > data );
//
// Editable interface
//
virtual bool canEdit(Ra::Core::Index roIdx) const override;
virtual Ra::Core::Transform getTransform(Ra::Core::Index roIdx) const override;
virtual void setTransform(Ra::Core::Index roIdx, const Ra::Core::Transform& transform) override;
public:
// debug function to display the hierarchy
void printSkeleton(const Ra::Core::Animation::Skeleton& skeleton);
//
// Loading data functions
//
void setWeights (Ra::Core::Animation::WeightMatrix m);
// Component communication
void setContentName (const std::string name);
void setupIO( const std::string& id );
const Ra::Core::Animation::Skeleton* getSkeletonOutput() const;
const Ra::Core::Animation::RefPose* getRefPoseOutput() const;
const Ra::Core::Animation::WeightMatrix* getWeightsOutput() const;
const bool* getWasReset() const;
const Ra::Core::Animation::Animation* getAnimation() const;
const Scalar* getTimeOutput() const;
private:
// Internal function to create the skinning weights.
void createWeightMatrix( const Ra::Asset::HandleData* data, const std::map< uint, uint >& indexTable,
const std::vector<uint>& duplicateTable, uint nbMeshVertices );
// Internal function to create the bone display objects.
void setupSkeletonDisplay();
private:
std::string m_contentName;
Ra::Core::Animation::Skeleton m_skel; // Skeleton
Ra::Core::Animation::RefPose m_refPose; // Ref pose in model space.
std::vector<Ra::Core::Animation::Animation> m_animations;
Ra::Core::Animation::WeightMatrix m_weights; // Skinning weights ( should go in skinning )
std::vector< std::unique_ptr<SkeletonBoneRenderObject> > m_boneDrawables ; // Vector of bone display objects
uint m_animationID;
bool m_animationTimeStep;
Scalar m_animationTime;
std::vector< Scalar > m_dt;
Scalar m_speed;
bool m_slowMo;
bool m_wasReset;
bool m_resetDone;
};
}
#endif //ANIMPLUGIN_ANIMATION_COMPONENT_HPP_
<|endoftext|>
|
<commit_before>/*------------------------------------------------------------------------
* Vulkan Conformance Tests
* ------------------------
*
* Copyright (c) 2019 Google LLC
* Copyright (c) 2019 The Khronos Group 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.
*
*//*!
* \file
* \brief Functional tests using amber
*//*--------------------------------------------------------------------*/
#include <amber/amber.h>
#include <iostream>
#include "deDefs.hpp"
#include "deUniquePtr.hpp"
#include "deFilePath.hpp"
#include "vktTestCaseUtil.hpp"
#include "tcuTestLog.hpp"
#include "vktAmberTestCase.hpp"
#include "vktAmberHelper.hpp"
#include "tcuResource.hpp"
#include "tcuTestLog.hpp"
namespace vkt
{
namespace cts_amber
{
AmberTestCase::AmberTestCase (tcu::TestContext& testCtx,
const char* name,
const char* description)
: TestCase(testCtx, name, description),
m_recipe(DE_NULL)
{
}
AmberTestCase::~AmberTestCase (void)
{
delete m_recipe;
}
TestInstance* AmberTestCase::createInstance(Context& ctx) const
{
return new AmberTestInstance(ctx, m_recipe);
}
static amber::EngineConfig* createEngineConfig(Context& ctx)
{
amber::EngineConfig* vkConfig = GetVulkanConfig(ctx.getInstance(),
ctx.getPhysicalDevice(), ctx.getDevice(), &ctx.getDeviceFeatures(),
&ctx.getDeviceFeatures2(), ctx.getInstanceExtensions(),
ctx.getDeviceExtensions(), ctx.getUniversalQueueFamilyIndex(),
ctx.getUniversalQueue(), ctx.getInstanceProcAddr());
return vkConfig;
}
// Returns true if the given feature is supported by the device.
// Throws an internal error If the feature is not recognized at all.
static bool isFeatureSupported(const vkt::Context& ctx, const std::string& feature)
{
if (feature == "Features.shaderInt16")
return ctx.getDeviceFeatures().shaderInt16;
if (feature == "Features.shaderInt64")
return ctx.getDeviceFeatures().shaderInt64;
if (feature == "Features.tessellationShader")
return ctx.getDeviceFeatures().tessellationShader;
if (feature == "Features.geometryShader")
return ctx.getDeviceFeatures().tessellationShader;
if (feature == "Features.vertexPipelineStoresAndAtomics")
return ctx.getDeviceFeatures().vertexPipelineStoresAndAtomics;
if (feature == "VariablePointerFeatures.variablePointersStorageBuffer")
return ctx.getVariablePointersFeatures().variablePointersStorageBuffer;
if (feature == "VariablePointerFeatures.variablePointers")
return ctx.getVariablePointersFeatures().variablePointers;
std::string message = std::string("Unexpected feature name: ") + feature;
TCU_THROW(InternalError, message.c_str());
}
void AmberTestCase::checkSupport(Context& ctx) const
{
// Check for instance and device extensions as declared by the test code.
if (m_required_extensions.size())
{
std::set<std::string> device_extensions(ctx.getDeviceExtensions().begin(),
ctx.getDeviceExtensions().end());
std::set<std::string> instance_extensions(ctx.getInstanceExtensions().begin(),
ctx.getInstanceExtensions().end());
std::string missing;
for (std::set<std::string>::iterator iter = m_required_extensions.begin();
iter != m_required_extensions.end();
++iter)
{
const std::string extension = *iter;
if ((device_extensions.count(extension) == 0) &&
(instance_extensions.count(extension) == 0))
{
missing += " " + extension;
}
}
if (missing.size() > 0)
{
std::string message("Test requires unsupported extensions:");
message += missing;
TCU_THROW(NotSupportedError, message.c_str());
}
}
// Check for required features. Do this after extensions are checked because
// some feature checks are only valid when corresponding extensions are enabled.
if (m_required_features.size())
{
std::string missing;
for (std::set<std::string>::iterator iter = m_required_features.begin();
iter != m_required_features.end();
++iter)
{
const std::string feature = *iter;
if (!isFeatureSupported(ctx, feature))
{
missing += " " + feature;
}
}
if (missing.size() > 0)
{
std::string message("Test requires unsupported features:");
message += missing;
TCU_THROW(NotSupportedError, message.c_str());
}
}
// Check for extensions as declared by the Amber script itself. Throw an internal
// error if that's more demanding.
amber::Amber am;
amber::Options amber_options;
amber_options.engine = amber::kEngineTypeVulkan;
amber_options.config = createEngineConfig(ctx);
amber_options.delegate = DE_NULL;
amber::Result r = am.AreAllRequirementsSupported(m_recipe, &amber_options);
if (!r.IsSuccess())
{
// dEQP does not to rely on external code to determine whether
// a test is supported. So throw an internal error here instead
// of a NotSupportedError. If an Amber test is not supported, then
// you must override this method and throw a NotSupported exception
// before reach here.
TCU_THROW(InternalError, r.Error().c_str());
}
delete amber_options.config;
}
bool AmberTestCase::parse(const char* category, const std::string& filename)
{
std::string readFilename("vulkan/amber/");
readFilename.append(category);
readFilename.append("/");
readFilename.append(filename);
std::string script = ShaderSourceProvider::getSource(m_testCtx.getArchive(), readFilename.c_str());
if (script.empty())
return false;
m_recipe = new amber::Recipe();
amber::Amber am;
amber::Result r = am.Parse(script, m_recipe);
if (!r.IsSuccess())
{
getTestContext().getLog()
<< tcu::TestLog::Message
<< "Failed to parse Amber test "
<< readFilename
<< ": "
<< r.Error()
<< "\n"
<< tcu::TestLog::EndMessage;
// TODO(dneto): Enhance Amber to not require this.
m_recipe->SetImpl(DE_NULL);
return false;
}
return true;
}
void AmberTestCase::initPrograms(vk::SourceCollections& programCollection) const
{
std::vector<amber::ShaderInfo> shaders = m_recipe->GetShaderInfo();
for (size_t i = 0; i < shaders.size(); ++i)
{
const amber::ShaderInfo& shader = shaders[i];
/* Hex encoded shaders do not need to be pre-compiled */
if (shader.format == amber::kShaderFormatSpirvHex)
continue;
if (shader.format == amber::kShaderFormatSpirvAsm)
{
programCollection.spirvAsmSources.add(shader.shader_name) << shader.shader_source;
}
else if (shader.format == amber::kShaderFormatGlsl)
{
switch (shader.type)
{
case amber::kShaderTypeCompute:
programCollection.glslSources.add(shader.shader_name)
<< glu::ComputeSource(shader.shader_source)
<< vk::ShaderBuildOptions(programCollection.usedVulkanVersion, vk::SPIRV_VERSION_1_0, 0u);
break;
case amber::kShaderTypeGeometry:
programCollection.glslSources.add(shader.shader_name)
<< glu::GeometrySource(shader.shader_source)
<< vk::ShaderBuildOptions(programCollection.usedVulkanVersion, vk::SPIRV_VERSION_1_0, 0u);
break;
case amber::kShaderTypeFragment:
programCollection.glslSources.add(shader.shader_name)
<< glu::FragmentSource(shader.shader_source)
<< vk::ShaderBuildOptions(programCollection.usedVulkanVersion, vk::SPIRV_VERSION_1_0, 0u);
break;
case amber::kShaderTypeVertex:
programCollection.glslSources.add(shader.shader_name)
<< glu::VertexSource(shader.shader_source)
<< vk::ShaderBuildOptions(programCollection.usedVulkanVersion, vk::SPIRV_VERSION_1_0, 0u);
break;
case amber::kShaderTypeTessellationControl:
programCollection.glslSources.add(shader.shader_name)
<< glu::TessellationControlSource(shader.shader_source)
<< vk::ShaderBuildOptions(programCollection.usedVulkanVersion, vk::SPIRV_VERSION_1_0, 0u);
break;
case amber::kShaderTypeTessellationEvaluation:
programCollection.glslSources.add(shader.shader_name)
<< glu::TessellationEvaluationSource(shader.shader_source)
<< vk::ShaderBuildOptions(programCollection.usedVulkanVersion, vk::SPIRV_VERSION_1_0, 0u);
break;
case amber::kShaderTypeMulti:
DE_ASSERT(false && "Multi shaders not supported");
break;
}
}
else
{
DE_ASSERT(false && "Shader format not supported");
}
}
}
tcu::TestStatus AmberTestInstance::iterate (void)
{
amber::ShaderMap shaderMap;
std::vector<amber::ShaderInfo> shaders = m_recipe->GetShaderInfo();
for (size_t i = 0; i < shaders.size(); ++i)
{
const amber::ShaderInfo& shader = shaders[i];
if (!m_context.getBinaryCollection().contains(shader.shader_name))
continue;
size_t len = m_context.getBinaryCollection().get(shader.shader_name).getSize();
/* This is a compiled spir-v binary which must be made of 4-byte words. We
* are moving into a word sized vector so divide by 4
*/
std::vector<deUint32> data;
data.resize(len >> 2);
deMemcpy(data.data(), m_context.getBinaryCollection().get(shader.shader_name).getBinary(), len);
shaderMap[shader.shader_name] = data;
}
amber::Amber am;
amber::Options amber_options;
amber_options.engine = amber::kEngineTypeVulkan;
amber_options.config = createEngineConfig(m_context);
amber_options.delegate = DE_NULL;
amber_options.pipeline_create_only = false;
amber::Result r = am.ExecuteWithShaderData(m_recipe, &amber_options, shaderMap);
if (!r.IsSuccess()) {
m_context.getTestContext().getLog()
<< tcu::TestLog::Message
<< r.Error()
<< "\n"
<< tcu::TestLog::EndMessage;
}
delete amber_options.config;
return r.IsSuccess() ? tcu::TestStatus::pass("Pass") :tcu::TestStatus::fail("Fail");
}
void AmberTestCase::addRequirement(const std::string& requirement)
{
if (requirement.find(".") != std::string::npos)
m_required_features.insert(requirement);
else
m_required_extensions.insert(requirement);
}
} // cts_amber
} // vkt
<commit_msg>Fix AmberTestCase feature mapping for geometryShader<commit_after>/*------------------------------------------------------------------------
* Vulkan Conformance Tests
* ------------------------
*
* Copyright (c) 2019 Google LLC
* Copyright (c) 2019 The Khronos Group 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.
*
*//*!
* \file
* \brief Functional tests using amber
*//*--------------------------------------------------------------------*/
#include <amber/amber.h>
#include <iostream>
#include "deDefs.hpp"
#include "deUniquePtr.hpp"
#include "deFilePath.hpp"
#include "vktTestCaseUtil.hpp"
#include "tcuTestLog.hpp"
#include "vktAmberTestCase.hpp"
#include "vktAmberHelper.hpp"
#include "tcuResource.hpp"
#include "tcuTestLog.hpp"
namespace vkt
{
namespace cts_amber
{
AmberTestCase::AmberTestCase (tcu::TestContext& testCtx,
const char* name,
const char* description)
: TestCase(testCtx, name, description),
m_recipe(DE_NULL)
{
}
AmberTestCase::~AmberTestCase (void)
{
delete m_recipe;
}
TestInstance* AmberTestCase::createInstance(Context& ctx) const
{
return new AmberTestInstance(ctx, m_recipe);
}
static amber::EngineConfig* createEngineConfig(Context& ctx)
{
amber::EngineConfig* vkConfig = GetVulkanConfig(ctx.getInstance(),
ctx.getPhysicalDevice(), ctx.getDevice(), &ctx.getDeviceFeatures(),
&ctx.getDeviceFeatures2(), ctx.getInstanceExtensions(),
ctx.getDeviceExtensions(), ctx.getUniversalQueueFamilyIndex(),
ctx.getUniversalQueue(), ctx.getInstanceProcAddr());
return vkConfig;
}
// Returns true if the given feature is supported by the device.
// Throws an internal error If the feature is not recognized at all.
static bool isFeatureSupported(const vkt::Context& ctx, const std::string& feature)
{
if (feature == "Features.shaderInt16")
return ctx.getDeviceFeatures().shaderInt16;
if (feature == "Features.shaderInt64")
return ctx.getDeviceFeatures().shaderInt64;
if (feature == "Features.tessellationShader")
return ctx.getDeviceFeatures().tessellationShader;
if (feature == "Features.geometryShader")
return ctx.getDeviceFeatures().geometryShader;
if (feature == "Features.vertexPipelineStoresAndAtomics")
return ctx.getDeviceFeatures().vertexPipelineStoresAndAtomics;
if (feature == "VariablePointerFeatures.variablePointersStorageBuffer")
return ctx.getVariablePointersFeatures().variablePointersStorageBuffer;
if (feature == "VariablePointerFeatures.variablePointers")
return ctx.getVariablePointersFeatures().variablePointers;
std::string message = std::string("Unexpected feature name: ") + feature;
TCU_THROW(InternalError, message.c_str());
}
void AmberTestCase::checkSupport(Context& ctx) const
{
// Check for instance and device extensions as declared by the test code.
if (m_required_extensions.size())
{
std::set<std::string> device_extensions(ctx.getDeviceExtensions().begin(),
ctx.getDeviceExtensions().end());
std::set<std::string> instance_extensions(ctx.getInstanceExtensions().begin(),
ctx.getInstanceExtensions().end());
std::string missing;
for (std::set<std::string>::iterator iter = m_required_extensions.begin();
iter != m_required_extensions.end();
++iter)
{
const std::string extension = *iter;
if ((device_extensions.count(extension) == 0) &&
(instance_extensions.count(extension) == 0))
{
missing += " " + extension;
}
}
if (missing.size() > 0)
{
std::string message("Test requires unsupported extensions:");
message += missing;
TCU_THROW(NotSupportedError, message.c_str());
}
}
// Check for required features. Do this after extensions are checked because
// some feature checks are only valid when corresponding extensions are enabled.
if (m_required_features.size())
{
std::string missing;
for (std::set<std::string>::iterator iter = m_required_features.begin();
iter != m_required_features.end();
++iter)
{
const std::string feature = *iter;
if (!isFeatureSupported(ctx, feature))
{
missing += " " + feature;
}
}
if (missing.size() > 0)
{
std::string message("Test requires unsupported features:");
message += missing;
TCU_THROW(NotSupportedError, message.c_str());
}
}
// Check for extensions as declared by the Amber script itself. Throw an internal
// error if that's more demanding.
amber::Amber am;
amber::Options amber_options;
amber_options.engine = amber::kEngineTypeVulkan;
amber_options.config = createEngineConfig(ctx);
amber_options.delegate = DE_NULL;
amber::Result r = am.AreAllRequirementsSupported(m_recipe, &amber_options);
if (!r.IsSuccess())
{
// dEQP does not to rely on external code to determine whether
// a test is supported. So throw an internal error here instead
// of a NotSupportedError. If an Amber test is not supported, then
// you must override this method and throw a NotSupported exception
// before reach here.
TCU_THROW(InternalError, r.Error().c_str());
}
delete amber_options.config;
}
bool AmberTestCase::parse(const char* category, const std::string& filename)
{
std::string readFilename("vulkan/amber/");
readFilename.append(category);
readFilename.append("/");
readFilename.append(filename);
std::string script = ShaderSourceProvider::getSource(m_testCtx.getArchive(), readFilename.c_str());
if (script.empty())
return false;
m_recipe = new amber::Recipe();
amber::Amber am;
amber::Result r = am.Parse(script, m_recipe);
if (!r.IsSuccess())
{
getTestContext().getLog()
<< tcu::TestLog::Message
<< "Failed to parse Amber test "
<< readFilename
<< ": "
<< r.Error()
<< "\n"
<< tcu::TestLog::EndMessage;
// TODO(dneto): Enhance Amber to not require this.
m_recipe->SetImpl(DE_NULL);
return false;
}
return true;
}
void AmberTestCase::initPrograms(vk::SourceCollections& programCollection) const
{
std::vector<amber::ShaderInfo> shaders = m_recipe->GetShaderInfo();
for (size_t i = 0; i < shaders.size(); ++i)
{
const amber::ShaderInfo& shader = shaders[i];
/* Hex encoded shaders do not need to be pre-compiled */
if (shader.format == amber::kShaderFormatSpirvHex)
continue;
if (shader.format == amber::kShaderFormatSpirvAsm)
{
programCollection.spirvAsmSources.add(shader.shader_name) << shader.shader_source;
}
else if (shader.format == amber::kShaderFormatGlsl)
{
switch (shader.type)
{
case amber::kShaderTypeCompute:
programCollection.glslSources.add(shader.shader_name)
<< glu::ComputeSource(shader.shader_source)
<< vk::ShaderBuildOptions(programCollection.usedVulkanVersion, vk::SPIRV_VERSION_1_0, 0u);
break;
case amber::kShaderTypeGeometry:
programCollection.glslSources.add(shader.shader_name)
<< glu::GeometrySource(shader.shader_source)
<< vk::ShaderBuildOptions(programCollection.usedVulkanVersion, vk::SPIRV_VERSION_1_0, 0u);
break;
case amber::kShaderTypeFragment:
programCollection.glslSources.add(shader.shader_name)
<< glu::FragmentSource(shader.shader_source)
<< vk::ShaderBuildOptions(programCollection.usedVulkanVersion, vk::SPIRV_VERSION_1_0, 0u);
break;
case amber::kShaderTypeVertex:
programCollection.glslSources.add(shader.shader_name)
<< glu::VertexSource(shader.shader_source)
<< vk::ShaderBuildOptions(programCollection.usedVulkanVersion, vk::SPIRV_VERSION_1_0, 0u);
break;
case amber::kShaderTypeTessellationControl:
programCollection.glslSources.add(shader.shader_name)
<< glu::TessellationControlSource(shader.shader_source)
<< vk::ShaderBuildOptions(programCollection.usedVulkanVersion, vk::SPIRV_VERSION_1_0, 0u);
break;
case amber::kShaderTypeTessellationEvaluation:
programCollection.glslSources.add(shader.shader_name)
<< glu::TessellationEvaluationSource(shader.shader_source)
<< vk::ShaderBuildOptions(programCollection.usedVulkanVersion, vk::SPIRV_VERSION_1_0, 0u);
break;
case amber::kShaderTypeMulti:
DE_ASSERT(false && "Multi shaders not supported");
break;
}
}
else
{
DE_ASSERT(false && "Shader format not supported");
}
}
}
tcu::TestStatus AmberTestInstance::iterate (void)
{
amber::ShaderMap shaderMap;
std::vector<amber::ShaderInfo> shaders = m_recipe->GetShaderInfo();
for (size_t i = 0; i < shaders.size(); ++i)
{
const amber::ShaderInfo& shader = shaders[i];
if (!m_context.getBinaryCollection().contains(shader.shader_name))
continue;
size_t len = m_context.getBinaryCollection().get(shader.shader_name).getSize();
/* This is a compiled spir-v binary which must be made of 4-byte words. We
* are moving into a word sized vector so divide by 4
*/
std::vector<deUint32> data;
data.resize(len >> 2);
deMemcpy(data.data(), m_context.getBinaryCollection().get(shader.shader_name).getBinary(), len);
shaderMap[shader.shader_name] = data;
}
amber::Amber am;
amber::Options amber_options;
amber_options.engine = amber::kEngineTypeVulkan;
amber_options.config = createEngineConfig(m_context);
amber_options.delegate = DE_NULL;
amber_options.pipeline_create_only = false;
amber::Result r = am.ExecuteWithShaderData(m_recipe, &amber_options, shaderMap);
if (!r.IsSuccess()) {
m_context.getTestContext().getLog()
<< tcu::TestLog::Message
<< r.Error()
<< "\n"
<< tcu::TestLog::EndMessage;
}
delete amber_options.config;
return r.IsSuccess() ? tcu::TestStatus::pass("Pass") :tcu::TestStatus::fail("Fail");
}
void AmberTestCase::addRequirement(const std::string& requirement)
{
if (requirement.find(".") != std::string::npos)
m_required_features.insert(requirement);
else
m_required_extensions.insert(requirement);
}
} // cts_amber
} // vkt
<|endoftext|>
|
<commit_before>#include "KAI/KAI.h"
#include <iostream>
#include <strstream>
#include <stdarg.h>
#include "KAI/Translator/Lexer.h"
using namespace std;
KAI_BEGIN
Lexer::Lexer(const char *in)
: input(in)
{
CreateLines();
AddKeywords();
Run();
}
void Lexer::AddKeywords()
{
keyWords["if"] = Token::If;
keyWords["else"] = Token::Else;
keyWords["for"] = Token::For;
keyWords["true"] = Token::True;
keyWords["false"] = Token::False;
keyWords["return"] = Token::Return;
keyWords["self"] = Token::Self;
keyWords["fun"] = Token::Fun;
keyWords["yield"] = Token::Yield;
keyWords["in"] = Token::In;
keyWords["while"] = Token::While;
keyWords["assert"] = Token::Assert;
}
bool Lexer::Run()
{
offset = 0;
lineNumber = 0;
while (!Failed && NextToken())
;
return Add(Token::None, 0);
}
void Lexer::Print() const
{
for (auto tok : tokens)
std::cout << tok << " ";
std::cout << std::endl;
}
Slice Lexer::Gather(int (*filt)(int))
{
int start = offset;
while (filt(Next()))
;
return Slice(start, offset);
}
bool Lexer::Add(Token::Type type, Slice slice)
{
tokens.push_back(Token(type, *this, lineNumber, slice));
return true;
}
bool Lexer::Add(Token::Type type, int len)
{
Add(type, Slice(offset, offset + len));
while (len--)
Next();
return true;
}
bool Lexer::LexAlpha()
{
Token tok(Token::Ident, *this, lineNumber, Gather(isalnum));
auto kw = keyWords.find(tok.Text());
if (kw != keyWords.end())
tok.type = kw->second;
tokens.push_back(tok);
return true;
}
int IsSpaceChar(int ch)
{
return ch == ' ';
}
bool Lexer::NextToken()
{
auto current = Current();
if (current == 0)
return false;
if (isalpha(current))
return LexAlpha();
if (isdigit(current))
return Add(Token::Int, Gather(isdigit));
switch (current)
{
case ':': return Add(Token::Colon);
case '\t': return Add(Token::Tab);
case '\n': return Add(Token::NewLine);
case ' ': return Add(Token::Whitespace, Gather(IsSpaceChar));
case '@': return Add(Token::Lookup);
case '\'': return LexAlpha();
case '-':
{
if (Peek() == '-')
{
Next();
return Add(Token::Decrement);
}
if (Peek() == '=')
{
Next();
return Add(Token::MinusAssign);
}
return Add(Token::Minus);
}
case '.':
{
if (Peek() == '.')
{
Next();
if (Peek() == '.')
{
Next();
return Add(Token::Replace, 3);
}
else
{
return Fail("Two dots");
}
}
return Add(Token::Dot);
}
case ',': return Add(Token::Comma);
case '+':
{
if (Peek() == '+')
{
Next();
return Add(Token::Increment);
}
if (Peek() == '=')
{
Next();
return Add(Token::PlusAssign);
}
return Add(Token::Plus);
}
case '*': return Add(Token::Mul);
case '/':
{
if (Peek() == '/')
{
Next();
int start = offset;
while (Next() != '\n')
;
return Add(Token::Comment, offset - start);
}
return Add(Token::Divide);
}
case ';': return Add(Token::Semi);
case '{': return Add(Token::OpenBrace);
case '}': return Add(Token::CloseBrace);
case '(': return Add(Token::OpenParan);
case ')': return Add(Token::CloseParan);
case '=': return AddIfNext('=', Token::Equiv, Token::Assign);
case '[': return Add(Token::OpenSquareBracket);
case ']': return Add(Token::CloseSquareBracket);
case '!': return AddIfNext('=', Token::NotEquiv, Token::Not);
case '&': return AddIfNext('&', Token::And, Token::BitAnd);
case '|': return AddIfNext('|', Token::Or, Token::BitOr);
case '"': return LexString();
}
if (current == '<')
{
if (Peek() == '=')
{
return AddTwoCharOp(Token::LessEquiv);
}
return Add(Token::Less);
}
if (current == '>')
{
if (Peek() == '=')
{
return AddTwoCharOp(Token::GreaterEqiv);
}
return Add(Token::Greater);
}
LexError("Unrecognised %c");
return false;
}
std::string Lexer::CreateError(Token tok, const char *fmt, ...)
{
char buff0[2000];
va_list ap;
va_start(ap, fmt);
vsprintf_s(buff0, fmt, ap);
const char *fmt1 = "%s(%d):[%d]: %s\n";
char buff[2000];
sprintf_s(buff, fmt1, "", tok.lineNumber, tok.slice.Start, buff0);
int beforeContext = 1;
int afterContext = 0;
const Lexer &lex = *tok.lexer;
int start = std::max(0, tok.lineNumber - beforeContext);
int end = std::min((int)lex.lines.size() - 1, tok.lineNumber + afterContext);
strstream err;
err << buff << endl;
for (int n = start; n <= end; ++n)
{
for (auto ch : lex.lines[n])
{
if (ch == '\t')
err << " ";
else
err << ch;
}
if (n == tok.lineNumber)
{
for (int ch = 0; ch < (int)lex.lines[n].size(); ++ch)
{
if (lex.lines[tok.lineNumber][ch] == '\t')
err << " ";
else if (ch == tok.slice.Start)
{
err << '^';
break;
}
}
err << endl;
}
}
err << ends;
return err.str();
}
bool Process::Fail(const std::string &err)
{
Failed = true;
Error = err;
return false;
}
bool Process::Fail(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
char buffer[1000];
vsprintf_s(buffer, fmt, ap);
return Fail(std::string(buffer));
}
char Lexer::Current() const
{
if (lineNumber == (int)lines.size())
return 0;
return Line()[offset];
}
const std::string &Lexer::Line() const
{
return lines[lineNumber];
}
char Lexer::Next()
{
if (EndOfLine())
{
offset = 0;
++lineNumber;
}
else
++offset;
if (lineNumber == (int)lines.size())
return 0;
return Line()[offset];
}
char Lexer::Peek() const
{
if (EndOfLine())
return 0;
return Line()[offset + 1];
}
void Lexer::CreateLines()
{
input.push_back('\n');
size_t lineStart = 0;
for (size_t n = 0; n < input.size(); ++n)
{
if (input[n] == '\n')
{
lines.push_back(input.substr(lineStart, n - lineStart + 1));
lineStart = n + 1;
}
}
}
bool Lexer::EndOfLine() const
{
return offset == (int)Line().size() - 1;
}
bool Lexer::AddIfNext(char ch, Token::Type thenType, Token::Type elseType)
{
if (Peek() == ch)
{
Next();
return Add(thenType, 2);
}
return Add(elseType, 1);
}
bool Lexer::AddTwoCharOp(Token::Type ty)
{
Add(ty, 2);
Next();
return true;
}
bool Lexer::LexString()
{
int start = offset;
Next();
while (!Failed && Current() != '"')
{
if (Current() == '\\')
{
switch (Next())
{
case '"':
case 'n':
case 't':
break;
default:
LexError("Bad escape sequence %c");
return false;
}
}
Next();
}
Next();
tokens.push_back(Token(Token::String, *this, lineNumber, Slice(start, offset)));
return true;
}
void Lexer::LexError(const char *text)
{
Fail(CreateError(Token(Token::None, *this, lineNumber, Slice(offset, offset)), text, Current()));
}
KAI_END
<commit_msg>Fix crash bug in LexString() with input of "<commit_after>#include "KAI/KAI.h"
#include <iostream>
#include <strstream>
#include <stdarg.h>
#include "KAI/Translator/Lexer.h"
using namespace std;
KAI_BEGIN
Lexer::Lexer(const char *in)
: input(in)
{
CreateLines();
AddKeywords();
Run();
}
void Lexer::AddKeywords()
{
keyWords["if"] = Token::If;
keyWords["else"] = Token::Else;
keyWords["for"] = Token::For;
keyWords["true"] = Token::True;
keyWords["false"] = Token::False;
keyWords["return"] = Token::Return;
keyWords["self"] = Token::Self;
keyWords["fun"] = Token::Fun;
keyWords["yield"] = Token::Yield;
keyWords["in"] = Token::In;
keyWords["while"] = Token::While;
keyWords["assert"] = Token::Assert;
}
bool Lexer::Run()
{
offset = 0;
lineNumber = 0;
while (!Failed && NextToken())
;
return Add(Token::None, 0);
}
void Lexer::Print() const
{
for (auto tok : tokens)
std::cout << tok << " ";
std::cout << std::endl;
}
Slice Lexer::Gather(int (*filt)(int))
{
int start = offset;
while (filt(Next()))
;
return Slice(start, offset);
}
bool Lexer::Add(Token::Type type, Slice slice)
{
tokens.push_back(Token(type, *this, lineNumber, slice));
return true;
}
bool Lexer::Add(Token::Type type, int len)
{
Add(type, Slice(offset, offset + len));
while (len--)
Next();
return true;
}
bool Lexer::LexAlpha()
{
Token tok(Token::Ident, *this, lineNumber, Gather(isalnum));
auto kw = keyWords.find(tok.Text());
if (kw != keyWords.end())
tok.type = kw->second;
tokens.push_back(tok);
return true;
}
int IsSpaceChar(int ch)
{
return ch == ' ';
}
bool Lexer::NextToken()
{
auto current = Current();
if (current == 0)
return false;
if (isalpha(current))
return LexAlpha();
if (isdigit(current))
return Add(Token::Int, Gather(isdigit));
switch (current)
{
case ':': return Add(Token::Colon);
case '\t': return Add(Token::Tab);
case '\n': return Add(Token::NewLine);
case ' ': return Add(Token::Whitespace, Gather(IsSpaceChar));
case '@': return Add(Token::Lookup);
case '\'': return LexAlpha();
case '-':
{
if (Peek() == '-')
{
Next();
return Add(Token::Decrement);
}
if (Peek() == '=')
{
Next();
return Add(Token::MinusAssign);
}
return Add(Token::Minus);
}
case '.':
{
if (Peek() == '.')
{
Next();
if (Peek() == '.')
{
Next();
return Add(Token::Replace, 3);
}
else
{
return Fail("Two dots");
}
}
return Add(Token::Dot);
}
case ',': return Add(Token::Comma);
case '+':
{
if (Peek() == '+')
{
Next();
return Add(Token::Increment);
}
if (Peek() == '=')
{
Next();
return Add(Token::PlusAssign);
}
return Add(Token::Plus);
}
case '*': return Add(Token::Mul);
case '/':
{
if (Peek() == '/')
{
Next();
int start = offset;
while (Next() != '\n')
;
return Add(Token::Comment, offset - start);
}
return Add(Token::Divide);
}
case ';': return Add(Token::Semi);
case '{': return Add(Token::OpenBrace);
case '}': return Add(Token::CloseBrace);
case '(': return Add(Token::OpenParan);
case ')': return Add(Token::CloseParan);
case '=': return AddIfNext('=', Token::Equiv, Token::Assign);
case '[': return Add(Token::OpenSquareBracket);
case ']': return Add(Token::CloseSquareBracket);
case '!': return AddIfNext('=', Token::NotEquiv, Token::Not);
case '&': return AddIfNext('&', Token::And, Token::BitAnd);
case '|': return AddIfNext('|', Token::Or, Token::BitOr);
case '"': return LexString();
}
if (current == '<')
{
if (Peek() == '=')
{
return AddTwoCharOp(Token::LessEquiv);
}
return Add(Token::Less);
}
if (current == '>')
{
if (Peek() == '=')
{
return AddTwoCharOp(Token::GreaterEqiv);
}
return Add(Token::Greater);
}
LexError("Unrecognised %c");
return false;
}
std::string Lexer::CreateError(Token tok, const char *fmt, ...)
{
char buff0[2000];
va_list ap;
va_start(ap, fmt);
vsprintf_s(buff0, fmt, ap);
const char *fmt1 = "%s(%d):[%d]: %s\n";
char buff[2000];
sprintf_s(buff, fmt1, "", tok.lineNumber, tok.slice.Start, buff0);
int beforeContext = 1;
int afterContext = 0;
const Lexer &lex = *tok.lexer;
int start = std::max(0, tok.lineNumber - beforeContext);
int end = std::min((int)lex.lines.size() - 1, tok.lineNumber + afterContext);
strstream err;
err << buff << endl;
for (int n = start; n <= end; ++n)
{
for (auto ch : lex.lines[n])
{
if (ch == '\t')
err << " ";
else
err << ch;
}
if (n == tok.lineNumber)
{
for (int ch = 0; ch < (int)lex.lines[n].size(); ++ch)
{
if (lex.lines[tok.lineNumber][ch] == '\t')
err << " ";
else if (ch == tok.slice.Start)
{
err << '^';
break;
}
}
err << endl;
}
}
err << ends;
return err.str();
}
bool Process::Fail(const std::string &err)
{
Failed = true;
Error = err;
return false;
}
bool Process::Fail(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
char buffer[1000];
vsprintf_s(buffer, fmt, ap);
return Fail(std::string(buffer));
}
char Lexer::Current() const
{
if (lineNumber == (int)lines.size())
return 0;
return Line()[offset];
}
const std::string &Lexer::Line() const
{
return lines[lineNumber];
}
char Lexer::Next()
{
if (EndOfLine())
{
offset = 0;
++lineNumber;
}
else
++offset;
if (lineNumber == (int)lines.size())
return 0;
return Line()[offset];
}
char Lexer::Peek() const
{
if (EndOfLine())
return 0;
return Line()[offset + 1];
}
void Lexer::CreateLines()
{
input.push_back('\n');
size_t lineStart = 0;
for (size_t n = 0; n < input.size(); ++n)
{
if (input[n] == '\n')
{
lines.push_back(input.substr(lineStart, n - lineStart + 1));
lineStart = n + 1;
}
}
}
bool Lexer::EndOfLine() const
{
return offset == (int)Line().size() - 1;
}
bool Lexer::AddIfNext(char ch, Token::Type thenType, Token::Type elseType)
{
if (Peek() == ch)
{
Next();
return Add(thenType, 2);
}
return Add(elseType, 1);
}
bool Lexer::AddTwoCharOp(Token::Type ty)
{
Add(ty, 2);
Next();
return true;
}
bool Lexer::LexString()
{
int start = offset;
Next();
while (!Failed && Current() != '"')
{
if (Current() == '\\')
{
switch (Next())
{
case '"':
case 'n':
case 't':
break;
default:
LexError("Bad escape sequence %c");
return false;
}
}
if (Peek() == 0)
{
Fail("Bad string literal");
return false;
}
Next();
}
Next();
tokens.push_back(Token(Token::String, *this, lineNumber, Slice(start, offset)));
return true;
}
void Lexer::LexError(const char *text)
{
Fail(CreateError(Token(Token::None, *this, lineNumber, Slice(offset, offset)), text, Current()));
}
KAI_END
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011-2012.
// 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)
//=======================================================================
#include <unordered_map>
#include "Type.hpp"
#include "ltac/stack_offsets.hpp"
#include "ltac/Address.hpp"
#include "ltac/Register.hpp"
#include "ltac/Statement.hpp"
using namespace eddic;
namespace {
template<typename Type, typename Variant>
bool opt_variant_equals(Variant& opt_variant, Type& value){
if(opt_variant){
if(auto* ptr = boost::get<Type>(&*opt_variant)){
if(*ptr == value){
return true;
}
}
}
return false;
}
template<typename Arg>
void change_address(Arg& arg, int bp_offset){
if(arg){
if(auto* ptr = boost::get<ltac::Address>(&*arg)){
auto& address = *ptr;
if(opt_variant_equals(address.base_register, ltac::BP)){
address.base_register = ltac::SP;
if(address.displacement){
*address.displacement += bp_offset;
} else {
address.displacement = bp_offset;
}
}
}
}
}
}
void ltac::fix_stack_offsets(std::shared_ptr<mtac::Program> program, Platform platform){
int bp_offset = 0;
std::unordered_map<std::string, int> offset_labels;
for(auto& function : program->functions){
for(auto& bb : function){
for(auto& statement : bb->l_statements){
if(auto* ptr = boost::get<std::shared_ptr<ltac::Instruction>>(&statement)){
auto instruction = *ptr;
change_address(instruction->arg1, bp_offset);
change_address(instruction->arg2, bp_offset);
change_address(instruction->arg3, bp_offset);
if(opt_variant_equals(instruction->arg1, ltac::BP)){
if(instruction->op == ltac::Operator::ADD){
bp_offset -= boost::get<int>(*instruction->arg2);
}
if(instruction->op == ltac::Operator::SUB){
bp_offset += boost::get<int>(*instruction->arg2);
}
}
if(instruction->op == ltac::Operator::PUSH){
bp_offset += INT->size(platform);
}
if(instruction->op == ltac::Operator::POP){
bp_offset -= INT->size(platform);
}
} else if(auto* ptr = boost::get<std::string>(&statement)){
if(offset_labels.count(*ptr)){
bp_offset = offset_labels[*ptr];
offset_labels.erase(*ptr);
}
} else if(auto* ptr = boost::get<std::shared_ptr<ltac::Jump>>(&statement)){
auto jump = *ptr;
if(jump->type != ltac::JumpType::CALL && jump->type != ltac::JumpType::ALWAYS){
offset_labels[jump->label] = bp_offset;
}
}
}
}
}
}
<commit_msg>Fix calculation of the stack offset<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011-2012.
// 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)
//=======================================================================
#include <unordered_map>
#include "Type.hpp"
#include "ltac/stack_offsets.hpp"
#include "ltac/Address.hpp"
#include "ltac/Register.hpp"
#include "ltac/Statement.hpp"
using namespace eddic;
namespace {
template<typename Type, typename Variant>
bool opt_variant_equals(Variant& opt_variant, Type& value){
if(opt_variant){
if(auto* ptr = boost::get<Type>(&*opt_variant)){
if(*ptr == value){
return true;
}
}
}
return false;
}
template<typename Arg>
void change_address(Arg& arg, int bp_offset){
if(arg){
if(auto* ptr = boost::get<ltac::Address>(&*arg)){
auto& address = *ptr;
if(opt_variant_equals(address.base_register, ltac::BP)){
address.base_register = ltac::SP;
if(address.displacement){
*address.displacement += bp_offset;
} else {
address.displacement = bp_offset;
}
}
}
}
}
}
void ltac::fix_stack_offsets(std::shared_ptr<mtac::Program> program, Platform platform){
int bp_offset = 0;
std::unordered_map<std::string, int> offset_labels;
for(auto& function : program->functions){
for(auto& bb : function){
for(auto& statement : bb->l_statements){
if(auto* ptr = boost::get<std::shared_ptr<ltac::Instruction>>(&statement)){
auto instruction = *ptr;
change_address(instruction->arg1, bp_offset);
change_address(instruction->arg2, bp_offset);
change_address(instruction->arg3, bp_offset);
if(opt_variant_equals(instruction->arg1, ltac::SP)){
if(instruction->op == ltac::Operator::ADD){
bp_offset -= boost::get<int>(*instruction->arg2);
}
if(instruction->op == ltac::Operator::SUB){
bp_offset += boost::get<int>(*instruction->arg2);
}
}
if(instruction->op == ltac::Operator::PUSH){
bp_offset += INT->size(platform);
}
if(instruction->op == ltac::Operator::POP){
bp_offset -= INT->size(platform);
}
} else if(auto* ptr = boost::get<std::string>(&statement)){
if(offset_labels.count(*ptr)){
bp_offset = offset_labels[*ptr];
offset_labels.erase(*ptr);
}
} else if(auto* ptr = boost::get<std::shared_ptr<ltac::Jump>>(&statement)){
auto jump = *ptr;
if(jump->type != ltac::JumpType::CALL && jump->type != ltac::JumpType::ALWAYS){
offset_labels[jump->label] = bp_offset;
}
}
}
}
}
}
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include "fuprlout.hxx"
#include <vcl/wrkwin.hxx>
#include <sfx2/dispatch.hxx>
#include <svl/smplhint.hxx>
#include <svl/itempool.hxx>
#include <sot/storage.hxx>
#include <vcl/msgbox.hxx>
#include <svx/svdundo.hxx>
#include <sfx2/viewfrm.hxx>
#include <sfx2/request.hxx>
#include "drawdoc.hxx"
#include "sdpage.hxx"
#include "pres.hxx"
#include "DrawViewShell.hxx"
#include "FrameView.hxx"
#include "stlpool.hxx"
#include "View.hxx"
#include "glob.hrc"
#include "glob.hxx"
#include "strings.hrc"
#include "strmname.h"
#include "app.hrc"
#include "DrawDocShell.hxx"
#include "unprlout.hxx"
#include "unchss.hxx"
#include "unmovss.hxx"
#include "sdattr.hxx"
#include "sdresid.hxx"
#include "drawview.hxx"
#include <editeng/outliner.hxx>
#include <editeng/editdata.hxx>
#include "sdabstdlg.hxx"
#include <boost/scoped_ptr.hpp>
namespace sd
{
TYPEINIT1( FuPresentationLayout, FuPoor );
#define DOCUMENT_TOKEN '#'
FuPresentationLayout::FuPresentationLayout (
ViewShell* pViewSh,
::sd::Window* pWin,
::sd::View* pView,
SdDrawDocument* pDoc,
SfxRequest& rReq)
: FuPoor(pViewSh, pWin, pView, pDoc, rReq)
{
}
rtl::Reference<FuPoor> FuPresentationLayout::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq )
{
rtl::Reference<FuPoor> xFunc( new FuPresentationLayout( pViewSh, pWin, pView, pDoc, rReq ) );
xFunc->DoExecute(rReq);
return xFunc;
}
void FuPresentationLayout::DoExecute( SfxRequest& rReq )
{
// prevent selected objects or objects which are under editing from disappearing
mpView->SdrEndTextEdit();
if(mpView->GetSdrPageView())
{
mpView->UnmarkAll();
}
bool bError = false;
// determine the active page
sal_uInt16 nSelectedPage = SDRPAGE_NOTFOUND;
for (sal_uInt16 nPage = 0; nPage < mpDoc->GetSdPageCount(PK_STANDARD); nPage++)
{
if (mpDoc->GetSdPage(nPage, PK_STANDARD)->IsSelected())
{
nSelectedPage = nPage;
break;
}
}
DBG_ASSERT(nSelectedPage != SDRPAGE_NOTFOUND, "no selected page");
SdPage* pSelectedPage = mpDoc->GetSdPage(nSelectedPage, PK_STANDARD);
OUString aOldLayoutName(pSelectedPage->GetLayoutName());
sal_Int32 nPos = aOldLayoutName.indexOf(SD_LT_SEPARATOR);
if (nPos != -1)
aOldLayoutName = aOldLayoutName.copy(0, nPos);
/* if we are on a master page, the changes apply for all pages and notes-
pages who are using the relevant layout */
bool bOnMaster = false;
if( mpViewShell && mpViewShell->ISA(DrawViewShell))
{
EditMode eEditMode =
static_cast<DrawViewShell*>(mpViewShell)->GetEditMode();
if (eEditMode == EM_MASTERPAGE)
bOnMaster = true;
}
bool bMasterPage = bOnMaster;
bool bCheckMasters = false;
// call dialog
bool bLoad = false; // appear the new master pages?
OUString aFile;
SfxItemSet aSet(mpDoc->GetPool(), ATTR_PRESLAYOUT_START, ATTR_PRESLAYOUT_END);
aSet.Put( SfxBoolItem( ATTR_PRESLAYOUT_LOAD, bLoad));
aSet.Put( SfxBoolItem( ATTR_PRESLAYOUT_MASTER_PAGE, bMasterPage ) );
aSet.Put( SfxBoolItem( ATTR_PRESLAYOUT_CHECK_MASTERS, bCheckMasters ) );
aSet.Put( SfxStringItem( ATTR_PRESLAYOUT_NAME, aOldLayoutName));
const SfxItemSet *pArgs = rReq.GetArgs ();
if (pArgs)
{
if (pArgs->GetItemState(ATTR_PRESLAYOUT_LOAD) == SfxItemState::SET)
bLoad = static_cast<const SfxBoolItem&>(pArgs->Get(ATTR_PRESLAYOUT_LOAD)).GetValue();
if( pArgs->GetItemState( ATTR_PRESLAYOUT_MASTER_PAGE ) == SfxItemState::SET )
bMasterPage = static_cast<const SfxBoolItem&>( pArgs->Get( ATTR_PRESLAYOUT_MASTER_PAGE ) ).GetValue();
if( pArgs->GetItemState( ATTR_PRESLAYOUT_CHECK_MASTERS ) == SfxItemState::SET )
bCheckMasters = static_cast<const SfxBoolItem&>( pArgs->Get( ATTR_PRESLAYOUT_CHECK_MASTERS ) ).GetValue();
if (pArgs->GetItemState(ATTR_PRESLAYOUT_NAME) == SfxItemState::SET)
aFile = static_cast<const SfxStringItem&>(pArgs->Get(ATTR_PRESLAYOUT_NAME)).GetValue();
}
else
{
SdAbstractDialogFactory* pFact = SdAbstractDialogFactory::Create();
boost::scoped_ptr<AbstractSdPresLayoutDlg> pDlg(pFact ? pFact->CreateSdPresLayoutDlg(mpDocSh, NULL, aSet ) : 0);
sal_uInt16 nResult = pDlg ? pDlg->Execute() : static_cast<short>(RET_CANCEL);
switch (nResult)
{
case RET_OK:
{
pDlg->GetAttr(aSet);
if (aSet.GetItemState(ATTR_PRESLAYOUT_LOAD) == SfxItemState::SET)
bLoad = static_cast<const SfxBoolItem&>(aSet.Get(ATTR_PRESLAYOUT_LOAD)).GetValue();
if( aSet.GetItemState( ATTR_PRESLAYOUT_MASTER_PAGE ) == SfxItemState::SET )
bMasterPage = static_cast<const SfxBoolItem&>(aSet.Get( ATTR_PRESLAYOUT_MASTER_PAGE ) ).GetValue();
if( aSet.GetItemState( ATTR_PRESLAYOUT_CHECK_MASTERS ) == SfxItemState::SET )
bCheckMasters = static_cast<const SfxBoolItem&>(aSet.Get( ATTR_PRESLAYOUT_CHECK_MASTERS ) ).GetValue();
if (aSet.GetItemState(ATTR_PRESLAYOUT_NAME) == SfxItemState::SET)
aFile = static_cast<const SfxStringItem&>(aSet.Get(ATTR_PRESLAYOUT_NAME)).GetValue();
}
break;
default:
bError = true;
}
}
if (!bError)
{
mpDocSh->SetWaitCursor( true );
/* Here, we only exchange masterpages, therefore the current page
remains the current page. To prevent calling PageOrderChangedHint
during insertion and extraction of the masterpages, we block. */
/* That isn't quitely right. If the masterpageview is active and you are
removing a masterpage, it's possible that you are removing the
current masterpage. So you have to call ResetActualPage ! */
if( mpViewShell->ISA(DrawViewShell) && !bCheckMasters )
static_cast<DrawView*>(mpView)->BlockPageOrderChangedHint(true);
if (bLoad)
{
OUString aFileName = aFile.getToken(0, DOCUMENT_TOKEN);
SdDrawDocument* pTempDoc = mpDoc->OpenBookmarkDoc( aFileName );
// #69581: If I chose the standard-template I got no filename and so I get no
// SdDrawDocument-Pointer. But the method SetMasterPage is able to handle
// a NULL-pointer as a Standard-template ( look at SdDrawDocument::SetMasterPage )
OUString aLayoutName;
if( pTempDoc )
aLayoutName = aFile.getToken(1, DOCUMENT_TOKEN);
mpDoc->SetMasterPage(nSelectedPage, aLayoutName, pTempDoc, bMasterPage, bCheckMasters);
mpDoc->CloseBookmarkDoc();
}
else
{
// use master page with the layout name aFile from current Doc
mpDoc->SetMasterPage(nSelectedPage, aFile, mpDoc, bMasterPage, bCheckMasters);
}
// remove blocking
if (mpViewShell->ISA(DrawViewShell) && !bCheckMasters )
static_cast<DrawView*>(mpView)->BlockPageOrderChangedHint(false);
// if the master page was visible, show it again
if (!bError && nSelectedPage != SDRPAGE_NOTFOUND)
{
if (bOnMaster)
{
if (mpViewShell->ISA(DrawViewShell))
{
::sd::View* pView =
static_cast<DrawViewShell*>(mpViewShell)->GetView();
sal_uInt16 nPgNum = pSelectedPage->TRG_GetMasterPage().GetPageNum();
if (static_cast<DrawViewShell*>(mpViewShell)->GetPageKind() == PK_NOTES)
nPgNum++;
pView->HideSdrPage();
pView->ShowSdrPage(pView->GetModel()->GetMasterPage(nPgNum));
}
// force update of TabBar
mpViewShell->GetViewFrame()->GetDispatcher()->Execute(SID_MASTERPAGE, SfxCallMode::ASYNCHRON | SfxCallMode::RECORD);
}
else
{
pSelectedPage->SetAutoLayout(pSelectedPage->GetAutoLayout());
}
}
// fake a mode change to repaint the page tab bar
if( mpViewShell && mpViewShell->ISA( DrawViewShell ) )
{
DrawViewShell* pDrawViewSh =
static_cast<DrawViewShell*>(mpViewShell);
EditMode eMode = pDrawViewSh->GetEditMode();
bool bLayer = pDrawViewSh->IsLayerModeActive();
pDrawViewSh->ChangeEditMode( eMode, !bLayer );
pDrawViewSh->ChangeEditMode( eMode, bLayer );
}
mpDocSh->SetWaitCursor( false );
}
}
} // end of namespace sd
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>allow slide design to affect multiple standard pages<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include "fuprlout.hxx"
#include <vcl/wrkwin.hxx>
#include <sfx2/dispatch.hxx>
#include <svl/smplhint.hxx>
#include <svl/itempool.hxx>
#include <sot/storage.hxx>
#include <vcl/msgbox.hxx>
#include <svx/svdundo.hxx>
#include <sfx2/viewfrm.hxx>
#include <sfx2/request.hxx>
#include "drawdoc.hxx"
#include "sdpage.hxx"
#include "pres.hxx"
#include "DrawViewShell.hxx"
#include "FrameView.hxx"
#include "stlpool.hxx"
#include "View.hxx"
#include "glob.hrc"
#include "glob.hxx"
#include "strings.hrc"
#include "strmname.h"
#include "app.hrc"
#include "DrawDocShell.hxx"
#include "SlideSorterViewShell.hxx"
#include "unprlout.hxx"
#include "unchss.hxx"
#include "unmovss.hxx"
#include "sdattr.hxx"
#include "sdresid.hxx"
#include "drawview.hxx"
#include <editeng/outliner.hxx>
#include <editeng/editdata.hxx>
#include "sdabstdlg.hxx"
#include <boost/scoped_ptr.hpp>
namespace sd
{
TYPEINIT1( FuPresentationLayout, FuPoor );
#define DOCUMENT_TOKEN '#'
FuPresentationLayout::FuPresentationLayout (
ViewShell* pViewSh,
::sd::Window* pWin,
::sd::View* pView,
SdDrawDocument* pDoc,
SfxRequest& rReq)
: FuPoor(pViewSh, pWin, pView, pDoc, rReq)
{
}
rtl::Reference<FuPoor> FuPresentationLayout::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq )
{
rtl::Reference<FuPoor> xFunc( new FuPresentationLayout( pViewSh, pWin, pView, pDoc, rReq ) );
xFunc->DoExecute(rReq);
return xFunc;
}
void FuPresentationLayout::DoExecute( SfxRequest& rReq )
{
// prevent selected objects or objects which are under editing from disappearing
mpView->SdrEndTextEdit();
if(mpView->GetSdrPageView())
{
mpView->UnmarkAll();
}
bool bError = false;
/* if we are on a master page, the changes apply for all pages and notes-
pages who are using the relevant layout */
bool bOnMaster = false;
if( mpViewShell && mpViewShell->ISA(DrawViewShell))
{
EditMode eEditMode =
static_cast<DrawViewShell*>(mpViewShell)->GetEditMode();
if (eEditMode == EM_MASTERPAGE)
bOnMaster = true;
}
std::vector<SdPage*> aUnselect;
if (!bOnMaster)
{
//We later rely on IsSelected, so transfer the selection here
//into the document
slidesorter::SlideSorterViewShell* pSlideSorterViewShell
= slidesorter::SlideSorterViewShell::GetSlideSorter(mpViewShell->GetViewShellBase());
if (pSlideSorterViewShell)
{
boost::shared_ptr<slidesorter::SlideSorterViewShell::PageSelection> xSelection(
pSlideSorterViewShell->GetPageSelection());
if (xSelection)
{
for (auto it = xSelection->begin(); it != xSelection->end(); ++it)
{
SdPage *pPage = *it;
if (pPage->IsSelected() || pPage->GetPageKind() != PK_STANDARD)
continue;
mpDoc->SetSelected(pPage, true);
aUnselect.push_back(pPage);
}
}
}
}
std::vector<SdPage*> aSelectedPages;
std::vector<sal_uInt16> aSelectedPageNums;
// determine the active pages
for (sal_uInt16 nPage = 0; nPage < mpDoc->GetSdPageCount(PK_STANDARD); nPage++)
{
SdPage* pPage = mpDoc->GetSdPage(nPage, PK_STANDARD);
if (pPage->IsSelected())
{
aSelectedPages.push_back(pPage);
aSelectedPageNums.push_back(nPage);
}
}
assert(!aSelectedPages.empty() && "no selected page");
OUString aOldLayoutName(aSelectedPages.back()->GetLayoutName());
sal_Int32 nPos = aOldLayoutName.indexOf(SD_LT_SEPARATOR);
if (nPos != -1)
aOldLayoutName = aOldLayoutName.copy(0, nPos);
bool bMasterPage = bOnMaster;
bool bCheckMasters = false;
// call dialog
bool bLoad = false; // appear the new master pages?
OUString aFile;
SfxItemSet aSet(mpDoc->GetPool(), ATTR_PRESLAYOUT_START, ATTR_PRESLAYOUT_END);
aSet.Put( SfxBoolItem( ATTR_PRESLAYOUT_LOAD, bLoad));
aSet.Put( SfxBoolItem( ATTR_PRESLAYOUT_MASTER_PAGE, bMasterPage ) );
aSet.Put( SfxBoolItem( ATTR_PRESLAYOUT_CHECK_MASTERS, bCheckMasters ) );
aSet.Put( SfxStringItem( ATTR_PRESLAYOUT_NAME, aOldLayoutName));
const SfxItemSet *pArgs = rReq.GetArgs ();
if (pArgs)
{
if (pArgs->GetItemState(ATTR_PRESLAYOUT_LOAD) == SfxItemState::SET)
bLoad = static_cast<const SfxBoolItem&>(pArgs->Get(ATTR_PRESLAYOUT_LOAD)).GetValue();
if( pArgs->GetItemState( ATTR_PRESLAYOUT_MASTER_PAGE ) == SfxItemState::SET )
bMasterPage = static_cast<const SfxBoolItem&>( pArgs->Get( ATTR_PRESLAYOUT_MASTER_PAGE ) ).GetValue();
if( pArgs->GetItemState( ATTR_PRESLAYOUT_CHECK_MASTERS ) == SfxItemState::SET )
bCheckMasters = static_cast<const SfxBoolItem&>( pArgs->Get( ATTR_PRESLAYOUT_CHECK_MASTERS ) ).GetValue();
if (pArgs->GetItemState(ATTR_PRESLAYOUT_NAME) == SfxItemState::SET)
aFile = static_cast<const SfxStringItem&>(pArgs->Get(ATTR_PRESLAYOUT_NAME)).GetValue();
}
else
{
SdAbstractDialogFactory* pFact = SdAbstractDialogFactory::Create();
boost::scoped_ptr<AbstractSdPresLayoutDlg> pDlg(pFact ? pFact->CreateSdPresLayoutDlg(mpDocSh, NULL, aSet ) : 0);
sal_uInt16 nResult = pDlg ? pDlg->Execute() : static_cast<short>(RET_CANCEL);
switch (nResult)
{
case RET_OK:
{
pDlg->GetAttr(aSet);
if (aSet.GetItemState(ATTR_PRESLAYOUT_LOAD) == SfxItemState::SET)
bLoad = static_cast<const SfxBoolItem&>(aSet.Get(ATTR_PRESLAYOUT_LOAD)).GetValue();
if( aSet.GetItemState( ATTR_PRESLAYOUT_MASTER_PAGE ) == SfxItemState::SET )
bMasterPage = static_cast<const SfxBoolItem&>(aSet.Get( ATTR_PRESLAYOUT_MASTER_PAGE ) ).GetValue();
if( aSet.GetItemState( ATTR_PRESLAYOUT_CHECK_MASTERS ) == SfxItemState::SET )
bCheckMasters = static_cast<const SfxBoolItem&>(aSet.Get( ATTR_PRESLAYOUT_CHECK_MASTERS ) ).GetValue();
if (aSet.GetItemState(ATTR_PRESLAYOUT_NAME) == SfxItemState::SET)
aFile = static_cast<const SfxStringItem&>(aSet.Get(ATTR_PRESLAYOUT_NAME)).GetValue();
}
break;
default:
bError = true;
}
}
if (!bError)
{
mpDocSh->SetWaitCursor( true );
/* Here, we only exchange masterpages, therefore the current page
remains the current page. To prevent calling PageOrderChangedHint
during insertion and extraction of the masterpages, we block. */
/* That isn't quitely right. If the masterpageview is active and you are
removing a masterpage, it's possible that you are removing the
current masterpage. So you have to call ResetActualPage ! */
if( mpViewShell->ISA(DrawViewShell) && !bCheckMasters )
static_cast<DrawView*>(mpView)->BlockPageOrderChangedHint(true);
if (bLoad)
{
OUString aFileName = aFile.getToken(0, DOCUMENT_TOKEN);
SdDrawDocument* pTempDoc = mpDoc->OpenBookmarkDoc( aFileName );
// #69581: If I chose the standard-template I got no filename and so I get no
// SdDrawDocument-Pointer. But the method SetMasterPage is able to handle
// a NULL-pointer as a Standard-template ( look at SdDrawDocument::SetMasterPage )
OUString aLayoutName;
if( pTempDoc )
aLayoutName = aFile.getToken(1, DOCUMENT_TOKEN);
for (auto nSelectedPage : aSelectedPageNums)
mpDoc->SetMasterPage(nSelectedPage, aLayoutName, pTempDoc, bMasterPage, bCheckMasters);
mpDoc->CloseBookmarkDoc();
}
else
{
// use master page with the layout name aFile from current Doc
for (auto nSelectedPage : aSelectedPageNums)
mpDoc->SetMasterPage(nSelectedPage, aFile, mpDoc, bMasterPage, bCheckMasters);
}
// remove blocking
if (mpViewShell->ISA(DrawViewShell) && !bCheckMasters )
static_cast<DrawView*>(mpView)->BlockPageOrderChangedHint(false);
// if the master page was visible, show it again
if (!bError)
{
if (bOnMaster)
{
if (mpViewShell->ISA(DrawViewShell))
{
::sd::View* pView =
static_cast<DrawViewShell*>(mpViewShell)->GetView();
for (auto pSelectedPage : aSelectedPages)
{
sal_uInt16 nPgNum = pSelectedPage->TRG_GetMasterPage().GetPageNum();
if (static_cast<DrawViewShell*>(mpViewShell)->GetPageKind() == PK_NOTES)
nPgNum++;
pView->HideSdrPage();
pView->ShowSdrPage(pView->GetModel()->GetMasterPage(nPgNum));
}
}
// force update of TabBar
mpViewShell->GetViewFrame()->GetDispatcher()->Execute(SID_MASTERPAGE, SfxCallMode::ASYNCHRON | SfxCallMode::RECORD);
}
else
{
for (auto pSelectedPage : aSelectedPages)
pSelectedPage->SetAutoLayout(pSelectedPage->GetAutoLayout());
}
}
//Undo transfer to document selection
for (auto pPage : aUnselect)
mpDoc->SetSelected(pPage, false);
// fake a mode change to repaint the page tab bar
if( mpViewShell && mpViewShell->ISA( DrawViewShell ) )
{
DrawViewShell* pDrawViewSh =
static_cast<DrawViewShell*>(mpViewShell);
EditMode eMode = pDrawViewSh->GetEditMode();
bool bLayer = pDrawViewSh->IsLayerModeActive();
pDrawViewSh->ChangeEditMode( eMode, !bLayer );
pDrawViewSh->ChangeEditMode( eMode, bLayer );
}
mpDocSh->SetWaitCursor( false );
}
}
} // end of namespace sd
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: drviewsh.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: aw $ $Date: 2002-04-12 12:44:07 $
*
* 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 _AEITEM_HXX //autogen
#include <svtools/aeitem.hxx>
#endif
#ifndef _SFXITEMSET_HXX //autogen
#include <svtools/itemset.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _SVXIDS_HRC
#include <svx/svxids.hrc>
#endif
#pragma hdrstop
#ifndef _SVX_FMSHELL_HXX // XXX nur temp (dg)
#include <svx/fmshell.hxx>
#endif
#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif
#include "app.hrc"
#include "strings.hrc"
#include "sdpage.hxx"
#include "frmview.hxx"
#include "sdresid.hxx"
#include "drawdoc.hxx"
#include "docshell.hxx"
#include "sdwindow.hxx"
#include "drviewsh.hxx"
#include "grviewsh.hxx"
#include "drawview.hxx"
#define TABCONTROL_INITIAL_SIZE 500
/*************************************************************************
|*
|* Sprung zu Bookmark
|*
\************************************************************************/
BOOL SdDrawViewShell::GotoBookmark(const String& rBookmark)
{
return (pDocSh->GotoBookmark(rBookmark));
}
/*************************************************************************
|*
|* Bereich sichtbar machen (Bildausschnitt scrollen)
|*
\************************************************************************/
void SdDrawViewShell::MakeVisible(const Rectangle& rRect, Window& rWin)
{
// #98568# In older versions, if in X or Y the size of the object was smaller than the
// visible area, the user-defined zoom was changed. This was decided to be a bug for 6.x,
// thus I developed a version which instead handles X/Y bigger/smaller and visibility
// questions seperately. The new behaviour is triggered with the bZoomAllowed parameter
// which for old behaviour should be set to sal_True. I looked at all uses of MakeVisible()
// in the application and found no valid reason for really changing the zoom factor, thus
// I decided to NOT expand (incompatible) this virtual method to get one more parameter. If
// this is wanted in later versions, feel free to add that bool to the parameter list.
sal_Bool bZoomAllowed(sal_False);
Size aLogicSize(rRect.GetSize());
// Sichtbarer Bereich
Size aVisSizePixel(rWin.GetOutputSizePixel());
Rectangle aVisArea(rWin.PixelToLogic(Rectangle(Point(0,0), aVisSizePixel)));
Size aVisAreaSize(aVisArea.GetSize());
if(!aVisArea.IsInside(rRect) && !pFuSlideShow)
{
// Objekt liegt nicht komplett im sichtbaren Bereich
sal_Int32 nFreeSpaceX(aVisAreaSize.Width() - aLogicSize.Width());
sal_Int32 nFreeSpaceY(aVisAreaSize.Height() - aLogicSize.Height());
if(bZoomAllowed && (nFreeSpaceX < 0 || nFreeSpaceY < 0))
{
// Objekt passt nicht in sichtbaren Bereich -> auf Objektgroesse zoomen
SetZoomRect(rRect);
}
else
{
// #98568# allow a mode for move-only visibility without zooming.
const sal_Int32 nPercentBorder(30);
const Rectangle aInnerRectangle(
aVisArea.Left() + ((aVisAreaSize.Width() * nPercentBorder) / 200),
aVisArea.Top() + ((aVisAreaSize.Height() * nPercentBorder) / 200),
aVisArea.Right() - ((aVisAreaSize.Width() * nPercentBorder) / 200),
aVisArea.Bottom() - ((aVisAreaSize.Height() * nPercentBorder) / 200)
);
Point aNewPos(aVisArea.TopLeft());
if(nFreeSpaceX < 0)
{
if(aInnerRectangle.Left() > rRect.Right())
{
// object moves out to the left
aNewPos.X() -= aVisAreaSize.Width() / 2;
}
if(aInnerRectangle.Right() < rRect.Left())
{
// object moves out to the right
aNewPos.X() += aVisAreaSize.Width() / 2;
}
}
else
{
if(nFreeSpaceX > rRect.GetWidth())
nFreeSpaceX = rRect.GetWidth();
while(rRect.Right() > aNewPos.X() + aVisAreaSize.Width())
aNewPos.X() += nFreeSpaceX;
while(rRect.Left() < aNewPos.X())
aNewPos.X() -= nFreeSpaceX;
}
if(nFreeSpaceY < 0)
{
if(aInnerRectangle.Top() > rRect.Bottom())
{
// object moves out to the top
aNewPos.Y() -= aVisAreaSize.Height() / 2;
}
if(aInnerRectangle.Bottom() < rRect.Top())
{
// object moves out to the right
aNewPos.Y() += aVisAreaSize.Height() / 2;
}
}
else
{
if(nFreeSpaceY > rRect.GetHeight())
nFreeSpaceY = rRect.GetHeight();
while(rRect.Bottom() > aNewPos.Y() + aVisAreaSize.Height())
aNewPos.Y() += nFreeSpaceY;
while(rRect.Top() < aNewPos.Y())
aNewPos.Y() -= nFreeSpaceY;
}
// did position change? Does it need to be set?
if(aNewPos != aVisArea.TopLeft())
{
aVisArea.SetPos(aNewPos);
SetZoomRect(aVisArea);
}
}
}
}
<commit_msg>INTEGRATION: CWS impress1 (1.4.226); FILE MERGED 2004/01/09 16:32:57 af 1.4.226.2: #111996# Renamed header files DrawView.hxx, Fader.hxx, and ShowView.hxx back to lowercase version. 2003/09/17 08:10:10 af 1.4.226.1: #111996# Transition to stacked sub-shells. Introduction of namespace sd.<commit_after>/*************************************************************************
*
* $RCSfile: drviewsh.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2004-01-20 12:48:48 $
*
* 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 "DrawViewShell.hxx"
#ifndef _AEITEM_HXX //autogen
#include <svtools/aeitem.hxx>
#endif
#ifndef _SFXITEMSET_HXX //autogen
#include <svtools/itemset.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _SVXIDS_HRC
#include <svx/svxids.hrc>
#endif
#pragma hdrstop
#ifndef _SVX_FMSHELL_HXX // XXX nur temp (dg)
#include <svx/fmshell.hxx>
#endif
#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif
#include "app.hrc"
#include "strings.hrc"
#include "sdpage.hxx"
#ifndef SD_FRAME_VIEW
#include "FrameView.hxx"
#endif
#include "sdresid.hxx"
#include "drawdoc.hxx"
#include "DrawDocShell.hxx"
#ifndef SD_WINDOW_HXX
#include "Window.hxx"
#endif
#ifndef SD_GRAPHIC_VIEW_SHELL_HXX
#include "GraphicViewShell.hxx"
#endif
#ifndef SD_DRAW_VIEW_HXX
#include "drawview.hxx"
#endif
namespace sd {
#define TABCONTROL_INITIAL_SIZE 500
/*************************************************************************
|*
|* Sprung zu Bookmark
|*
\************************************************************************/
BOOL DrawViewShell::GotoBookmark(const String& rBookmark)
{
return (GetDocSh()->GotoBookmark(rBookmark));
}
/*************************************************************************
|*
|* Bereich sichtbar machen (Bildausschnitt scrollen)
|*
\************************************************************************/
void DrawViewShell::MakeVisible(const Rectangle& rRect, Window& rWin)
{
// #98568# In older versions, if in X or Y the size of the object was smaller than the
// visible area, the user-defined zoom was changed. This was decided to be a bug for 6.x,
// thus I developed a version which instead handles X/Y bigger/smaller and visibility
// questions seperately. The new behaviour is triggered with the bZoomAllowed parameter
// which for old behaviour should be set to sal_True. I looked at all uses of MakeVisible()
// in the application and found no valid reason for really changing the zoom factor, thus
// I decided to NOT expand (incompatible) this virtual method to get one more parameter. If
// this is wanted in later versions, feel free to add that bool to the parameter list.
sal_Bool bZoomAllowed(sal_False);
Size aLogicSize(rRect.GetSize());
// Sichtbarer Bereich
Size aVisSizePixel(rWin.GetOutputSizePixel());
Rectangle aVisArea(rWin.PixelToLogic(Rectangle(Point(0,0), aVisSizePixel)));
Size aVisAreaSize(aVisArea.GetSize());
if(!aVisArea.IsInside(rRect) && !pFuSlideShow)
{
// Objekt liegt nicht komplett im sichtbaren Bereich
sal_Int32 nFreeSpaceX(aVisAreaSize.Width() - aLogicSize.Width());
sal_Int32 nFreeSpaceY(aVisAreaSize.Height() - aLogicSize.Height());
if(bZoomAllowed && (nFreeSpaceX < 0 || nFreeSpaceY < 0))
{
// Objekt passt nicht in sichtbaren Bereich -> auf Objektgroesse zoomen
SetZoomRect(rRect);
}
else
{
// #98568# allow a mode for move-only visibility without zooming.
const sal_Int32 nPercentBorder(30);
const Rectangle aInnerRectangle(
aVisArea.Left() + ((aVisAreaSize.Width() * nPercentBorder) / 200),
aVisArea.Top() + ((aVisAreaSize.Height() * nPercentBorder) / 200),
aVisArea.Right() - ((aVisAreaSize.Width() * nPercentBorder) / 200),
aVisArea.Bottom() - ((aVisAreaSize.Height() * nPercentBorder) / 200)
);
Point aNewPos(aVisArea.TopLeft());
if(nFreeSpaceX < 0)
{
if(aInnerRectangle.Left() > rRect.Right())
{
// object moves out to the left
aNewPos.X() -= aVisAreaSize.Width() / 2;
}
if(aInnerRectangle.Right() < rRect.Left())
{
// object moves out to the right
aNewPos.X() += aVisAreaSize.Width() / 2;
}
}
else
{
if(nFreeSpaceX > rRect.GetWidth())
nFreeSpaceX = rRect.GetWidth();
while(rRect.Right() > aNewPos.X() + aVisAreaSize.Width())
aNewPos.X() += nFreeSpaceX;
while(rRect.Left() < aNewPos.X())
aNewPos.X() -= nFreeSpaceX;
}
if(nFreeSpaceY < 0)
{
if(aInnerRectangle.Top() > rRect.Bottom())
{
// object moves out to the top
aNewPos.Y() -= aVisAreaSize.Height() / 2;
}
if(aInnerRectangle.Bottom() < rRect.Top())
{
// object moves out to the right
aNewPos.Y() += aVisAreaSize.Height() / 2;
}
}
else
{
if(nFreeSpaceY > rRect.GetHeight())
nFreeSpaceY = rRect.GetHeight();
while(rRect.Bottom() > aNewPos.Y() + aVisAreaSize.Height())
aNewPos.Y() += nFreeSpaceY;
while(rRect.Top() < aNewPos.Y())
aNewPos.Y() -= nFreeSpaceY;
}
// did position change? Does it need to be set?
if(aNewPos != aVisArea.TopLeft())
{
aVisArea.SetPos(aNewPos);
SetZoomRect(aVisArea);
}
}
}
}
}
<|endoftext|>
|
<commit_before>/***************************************************************************
* Copyright (C) 2005-2007 by the FIFE Team *
* fife-public@lists.sourceforge.net *
* This file is part of FIFE. *
* *
* FIFE is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA *
***************************************************************************/
// Standard C++ library includes
// 3rd party library includes
// FIFE includes
// These includes are split up in two parts, separated by one empty line
// First block: files included from the FIFE root src directory
// Second block: files included from the same folder
#include "model/structures/instance.h"
#include "instancetree.h"
namespace FIFE {
InstanceTree::InstanceTree(): FifeClass() {
}
InstanceTree::~InstanceTree() {
}
bool InstanceTree::addInstance(Instance* instance) {
ModelCoordinate coords = instance->getLocation().getLayerCoordinates();
InstanceList& list = m_tree.find_container(coords.x,coords.y,0,0)->data();
list.push_back(instance);
return true;
}
bool InstanceTree::removeInstance(Instance* instance) {
ModelCoordinate coords = instance->getLocation().getLayerCoordinates();
InstanceList& list = m_tree.find_container(coords.x,coords.y, 0, 0)->data();
for(InstanceList::iterator i = list.begin(); i != list.end(); ++i) {
if((*i) == instance) {
list.erase(i);
return true;
}
}
return false;
}
class InstanceListCollector {
public:
InstanceTree::InstanceList& instanceList;
InstanceListCollector(InstanceTree::InstanceList& a_instanceList) : instanceList(a_instanceList) {
}
bool visit(InstanceTree::InstanceTreeNode* node, int d);
};
bool InstanceListCollector::visit(InstanceTree::InstanceTreeNode* node, int d) {
InstanceTree::InstanceList& list = node->data();
std::copy(list.begin(),list.end(),std::back_inserter(instanceList));
return true;
}
void InstanceTree::findInstances(const ModelCoordinate& point, int w, int h, InstanceTree::InstanceList& list) {
InstanceTreeNode * node = m_tree.find_container(point.x, point.y, w, h);
InstanceListCollector collector(list);
node->apply_visitor(collector);
node = node->parent();
while( node ) {
std::copy(node->data().begin(),node->data().end(),std::back_inserter(list));
node = node->parent();
}
}
}
<commit_msg>QuadTree: Part II. Check parent tree nodes for intersection.<commit_after>/***************************************************************************
* Copyright (C) 2005-2007 by the FIFE Team *
* fife-public@lists.sourceforge.net *
* This file is part of FIFE. *
* *
* FIFE is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA *
***************************************************************************/
// Standard C++ library includes
// 3rd party library includes
// FIFE includes
// These includes are split up in two parts, separated by one empty line
// First block: files included from the FIFE root src directory
// Second block: files included from the same folder
#include "model/structures/instance.h"
#include "util/rect.h"
#include "instancetree.h"
namespace FIFE {
InstanceTree::InstanceTree(): FifeClass() {
}
InstanceTree::~InstanceTree() {
}
bool InstanceTree::addInstance(Instance* instance) {
ModelCoordinate coords = instance->getLocation().getLayerCoordinates();
InstanceList& list = m_tree.find_container(coords.x,coords.y,0,0)->data();
list.push_back(instance);
return true;
}
bool InstanceTree::removeInstance(Instance* instance) {
ModelCoordinate coords = instance->getLocation().getLayerCoordinates();
InstanceList& list = m_tree.find_container(coords.x,coords.y, 0, 0)->data();
for(InstanceList::iterator i = list.begin(); i != list.end(); ++i) {
if((*i) == instance) {
list.erase(i);
return true;
}
}
return false;
}
class InstanceListCollector {
public:
InstanceTree::InstanceList& instanceList;
InstanceListCollector(InstanceTree::InstanceList& a_instanceList) : instanceList(a_instanceList) {
}
bool visit(InstanceTree::InstanceTreeNode* node, int d);
};
bool InstanceListCollector::visit(InstanceTree::InstanceTreeNode* node, int d) {
InstanceTree::InstanceList& list = node->data();
std::copy(list.begin(),list.end(),std::back_inserter(instanceList));
return true;
}
void InstanceTree::findInstances(const ModelCoordinate& point, int w, int h, InstanceTree::InstanceList& list) {
InstanceTreeNode * node = m_tree.find_container(point.x, point.y, w, h);
InstanceListCollector collector(list);
node->apply_visitor(collector);
Rect rect(point.x, point.y, w, h);
node = node->parent();
while( node ) {
for(InstanceList::const_iterator it(node->data().begin()); it != node->data().end(); ++it) {
ModelCoordinate coords = (*it)->getLocation().getLayerCoordinates();
if( rect.contains(Point(coords.x,coords.y)) ) {
list.push_back(*it);
}
}
node = node->parent();
}
}
}
<|endoftext|>
|
<commit_before>// Ouzel by Elviss Strazdins
#ifndef OUZEL_GRAPHICS_OGLPROCEDUREGETTER_HPP
#define OUZEL_GRAPHICS_OGLPROCEDUREGETTER_HPP
#include "../../core/Setup.h"
#if OUZEL_COMPILE_OPENGL
#include <algorithm>
#include <stdexcept>
#include "OGL.h"
#if OUZEL_OPENGLES
# include "GLES/gl.h"
# include "GLES2/gl2.h"
# include "GLES2/gl2ext.h"
# include "GLES3/gl3.h"
#else
# include "GL/glcorearb.h"
# include "GL/glext.h"
#endif
#if OUZEL_OPENGL_INTERFACE_EGL
# include "EGL/egl.h"
#elif OUZEL_OPENGL_INTERFACE_WGL
# include "GL/wglext.h"
# include "../../platform/winapi/Library.hpp"
#endif
#include "../../core/Engine.hpp"
#include "../../utils/Utils.hpp"
namespace ouzel::graphics::opengl
{
class ProcedureGetter final
{
public:
ProcedureGetter(ApiVersion version):
apiVersion{version}
{
const auto glGetErrorProc = getProcAddress<PFNGLGETERRORPROC>("glGetError", ApiVersion{1, 0});
if (apiVersion >= ApiVersion{3, 0})
{
const auto glGetIntegervProc = getProcAddress<PFNGLGETINTEGERVPROC>("glGetIntegerv", ApiVersion{1, 0});
const auto glGetStringiProc = getProcAddress<PFNGLGETSTRINGIPROC>("glGetStringi", ApiVersion{3, 0});
GLint extensionCount;
glGetIntegervProc(GL_NUM_EXTENSIONS, &extensionCount);
if (const auto error = glGetErrorProc(); error != GL_NO_ERROR)
logger.log(Log::Level::warning) << "Failed to get OpenGL extension count, error: " + std::to_string(error);
else
for (GLuint i = 0; i < static_cast<GLuint>(extensionCount); ++i)
{
const auto extensionPtr = glGetStringiProc(GL_EXTENSIONS, i);
if (const auto getStringError = glGetErrorProc(); getStringError != GL_NO_ERROR)
logger.log(Log::Level::warning) << "Failed to get OpenGL extension, error: " + std::to_string(getStringError);
else if (!extensionPtr)
logger.log(Log::Level::warning) << "Failed to get OpenGL extension";
else
extensions.emplace_back(reinterpret_cast<const char*>(extensionPtr));
}
}
else
{
const auto glGetStringProc = getProcAddress<PFNGLGETSTRINGPROC>("glGetString", ApiVersion{1, 0});
const auto extensionsPtr = glGetStringProc(GL_EXTENSIONS);
if (const auto error = glGetErrorProc(); error != GL_NO_ERROR)
logger.log(Log::Level::warning) << "Failed to get OpenGL extensions, error: " + std::to_string(error);
else if (!extensionsPtr)
logger.log(Log::Level::warning) << "Failed to get OpenGL extensions";
else
extensions = explodeString(reinterpret_cast<const char*>(extensionsPtr), ' ');
}
logger.log(Log::Level::all) << "Supported OpenGL extensions: " << extensions;
}
template <typename T>
T get(const char* name, ApiVersion procApiVersion) const noexcept
{
return (apiVersion >= procApiVersion) ? getProcAddress<T>(name, procApiVersion) : nullptr;
}
template <typename T>
T get(const char* name, const char* extension) const noexcept
{
return hasExtension(extension) ? getProcAddress<T>(name) : nullptr;
}
template <typename T>
T get(const char* name,
ApiVersion procApiVersion,
const std::map<const char*, const char*>& procExtensions) const noexcept
{
if (apiVersion >= procApiVersion)
return getProcAddress<T>(name, procApiVersion);
else
for (const auto& extension : procExtensions)
if (auto result = get<T>(extension.first, extension.second))
return result;
return nullptr;
}
bool hasExtension(const char* ext) const noexcept
{
return std::find(extensions.begin(), extensions.end(), ext) != extensions.end();
}
private:
template <typename T>
T getProcAddress(const char* name, ApiVersion procApiVersion) const noexcept
{
#if OUZEL_OPENGL_INTERFACE_EGL
# if OUZEL_OPENGLES
return procApiVersion >= ApiVersion{3, 0} ?
reinterpret_cast<T>(eglGetProcAddress(name)) :
reinterpret_cast<T>(reinterpret_cast<std::uintptr_t>(dlsym(RTLD_DEFAULT, name)));
# else
(void)procApiVersion;
return reinterpret_cast<T>(eglGetProcAddress(name));
# endif
#elif OUZEL_OPENGL_INTERFACE_WGL
return procApiVersion > ApiVersion{1, 1} ?
reinterpret_cast<T>(wglGetProcAddress(name)) :
reinterpret_cast<T>(GetProcAddress(library.get(), name));
#else
(void)procApiVersion;
return reinterpret_cast<T>(reinterpret_cast<std::uintptr_t>(dlsym(RTLD_DEFAULT, name)));
#endif
}
template <typename T>
T getProcAddress(const char* name) const noexcept
{
#if OUZEL_OPENGL_INTERFACE_EGL
return reinterpret_cast<T>(eglGetProcAddress(name));
#elif OUZEL_OPENGL_INTERFACE_WGL
return reinterpret_cast<T>(wglGetProcAddress(name));
#else
return reinterpret_cast<T>(reinterpret_cast<std::uintptr_t>(dlsym(RTLD_DEFAULT, name)));
#endif
}
ApiVersion apiVersion;
std::vector<std::string> extensions;
#if OUZEL_OPENGL_INTERFACE_WGL
platform::winapi::Library library{"opengl32.dll"};
#endif
};
}
#endif
#endif // OUZEL_GRAPHICS_OGLPROCEDUREGETTER_HPP
<commit_msg>Use structured bindings for procedure getter<commit_after>// Ouzel by Elviss Strazdins
#ifndef OUZEL_GRAPHICS_OGLPROCEDUREGETTER_HPP
#define OUZEL_GRAPHICS_OGLPROCEDUREGETTER_HPP
#include "../../core/Setup.h"
#if OUZEL_COMPILE_OPENGL
#include <algorithm>
#include <stdexcept>
#include "OGL.h"
#if OUZEL_OPENGLES
# include "GLES/gl.h"
# include "GLES2/gl2.h"
# include "GLES2/gl2ext.h"
# include "GLES3/gl3.h"
#else
# include "GL/glcorearb.h"
# include "GL/glext.h"
#endif
#if OUZEL_OPENGL_INTERFACE_EGL
# include "EGL/egl.h"
#elif OUZEL_OPENGL_INTERFACE_WGL
# include "GL/wglext.h"
# include "../../platform/winapi/Library.hpp"
#endif
#include "../../core/Engine.hpp"
#include "../../utils/Utils.hpp"
namespace ouzel::graphics::opengl
{
class ProcedureGetter final
{
public:
ProcedureGetter(ApiVersion version):
apiVersion{version}
{
const auto glGetErrorProc = getProcAddress<PFNGLGETERRORPROC>("glGetError", ApiVersion{1, 0});
if (apiVersion >= ApiVersion{3, 0})
{
const auto glGetIntegervProc = getProcAddress<PFNGLGETINTEGERVPROC>("glGetIntegerv", ApiVersion{1, 0});
const auto glGetStringiProc = getProcAddress<PFNGLGETSTRINGIPROC>("glGetStringi", ApiVersion{3, 0});
GLint extensionCount;
glGetIntegervProc(GL_NUM_EXTENSIONS, &extensionCount);
if (const auto error = glGetErrorProc(); error != GL_NO_ERROR)
logger.log(Log::Level::warning) << "Failed to get OpenGL extension count, error: " + std::to_string(error);
else
for (GLuint i = 0; i < static_cast<GLuint>(extensionCount); ++i)
{
const auto extensionPtr = glGetStringiProc(GL_EXTENSIONS, i);
if (const auto getStringError = glGetErrorProc(); getStringError != GL_NO_ERROR)
logger.log(Log::Level::warning) << "Failed to get OpenGL extension, error: " + std::to_string(getStringError);
else if (!extensionPtr)
logger.log(Log::Level::warning) << "Failed to get OpenGL extension";
else
extensions.emplace_back(reinterpret_cast<const char*>(extensionPtr));
}
}
else
{
const auto glGetStringProc = getProcAddress<PFNGLGETSTRINGPROC>("glGetString", ApiVersion{1, 0});
const auto extensionsPtr = glGetStringProc(GL_EXTENSIONS);
if (const auto error = glGetErrorProc(); error != GL_NO_ERROR)
logger.log(Log::Level::warning) << "Failed to get OpenGL extensions, error: " + std::to_string(error);
else if (!extensionsPtr)
logger.log(Log::Level::warning) << "Failed to get OpenGL extensions";
else
extensions = explodeString(reinterpret_cast<const char*>(extensionsPtr), ' ');
}
logger.log(Log::Level::all) << "Supported OpenGL extensions: " << extensions;
}
template <typename T>
T get(const char* name, ApiVersion procApiVersion) const noexcept
{
return (apiVersion >= procApiVersion) ? getProcAddress<T>(name, procApiVersion) : nullptr;
}
template <typename T>
T get(const char* name, const char* extension) const noexcept
{
return hasExtension(extension) ? getProcAddress<T>(name) : nullptr;
}
template <typename T>
T get(const char* name,
ApiVersion procApiVersion,
const std::map<const char*, const char*>& procExtensions) const noexcept
{
if (apiVersion >= procApiVersion)
return getProcAddress<T>(name, procApiVersion);
else
for (const auto [procName, extension] : procExtensions)
if (auto result = get<T>(procName, extension))
return result;
return nullptr;
}
bool hasExtension(const char* ext) const noexcept
{
return std::find(extensions.begin(), extensions.end(), ext) != extensions.end();
}
private:
template <typename T>
T getProcAddress(const char* name, ApiVersion procApiVersion) const noexcept
{
#if OUZEL_OPENGL_INTERFACE_EGL
# if OUZEL_OPENGLES
return procApiVersion >= ApiVersion{3, 0} ?
reinterpret_cast<T>(eglGetProcAddress(name)) :
reinterpret_cast<T>(reinterpret_cast<std::uintptr_t>(dlsym(RTLD_DEFAULT, name)));
# else
(void)procApiVersion;
return reinterpret_cast<T>(eglGetProcAddress(name));
# endif
#elif OUZEL_OPENGL_INTERFACE_WGL
return procApiVersion > ApiVersion{1, 1} ?
reinterpret_cast<T>(wglGetProcAddress(name)) :
reinterpret_cast<T>(GetProcAddress(library.get(), name));
#else
(void)procApiVersion;
return reinterpret_cast<T>(reinterpret_cast<std::uintptr_t>(dlsym(RTLD_DEFAULT, name)));
#endif
}
template <typename T>
T getProcAddress(const char* name) const noexcept
{
#if OUZEL_OPENGL_INTERFACE_EGL
return reinterpret_cast<T>(eglGetProcAddress(name));
#elif OUZEL_OPENGL_INTERFACE_WGL
return reinterpret_cast<T>(wglGetProcAddress(name));
#else
return reinterpret_cast<T>(reinterpret_cast<std::uintptr_t>(dlsym(RTLD_DEFAULT, name)));
#endif
}
ApiVersion apiVersion;
std::vector<std::string> extensions;
#if OUZEL_OPENGL_INTERFACE_WGL
platform::winapi::Library library{"opengl32.dll"};
#endif
};
}
#endif
#endif // OUZEL_GRAPHICS_OGLPROCEDUREGETTER_HPP
<|endoftext|>
|
<commit_before>#include "multiverso/server.h"
#include <algorithm>
#include <sstream>
#include <string>
#include <vector>
#include "multiverso/actor.h"
#include "multiverso/dashboard.h"
#include "multiverso/multiverso.h"
#include "multiverso/table_interface.h"
#include "multiverso/io/io.h"
#include "multiverso/util/configure.h"
#include "multiverso/util/mt_queue.h"
#include "multiverso/zoo.h"
namespace multiverso {
MV_DEFINE_bool(sync, false, "sync or async");
MV_DEFINE_int(backup_worker_ratio, 0, "ratio% of backup workers, set 20 means 20%");
Server::Server() : Actor(actor::kServer) {
RegisterHandler(MsgType::Request_Get, std::bind(
&Server::ProcessGet, this, std::placeholders::_1));
RegisterHandler(MsgType::Request_Add, std::bind(
&Server::ProcessAdd, this, std::placeholders::_1));
}
int Server::RegisterTable(ServerTable* server_table) {
int id = static_cast<int>(store_.size());
store_.push_back(server_table);
return id;
}
void Server::ProcessGet(MessagePtr& msg) {
MONITOR_BEGIN(SERVER_PROCESS_GET);
if (msg->data().size() != 0) {
MessagePtr reply(msg->CreateReplyMessage());
int table_id = msg->table_id();
CHECK(table_id >= 0 && table_id < store_.size());
store_[table_id]->ProcessGet(msg->data(), &reply->data());
SendTo(actor::kCommunicator, reply);
}
MONITOR_END(SERVER_PROCESS_GET);
}
void Server::ProcessAdd(MessagePtr& msg) {
MONITOR_BEGIN(SERVER_PROCESS_ADD)
if (msg->data().size() != 0) {
MessagePtr reply(msg->CreateReplyMessage());
int table_id = msg->table_id();
CHECK(table_id >= 0 && table_id < store_.size());
store_[table_id]->ProcessAdd(msg->data());
SendTo(actor::kCommunicator, reply);
}
MONITOR_END(SERVER_PROCESS_ADD)
}
// The Sync Server implement logic to support Sync SGD training
// The implementation assumes all the workers will call same number
// of Add and/or Get requests
// The server promise all workers i-th Get will get the same parameters
// If worker k has add delta to server j times when its i-th Get
// then the server will return the parameter after all K
// workers finished their j-th update
class SyncServer : public Server {
public:
SyncServer() : Server() {
RegisterHandler(MsgType::Server_Finish_Train, std::bind(
&SyncServer::ProcessFinishTrain, this, std::placeholders::_1));
int num_worker = Zoo::Get()->num_workers();
worker_get_clocks_.reset(new VectorClock(num_worker));
worker_add_clocks_.reset(new VectorClock(num_worker));
}
// make some modification to suit to the sync server
// please not use in other place, may different with the general vector clock
class VectorClock {
public:
explicit VectorClock(int n) :
local_clock_(n, 0), global_clock_(0), size_(0) {}
static bool except_max_int_compare(int a, int b) {
return (b == std::numeric_limits<int>::max() ? false : a < b);
}
// Return true when all clock reach a same number
virtual bool Update(int i) {
++local_clock_[i];
if (global_clock_ < *(std::min_element(std::begin(local_clock_),
std::end(local_clock_)))) {
++global_clock_;
if (global_clock_ == *(std::max_element(std::begin(local_clock_),
std::end(local_clock_), except_max_int_compare))) {
return true;
}
}
return false;
}
virtual bool FinishTrain(int i) {
local_clock_[i] = std::numeric_limits<int>::max();
if (global_clock_ < *(std::min_element(std::begin(local_clock_),
std::end(local_clock_)))) {
++global_clock_;
if (global_clock_ == *(std::max_element(std::begin(local_clock_),
std::end(local_clock_), except_max_int_compare))) {
return true;
}
}
return false;
}
std::string DebugString() {
std::string os = "global ";
os += std::to_string(global_clock_) + " local: ";
for (auto i : local_clock_) os += std::to_string(i) + " ";
return os;
}
int local_clock(int i) const { return local_clock_[i]; }
int global_clock() const { return global_clock_; }
protected:
std::vector<int> local_clock_;
int global_clock_;
int size_;
};
protected:
void ProcessAdd(MessagePtr& msg) override {
// 1. Before add: cache faster worker
int worker = Zoo::Get()->rank_to_worker_id(msg->src());
if (worker_get_clocks_->local_clock(worker) >
worker_get_clocks_->global_clock()) {
msg_add_cache_.Push(msg);
return;
}
// 2. Process Add
Server::ProcessAdd(msg);
// 3. After add: process cached process get if necessary
if (worker_add_clocks_->Update(worker)) {
CHECK(msg_add_cache_.Empty());
while (!msg_get_cache_.Empty()) {
MessagePtr get_msg;
CHECK(msg_get_cache_.TryPop(get_msg));
int get_worker = Zoo::Get()->rank_to_worker_id(get_msg->src());
Server::ProcessGet(get_msg);
CHECK(!worker_get_clocks_->Update(get_worker));
}
}
}
void ProcessGet(MessagePtr& msg) override {
// 1. Before get: cache faster worker
int worker = Zoo::Get()->rank_to_worker_id(msg->src());
if (worker_add_clocks_->local_clock(worker) >
worker_add_clocks_->global_clock() ||
worker_get_clocks_->local_clock(worker) >
worker_get_clocks_->global_clock()) {
// Will wait for other worker finished Add
msg_get_cache_.Push(msg);
return;
}
// 2. Process Get
Server::ProcessGet(msg);
// 3. After get: process cached process add if necessary
if (worker_get_clocks_->Update(worker)) {
while (!msg_add_cache_.Empty()) {
MessagePtr add_msg;
CHECK(msg_add_cache_.TryPop(add_msg));
int add_worker = Zoo::Get()->rank_to_worker_id(add_msg->src());
Server::ProcessAdd(add_msg);
CHECK(!worker_add_clocks_->Update(add_worker));
}
}
}
void ProcessFinishTrain(MessagePtr& msg) {
int worker = Zoo::Get()->rank_to_worker_id(msg->src());
Log::Debug("[ProcessFinishTrain] Server %d, worker %d has finished training.\n",
Zoo::Get()->server_rank(), worker);
if (worker_get_clocks_->FinishTrain(worker)) {
CHECK(msg_get_cache_.Empty());
while (!msg_add_cache_.Empty()) {
MessagePtr add_msg;
CHECK(msg_add_cache_.TryPop(add_msg));
int add_worker = Zoo::Get()->rank_to_worker_id(add_msg->src());
Server::ProcessAdd(add_msg);
worker_add_clocks_->Update(add_worker);
}
}
if (worker_add_clocks_->FinishTrain(worker)) {
CHECK(msg_add_cache_.Empty());
while (!msg_get_cache_.Empty()) {
MessagePtr get_msg;
CHECK(msg_get_cache_.TryPop(get_msg));
int get_worker = Zoo::Get()->rank_to_worker_id(get_msg->src());
Server::ProcessGet(get_msg);
worker_get_clocks_->Update(get_worker);
}
}
}
private:
std::unique_ptr<VectorClock> worker_get_clocks_;
std::unique_ptr<VectorClock> worker_add_clocks_;
MtQueue<MessagePtr> msg_add_cache_;
MtQueue<MessagePtr> msg_get_cache_;
};
Server* Server::GetServer() {
if (!MV_CONFIG_sync) {
Log::Info("Create a async server\n");
return new Server();
}
// if (MV_CONFIG_backup_worker_ratio > 0.0) {
Log::Info("Create a sync server\n");
return new SyncServer();
// }
}
} // namespace multiverso
<commit_msg>fix sync server bug<commit_after>#include "multiverso/server.h"
#include <algorithm>
#include <sstream>
#include <string>
#include <vector>
#include "multiverso/actor.h"
#include "multiverso/dashboard.h"
#include "multiverso/multiverso.h"
#include "multiverso/table_interface.h"
#include "multiverso/io/io.h"
#include "multiverso/util/configure.h"
#include "multiverso/util/mt_queue.h"
#include "multiverso/zoo.h"
namespace multiverso {
MV_DEFINE_bool(sync, false, "sync or async");
MV_DEFINE_int(backup_worker_ratio, 0, "ratio% of backup workers, set 20 means 20%");
Server::Server() : Actor(actor::kServer) {
RegisterHandler(MsgType::Request_Get, std::bind(
&Server::ProcessGet, this, std::placeholders::_1));
RegisterHandler(MsgType::Request_Add, std::bind(
&Server::ProcessAdd, this, std::placeholders::_1));
}
int Server::RegisterTable(ServerTable* server_table) {
int id = static_cast<int>(store_.size());
store_.push_back(server_table);
return id;
}
void Server::ProcessGet(MessagePtr& msg) {
MONITOR_BEGIN(SERVER_PROCESS_GET);
if (msg->data().size() != 0) {
MessagePtr reply(msg->CreateReplyMessage());
int table_id = msg->table_id();
CHECK(table_id >= 0 && table_id < store_.size());
store_[table_id]->ProcessGet(msg->data(), &reply->data());
SendTo(actor::kCommunicator, reply);
}
MONITOR_END(SERVER_PROCESS_GET);
}
void Server::ProcessAdd(MessagePtr& msg) {
MONITOR_BEGIN(SERVER_PROCESS_ADD)
if (msg->data().size() != 0) {
MessagePtr reply(msg->CreateReplyMessage());
int table_id = msg->table_id();
CHECK(table_id >= 0 && table_id < store_.size());
store_[table_id]->ProcessAdd(msg->data());
SendTo(actor::kCommunicator, reply);
}
MONITOR_END(SERVER_PROCESS_ADD)
}
// The Sync Server implement logic to support Sync SGD training
// The implementation assumes all the workers will call same number
// of Add and/or Get requests
// The server promise all workers i-th Get will get the same parameters
// If worker k has add delta to server j times when its i-th Get
// then the server will return the parameter after all K
// workers finished their j-th update
class SyncServer : public Server {
public:
SyncServer() : Server() {
RegisterHandler(MsgType::Server_Finish_Train, std::bind(
&SyncServer::ProcessFinishTrain, this, std::placeholders::_1));
int num_worker = Zoo::Get()->num_workers();
worker_get_clocks_.reset(new VectorClock(num_worker));
worker_add_clocks_.reset(new VectorClock(num_worker));
num_waited_add_.resize(num_worker, 0);
}
// make some modification to suit to the sync server
// please not use in other place, may different with the general vector clock
class VectorClock {
public:
explicit VectorClock(int n) :
local_clock_(n, 0), global_clock_(0), size_(0) {}
static bool except_max_int_compare(int a, int b) {
return (b == std::numeric_limits<int>::max() ? false : a < b);
}
// Return true when all clock reach a same number
virtual bool Update(int i) {
++local_clock_[i];
if (global_clock_ < *(std::min_element(std::begin(local_clock_),
std::end(local_clock_)))) {
++global_clock_;
if (global_clock_ == *(std::max_element(std::begin(local_clock_),
std::end(local_clock_), except_max_int_compare))) {
return true;
}
}
return false;
}
virtual bool FinishTrain(int i) {
local_clock_[i] = std::numeric_limits<int>::max();
if (global_clock_ < *(std::min_element(std::begin(local_clock_),
std::end(local_clock_)))) {
++global_clock_;
if (global_clock_ == *(std::max_element(std::begin(local_clock_),
std::end(local_clock_), except_max_int_compare))) {
return true;
}
}
return false;
}
std::string DebugString() {
std::string os = "global ";
os += std::to_string(global_clock_) + " local: ";
for (auto i : local_clock_) os += std::to_string(i) + " ";
return os;
}
int local_clock(int i) const { return local_clock_[i]; }
int global_clock() const { return global_clock_; }
protected:
std::vector<int> local_clock_;
int global_clock_;
int size_;
};
protected:
void ProcessAdd(MessagePtr& msg) override {
// 1. Before add: cache faster worker
int worker = Zoo::Get()->rank_to_worker_id(msg->src());
if (worker_get_clocks_->local_clock(worker) >
worker_get_clocks_->global_clock()) {
msg_add_cache_.Push(msg);
++num_waited_add_[worker];
return;
}
// 2. Process Add
Server::ProcessAdd(msg);
// 3. After add: process cached process get if necessary
if (worker_add_clocks_->Update(worker)) {
CHECK(msg_add_cache_.Empty());
while (!msg_get_cache_.Empty()) {
MessagePtr get_msg;
CHECK(msg_get_cache_.TryPop(get_msg));
int get_worker = Zoo::Get()->rank_to_worker_id(get_msg->src());
Server::ProcessGet(get_msg);
CHECK(!worker_get_clocks_->Update(get_worker));
}
}
}
void ProcessGet(MessagePtr& msg) override {
// 1. Before get: cache faster worker
int worker = Zoo::Get()->rank_to_worker_id(msg->src());
if (worker_add_clocks_->local_clock(worker) >
worker_add_clocks_->global_clock() ||
num_waited_add_[worker] > 0) {
// Will wait for other worker finished Add
msg_get_cache_.Push(msg);
return;
}
// 2. Process Get
Server::ProcessGet(msg);
// 3. After get: process cached process add if necessary
if (worker_get_clocks_->Update(worker)) {
while (!msg_add_cache_.Empty()) {
MessagePtr add_msg;
CHECK(msg_add_cache_.TryPop(add_msg));
int add_worker = Zoo::Get()->rank_to_worker_id(add_msg->src());
Server::ProcessAdd(add_msg);
CHECK(!worker_add_clocks_->Update(add_worker));
--num_waited_add_[add_worker];
}
}
}
void ProcessFinishTrain(MessagePtr& msg) {
int worker = Zoo::Get()->rank_to_worker_id(msg->src());
Log::Debug("[ProcessFinishTrain] Server %d, worker %d has finished training.\n",
Zoo::Get()->server_rank(), worker);
if (worker_get_clocks_->FinishTrain(worker)) {
CHECK(msg_get_cache_.Empty());
while (!msg_add_cache_.Empty()) {
MessagePtr add_msg;
CHECK(msg_add_cache_.TryPop(add_msg));
int add_worker = Zoo::Get()->rank_to_worker_id(add_msg->src());
Server::ProcessAdd(add_msg);
worker_add_clocks_->Update(add_worker);
}
}
if (worker_add_clocks_->FinishTrain(worker)) {
CHECK(msg_add_cache_.Empty());
while (!msg_get_cache_.Empty()) {
MessagePtr get_msg;
CHECK(msg_get_cache_.TryPop(get_msg));
int get_worker = Zoo::Get()->rank_to_worker_id(get_msg->src());
Server::ProcessGet(get_msg);
worker_get_clocks_->Update(get_worker);
}
}
}
private:
std::unique_ptr<VectorClock> worker_get_clocks_;
std::unique_ptr<VectorClock> worker_add_clocks_;
std::vector<int> num_waited_add_;
MtQueue<MessagePtr> msg_add_cache_;
MtQueue<MessagePtr> msg_get_cache_;
};
Server* Server::GetServer() {
if (!MV_CONFIG_sync) {
Log::Info("Create a async server\n");
return new Server();
}
// if (MV_CONFIG_backup_worker_ratio > 0.0) {
Log::Info("Create a sync server\n");
return new SyncServer();
// }
}
} // namespace multiverso
<|endoftext|>
|
<commit_before>// Copyright (c) 2019, 2021 by Robert Bosch GmbH. All rights reserved.
// Copyright (c) 2021 by Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
#ifndef IOX_HOOFS_CXX_CONVERT_INL
#define IOX_HOOFS_CXX_CONVERT_INL
namespace iox
{
namespace cxx
{
///@brief specialization for uint8_t and int8_t is required since uint8_t is unsigned char and int8_t is signed char
/// and stringstream will not convert these to string as it is already a character.
template <>
inline typename std::enable_if<!std::is_convertible<uint8_t, std::string>::value, std::string>::type
convert::toString(const uint8_t& t) noexcept
{
return toString(static_cast<uint16_t>(t));
}
template <>
inline typename std::enable_if<!std::is_convertible<int8_t, std::string>::value, std::string>::type
convert::toString(const int8_t& t) noexcept
{
return toString(static_cast<int16_t>(t));
}
template <typename Source>
inline typename std::enable_if<!std::is_convertible<Source, std::string>::value, std::string>::type
convert::toString(const Source& t) noexcept
{
std::stringstream ss;
ss << t;
return ss.str();
}
template <typename Source>
inline typename std::enable_if<std::is_convertible<Source, std::string>::value, std::string>::type
convert::toString(const Source& t) noexcept
{
return t;
}
template <typename Destination>
inline typename std::enable_if<std::is_convertible<const char*, Destination>::value, bool>::type
fromString(const char* v, Destination& dest) noexcept
{
dest = Destination(v);
return true;
}
template <>
inline bool convert::fromString<std::string>(const char* v, std::string& dest) noexcept
{
dest = std::string(v);
return true;
}
template <>
inline bool convert::fromString<char>(const char* v, char& dest) noexcept
{
if (strlen(v) != 1u)
{
std::cerr << v << " is not a char" << std::endl;
return false;
}
dest = v[0];
return true;
}
template <>
inline bool convert::fromString<string<100>>(const char* v, string<100>& dest) noexcept
{
dest = string<100>(TruncateToCapacity, v);
return true;
}
inline bool convert::stringIsNumber(const char* v, const NumberType type) noexcept
{
if (v[0] == '\0')
return false;
bool hasDot = false;
for (uint32_t i = 0u; v[i] != '\0'; ++i)
{
if (v[i] >= 48 && v[i] <= 57) // 48 == ascii 0, 57 == ascii 9
{
continue;
}
else if (type != NumberType::UNSIGNED_INTEGER && i == 0u
&& (v[i] == 43 || v[i] == 45)) // 43 == ascii +, 45 == ascii -
{
continue;
}
else if (type == NumberType::FLOAT && !hasDot && v[i] == 46) // 46 == ascii .
{
hasDot = true;
}
else
{
return false;
}
}
return true;
}
inline bool convert::stringIsNumberWithErrorMessage(const char* v, const NumberType type) noexcept
{
if (!stringIsNumber(v, type))
{
std::cerr << v << " is not ";
switch (type)
{
case NumberType::FLOAT:
{
std::cerr << "a float";
break;
}
case NumberType::INTEGER:
{
std::cerr << "a signed integer";
break;
}
case NumberType::UNSIGNED_INTEGER:
{
std::cerr << "an unsigned integer";
break;
}
}
std::cerr << std::endl;
return false;
}
return true;
}
template <>
inline bool convert::fromString<float>(const char* v, float& dest) noexcept
{
if (!stringIsNumberWithErrorMessage(v, NumberType::FLOAT))
{
return false;
}
return !posix::posixCall(strtof)(v, nullptr)
.failureReturnValue(HUGE_VALF, -HUGE_VALF)
.evaluate()
.and_then([&](auto& r) { dest = r.value; })
.has_error();
}
template <>
inline bool convert::fromString<double>(const char* v, double& dest) noexcept
{
if (!stringIsNumberWithErrorMessage(v, NumberType::FLOAT))
{
return false;
}
return !posix::posixCall(strtod)(v, nullptr)
.failureReturnValue(HUGE_VAL, -HUGE_VAL)
.evaluate()
.and_then([&](auto& r) { dest = r.value; })
.has_error();
}
template <>
inline bool convert::fromString<long double>(const char* v, long double& dest) noexcept
{
if (!stringIsNumberWithErrorMessage(v, NumberType::FLOAT))
{
return false;
}
return !posix::posixCall(strtold)(v, nullptr)
.failureReturnValue(HUGE_VALL, -HUGE_VALL)
.evaluate()
.and_then([&](auto& r) { dest = r.value; })
.has_error();
}
template <>
inline bool convert::fromString<uint64_t>(const char* v, uint64_t& dest) noexcept
{
if (!stringIsNumberWithErrorMessage(v, NumberType::UNSIGNED_INTEGER))
{
return false;
}
auto call = posix::posixCall(strtoull)(v, nullptr, STRTOULL_BASE).failureReturnValue(ULLONG_MAX).evaluate();
if (call.has_error())
{
return false;
}
if (call->value > std::numeric_limits<uint64_t>::max())
{
std::cerr << call->value << " too large, uint64_t overflow" << std::endl;
return false;
}
dest = static_cast<uint64_t>(call->value);
return true;
}
#ifdef __APPLE__
/// introduced for mac os since unsigned long is not uint64_t despite it has the same size
/// who knows why ¯\_(ツ)_/¯
template <>
inline bool convert::fromString<unsigned long>(const char* v, unsigned long& dest) noexcept
{
uint64_t temp{0};
bool retVal = fromString(v, temp);
dest = temp;
return retVal;
}
#endif
template <>
inline bool convert::fromString<uint32_t>(const char* v, uint32_t& dest) noexcept
{
if (!stringIsNumberWithErrorMessage(v, NumberType::UNSIGNED_INTEGER))
{
return false;
}
auto call = posix::posixCall(strtoull)(v, nullptr, STRTOULL_BASE).failureReturnValue(ULLONG_MAX).evaluate();
if (call.has_error())
{
return false;
}
if (call->value > std::numeric_limits<uint32_t>::max())
{
std::cerr << call->value << " too large, uint32_t overflow" << std::endl;
return false;
}
dest = static_cast<uint32_t>(call->value);
return true;
}
template <>
inline bool convert::fromString<uint16_t>(const char* v, uint16_t& dest) noexcept
{
if (!stringIsNumberWithErrorMessage(v, NumberType::UNSIGNED_INTEGER))
{
return false;
}
auto call = posix::posixCall(strtoul)(v, nullptr, STRTOULL_BASE).failureReturnValue(ULONG_MAX).evaluate();
if (call.has_error())
{
return false;
}
if (call->value > std::numeric_limits<uint16_t>::max())
{
std::cerr << call->value << " too large, uint16_t overflow" << std::endl;
return false;
}
dest = static_cast<uint16_t>(call->value);
return true;
}
template <>
inline bool convert::fromString<uint8_t>(const char* v, uint8_t& dest) noexcept
{
if (!stringIsNumberWithErrorMessage(v, NumberType::UNSIGNED_INTEGER))
{
return false;
}
auto call = posix::posixCall(strtoul)(v, nullptr, STRTOULL_BASE).failureReturnValue(ULONG_MAX).evaluate();
if (call.has_error())
{
return false;
}
if (call->value > std::numeric_limits<uint8_t>::max())
{
std::cerr << call->value << " too large, uint8_t overflow" << std::endl;
return false;
}
dest = static_cast<uint8_t>(call->value);
return true;
}
template <>
inline bool convert::fromString<int64_t>(const char* v, int64_t& dest) noexcept
{
if (!stringIsNumberWithErrorMessage(v, NumberType::INTEGER))
{
return false;
}
auto call =
posix::posixCall(strtoll)(v, nullptr, STRTOULL_BASE).failureReturnValue(LLONG_MAX, LLONG_MIN).evaluate();
if (call.has_error())
{
return false;
}
if (call->value > std::numeric_limits<int64_t>::max() || call->value < std::numeric_limits<int64_t>::min())
{
std::cerr << call->value << " is out of range, int64_t overflow" << std::endl;
return false;
}
dest = static_cast<int64_t>(call->value);
return true;
}
template <>
inline bool convert::fromString<int32_t>(const char* v, int32_t& dest) noexcept
{
if (!stringIsNumberWithErrorMessage(v, NumberType::INTEGER))
{
return false;
}
auto call =
posix::posixCall(strtoll)(v, nullptr, STRTOULL_BASE).failureReturnValue(LLONG_MAX, LLONG_MIN).evaluate();
if (call.has_error())
{
return false;
}
if (call->value > std::numeric_limits<int32_t>::max() || call->value < std::numeric_limits<int32_t>::min())
{
std::cerr << call->value << " is out of range, int32_t overflow" << std::endl;
return false;
}
dest = static_cast<int32_t>(call->value);
return true;
}
template <>
inline bool convert::fromString<int16_t>(const char* v, int16_t& dest) noexcept
{
if (!stringIsNumberWithErrorMessage(v, NumberType::INTEGER))
{
return false;
}
auto call = posix::posixCall(strtol)(v, nullptr, STRTOULL_BASE).failureReturnValue(LONG_MAX, LONG_MIN).evaluate();
if (call.has_error())
{
return false;
}
if (call->value > std::numeric_limits<int16_t>::max() || call->value < std::numeric_limits<int16_t>::min())
{
std::cerr << call->value << " is out of range, int16_t overflow" << std::endl;
return false;
}
dest = static_cast<int16_t>(call->value);
return true;
}
template <>
inline bool convert::fromString<int8_t>(const char* v, int8_t& dest) noexcept
{
if (!stringIsNumberWithErrorMessage(v, NumberType::INTEGER))
{
return false;
}
auto call = posix::posixCall(strtol)(v, nullptr, STRTOULL_BASE).failureReturnValue(LONG_MAX, LONG_MIN).evaluate();
if (call.has_error())
{
return false;
}
if (call->value > std::numeric_limits<int8_t>::max() || call->value < std::numeric_limits<int8_t>::min())
{
std::cerr << call->value << " is out of range, int8_t overflow" << std::endl;
return false;
}
dest = static_cast<int8_t>(call->value);
return true;
}
template <>
inline bool convert::fromString<bool>(const char* v, bool& dest) noexcept
{
if (!stringIsNumberWithErrorMessage(v, NumberType::UNSIGNED_INTEGER))
{
return false;
}
return !posix::posixCall(strtoul)(v, nullptr, STRTOULL_BASE)
.failureReturnValue(ULONG_MAX)
.evaluate()
.and_then([&](auto& r) { dest = static_cast<bool>(r.value); })
.has_error();
}
} // namespace cxx
} // namespace iox
#endif // IOX_HOOFS_CXX_CONVERT_INL
<commit_msg>iox-#1196 Fix warnings in convert inl<commit_after>// Copyright (c) 2019, 2021 by Robert Bosch GmbH. All rights reserved.
// Copyright (c) 2021 by Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
#ifndef IOX_HOOFS_CXX_CONVERT_INL
#define IOX_HOOFS_CXX_CONVERT_INL
#include "iceoryx_hoofs/cxx/convert.hpp"
namespace iox
{
namespace cxx
{
///@brief specialization for uint8_t and int8_t is required since uint8_t is unsigned char and int8_t is signed char
/// and stringstream will not convert these to string as it is already a character.
template <>
inline typename std::enable_if<!std::is_convertible<uint8_t, std::string>::value, std::string>::type
convert::toString(const uint8_t& t) noexcept
{
return toString(static_cast<uint16_t>(t));
}
template <>
inline typename std::enable_if<!std::is_convertible<int8_t, std::string>::value, std::string>::type
convert::toString(const int8_t& t) noexcept
{
return toString(static_cast<int16_t>(t));
}
template <typename Source>
inline typename std::enable_if<!std::is_convertible<Source, std::string>::value, std::string>::type
convert::toString(const Source& t) noexcept
{
std::stringstream ss;
ss << t;
return ss.str();
}
template <typename Source>
inline typename std::enable_if<std::is_convertible<Source, std::string>::value, std::string>::type
convert::toString(const Source& t) noexcept
{
return t;
}
template <typename Destination>
inline typename std::enable_if<std::is_convertible<const char*, Destination>::value, bool>::type
fromString(const char* v, Destination& dest) noexcept
{
dest = Destination(v);
return true;
}
template <>
inline bool convert::fromString<std::string>(const char* v, std::string& dest) noexcept
{
dest = std::string(v);
return true;
}
template <>
inline bool convert::fromString<char>(const char* v, char& dest) noexcept
{
if (strlen(v) != 1U)
{
std::cerr << v << " is not a char" << std::endl;
return false;
}
/// @NOLINTJUSTIFICATION encapsulated in abstraction
/// @NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
dest = v[0];
return true;
}
/// @NOLINTJUSTIFICATION iox-#1196 todo convert must be refactored
/// @NOLINTBEGIN(cppcoreguidelines-avoid-magic-numbers)
template <>
inline bool convert::fromString<string<100>>(const char* v, string<100>& dest) noexcept
{
dest = string<100>(TruncateToCapacity, v);
return true;
}
/// @NOLINTEND(cppcoreguidelines-avoid-magic-numbers)
inline bool convert::stringIsNumber(const char* v, const NumberType type) noexcept
{
/// @NOLINTJUSTIFICATION encapsulated in abstraction
/// @NOLINTBEGIN(cppcoreguidelines-pro-bounds-pointer-arithmetic)
if (v[0] == '\0')
{
return false;
}
bool hasDot = false;
for (uint32_t i = 0U; v[i] != '\0'; ++i)
{
if (v[i] >= '0' && v[i] <= '9')
{
continue;
}
if (type != NumberType::UNSIGNED_INTEGER && i == 0U && (v[i] == '+' || v[i] == '-'))
{
continue;
}
if (type == NumberType::FLOAT && !hasDot && v[i] == '.')
{
hasDot = true;
}
else
{
return false;
}
}
/// @NOLINTEND(cppcoreguidelines-pro-bounds-pointer-arithmetic)
return true;
}
inline bool convert::stringIsNumberWithErrorMessage(const char* v, const NumberType type) noexcept
{
if (!stringIsNumber(v, type))
{
std::cerr << v << " is not ";
switch (type)
{
case NumberType::FLOAT:
{
std::cerr << "a float";
break;
}
case NumberType::INTEGER:
{
std::cerr << "a signed integer";
break;
}
case NumberType::UNSIGNED_INTEGER:
{
std::cerr << "an unsigned integer";
break;
}
}
std::cerr << std::endl;
return false;
}
return true;
}
template <>
inline bool convert::fromString<float>(const char* v, float& dest) noexcept
{
if (!stringIsNumberWithErrorMessage(v, NumberType::FLOAT))
{
return false;
}
return !posix::posixCall(strtof)(v, nullptr)
.failureReturnValue(HUGE_VALF, -HUGE_VALF)
.evaluate()
.and_then([&](auto& r) { dest = r.value; })
.has_error();
}
template <>
inline bool convert::fromString<double>(const char* v, double& dest) noexcept
{
if (!stringIsNumberWithErrorMessage(v, NumberType::FLOAT))
{
return false;
}
return !posix::posixCall(strtod)(v, nullptr)
.failureReturnValue(HUGE_VAL, -HUGE_VAL)
.evaluate()
.and_then([&](auto& r) { dest = r.value; })
.has_error();
}
template <>
inline bool convert::fromString<long double>(const char* v, long double& dest) noexcept
{
if (!stringIsNumberWithErrorMessage(v, NumberType::FLOAT))
{
return false;
}
return !posix::posixCall(strtold)(v, nullptr)
.failureReturnValue(HUGE_VALL, -HUGE_VALL)
.evaluate()
.and_then([&](auto& r) { dest = r.value; })
.has_error();
}
template <>
inline bool convert::fromString<uint64_t>(const char* v, uint64_t& dest) noexcept
{
if (!stringIsNumberWithErrorMessage(v, NumberType::UNSIGNED_INTEGER))
{
return false;
}
auto call = posix::posixCall(strtoull)(v, nullptr, STRTOULL_BASE).failureReturnValue(ULLONG_MAX).evaluate();
if (call.has_error())
{
return false;
}
if (call->value > std::numeric_limits<uint64_t>::max())
{
std::cerr << call->value << " too large, uint64_t overflow" << std::endl;
return false;
}
dest = static_cast<uint64_t>(call->value);
return true;
}
#ifdef __APPLE__
/// introduced for mac os since unsigned long is not uint64_t despite it has the same size
/// who knows why ¯\_(ツ)_/¯
template <>
inline bool convert::fromString<unsigned long>(const char* v, unsigned long& dest) noexcept
{
uint64_t temp{0};
bool retVal = fromString(v, temp);
dest = temp;
return retVal;
}
#endif
template <>
inline bool convert::fromString<uint32_t>(const char* v, uint32_t& dest) noexcept
{
if (!stringIsNumberWithErrorMessage(v, NumberType::UNSIGNED_INTEGER))
{
return false;
}
auto call = posix::posixCall(strtoull)(v, nullptr, STRTOULL_BASE).failureReturnValue(ULLONG_MAX).evaluate();
if (call.has_error())
{
return false;
}
if (call->value > std::numeric_limits<uint32_t>::max())
{
std::cerr << call->value << " too large, uint32_t overflow" << std::endl;
return false;
}
dest = static_cast<uint32_t>(call->value);
return true;
}
template <>
inline bool convert::fromString<uint16_t>(const char* v, uint16_t& dest) noexcept
{
if (!stringIsNumberWithErrorMessage(v, NumberType::UNSIGNED_INTEGER))
{
return false;
}
auto call = posix::posixCall(strtoul)(v, nullptr, STRTOULL_BASE).failureReturnValue(ULONG_MAX).evaluate();
if (call.has_error())
{
return false;
}
if (call->value > std::numeric_limits<uint16_t>::max())
{
std::cerr << call->value << " too large, uint16_t overflow" << std::endl;
return false;
}
dest = static_cast<uint16_t>(call->value);
return true;
}
template <>
inline bool convert::fromString<uint8_t>(const char* v, uint8_t& dest) noexcept
{
if (!stringIsNumberWithErrorMessage(v, NumberType::UNSIGNED_INTEGER))
{
return false;
}
auto call = posix::posixCall(strtoul)(v, nullptr, STRTOULL_BASE).failureReturnValue(ULONG_MAX).evaluate();
if (call.has_error())
{
return false;
}
if (call->value > std::numeric_limits<uint8_t>::max())
{
std::cerr << call->value << " too large, uint8_t overflow" << std::endl;
return false;
}
dest = static_cast<uint8_t>(call->value);
return true;
}
template <>
inline bool convert::fromString<int64_t>(const char* v, int64_t& dest) noexcept
{
if (!stringIsNumberWithErrorMessage(v, NumberType::INTEGER))
{
return false;
}
auto call =
posix::posixCall(strtoll)(v, nullptr, STRTOULL_BASE).failureReturnValue(LLONG_MAX, LLONG_MIN).evaluate();
if (call.has_error())
{
return false;
}
if (call->value > std::numeric_limits<int64_t>::max() || call->value < std::numeric_limits<int64_t>::min())
{
std::cerr << call->value << " is out of range, int64_t overflow" << std::endl;
return false;
}
dest = static_cast<int64_t>(call->value);
return true;
}
template <>
inline bool convert::fromString<int32_t>(const char* v, int32_t& dest) noexcept
{
if (!stringIsNumberWithErrorMessage(v, NumberType::INTEGER))
{
return false;
}
auto call =
posix::posixCall(strtoll)(v, nullptr, STRTOULL_BASE).failureReturnValue(LLONG_MAX, LLONG_MIN).evaluate();
if (call.has_error())
{
return false;
}
if (call->value > std::numeric_limits<int32_t>::max() || call->value < std::numeric_limits<int32_t>::min())
{
std::cerr << call->value << " is out of range, int32_t overflow" << std::endl;
return false;
}
dest = static_cast<int32_t>(call->value);
return true;
}
template <>
inline bool convert::fromString<int16_t>(const char* v, int16_t& dest) noexcept
{
if (!stringIsNumberWithErrorMessage(v, NumberType::INTEGER))
{
return false;
}
auto call = posix::posixCall(strtol)(v, nullptr, STRTOULL_BASE).failureReturnValue(LONG_MAX, LONG_MIN).evaluate();
if (call.has_error())
{
return false;
}
if (call->value > std::numeric_limits<int16_t>::max() || call->value < std::numeric_limits<int16_t>::min())
{
std::cerr << call->value << " is out of range, int16_t overflow" << std::endl;
return false;
}
dest = static_cast<int16_t>(call->value);
return true;
}
template <>
inline bool convert::fromString<int8_t>(const char* v, int8_t& dest) noexcept
{
if (!stringIsNumberWithErrorMessage(v, NumberType::INTEGER))
{
return false;
}
auto call = posix::posixCall(strtol)(v, nullptr, STRTOULL_BASE).failureReturnValue(LONG_MAX, LONG_MIN).evaluate();
if (call.has_error())
{
return false;
}
if (call->value > std::numeric_limits<int8_t>::max() || call->value < std::numeric_limits<int8_t>::min())
{
std::cerr << call->value << " is out of range, int8_t overflow" << std::endl;
return false;
}
dest = static_cast<int8_t>(call->value);
return true;
}
template <>
inline bool convert::fromString<bool>(const char* v, bool& dest) noexcept
{
if (!stringIsNumberWithErrorMessage(v, NumberType::UNSIGNED_INTEGER))
{
return false;
}
return !posix::posixCall(strtoul)(v, nullptr, STRTOULL_BASE)
.failureReturnValue(ULONG_MAX)
.evaluate()
.and_then([&](auto& r) { dest = static_cast<bool>(r.value); })
.has_error();
}
} // namespace cxx
} // namespace iox
#endif // IOX_HOOFS_CXX_CONVERT_INL
<|endoftext|>
|
<commit_before>/* based on http://www.boost.org/doc/libs/1_61_0/doc/html/boost_asio/example/cpp03/echo/blocking_tcp_echo_client.cpp */
#include <iostream>
#include <boost/asio.hpp>
#include "../HttpParser.hpp"
using boost::asio::ip::tcp;
using namespace http;
int main(int argc, char* argv[])
{
try {
if (argc != 2) {
std::cerr << "Usage: " << argv[0] << " <URL>" << std::endl;
return 1;
}
Url url;
bool urlParsedOk = false;
try {
url = parseUrl(argv[1]);
urlParsedOk = true;
} catch (const UrlParseError&) {
}
if (!urlParsedOk || url.host.empty()) {
std::cerr << "This does not appear to be a valid URL of a HTTP resource: "
<< argv[1] << std::endl;
return 1;
}
if (url.schema != "http") {
std::cerr << "This program only supports plain HTTP." << std::endl;
return 1;
}
if (0 == url.port) { // no port specified explicitly in the URL
url.port = 80; // good as long as we only support http://
}
//std::cout << url << std::endl;
std::ostringstream ss;
ss << "GET " << url.path;
if (!url.query.empty()) {
ss << '?' << url.query;
}
ss << " HTTP/1.1\r\n"
<< "Host: " << url.host << "\r\n"
<< "Connection: close\r\n"
<< "\r\n";
const std::string request = ss.str();
std::cout << request << std::endl;
boost::asio::io_service ioService;
tcp::resolver resolver(ioService);
tcp::resolver::query query(tcp::v4(), url.host, std::to_string(url.port));
tcp::resolver::iterator it = resolver.resolve(query);
tcp::socket socket(ioService);
std::cout << "Connecting to " << url.host << ':' << url.port << "... "
<< std::flush;
boost::asio::connect(socket, it);
std::cout << "done\nSending request." << std::endl;
boost::asio::write(socket, boost::asio::buffer(request));
std::cout << "Reading response." << std::endl;
// TODO: use BigResponseParser to save the response body to a file.
// TODO: determine file name (may want to get response headers first
char reply[2048];
size_t reply_length = boost::asio::read(socket,
boost::asio::buffer(reply, sizeof(reply)));
std::cout << "Reply is:\n";
std::cout.write(reply, reply_length);
std::cout << "\n";
} catch (const std::runtime_error &e) {
std::cerr << "Interrupted by exception: " << e.what() << std::endl;
return 1;
}
return 0;
}
<commit_msg>Still working on the BigResponseParser usage example<commit_after>/* based on http://www.boost.org/doc/libs/1_61_0/doc/html/boost_asio/example/cpp03/echo/blocking_tcp_echo_client.cpp */
#include <iostream>
#include <fstream>
#include <libgen.h> /* for basename */
#include <boost/asio.hpp>
#include "../HttpParser.hpp"
using boost::asio::ip::tcp;
using namespace http;
std::string determineFileName(const std::string& urlPath,
const http::Response& response)
{
// TODO this obviously needs refinement
return basename((char*) urlPath.c_str());
}
int main(int argc, char* argv[])
{
try {
if (argc != 2) {
std::cerr << "Usage: " << argv[0] << " <URL>" << std::endl;
return 1;
}
Url url;
bool urlParsedOk = false;
try {
url = parseUrl(argv[1]);
urlParsedOk = true;
} catch (const UrlParseError&) {
}
if (!urlParsedOk || url.host.empty()) {
std::cerr << "This does not appear to be a valid URL of a HTTP resource: "
<< argv[1] << std::endl;
return 1;
}
if (url.schema != "http") {
std::cerr << "This program only supports plain HTTP." << std::endl;
return 1;
}
if (0 == url.port) { // no port specified explicitly in the URL
url.port = 80; // good as long as we only support http://
}
std::ostringstream ss;
ss << "GET " << url.path;
if (!url.query.empty()) {
ss << '?' << url.query;
}
ss << " HTTP/1.1\r\n"
<< "Host: " << url.host << "\r\n"
<< "Connection: close\r\n"
<< "\r\n";
const std::string request = ss.str();
std::cout << request << std::endl;
boost::asio::io_service ioService;
tcp::resolver resolver(ioService);
tcp::resolver::query query(tcp::v4(), url.host, std::to_string(url.port));
tcp::resolver::iterator it = resolver.resolve(query);
tcp::socket socket(ioService);
std::cout << "Connecting to " << url.host << ':' << url.port << "... "
<< std::flush;
boost::asio::connect(socket, it);
std::cout << "done\nSending request." << std::endl;
boost::asio::write(socket, boost::asio::buffer(request));
std::cout << "Reading response." << std::endl;
std::string fileName;
std::ofstream outputFile;
outputFile.exceptions(std::ofstream::failbit | std::ofstream::badbit);
bool completed = false;
auto myCallback = [&] (const http::Response& response,
const char *bodyPart, std::size_t bodyPartLength, bool finished) {
if (!outputFile.is_open()) {
fileName = determineFileName(url.path, response);
std::cout << "Saving to " << fileName << std::endl;
outputFile.open(fileName,
std::ios::out | std::ios::trunc | std::ios::binary);
}
outputFile.write(bodyPart, bodyPartLength);
completed = finished;
if (completed) {
std::cout << "Done." << std::endl;
}
};
http::BigResponseParser parser(myCallback);
parser.setMaxHeadersLength(1024 * 1024);
while (!completed) {
boost::system::error_code ec;
char reply[2048];
size_t reply_length = boost::asio::read(socket,
boost::asio::buffer(reply, sizeof(reply)), ec);
if (!ec) {
parser.feed(reply, reply_length);
} else if (boost::asio::error::eof == ec) {
parser.feed(reply, reply_length);
parser.feedEof();
} else {
throw boost::system::system_error(ec);
}
}
} catch (const std::runtime_error& e) {
std::cerr << "Interrupted by exception: " << e.what() << std::endl;
return 1;
}
return 0;
}
<|endoftext|>
|
<commit_before>#include "selfdrive/ui/qt/setup/setup.h"
#include <cstdio>
#include <cstdlib>
#include <sstream>
#include <QApplication>
#include <QLabel>
#include <QVBoxLayout>
#include <curl/curl.h>
#include "selfdrive/hardware/hw.h"
#include "selfdrive/ui/qt/api.h"
#include "selfdrive/ui/qt/qt_window.h"
#include "selfdrive/ui/qt/offroad/networking.h"
#include "selfdrive/ui/qt/widgets/input.h"
const char* USER_AGENT = "AGNOSSetup-0.1";
const QString DASHCAM_URL = "https://dashcam.comma.ai";
void Setup::download(QString url) {
CURL *curl = curl_easy_init();
if (!curl) {
emit finished(false);
return;
}
char tmpfile[] = "/tmp/installer_XXXXXX";
FILE *fp = fdopen(mkstemp(tmpfile), "w");
curl_easy_setopt(curl, CURLOPT_URL, url.toStdString().c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, NULL);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_USERAGENT, USER_AGENT);
int ret = curl_easy_perform(curl);
long res_status = 0;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &res_status);
if (ret == CURLE_OK && res_status == 200) {
rename(tmpfile, "/tmp/installer");
emit finished(true);
} else {
emit finished(false);
}
curl_easy_cleanup(curl);
fclose(fp);
}
QWidget * Setup::low_voltage() {
QWidget *widget = new QWidget();
QVBoxLayout *main_layout = new QVBoxLayout(widget);
main_layout->setContentsMargins(55, 0, 55, 55);
main_layout->setSpacing(0);
// inner text layout: warning icon, title, and body
QVBoxLayout *inner_layout = new QVBoxLayout();
inner_layout->setContentsMargins(110, 144, 365, 0);
main_layout->addLayout(inner_layout);
QLabel *triangle = new QLabel();
triangle->setPixmap(QPixmap(ASSET_PATH + "offroad/icon_warning.png"));
inner_layout->addWidget(triangle, 0, Qt::AlignTop | Qt::AlignLeft);
inner_layout->addSpacing(80);
QLabel *title = new QLabel("WARNING: Low Voltage");
title->setStyleSheet("font-size: 90px; font-weight: 500; color: #FF594F;");
inner_layout->addWidget(title, 0, Qt::AlignTop | Qt::AlignLeft);
inner_layout->addSpacing(25);
QLabel *body = new QLabel("Power your device in a car with a harness or proceed at your own risk.");
body->setWordWrap(true);
body->setAlignment(Qt::AlignTop | Qt::AlignLeft);
body->setStyleSheet("font-size: 80px; font-weight: 300;");
inner_layout->addWidget(body);
inner_layout->addStretch();
// power off + continue buttons
QHBoxLayout *blayout = new QHBoxLayout();
blayout->setSpacing(50);
main_layout->addLayout(blayout, 0);
QPushButton *poweroff = new QPushButton("Power off");
poweroff->setObjectName("navBtn");
blayout->addWidget(poweroff);
QObject::connect(poweroff, &QPushButton::clicked, this, [=]() {
Hardware::poweroff();
});
QPushButton *cont = new QPushButton("Continue");
cont->setObjectName("navBtn");
blayout->addWidget(cont);
QObject::connect(cont, &QPushButton::clicked, this, &Setup::nextPage);
return widget;
}
QWidget * Setup::getting_started() {
QWidget *widget = new QWidget();
QHBoxLayout *main_layout = new QHBoxLayout(widget);
main_layout->setMargin(0);
QVBoxLayout *vlayout = new QVBoxLayout();
vlayout->setContentsMargins(165, 280, 100, 0);
main_layout->addLayout(vlayout);
QLabel *title = new QLabel("Getting Started");
title->setStyleSheet("font-size: 90px; font-weight: 500;");
vlayout->addWidget(title, 0, Qt::AlignTop | Qt::AlignLeft);
vlayout->addSpacing(90);
QLabel *desc = new QLabel("Before we get on the road, let’s finish installation and cover some details.");
desc->setWordWrap(true);
desc->setStyleSheet("font-size: 80px; font-weight: 300;");
vlayout->addWidget(desc, 0, Qt::AlignTop | Qt::AlignLeft);
vlayout->addStretch();
QPushButton *btn = new QPushButton();
btn->setIcon(QIcon(":/img_continue_triangle.svg"));
btn->setIconSize(QSize(54, 106));
btn->setFixedSize(310, 1080);
btn->setProperty("primary", true);
btn->setStyleSheet("border: none;");
main_layout->addWidget(btn, 0, Qt::AlignRight);
QObject::connect(btn, &QPushButton::clicked, this, &Setup::nextPage);
return widget;
}
QWidget * Setup::network_setup() {
QWidget *widget = new QWidget();
QVBoxLayout *main_layout = new QVBoxLayout(widget);
main_layout->setContentsMargins(55, 50, 55, 50);
// title
QLabel *title = new QLabel("Connect to Wi-Fi");
title->setStyleSheet("font-size: 90px; font-weight: 500;");
main_layout->addWidget(title, 0, Qt::AlignLeft | Qt::AlignTop);
main_layout->addSpacing(25);
// wifi widget
Networking *networking = new Networking(this, false);
networking->setStyleSheet("Networking {background-color: #292929; border-radius: 13px;}");
main_layout->addWidget(networking, 1);
main_layout->addSpacing(35);
// back + continue buttons
QHBoxLayout *blayout = new QHBoxLayout;
main_layout->addLayout(blayout);
blayout->setSpacing(50);
QPushButton *back = new QPushButton("Back");
back->setObjectName("navBtn");
QObject::connect(back, &QPushButton::clicked, this, &Setup::prevPage);
blayout->addWidget(back);
QPushButton *cont = new QPushButton();
cont->setObjectName("navBtn");
cont->setProperty("primary", true);
QObject::connect(cont, &QPushButton::clicked, this, &Setup::nextPage);
blayout->addWidget(cont);
// setup timer for testing internet connection
HttpRequest *request = new HttpRequest(this, false, 2500);
QObject::connect(request, &HttpRequest::requestDone, [=](const QString &, bool success) {
cont->setEnabled(success);
if (success) {
const bool cell = networking->wifi->currentNetworkType() == NetworkType::CELL;
cont->setText(cell ? "Continue without Wi-Fi" : "Continue");
} else {
cont->setText("Waiting for internet");
}
repaint();
});
request->sendRequest(DASHCAM_URL);
QTimer *timer = new QTimer(this);
QObject::connect(timer, &QTimer::timeout, [=]() {
if (!request->active() && cont->isVisible()) {
request->sendRequest(DASHCAM_URL);
}
});
timer->start(1000);
return widget;
}
QWidget * radio_button(QString title, QButtonGroup *group) {
QPushButton *btn = new QPushButton(title);
btn->setCheckable(true);
group->addButton(btn);
btn->setStyleSheet(R"(
QPushButton {
height: 230;
padding-left: 100px;
padding-right: 100px;
text-align: left;
font-size: 80px;
font-weight: 400;
border-radius: 10px;
background-color: #4F4F4F;
}
QPushButton:checked {
background-color: #465BEA;
}
)");
// checkmark icon
QPixmap pix(":/img_circled_check.svg");
btn->setIcon(pix);
btn->setIconSize(QSize(0, 0));
btn->setLayoutDirection(Qt::RightToLeft);
QObject::connect(btn, &QPushButton::toggled, [=](bool checked) {
btn->setIconSize(checked ? QSize(104, 104) : QSize(0, 0));
});
return btn;
}
QWidget * Setup::software_selection() {
QWidget *widget = new QWidget();
QVBoxLayout *main_layout = new QVBoxLayout(widget);
main_layout->setContentsMargins(55, 50, 55, 50);
main_layout->setSpacing(0);
// title
QLabel *title = new QLabel("Choose Software to Install");
title->setStyleSheet("font-size: 90px; font-weight: 500;");
main_layout->addWidget(title, 0, Qt::AlignLeft | Qt::AlignTop);
main_layout->addSpacing(50);
// dashcam + custom radio buttons
QButtonGroup *group = new QButtonGroup(widget);
group->setExclusive(true);
QWidget *dashcam = radio_button("Dashcam", group);
main_layout->addWidget(dashcam);
main_layout->addSpacing(30);
QWidget *custom = radio_button("Custom Software", group);
main_layout->addWidget(custom);
main_layout->addStretch();
// back + continue buttons
QHBoxLayout *blayout = new QHBoxLayout;
main_layout->addLayout(blayout);
blayout->setSpacing(50);
QPushButton *back = new QPushButton("Back");
back->setObjectName("navBtn");
QObject::connect(back, &QPushButton::clicked, this, &Setup::prevPage);
blayout->addWidget(back);
QPushButton *cont = new QPushButton("Continue");
cont->setObjectName("navBtn");
cont->setEnabled(false);
cont->setProperty("primary", true);
blayout->addWidget(cont);
QObject::connect(cont, &QPushButton::clicked, [=]() {
auto w = currentWidget();
QTimer::singleShot(0, [=]() {
setCurrentWidget(downloading_widget);
});
QString url = DASHCAM_URL;
if (group->checkedButton() != dashcam) {
url = InputDialog::getText("Enter URL", this, "for Custom Software");
}
if (!url.isEmpty()) {
QTimer::singleShot(1000, this, [=]() {
download(url);
});
} else {
setCurrentWidget(w);
}
});
connect(group, QOverload<QAbstractButton *>::of(&QButtonGroup::buttonClicked), [=](QAbstractButton *btn) {
btn->setChecked(true);
cont->setEnabled(true);
});
return widget;
}
QWidget * Setup::downloading() {
QWidget *widget = new QWidget();
QVBoxLayout *main_layout = new QVBoxLayout(widget);
QLabel *txt = new QLabel("Downloading...");
txt->setStyleSheet("font-size: 90px; font-weight: 500;");
main_layout->addWidget(txt, 0, Qt::AlignCenter);
return widget;
}
QWidget * Setup::download_failed() {
QWidget *widget = new QWidget();
QVBoxLayout *main_layout = new QVBoxLayout(widget);
main_layout->setContentsMargins(55, 225, 55, 55);
main_layout->setSpacing(0);
QLabel *title = new QLabel("Download Failed");
title->setStyleSheet("font-size: 90px; font-weight: 500;");
main_layout->addWidget(title, 0, Qt::AlignTop | Qt::AlignLeft);
main_layout->addSpacing(67);
QLabel *body = new QLabel("Ensure the entered URL is valid, and the device’s internet connection is good.");
body->setWordWrap(true);
body->setAlignment(Qt::AlignTop | Qt::AlignLeft);
body->setStyleSheet("font-size: 80px; font-weight: 300; margin-right: 100px;");
main_layout->addWidget(body);
main_layout->addStretch();
// reboot + start over buttons
QHBoxLayout *blayout = new QHBoxLayout();
blayout->setSpacing(50);
main_layout->addLayout(blayout, 0);
QPushButton *reboot = new QPushButton("Reboot device");
reboot->setObjectName("navBtn");
blayout->addWidget(reboot);
QObject::connect(reboot, &QPushButton::clicked, this, [=]() {
Hardware::reboot();
});
QPushButton *restart = new QPushButton("Start over");
restart->setObjectName("navBtn");
restart->setProperty("primary", true);
blayout->addWidget(restart);
QObject::connect(restart, &QPushButton::clicked, this, [=]() {
setCurrentIndex(2);
});
widget->setStyleSheet(R"(
QLabel {
margin-left: 117;
}
)");
return widget;
}
void Setup::prevPage() {
setCurrentIndex(currentIndex() - 1);
}
void Setup::nextPage() {
setCurrentIndex(currentIndex() + 1);
}
Setup::Setup(QWidget *parent) : QStackedWidget(parent) {
std::stringstream buffer;
buffer << std::ifstream("/sys/class/hwmon/hwmon1/in1_input").rdbuf();
float voltage = (float)std::atoi(buffer.str().c_str()) / 1000.;
if (voltage < 7) {
addWidget(low_voltage());
}
addWidget(getting_started());
addWidget(network_setup());
addWidget(software_selection());
downloading_widget = downloading();
addWidget(downloading_widget);
failed_widget = download_failed();
addWidget(failed_widget);
QObject::connect(this, &Setup::finished, [=](bool success) {
// hide setup on success
qDebug() << "finished" << success;
if (success) {
QTimer::singleShot(3000, this, &QWidget::hide);
} else {
setCurrentWidget(failed_widget);
}
});
// TODO: revisit pressed bg color
setStyleSheet(R"(
* {
color: white;
font-family: Inter;
}
Setup {
background-color: black;
}
QPushButton#navBtn {
height: 160;
font-size: 55px;
font-weight: 400;
border-radius: 10px;
background-color: #333333;
}
QPushButton#navBtn:disabled, QPushButton[primary='true']:disabled {
color: #808080;
background-color: #333333;
}
QPushButton#navBtn:pressed {
background-color: #444444;
}
QPushButton[primary='true'], #navBtn[primary='true'] {
background-color: #465BEA;
}
QPushButton[primary='true']:pressed, #navBtn:pressed[primary='true'] {
background-color: #3049F4;
}
)");
}
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
Setup setup;
setMainWindow(&setup);
return a.exec();
}
<commit_msg>setup: add OS version to user agent (#23656)<commit_after>#include "selfdrive/ui/qt/setup/setup.h"
#include <cstdio>
#include <cstdlib>
#include <sstream>
#include <QApplication>
#include <QLabel>
#include <QVBoxLayout>
#include <curl/curl.h>
#include "selfdrive/common/util.h"
#include "selfdrive/hardware/hw.h"
#include "selfdrive/ui/qt/api.h"
#include "selfdrive/ui/qt/qt_window.h"
#include "selfdrive/ui/qt/offroad/networking.h"
#include "selfdrive/ui/qt/widgets/input.h"
const std::string USER_AGENT = "AGNOSSetup-";
const QString DASHCAM_URL = "https://dashcam.comma.ai";
void Setup::download(QString url) {
CURL *curl = curl_easy_init();
if (!curl) {
emit finished(false);
return;
}
auto version = util::read_file("/VERSION");
char tmpfile[] = "/tmp/installer_XXXXXX";
FILE *fp = fdopen(mkstemp(tmpfile), "w");
curl_easy_setopt(curl, CURLOPT_URL, url.toStdString().c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, NULL);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_USERAGENT, (USER_AGENT + version).c_str());
int ret = curl_easy_perform(curl);
long res_status = 0;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &res_status);
if (ret == CURLE_OK && res_status == 200) {
rename(tmpfile, "/tmp/installer");
emit finished(true);
} else {
emit finished(false);
}
curl_easy_cleanup(curl);
fclose(fp);
}
QWidget * Setup::low_voltage() {
QWidget *widget = new QWidget();
QVBoxLayout *main_layout = new QVBoxLayout(widget);
main_layout->setContentsMargins(55, 0, 55, 55);
main_layout->setSpacing(0);
// inner text layout: warning icon, title, and body
QVBoxLayout *inner_layout = new QVBoxLayout();
inner_layout->setContentsMargins(110, 144, 365, 0);
main_layout->addLayout(inner_layout);
QLabel *triangle = new QLabel();
triangle->setPixmap(QPixmap(ASSET_PATH + "offroad/icon_warning.png"));
inner_layout->addWidget(triangle, 0, Qt::AlignTop | Qt::AlignLeft);
inner_layout->addSpacing(80);
QLabel *title = new QLabel("WARNING: Low Voltage");
title->setStyleSheet("font-size: 90px; font-weight: 500; color: #FF594F;");
inner_layout->addWidget(title, 0, Qt::AlignTop | Qt::AlignLeft);
inner_layout->addSpacing(25);
QLabel *body = new QLabel("Power your device in a car with a harness or proceed at your own risk.");
body->setWordWrap(true);
body->setAlignment(Qt::AlignTop | Qt::AlignLeft);
body->setStyleSheet("font-size: 80px; font-weight: 300;");
inner_layout->addWidget(body);
inner_layout->addStretch();
// power off + continue buttons
QHBoxLayout *blayout = new QHBoxLayout();
blayout->setSpacing(50);
main_layout->addLayout(blayout, 0);
QPushButton *poweroff = new QPushButton("Power off");
poweroff->setObjectName("navBtn");
blayout->addWidget(poweroff);
QObject::connect(poweroff, &QPushButton::clicked, this, [=]() {
Hardware::poweroff();
});
QPushButton *cont = new QPushButton("Continue");
cont->setObjectName("navBtn");
blayout->addWidget(cont);
QObject::connect(cont, &QPushButton::clicked, this, &Setup::nextPage);
return widget;
}
QWidget * Setup::getting_started() {
QWidget *widget = new QWidget();
QHBoxLayout *main_layout = new QHBoxLayout(widget);
main_layout->setMargin(0);
QVBoxLayout *vlayout = new QVBoxLayout();
vlayout->setContentsMargins(165, 280, 100, 0);
main_layout->addLayout(vlayout);
QLabel *title = new QLabel("Getting Started");
title->setStyleSheet("font-size: 90px; font-weight: 500;");
vlayout->addWidget(title, 0, Qt::AlignTop | Qt::AlignLeft);
vlayout->addSpacing(90);
QLabel *desc = new QLabel("Before we get on the road, let’s finish installation and cover some details.");
desc->setWordWrap(true);
desc->setStyleSheet("font-size: 80px; font-weight: 300;");
vlayout->addWidget(desc, 0, Qt::AlignTop | Qt::AlignLeft);
vlayout->addStretch();
QPushButton *btn = new QPushButton();
btn->setIcon(QIcon(":/img_continue_triangle.svg"));
btn->setIconSize(QSize(54, 106));
btn->setFixedSize(310, 1080);
btn->setProperty("primary", true);
btn->setStyleSheet("border: none;");
main_layout->addWidget(btn, 0, Qt::AlignRight);
QObject::connect(btn, &QPushButton::clicked, this, &Setup::nextPage);
return widget;
}
QWidget * Setup::network_setup() {
QWidget *widget = new QWidget();
QVBoxLayout *main_layout = new QVBoxLayout(widget);
main_layout->setContentsMargins(55, 50, 55, 50);
// title
QLabel *title = new QLabel("Connect to Wi-Fi");
title->setStyleSheet("font-size: 90px; font-weight: 500;");
main_layout->addWidget(title, 0, Qt::AlignLeft | Qt::AlignTop);
main_layout->addSpacing(25);
// wifi widget
Networking *networking = new Networking(this, false);
networking->setStyleSheet("Networking {background-color: #292929; border-radius: 13px;}");
main_layout->addWidget(networking, 1);
main_layout->addSpacing(35);
// back + continue buttons
QHBoxLayout *blayout = new QHBoxLayout;
main_layout->addLayout(blayout);
blayout->setSpacing(50);
QPushButton *back = new QPushButton("Back");
back->setObjectName("navBtn");
QObject::connect(back, &QPushButton::clicked, this, &Setup::prevPage);
blayout->addWidget(back);
QPushButton *cont = new QPushButton();
cont->setObjectName("navBtn");
cont->setProperty("primary", true);
QObject::connect(cont, &QPushButton::clicked, this, &Setup::nextPage);
blayout->addWidget(cont);
// setup timer for testing internet connection
HttpRequest *request = new HttpRequest(this, false, 2500);
QObject::connect(request, &HttpRequest::requestDone, [=](const QString &, bool success) {
cont->setEnabled(success);
if (success) {
const bool cell = networking->wifi->currentNetworkType() == NetworkType::CELL;
cont->setText(cell ? "Continue without Wi-Fi" : "Continue");
} else {
cont->setText("Waiting for internet");
}
repaint();
});
request->sendRequest(DASHCAM_URL);
QTimer *timer = new QTimer(this);
QObject::connect(timer, &QTimer::timeout, [=]() {
if (!request->active() && cont->isVisible()) {
request->sendRequest(DASHCAM_URL);
}
});
timer->start(1000);
return widget;
}
QWidget * radio_button(QString title, QButtonGroup *group) {
QPushButton *btn = new QPushButton(title);
btn->setCheckable(true);
group->addButton(btn);
btn->setStyleSheet(R"(
QPushButton {
height: 230;
padding-left: 100px;
padding-right: 100px;
text-align: left;
font-size: 80px;
font-weight: 400;
border-radius: 10px;
background-color: #4F4F4F;
}
QPushButton:checked {
background-color: #465BEA;
}
)");
// checkmark icon
QPixmap pix(":/img_circled_check.svg");
btn->setIcon(pix);
btn->setIconSize(QSize(0, 0));
btn->setLayoutDirection(Qt::RightToLeft);
QObject::connect(btn, &QPushButton::toggled, [=](bool checked) {
btn->setIconSize(checked ? QSize(104, 104) : QSize(0, 0));
});
return btn;
}
QWidget * Setup::software_selection() {
QWidget *widget = new QWidget();
QVBoxLayout *main_layout = new QVBoxLayout(widget);
main_layout->setContentsMargins(55, 50, 55, 50);
main_layout->setSpacing(0);
// title
QLabel *title = new QLabel("Choose Software to Install");
title->setStyleSheet("font-size: 90px; font-weight: 500;");
main_layout->addWidget(title, 0, Qt::AlignLeft | Qt::AlignTop);
main_layout->addSpacing(50);
// dashcam + custom radio buttons
QButtonGroup *group = new QButtonGroup(widget);
group->setExclusive(true);
QWidget *dashcam = radio_button("Dashcam", group);
main_layout->addWidget(dashcam);
main_layout->addSpacing(30);
QWidget *custom = radio_button("Custom Software", group);
main_layout->addWidget(custom);
main_layout->addStretch();
// back + continue buttons
QHBoxLayout *blayout = new QHBoxLayout;
main_layout->addLayout(blayout);
blayout->setSpacing(50);
QPushButton *back = new QPushButton("Back");
back->setObjectName("navBtn");
QObject::connect(back, &QPushButton::clicked, this, &Setup::prevPage);
blayout->addWidget(back);
QPushButton *cont = new QPushButton("Continue");
cont->setObjectName("navBtn");
cont->setEnabled(false);
cont->setProperty("primary", true);
blayout->addWidget(cont);
QObject::connect(cont, &QPushButton::clicked, [=]() {
auto w = currentWidget();
QTimer::singleShot(0, [=]() {
setCurrentWidget(downloading_widget);
});
QString url = DASHCAM_URL;
if (group->checkedButton() != dashcam) {
url = InputDialog::getText("Enter URL", this, "for Custom Software");
}
if (!url.isEmpty()) {
QTimer::singleShot(1000, this, [=]() {
download(url);
});
} else {
setCurrentWidget(w);
}
});
connect(group, QOverload<QAbstractButton *>::of(&QButtonGroup::buttonClicked), [=](QAbstractButton *btn) {
btn->setChecked(true);
cont->setEnabled(true);
});
return widget;
}
QWidget * Setup::downloading() {
QWidget *widget = new QWidget();
QVBoxLayout *main_layout = new QVBoxLayout(widget);
QLabel *txt = new QLabel("Downloading...");
txt->setStyleSheet("font-size: 90px; font-weight: 500;");
main_layout->addWidget(txt, 0, Qt::AlignCenter);
return widget;
}
QWidget * Setup::download_failed() {
QWidget *widget = new QWidget();
QVBoxLayout *main_layout = new QVBoxLayout(widget);
main_layout->setContentsMargins(55, 225, 55, 55);
main_layout->setSpacing(0);
QLabel *title = new QLabel("Download Failed");
title->setStyleSheet("font-size: 90px; font-weight: 500;");
main_layout->addWidget(title, 0, Qt::AlignTop | Qt::AlignLeft);
main_layout->addSpacing(67);
QLabel *body = new QLabel("Ensure the entered URL is valid, and the device’s internet connection is good.");
body->setWordWrap(true);
body->setAlignment(Qt::AlignTop | Qt::AlignLeft);
body->setStyleSheet("font-size: 80px; font-weight: 300; margin-right: 100px;");
main_layout->addWidget(body);
main_layout->addStretch();
// reboot + start over buttons
QHBoxLayout *blayout = new QHBoxLayout();
blayout->setSpacing(50);
main_layout->addLayout(blayout, 0);
QPushButton *reboot = new QPushButton("Reboot device");
reboot->setObjectName("navBtn");
blayout->addWidget(reboot);
QObject::connect(reboot, &QPushButton::clicked, this, [=]() {
Hardware::reboot();
});
QPushButton *restart = new QPushButton("Start over");
restart->setObjectName("navBtn");
restart->setProperty("primary", true);
blayout->addWidget(restart);
QObject::connect(restart, &QPushButton::clicked, this, [=]() {
setCurrentIndex(2);
});
widget->setStyleSheet(R"(
QLabel {
margin-left: 117;
}
)");
return widget;
}
void Setup::prevPage() {
setCurrentIndex(currentIndex() - 1);
}
void Setup::nextPage() {
setCurrentIndex(currentIndex() + 1);
}
Setup::Setup(QWidget *parent) : QStackedWidget(parent) {
std::stringstream buffer;
buffer << std::ifstream("/sys/class/hwmon/hwmon1/in1_input").rdbuf();
float voltage = (float)std::atoi(buffer.str().c_str()) / 1000.;
if (voltage < 7) {
addWidget(low_voltage());
}
addWidget(getting_started());
addWidget(network_setup());
addWidget(software_selection());
downloading_widget = downloading();
addWidget(downloading_widget);
failed_widget = download_failed();
addWidget(failed_widget);
QObject::connect(this, &Setup::finished, [=](bool success) {
// hide setup on success
qDebug() << "finished" << success;
if (success) {
QTimer::singleShot(3000, this, &QWidget::hide);
} else {
setCurrentWidget(failed_widget);
}
});
// TODO: revisit pressed bg color
setStyleSheet(R"(
* {
color: white;
font-family: Inter;
}
Setup {
background-color: black;
}
QPushButton#navBtn {
height: 160;
font-size: 55px;
font-weight: 400;
border-radius: 10px;
background-color: #333333;
}
QPushButton#navBtn:disabled, QPushButton[primary='true']:disabled {
color: #808080;
background-color: #333333;
}
QPushButton#navBtn:pressed {
background-color: #444444;
}
QPushButton[primary='true'], #navBtn[primary='true'] {
background-color: #465BEA;
}
QPushButton[primary='true']:pressed, #navBtn:pressed[primary='true'] {
background-color: #3049F4;
}
)");
}
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
Setup setup;
setMainWindow(&setup);
return a.exec();
}
<|endoftext|>
|
<commit_before>/*
* DISTRHO Plugin Framework (DPF)
* Copyright (C) 2012-2021 Filipe Coelho <falktx@falktx.com>
*
* Permission to use, copy, modify, and/or distribute this software for any purpose with
* or without fee is hereby granted, provided that the above copyright notice and this
* permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
* TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
* NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
* IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "tests.hpp"
#include "widgets/ExampleColorWidget.hpp"
#include "widgets/ExampleImagesWidget.hpp"
#include "widgets/ExampleRectanglesWidget.hpp"
#include "widgets/ExampleShapesWidget.hpp"
#ifdef DGL_OPENGL
#include "widgets/ExampleTextWidget.hpp"
#endif
#include "demo_res/DemoArtwork.cpp"
#include "images_res/CatPics.cpp"
#ifdef DGL_CAIRO
#include "../dgl/Cairo.hpp"
typedef DGL_NAMESPACE::CairoImage DemoImage;
#endif
#ifdef DGL_OPENGL
#include "../dgl/OpenGL.hpp"
typedef DGL_NAMESPACE::OpenGLImage DemoImage;
#endif
#ifdef DGL_VULKAN
#include "../dgl/Vulkan.hpp"
typedef DGL_NAMESPACE::VulkanImage DemoImage;
#endif
START_NAMESPACE_DGL
typedef ExampleImagesWidget<SubWidget, DemoImage> ExampleImagesSubWidget;
typedef ExampleImagesWidget<TopLevelWidget, DemoImage> ExampleImagesTopLevelWidget;
typedef ExampleImagesWidget<StandaloneWindow, DemoImage> ExampleImagesStandaloneWindow;
// --------------------------------------------------------------------------------------------------------------------
// Left side tab-like widget
class LeftSideWidget : public SubWidget
{
public:
#ifdef DGL_OPENGL
static const int kPageCount = 5;
#else
static const int kPageCount = 4;
#endif
class Callback
{
public:
virtual ~Callback() {}
virtual void curPageChanged(int curPage) = 0;
};
LeftSideWidget(Widget* parent, Callback* const cb)
: SubWidget(parent),
callback(cb),
curPage(0),
curHover(-1)
{
using namespace DemoArtwork;
img1.loadFromMemory(ico1Data, ico1Width, ico1Height, kImageFormatBGR);
img2.loadFromMemory(ico2Data, ico2Width, ico2Height, kImageFormatBGR);
img3.loadFromMemory(ico3Data, ico3Width, ico2Height, kImageFormatBGR);
img4.loadFromMemory(ico4Data, ico4Width, ico4Height, kImageFormatBGR);
#ifdef DGL_OPENGL
img5.loadFromMemory(ico5Data, ico5Width, ico5Height, kImageFormatBGR);
// for text
nvg.loadSharedResources();
#endif
}
protected:
void onDisplay() override
{
const GraphicsContext& context(getGraphicsContext());
const int iconSize = bgIcon.getWidth();
Color(0.027f, 0.027f, 0.027f).setFor(context);
Rectangle<uint>(0, 0, getSize()).draw(context);
bgIcon.setY(curPage*iconSize + curPage*3);
Color(0.129f, 0.129f, 0.129f).setFor(context);
bgIcon.draw(context);
Color(0.184f, 0.184f, 0.184f).setFor(context);
bgIcon.drawOutline(context);
if (curHover != curPage && curHover != -1)
{
Rectangle<int> rHover(1, curHover*iconSize + curHover*3, iconSize-2, iconSize-2);
Color(0.071f, 0.071f, 0.071f).setFor(context);
rHover.draw(context);
Color(0.102f, 0.102f, 0.102f).setFor(context);
rHover.drawOutline(context);
}
Color(0.184f, 0.184f, 0.184f).setFor(context);
lineSep.draw(context);
// reset color
Color(1.0f, 1.0f, 1.0f, 1.0f).setFor(context, true);
const int pad = iconSize/2 - DemoArtwork::ico1Width/2;
img1.drawAt(context, pad, pad);
img2.drawAt(context, pad, pad + 3 + iconSize);
img3.drawAt(context, pad, pad + 6 + iconSize*2);
img4.drawAt(context, pad, pad + 9 + iconSize*3);
#ifdef DGL_OPENGL
img5.drawAt(context, pad, pad + 12 + iconSize*4);
// draw some text
nvg.beginFrame(this);
nvg.fontSize(23.0f);
nvg.textAlign(NanoVG::ALIGN_LEFT|NanoVG::ALIGN_TOP);
//nvg.textLineHeight(20.0f);
nvg.fillColor(220,220,220,220);
nvg.textBox(10, 420, iconSize, "Haha,", nullptr);
nvg.textBox(15, 440, iconSize, "Look!", nullptr);
nvg.endFrame();
#endif
}
bool onMouse(const MouseEvent& ev) override
{
if (ev.button != 1 || ! ev.press)
return false;
if (! contains(ev.pos))
return false;
const int iconSize = bgIcon.getWidth();
for (int i=0; i<kPageCount; ++i)
{
bgIcon.setY(i*iconSize + i*3);
if (bgIcon.contains(ev.pos))
{
curPage = i;
callback->curPageChanged(i);
repaint();
break;
}
}
return true;
}
bool onMotion(const MotionEvent& ev) override
{
if (contains(ev.pos))
{
const int iconSize = bgIcon.getWidth();
for (int i=0; i<kPageCount; ++i)
{
bgIcon.setY(i*iconSize + i*3);
if (bgIcon.contains(ev.pos))
{
if (curHover == i)
return true;
curHover = i;
repaint();
return true;
}
}
if (curHover == -1)
return true;
curHover = -1;
repaint();
return true;
}
else
{
if (curHover == -1)
return false;
curHover = -1;
repaint();
return true;
}
}
void onResize(const ResizeEvent& ev) override
{
const uint width = ev.size.getWidth();
const uint height = ev.size.getHeight();
bgIcon.setWidth(width-4);
bgIcon.setHeight(width-4);
lineSep.setStartPos(width, 0);
lineSep.setEndPos(width, height);
}
private:
Callback* const callback;
int curPage, curHover;
Rectangle<double> bgIcon;
Line<int> lineSep;
DemoImage img1, img2, img3, img4, img5;
#ifdef DGL_OPENGL
// for text
NanoVG nvg;
#endif
};
// --------------------------------------------------------------------------------------------------------------------
// Main Demo Window, having a left-side tab-like widget and main area for current widget
class DemoWindow : public StandaloneWindow,
public LeftSideWidget::Callback
{
static const int kSidebarWidth = 81;
public:
#ifdef DGL_CAIRO
static constexpr const char* const kExampleWidgetName = "Demo - Cairo";
#endif
#ifdef DGL_OPENGL
static constexpr const char* const kExampleWidgetName = "Demo - OpenGL";
#endif
#ifdef DGL_VULKAN
static constexpr const char* const kExampleWidgetName = "Demo - Vulkan";
#endif
DemoWindow(Application& app)
: StandaloneWindow(app),
wColor(this),
wImages(this),
wRects(this),
wShapes(this),
#ifdef DGL_OPENGL
wText(this),
#endif
wLeft(this, this),
curWidget(nullptr)
{
wColor.hide();
wImages.hide();
wRects.hide();
wShapes.hide();
#ifdef DGL_OPENGL
wText.hide();
#endif
wColor.setAbsoluteX(kSidebarWidth);
wImages.setAbsoluteX(kSidebarWidth);
wRects.setAbsoluteX(kSidebarWidth);
wShapes.setAbsoluteX(kSidebarWidth);
#ifdef DGL_OPENGL
wText.setAbsoluteX(kSidebarWidth);
#endif
wLeft.setAbsolutePos(2, 2);
curPageChanged(0);
}
protected:
void curPageChanged(int curPage) override
{
if (curWidget != nullptr)
curWidget->hide();
switch (curPage)
{
case 0:
curWidget = &wColor;
break;
case 1:
curWidget = &wImages;
break;
case 2:
curWidget = &wRects;
break;
case 3:
curWidget = &wShapes;
break;
#ifdef DGL_OPENGL
case 4:
curWidget = &wText;
break;
#endif
default:
curWidget = nullptr;
break;
}
if (curWidget != nullptr)
curWidget->show();
}
void onDisplay() override
{
}
void onReshape(uint width, uint height) override
{
StandaloneWindow::onReshape(width, height);
if (width < kSidebarWidth)
return;
Size<uint> size(width-kSidebarWidth, height);
wColor.setSize(size);
wImages.setSize(size);
wRects.setSize(size);
wShapes.setSize(size);
#ifdef DGL_OPENGL
wText.setSize(size);
#endif
wLeft.setSize(kSidebarWidth-4, height-4);
}
private:
ExampleColorSubWidget wColor;
ExampleImagesSubWidget wImages;
ExampleRectanglesSubWidget wRects;
ExampleShapesSubWidget wShapes;
#ifdef DGL_OPENGL
ExampleTextSubWidget wText;
#endif
LeftSideWidget wLeft;
Widget* curWidget;
};
// --------------------------------------------------------------------------------------------------------------------
// Special handy function that runs a StandaloneWindow inside the function scope
template <class ExampleWidgetStandaloneWindow>
void createAndShowExampleWidgetStandaloneWindow(Application& app)
{
ExampleWidgetStandaloneWindow swin(app);
swin.setResizable(true);
swin.setSize(600, 500);
swin.setTitle(ExampleWidgetStandaloneWindow::kExampleWidgetName);
swin.show();
app.exec();
}
// --------------------------------------------------------------------------------------------------------------------
END_NAMESPACE_DGL
int main(int argc, char* argv[])
{
USE_NAMESPACE_DGL;
using DGL_NAMESPACE::Window;
Application app;
if (argc > 1)
{
/**/ if (std::strcmp(argv[1], "color") == 0)
createAndShowExampleWidgetStandaloneWindow<ExampleColorStandaloneWindow>(app);
else if (std::strcmp(argv[1], "images") == 0)
createAndShowExampleWidgetStandaloneWindow<ExampleImagesStandaloneWindow>(app);
else if (std::strcmp(argv[1], "rectangles") == 0)
createAndShowExampleWidgetStandaloneWindow<ExampleRectanglesStandaloneWindow>(app);
else if (std::strcmp(argv[1], "shapes") == 0)
createAndShowExampleWidgetStandaloneWindow<ExampleShapesStandaloneWindow>(app);
#ifdef DGL_OPENGL
else if (std::strcmp(argv[1], "text") == 0)
createAndShowExampleWidgetStandaloneWindow<ExampleTextStandaloneWindow>(app);
#endif
else
d_stderr2("Invalid demo mode, must be one of: color, images, rectangles or shapes");
}
else
{
createAndShowExampleWidgetStandaloneWindow<DemoWindow>(app);
}
return 0;
}
// --------------------------------------------------------------------------------------------------------------------
<commit_msg>Add a resize handle to test demo<commit_after>/*
* DISTRHO Plugin Framework (DPF)
* Copyright (C) 2012-2021 Filipe Coelho <falktx@falktx.com>
*
* Permission to use, copy, modify, and/or distribute this software for any purpose with
* or without fee is hereby granted, provided that the above copyright notice and this
* permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
* TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
* NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
* IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "tests.hpp"
#include "widgets/ExampleColorWidget.hpp"
#include "widgets/ExampleImagesWidget.hpp"
#include "widgets/ExampleRectanglesWidget.hpp"
#include "widgets/ExampleShapesWidget.hpp"
#ifdef DGL_OPENGL
#include "widgets/ExampleTextWidget.hpp"
#endif
#include "demo_res/DemoArtwork.cpp"
#include "images_res/CatPics.cpp"
#ifdef DGL_CAIRO
#include "../dgl/Cairo.hpp"
typedef DGL_NAMESPACE::CairoImage DemoImage;
#endif
#ifdef DGL_OPENGL
#include "../dgl/OpenGL.hpp"
typedef DGL_NAMESPACE::OpenGLImage DemoImage;
#endif
#ifdef DGL_VULKAN
#include "../dgl/Vulkan.hpp"
typedef DGL_NAMESPACE::VulkanImage DemoImage;
#endif
START_NAMESPACE_DGL
typedef ExampleImagesWidget<SubWidget, DemoImage> ExampleImagesSubWidget;
typedef ExampleImagesWidget<TopLevelWidget, DemoImage> ExampleImagesTopLevelWidget;
typedef ExampleImagesWidget<StandaloneWindow, DemoImage> ExampleImagesStandaloneWindow;
// --------------------------------------------------------------------------------------------------------------------
// Left side tab-like widget
class LeftSideWidget : public SubWidget
{
public:
#ifdef DGL_OPENGL
static const int kPageCount = 5;
#else
static const int kPageCount = 4;
#endif
class Callback
{
public:
virtual ~Callback() {}
virtual void curPageChanged(int curPage) = 0;
};
LeftSideWidget(Widget* parent, Callback* const cb)
: SubWidget(parent),
callback(cb),
curPage(0),
curHover(-1)
{
using namespace DemoArtwork;
img1.loadFromMemory(ico1Data, ico1Width, ico1Height, kImageFormatBGR);
img2.loadFromMemory(ico2Data, ico2Width, ico2Height, kImageFormatBGR);
img3.loadFromMemory(ico3Data, ico3Width, ico2Height, kImageFormatBGR);
img4.loadFromMemory(ico4Data, ico4Width, ico4Height, kImageFormatBGR);
#ifdef DGL_OPENGL
img5.loadFromMemory(ico5Data, ico5Width, ico5Height, kImageFormatBGR);
// for text
nvg.loadSharedResources();
#endif
}
protected:
void onDisplay() override
{
const GraphicsContext& context(getGraphicsContext());
const int iconSize = bgIcon.getWidth();
Color(0.027f, 0.027f, 0.027f).setFor(context);
Rectangle<uint>(0, 0, getSize()).draw(context);
bgIcon.setY(curPage*iconSize + curPage*3);
Color(0.129f, 0.129f, 0.129f).setFor(context);
bgIcon.draw(context);
Color(0.184f, 0.184f, 0.184f).setFor(context);
bgIcon.drawOutline(context);
if (curHover != curPage && curHover != -1)
{
Rectangle<int> rHover(1, curHover*iconSize + curHover*3, iconSize-2, iconSize-2);
Color(0.071f, 0.071f, 0.071f).setFor(context);
rHover.draw(context);
Color(0.102f, 0.102f, 0.102f).setFor(context);
rHover.drawOutline(context);
}
Color(0.184f, 0.184f, 0.184f).setFor(context);
lineSep.draw(context);
// reset color
Color(1.0f, 1.0f, 1.0f, 1.0f).setFor(context, true);
const int pad = iconSize/2 - DemoArtwork::ico1Width/2;
img1.drawAt(context, pad, pad);
img2.drawAt(context, pad, pad + 3 + iconSize);
img3.drawAt(context, pad, pad + 6 + iconSize*2);
img4.drawAt(context, pad, pad + 9 + iconSize*3);
#ifdef DGL_OPENGL
img5.drawAt(context, pad, pad + 12 + iconSize*4);
// draw some text
nvg.beginFrame(this);
nvg.fontSize(23.0f);
nvg.textAlign(NanoVG::ALIGN_LEFT|NanoVG::ALIGN_TOP);
//nvg.textLineHeight(20.0f);
nvg.fillColor(220,220,220,220);
nvg.textBox(10, 420, iconSize, "Haha,", nullptr);
nvg.textBox(15, 440, iconSize, "Look!", nullptr);
nvg.endFrame();
#endif
}
bool onMouse(const MouseEvent& ev) override
{
if (ev.button != 1 || ! ev.press)
return false;
if (! contains(ev.pos))
return false;
const int iconSize = bgIcon.getWidth();
for (int i=0; i<kPageCount; ++i)
{
bgIcon.setY(i*iconSize + i*3);
if (bgIcon.contains(ev.pos))
{
curPage = i;
callback->curPageChanged(i);
repaint();
break;
}
}
return true;
}
bool onMotion(const MotionEvent& ev) override
{
if (contains(ev.pos))
{
const int iconSize = bgIcon.getWidth();
for (int i=0; i<kPageCount; ++i)
{
bgIcon.setY(i*iconSize + i*3);
if (bgIcon.contains(ev.pos))
{
if (curHover == i)
return true;
curHover = i;
repaint();
return true;
}
}
if (curHover == -1)
return true;
curHover = -1;
repaint();
return true;
}
else
{
if (curHover == -1)
return false;
curHover = -1;
repaint();
return true;
}
}
void onResize(const ResizeEvent& ev) override
{
const uint width = ev.size.getWidth();
const uint height = ev.size.getHeight();
bgIcon.setWidth(width-4);
bgIcon.setHeight(width-4);
lineSep.setStartPos(width, 0);
lineSep.setEndPos(width, height);
}
private:
Callback* const callback;
int curPage, curHover;
Rectangle<double> bgIcon;
Line<int> lineSep;
DemoImage img1, img2, img3, img4, img5;
#ifdef DGL_OPENGL
// for text
NanoVG nvg;
#endif
};
// --------------------------------------------------------------------------------------------------------------------
// Resize handle widget
class ResizeHandle : public TopLevelWidget
{
Rectangle<uint> area;
Line<double> l1, l2, l3;
uint baseSize;
// event handling state
bool resizing;
Point<double> lastResizePoint;
Size<double> resizingSize;
public:
explicit ResizeHandle(TopLevelWidget* const tlw)
: TopLevelWidget(tlw->getWindow()),
baseSize(16),
resizing(false)
{
resetArea();
}
explicit ResizeHandle(Window& window)
: TopLevelWidget(window),
baseSize(16),
resizing(false)
{
resetArea();
}
void setBaseSize(const uint size)
{
baseSize = std::max(16u, size);
resetArea();
}
protected:
void onDisplay() override
{
const GraphicsContext& context(getGraphicsContext());
const double offset = getScaleFactor();
// draw white lines, 1px wide
Color(1.0f, 1.0f, 1.0f).setFor(context);
l1.draw(context, 1);
l2.draw(context, 1);
l3.draw(context, 1);
// draw black lines, offset by 1px and 2px wide
Color(0.0f, 0.0f, 0.0f).setFor(context);
Line<double> l1b(l1), l2b(l2), l3b(l3);
l1b.moveBy(offset, offset);
l2b.moveBy(offset, offset);
l3b.moveBy(offset, offset);
l1b.draw(context, 1);
l2b.draw(context, 1);
l3b.draw(context, 1);
}
bool onMouse(const MouseEvent& ev) override
{
if (ev.button != 1)
return false;
if (ev.press && area.contains(ev.pos))
{
resizing = true;
resizingSize = Size<double>(getWidth(), getHeight());
lastResizePoint = ev.pos;
return true;
}
if (resizing && ! ev.press)
{
resizing = false;
return true;
}
return false;
}
bool onMotion(const MotionEvent& ev) override
{
if (! resizing)
return false;
const Size<double> offset(ev.pos.getX() - lastResizePoint.getX(),
ev.pos.getY() - lastResizePoint.getY());
resizingSize += offset;
lastResizePoint = ev.pos;
// TODO min width, min height
const uint minWidth = 16;
const uint minHeight = 16;
if (resizingSize.getWidth() < minWidth)
resizingSize.setWidth(minWidth);
if (resizingSize.getHeight() < minHeight)
resizingSize.setHeight(minHeight);
setSize(resizingSize.getWidth(), resizingSize.getHeight());
return true;
}
void onResize(const ResizeEvent& ev) override
{
TopLevelWidget::onResize(ev);
resetArea();
}
private:
void resetArea()
{
const double scaleFactor = getScaleFactor();
const uint margin = 0.0 * scaleFactor;
const uint size = baseSize * scaleFactor;
area = Rectangle<uint>(getWidth() - size - margin,
getHeight() - size - margin,
size, size);
recreateLines(area.getX(), area.getY(), size);
}
void recreateLines(const uint x, const uint y, const uint size)
{
uint linesize = size;
uint offset = 0;
// 1st line, full diagonal size
l1.setStartPos(x + size, y);
l1.setEndPos(x, y + size);
// 2nd line, bit more to the right and down, cropped
offset += size / 3;
linesize -= size / 3;
l2.setStartPos(x + linesize + offset, y + offset);
l2.setEndPos(x + offset, y + linesize + offset);
// 3rd line, even more right and down
offset += size / 3;
linesize -= size / 3;
l3.setStartPos(x + linesize + offset, y + offset);
l3.setEndPos(x + offset, y + linesize + offset);
}
};
// --------------------------------------------------------------------------------------------------------------------
// Main Demo Window, having a left-side tab-like widget and main area for current widget
class DemoWindow : public StandaloneWindow,
public LeftSideWidget::Callback
{
static const int kSidebarWidth = 81;
public:
#ifdef DGL_CAIRO
static constexpr const char* const kExampleWidgetName = "Demo - Cairo";
#endif
#ifdef DGL_OPENGL
static constexpr const char* const kExampleWidgetName = "Demo - OpenGL";
#endif
#ifdef DGL_VULKAN
static constexpr const char* const kExampleWidgetName = "Demo - Vulkan";
#endif
DemoWindow(Application& app)
: StandaloneWindow(app),
wColor(this),
wImages(this),
wRects(this),
wShapes(this),
#ifdef DGL_OPENGL
wText(this),
#endif
wLeft(this, this),
resizer(this),
curWidget(nullptr)
{
wColor.hide();
wImages.hide();
wRects.hide();
wShapes.hide();
#ifdef DGL_OPENGL
wText.hide();
#endif
wColor.setAbsoluteX(kSidebarWidth);
wImages.setAbsoluteX(kSidebarWidth);
wRects.setAbsoluteX(kSidebarWidth);
wShapes.setAbsoluteX(kSidebarWidth);
#ifdef DGL_OPENGL
wText.setAbsoluteX(kSidebarWidth);
#endif
wLeft.setAbsolutePos(2, 2);
curPageChanged(0);
}
protected:
void curPageChanged(int curPage) override
{
if (curWidget != nullptr)
curWidget->hide();
switch (curPage)
{
case 0:
curWidget = &wColor;
break;
case 1:
curWidget = &wImages;
break;
case 2:
curWidget = &wRects;
break;
case 3:
curWidget = &wShapes;
break;
#ifdef DGL_OPENGL
case 4:
curWidget = &wText;
break;
#endif
default:
curWidget = nullptr;
break;
}
if (curWidget != nullptr)
curWidget->show();
}
void onDisplay() override
{
}
void onReshape(uint width, uint height) override
{
StandaloneWindow::onReshape(width, height);
if (width < kSidebarWidth)
return;
Size<uint> size(width-kSidebarWidth, height);
wColor.setSize(size);
wImages.setSize(size);
wRects.setSize(size);
wShapes.setSize(size);
#ifdef DGL_OPENGL
wText.setSize(size);
#endif
wLeft.setSize(kSidebarWidth-4, height-4);
}
private:
ExampleColorSubWidget wColor;
ExampleImagesSubWidget wImages;
ExampleRectanglesSubWidget wRects;
ExampleShapesSubWidget wShapes;
#ifdef DGL_OPENGL
ExampleTextSubWidget wText;
#endif
LeftSideWidget wLeft;
ResizeHandle resizer;
Widget* curWidget;
};
// --------------------------------------------------------------------------------------------------------------------
// Special handy function that runs a StandaloneWindow inside the function scope
template <class ExampleWidgetStandaloneWindow>
void createAndShowExampleWidgetStandaloneWindow(Application& app)
{
ExampleWidgetStandaloneWindow swin(app);
swin.setResizable(true);
swin.setSize(600, 500);
swin.setTitle(ExampleWidgetStandaloneWindow::kExampleWidgetName);
swin.show();
app.exec();
}
// --------------------------------------------------------------------------------------------------------------------
END_NAMESPACE_DGL
int main(int argc, char* argv[])
{
USE_NAMESPACE_DGL;
using DGL_NAMESPACE::Window;
Application app;
if (argc > 1)
{
/**/ if (std::strcmp(argv[1], "color") == 0)
createAndShowExampleWidgetStandaloneWindow<ExampleColorStandaloneWindow>(app);
else if (std::strcmp(argv[1], "images") == 0)
createAndShowExampleWidgetStandaloneWindow<ExampleImagesStandaloneWindow>(app);
else if (std::strcmp(argv[1], "rectangles") == 0)
createAndShowExampleWidgetStandaloneWindow<ExampleRectanglesStandaloneWindow>(app);
else if (std::strcmp(argv[1], "shapes") == 0)
createAndShowExampleWidgetStandaloneWindow<ExampleShapesStandaloneWindow>(app);
#ifdef DGL_OPENGL
else if (std::strcmp(argv[1], "text") == 0)
createAndShowExampleWidgetStandaloneWindow<ExampleTextStandaloneWindow>(app);
#endif
else
d_stderr2("Invalid demo mode, must be one of: color, images, rectangles or shapes");
}
else
{
createAndShowExampleWidgetStandaloneWindow<DemoWindow>(app);
}
return 0;
}
// --------------------------------------------------------------------------------------------------------------------
<|endoftext|>
|
<commit_before><commit_msg>tentatively kill crawlers explicitly (find a better solution via SG_proc). Don't cancel the crawl thread; let it exit on its own.<commit_after><|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2010 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
#include <mapnik/markers_symbolizer.hpp>
namespace mapnik {
static const char * marker_placement_strings[] = {
"point",
"line",
""
};
IMPLEMENT_ENUM( marker_placement_e, marker_placement_strings )
static const char * marker_type_strings[] = {
"arrow",
"ellipse",
""
};
IMPLEMENT_ENUM( marker_type_e, marker_type_strings )
markers_symbolizer::markers_symbolizer()
: symbolizer_with_image(path_expression_ptr(new path_expression)),
symbolizer_base(),
allow_overlap_(false),
fill_(color(0,0,255)),
spacing_(100.0),
max_error_(0.2),
width_(5.0),
height_(5.0),
stroke_(),
marker_p_(),
marker_type_() {}
markers_symbolizer::markers_symbolizer(path_expression_ptr filename)
: symbolizer_with_image(filename),
symbolizer_base(),
allow_overlap_(false),
fill_(color(0,0,255)),
spacing_(100.0),
max_error_(0.2),
width_(5.0),
height_(5.0),
stroke_(),
marker_p_(),
marker_type_() {}
markers_symbolizer::markers_symbolizer(markers_symbolizer const& rhs)
: symbolizer_with_image(rhs),
symbolizer_base(rhs),
allow_overlap_(rhs.allow_overlap_),
fill_(rhs.fill_),
spacing_(rhs.spacing_),
max_error_(rhs.max_error_),
width_(rhs.width_),
height_(rhs.height_),
stroke_(rhs.stroke_),
marker_p_(rhs.marker_p_),
marker_type_(rhs.marker_type_) {}
void markers_symbolizer::set_allow_overlap(bool overlap)
{
allow_overlap_ = overlap;
}
bool markers_symbolizer::get_allow_overlap() const
{
return allow_overlap_;
}
void markers_symbolizer::set_spacing(double spacing)
{
spacing_ = spacing;
}
double markers_symbolizer::get_spacing() const
{
return spacing_;
}
void markers_symbolizer::set_max_error(double max_error)
{
max_error_ = max_error;
}
double markers_symbolizer::get_max_error() const
{
return max_error_;
}
void markers_symbolizer::set_fill(color fill)
{
fill_ = fill;
}
color const& markers_symbolizer::get_fill() const
{
return fill_;
}
void markers_symbolizer::set_width(double width)
{
width_ = width;
}
double markers_symbolizer::get_width() const
{
return width_;
}
void markers_symbolizer::set_height(double height)
{
height_ = height;
}
double markers_symbolizer::get_height() const
{
return height_;
}
stroke const& markers_symbolizer::get_stroke() const
{
return stroke_;
}
void markers_symbolizer::set_stroke(stroke const& stroke)
{
stroke_ = stroke;
}
void markers_symbolizer::set_marker_placement(marker_placement_e marker_p)
{
marker_p_ = marker_p;
}
marker_placement_e markers_symbolizer::get_marker_placement() const
{
return marker_p_;
}
void markers_symbolizer::set_marker_type(marker_type_e marker_type)
{
marker_type_ = marker_type;
}
marker_type_e markers_symbolizer::get_marker_type() const
{
return marker_type_;
}
}
<commit_msg>correctly initalize markers_symbolizer default values - avoid segfaul in carto-parser<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2010 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
#include <mapnik/markers_symbolizer.hpp>
namespace mapnik {
static const char * marker_placement_strings[] = {
"point",
"line",
""
};
IMPLEMENT_ENUM( marker_placement_e, marker_placement_strings )
static const char * marker_type_strings[] = {
"arrow",
"ellipse",
""
};
IMPLEMENT_ENUM( marker_type_e, marker_type_strings )
markers_symbolizer::markers_symbolizer()
: symbolizer_with_image(path_expression_ptr(new path_expression)),
symbolizer_base(),
allow_overlap_(false),
fill_(color(0,0,255)),
spacing_(100.0),
max_error_(0.2),
width_(5.0),
height_(5.0),
stroke_(),
marker_p_(MARKER_LINE_PLACEMENT),
marker_type_(ARROW) {}
markers_symbolizer::markers_symbolizer(path_expression_ptr filename)
: symbolizer_with_image(filename),
symbolizer_base(),
allow_overlap_(false),
fill_(color(0,0,255)),
spacing_(100.0),
max_error_(0.2),
width_(5.0),
height_(5.0),
stroke_(),
marker_p_(MARKER_LINE_PLACEMENT),
marker_type_(ARROW) {}
markers_symbolizer::markers_symbolizer(markers_symbolizer const& rhs)
: symbolizer_with_image(rhs),
symbolizer_base(rhs),
allow_overlap_(rhs.allow_overlap_),
fill_(rhs.fill_),
spacing_(rhs.spacing_),
max_error_(rhs.max_error_),
width_(rhs.width_),
height_(rhs.height_),
stroke_(rhs.stroke_),
marker_p_(rhs.marker_p_),
marker_type_(rhs.marker_type_) {}
void markers_symbolizer::set_allow_overlap(bool overlap)
{
allow_overlap_ = overlap;
}
bool markers_symbolizer::get_allow_overlap() const
{
return allow_overlap_;
}
void markers_symbolizer::set_spacing(double spacing)
{
spacing_ = spacing;
}
double markers_symbolizer::get_spacing() const
{
return spacing_;
}
void markers_symbolizer::set_max_error(double max_error)
{
max_error_ = max_error;
}
double markers_symbolizer::get_max_error() const
{
return max_error_;
}
void markers_symbolizer::set_fill(color fill)
{
fill_ = fill;
}
color const& markers_symbolizer::get_fill() const
{
return fill_;
}
void markers_symbolizer::set_width(double width)
{
width_ = width;
}
double markers_symbolizer::get_width() const
{
return width_;
}
void markers_symbolizer::set_height(double height)
{
height_ = height;
}
double markers_symbolizer::get_height() const
{
return height_;
}
stroke const& markers_symbolizer::get_stroke() const
{
return stroke_;
}
void markers_symbolizer::set_stroke(stroke const& stroke)
{
stroke_ = stroke;
}
void markers_symbolizer::set_marker_placement(marker_placement_e marker_p)
{
marker_p_ = marker_p;
}
marker_placement_e markers_symbolizer::get_marker_placement() const
{
return marker_p_;
}
void markers_symbolizer::set_marker_type(marker_type_e marker_type)
{
marker_type_ = marker_type;
}
marker_type_e markers_symbolizer::get_marker_type() const
{
return marker_type_;
}
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <fstream>
#include <string>
#include <conio.h>
#include <math.h>
#include <random>
#include <winsock2.h>
#include <ws2tcpip.h>
#include "CPositionSensor.h"
#include "CCrazyflie.h"
#include "CPositionControllerSimple.h"
#include "clockgettime.h"
#include "CLogs.h"
#define KEY_UP 72
#define KEY_DOWN 80
#define KEY_LEFT 75
#define KEY_RIGHT 77
#define DEFAULT_PORT "26517" // GamesOnTrack TCP connection
typedef std::numeric_limits< double > dbl;
int main(int argc, char **argv) {
double sensor_XYZ[3] = { 0,0,0 }; /* meters, meters, meters, meters */
double ctrl_ref_XYZ[4] = { 0,0,0,0 }; /* meters, meters, meters, meters */
double ctrl_cmd_RPYT[4] = { 0,0,0,0 }; /* degrees, degrees, degress, ? */
double dt;
bool MissingGoT = FALSE;
CLogs *log = new CLogs();
double scale_ref = 0.1;
// Initialize the quadrotor
CCrazyRadio *crRadio = new CCrazyRadio("radio://0/80/250K"); // Address does not matter for now
if (!crRadio->startRadio())
{
std::cerr << "Could not connect to dongle. Did you plug it in?" << std::endl;
exit(-1);
}
CCrazyflie *cflieCopter = new CCrazyflie(crRadio);
std::cout << "Initializing connection. ";
cflieCopter->setSendSetpoints(true);
cflieCopter->setSendExtPosition(true); // if, for example, we want to make position control on the quad, instead of in this program
// First command
cflieCopter->setRoll(0);
cflieCopter->setPitch(0);
cflieCopter->setYaw(0);
cflieCopter->setThrust(0);
// Make sure to check the Crazyflie library for initialization settings
// such as logging and parameters:
// CCrazyflie::startLogging()
// CCrazyflie::sendFlightModeParameters()
while (!cflieCopter->isInitialized())
{
cflieCopter->cycle();
}
// Quick loop to test external position data communication
//---------------------------------------------------------
//float fX, fY, fZ;
//bool exit_loop_x = false;
//while ((cflieCopter->cycle()) && (!exit_loop_x))
//{
//
// fX = rand()/1000.0;
// fY = rand()/1000.0;
// fZ = rand()/1000.0;
// cflieCopter->setExtPosition(fX, fY, fZ);
// std::cout << fX << " " << fY << " " << fZ << std::endl;
// log->CF(cflieCopter);
// if (_kbhit())
// {
// exit_loop_x = true;
// }
//
//}
//delete cflieCopter;
//delete crRadio;
//delete log;
//exit(0);
// -----------------------------------------------------------
// Initialize the GoT connection
CPositionSensor *GoT = new CPositionSensor("localhost", DEFAULT_PORT, log);
GoT->init();
GoT->giveP(ctrl_ref_XYZ);
// Initialize the position controller
ctrl_ref_XYZ[2] = ctrl_ref_XYZ[2] - 0.25; // take off to x meters
CPositionController *posController = new CPositionController(ctrl_ref_XYZ, log);
double mylogtime = currentTime();
bool exit_loop = false;
int ch;
std::cout.precision(dbl::max_digits10);
std::cout << " \n Ok. Started! (Pressing any other keys than arrows and q/a and k/l will stop.) \n";
// The main control loop
while ((cflieCopter->cycle()) && (!exit_loop))
{
if (GoT->readNewData() && (GoT->giveTimestamp() - GoT->giveTimestampOld() > 0.0001))
{
dt = GoT->giveP(sensor_XYZ);
// Example of how to send external position data to the Crazyflie
// cflieCopter->setExtPosition(ctrl_ref_XYZ[0]-sensor_XYZ[0], ctrl_ref_XYZ[1]-sensor_XYZ[1], ctrl_ref_XYZ[2] - sensor_XYZ[2]);
posController->update(sensor_XYZ, dt);
posController->giveCmd(ctrl_cmd_RPYT);
cflieCopter->setRoll(ctrl_cmd_RPYT[0]);
cflieCopter->setPitch(-ctrl_cmd_RPYT[1]);
cflieCopter->setYaw(ctrl_cmd_RPYT[2]);
cflieCopter->setThrust(ctrl_cmd_RPYT[3]);
if (sensor_XYZ[2] < -2.0)
{
cflieCopter->setThrust(_PID_THRUST_OFFSET*0.95);
std::cout << "---- HEIGHT SAFETY: " << sensor_XYZ[2] << " \n";
}
}
if (currentTime() - GoT->giveTimestampOld() > 1)
{
cflieCopter->setRoll(0);
cflieCopter->setPitch(0);
cflieCopter->setYaw(0);
cflieCopter->setThrust(_PID_THRUST_OFFSET*0.95);
std::cout << "-------------Safety----------------" << std::endl;
}
// Change the control reference from the keyboard
if (_kbhit())
{
ch = _getch();
if (ch == 224)
{
ch = _getch();
switch (ch)
{
case KEY_UP:
ctrl_ref_XYZ[0] = ctrl_ref_XYZ[0] + scale_ref; // x position meters
break;
case KEY_DOWN:
ctrl_ref_XYZ[0] = ctrl_ref_XYZ[0] - scale_ref;
break;
case KEY_LEFT:
ctrl_ref_XYZ[1] = ctrl_ref_XYZ[1] - scale_ref; // y position meters
break;
case KEY_RIGHT:
ctrl_ref_XYZ[1] = ctrl_ref_XYZ[1] + scale_ref;
break;
default:
exit_loop = true;
}
}
else
{
switch (ch)
{
case 113: // q
ctrl_ref_XYZ[2] = ctrl_ref_XYZ[2] - scale_ref; // z position meters
break;
case 97: // a
ctrl_ref_XYZ[2] = ctrl_ref_XYZ[2] + scale_ref;
break;
case 107: // k
ctrl_ref_XYZ[3] = ctrl_ref_XYZ[3] - 5; // the yaw angle
break;
case 108: // l
ctrl_ref_XYZ[3] = ctrl_ref_XYZ[3] + 5; // the yaw angle
break;
default:
exit_loop = true;
}
}
posController->setRef(ctrl_ref_XYZ);
}
// Logging
log->CF(cflieCopter);
}
// ----------- END MAIN CONTROL LOOP ---------------------
// Send quadrotor stop
cflieCopter->setRoll(0);
cflieCopter->setPitch(0);
cflieCopter->setYaw(0);
cflieCopter->setThrust(0);
// Do a small loop to make sure the kill engine command is sent
exit_loop = false;
double time1=currentTime(); // seconds
while ( (cflieCopter->cycle()) && (!exit_loop) )
{
if (currentTime() - time1 > 1.0)
{
exit_loop = true;
}
}
mylogtime = currentTime() - mylogtime - 1;
std::cout << "Run time was:" << mylogtime << " [sec].";
delete GoT;
delete posController;
delete cflieCopter;
delete crRadio;
delete log;
return 0;
}
<commit_msg>Added user question for GoT transmitter ID filtering<commit_after>#include <iostream>
#include <fstream>
#include <string>
#include <conio.h>
#include <math.h>
#include <random>
#include <winsock2.h>
#include <ws2tcpip.h>
#include "CPositionSensor.h"
#include "CCrazyflie.h"
#include "CPositionControllerSimple.h"
#include "clockgettime.h"
#include "CLogs.h"
#define KEY_UP 72
#define KEY_DOWN 80
#define KEY_LEFT 75
#define KEY_RIGHT 77
#define DEFAULT_PORT "26517" // GamesOnTrack TCP connection
typedef std::numeric_limits< double > dbl;
int main(int argc, char **argv) {
double sensor_XYZ[3] = { 0,0,0 }; /* meters, meters, meters, meters */
double ctrl_ref_XYZ[4] = { 0,0,0,0 }; /* meters, meters, meters, meters */
double ctrl_cmd_RPYT[4] = { 0,0,0,0 }; /* degrees, degrees, degress, ? */
double dt;
bool MissingGoT = FALSE;
CLogs *log = new CLogs();
double scale_ref = 0.1;
// Initialize the quadrotor
CCrazyRadio *crRadio = new CCrazyRadio("radio://0/80/250K"); // Address does not matter for now
if (!crRadio->startRadio())
{
std::cerr << "Could not connect to dongle. Did you plug it in?" << std::endl;
exit(-1);
}
CCrazyflie *cflieCopter = new CCrazyflie(crRadio);
std::cout << "Initializing connection. ";
cflieCopter->setSendSetpoints(true);
cflieCopter->setSendExtPosition(true); // if, for example, we want to make position control on the quad, instead of in this program
// First command
cflieCopter->setRoll(0);
cflieCopter->setPitch(0);
cflieCopter->setYaw(0);
cflieCopter->setThrust(0);
// Make sure to check the Crazyflie library for initialization settings
// such as logging and parameters:
// CCrazyflie::startLogging()
// CCrazyflie::sendFlightModeParameters()
while (!cflieCopter->isInitialized())
{
cflieCopter->cycle();
}
// Quick loop to test external position data communication
//---------------------------------------------------------
//float fX, fY, fZ;
//bool exit_loop_x = false;
//while ((cflieCopter->cycle()) && (!exit_loop_x))
//{
//
// fX = rand()/1000.0;
// fY = rand()/1000.0;
// fZ = rand()/1000.0;
// cflieCopter->setExtPosition(fX, fY, fZ);
// std::cout << fX << " " << fY << " " << fZ << std::endl;
// log->CF(cflieCopter);
// if (_kbhit())
// {
// exit_loop_x = true;
// }
//
//}
//delete cflieCopter;
//delete crRadio;
//delete log;
//exit(0);
// -----------------------------------------------------------
// Initialize the GoT connection
CPositionSensor *GoT = new CPositionSensor("localhost", DEFAULT_PORT, log);
int tID=0;
printf_s("\n GoT Transmitter ID (leave 0 to receive all packets): ");
scanf_s("%d", &tID);
GoT->init(tID);
GoT->giveP(ctrl_ref_XYZ);
// Initialize the position controller
ctrl_ref_XYZ[2] = ctrl_ref_XYZ[2] - 0.25; // take off to x meters
CPositionController *posController = new CPositionController(ctrl_ref_XYZ, log);
double mylogtime = currentTime();
bool exit_loop = false;
int ch;
std::cout.precision(dbl::max_digits10);
std::cout << " \n Ok. Started! (Pressing any other keys than arrows and q/a and k/l will stop.) \n";
// The main control loop
while ((cflieCopter->cycle()) && (!exit_loop))
{
if (GoT->readNewData() && (GoT->giveTimestamp() - GoT->giveTimestampOld() > 0.0001))
{
dt = GoT->giveP(sensor_XYZ);
// Example of how to send external position data to the Crazyflie
// cflieCopter->setExtPosition(ctrl_ref_XYZ[0]-sensor_XYZ[0], ctrl_ref_XYZ[1]-sensor_XYZ[1], ctrl_ref_XYZ[2] - sensor_XYZ[2]);
posController->update(sensor_XYZ, dt);
posController->giveCmd(ctrl_cmd_RPYT);
cflieCopter->setRoll(ctrl_cmd_RPYT[0]);
cflieCopter->setPitch(-ctrl_cmd_RPYT[1]);
cflieCopter->setYaw(ctrl_cmd_RPYT[2]);
cflieCopter->setThrust(ctrl_cmd_RPYT[3]);
if (sensor_XYZ[2] < -2.0)
{
cflieCopter->setThrust(_PID_THRUST_OFFSET*0.95);
std::cout << "---- HEIGHT SAFETY: " << sensor_XYZ[2] << " \n";
}
}
if (currentTime() - GoT->giveTimestampOld() > 1)
{
cflieCopter->setRoll(0);
cflieCopter->setPitch(0);
cflieCopter->setYaw(0);
cflieCopter->setThrust(_PID_THRUST_OFFSET*0.95);
std::cout << "-------------Safety----------------" << std::endl;
}
// Change the control reference from the keyboard
if (_kbhit())
{
ch = _getch();
if (ch == 224)
{
ch = _getch();
switch (ch)
{
case KEY_UP:
ctrl_ref_XYZ[0] = ctrl_ref_XYZ[0] + scale_ref; // x position meters
break;
case KEY_DOWN:
ctrl_ref_XYZ[0] = ctrl_ref_XYZ[0] - scale_ref;
break;
case KEY_LEFT:
ctrl_ref_XYZ[1] = ctrl_ref_XYZ[1] - scale_ref; // y position meters
break;
case KEY_RIGHT:
ctrl_ref_XYZ[1] = ctrl_ref_XYZ[1] + scale_ref;
break;
default:
exit_loop = true;
}
}
else
{
switch (ch)
{
case 113: // q
ctrl_ref_XYZ[2] = ctrl_ref_XYZ[2] - scale_ref; // z position meters
break;
case 97: // a
ctrl_ref_XYZ[2] = ctrl_ref_XYZ[2] + scale_ref;
break;
case 107: // k
ctrl_ref_XYZ[3] = ctrl_ref_XYZ[3] - 5; // the yaw angle
break;
case 108: // l
ctrl_ref_XYZ[3] = ctrl_ref_XYZ[3] + 5; // the yaw angle
break;
default:
exit_loop = true;
}
}
posController->setRef(ctrl_ref_XYZ);
}
// Logging
log->CF(cflieCopter);
}
// ----------- END MAIN CONTROL LOOP ---------------------
// Send quadrotor stop
cflieCopter->setRoll(0);
cflieCopter->setPitch(0);
cflieCopter->setYaw(0);
cflieCopter->setThrust(0);
// Do a small loop to make sure the kill engine command is sent
exit_loop = false;
double time1=currentTime(); // seconds
while ( (cflieCopter->cycle()) && (!exit_loop) )
{
if (currentTime() - time1 > 1.0)
{
exit_loop = true;
}
}
mylogtime = currentTime() - mylogtime - 1;
std::cout << "Run time was:" << mylogtime << " [sec].";
delete GoT;
delete posController;
delete cflieCopter;
delete crRadio;
delete log;
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2003-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Erik Hallnor
*/
/** @file
* Definitions of a simple cache block class.
*/
#ifndef __CACHE_BLK_HH__
#define __CACHE_BLK_HH__
#include "sim/root.hh" // for Tick
#include "arch/isa_traits.hh" // for Addr
/**
* Cache block status bit assignments
*/
enum CacheBlkStatusBits {
/** valid, readable */
BlkValid = 0x01,
/** write permission */
BlkWritable = 0x02,
/** dirty (modified) */
BlkDirty = 0x04,
/** compressed */
BlkCompressed = 0x08,
/** block was referenced */
BlkReferenced = 0x10,
/** block was a hardware prefetch yet unaccessed*/
BlkHWPrefetched = 0x20
};
/**
* A Basic Cache block.
* Contains the tag, status, and a pointer to data.
*/
class CacheBlk
{
public:
/** The address space ID of this block. */
int asid;
/** Data block tag value. */
Addr tag;
/**
* Contains a copy of the data in this block for easy access. This is used
* for efficient execution when the data could be actually stored in
* another format (COW, compressed, sub-blocked, etc). In all cases the
* data stored here should be kept consistant with the actual data
* referenced by this block.
*/
uint8_t *data;
/** the number of bytes stored in this block. */
int size;
/** block state: OR of CacheBlkStatusBit */
typedef unsigned State;
/** The current status of this block. @sa CacheBlockStatusBits */
State status;
/** Which curTick will this block be accessable */
Tick whenReady;
/**
* The set this block belongs to.
* @todo Move this into subclasses when we fix CacheTags to use them.
*/
int set;
/** Number of references to this block since it was brought in. */
int refCount;
CacheBlk()
: asid(-1), tag(0), data(0) ,size(0), status(0), whenReady(0),
set(-1), refCount(0)
{}
/**
* Copy the state of the given block into this one.
* @param rhs The block to copy.
* @return a const reference to this block.
*/
const CacheBlk& operator=(const CacheBlk& rhs)
{
asid = rhs.asid;
tag = rhs.tag;
data = rhs.data;
size = rhs.size;
status = rhs.status;
whenReady = rhs.whenReady;
set = rhs.set;
refCount = rhs.refCount;
return *this;
}
/**
* Checks the write permissions of this block.
* @return True if the block is writable.
*/
bool isWritable() const
{
const int needed_bits = BlkWritable | BlkValid;
return (status & needed_bits) == needed_bits;
}
/**
* Checks that a block is valid (readable).
* @return True if the block is valid.
*/
bool isValid() const
{
return (status & BlkValid) != 0;
}
/**
* Check to see if a block has been written.
* @return True if the block is dirty.
*/
bool isModified() const
{
return (status & BlkDirty) != 0;
}
/**
* Check to see if this block contains compressed data.
* @return True iF the block's data is compressed.
*/
bool isCompressed() const
{
return (status & BlkCompressed) != 0;
}
/**
* Check if this block has been referenced.
* @return True if the block has been referenced.
*/
bool isReferenced() const
{
return (status & BlkReferenced) != 0;
}
/**
* Check if this block was the result of a hardware prefetch, yet to
* be touched.
* @return True if the block was a hardware prefetch, unaccesed.
*/
bool isPrefetch() const
{
return (status & BlkHWPrefetched) != 0;
}
};
/**
* Output a CacheBlk to the given ostream.
* @param out The stream for the output.
* @param blk The cache block to print.
*
* @return The output stream.
*/
inline std::ostream &
operator<<(std::ostream &out, const CacheBlk &blk)
{
out << std::hex << std::endl;
out << " Tag: " << blk.tag << std::endl;
out << " Status: " << blk.status << std::endl;
return(out << std::dec);
}
#endif //__CACHE_BLK_HH__
<commit_msg>#include of iostream needed.<commit_after>/*
* Copyright (c) 2003-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Erik Hallnor
*/
/** @file
* Definitions of a simple cache block class.
*/
#ifndef __CACHE_BLK_HH__
#define __CACHE_BLK_HH__
#include "sim/root.hh" // for Tick
#include "arch/isa_traits.hh" // for Addr
#include <iostream>
/**
* Cache block status bit assignments
*/
enum CacheBlkStatusBits {
/** valid, readable */
BlkValid = 0x01,
/** write permission */
BlkWritable = 0x02,
/** dirty (modified) */
BlkDirty = 0x04,
/** compressed */
BlkCompressed = 0x08,
/** block was referenced */
BlkReferenced = 0x10,
/** block was a hardware prefetch yet unaccessed*/
BlkHWPrefetched = 0x20
};
/**
* A Basic Cache block.
* Contains the tag, status, and a pointer to data.
*/
class CacheBlk
{
public:
/** The address space ID of this block. */
int asid;
/** Data block tag value. */
Addr tag;
/**
* Contains a copy of the data in this block for easy access. This is used
* for efficient execution when the data could be actually stored in
* another format (COW, compressed, sub-blocked, etc). In all cases the
* data stored here should be kept consistant with the actual data
* referenced by this block.
*/
uint8_t *data;
/** the number of bytes stored in this block. */
int size;
/** block state: OR of CacheBlkStatusBit */
typedef unsigned State;
/** The current status of this block. @sa CacheBlockStatusBits */
State status;
/** Which curTick will this block be accessable */
Tick whenReady;
/**
* The set this block belongs to.
* @todo Move this into subclasses when we fix CacheTags to use them.
*/
int set;
/** Number of references to this block since it was brought in. */
int refCount;
CacheBlk()
: asid(-1), tag(0), data(0) ,size(0), status(0), whenReady(0),
set(-1), refCount(0)
{}
/**
* Copy the state of the given block into this one.
* @param rhs The block to copy.
* @return a const reference to this block.
*/
const CacheBlk& operator=(const CacheBlk& rhs)
{
asid = rhs.asid;
tag = rhs.tag;
data = rhs.data;
size = rhs.size;
status = rhs.status;
whenReady = rhs.whenReady;
set = rhs.set;
refCount = rhs.refCount;
return *this;
}
/**
* Checks the write permissions of this block.
* @return True if the block is writable.
*/
bool isWritable() const
{
const int needed_bits = BlkWritable | BlkValid;
return (status & needed_bits) == needed_bits;
}
/**
* Checks that a block is valid (readable).
* @return True if the block is valid.
*/
bool isValid() const
{
return (status & BlkValid) != 0;
}
/**
* Check to see if a block has been written.
* @return True if the block is dirty.
*/
bool isModified() const
{
return (status & BlkDirty) != 0;
}
/**
* Check to see if this block contains compressed data.
* @return True iF the block's data is compressed.
*/
bool isCompressed() const
{
return (status & BlkCompressed) != 0;
}
/**
* Check if this block has been referenced.
* @return True if the block has been referenced.
*/
bool isReferenced() const
{
return (status & BlkReferenced) != 0;
}
/**
* Check if this block was the result of a hardware prefetch, yet to
* be touched.
* @return True if the block was a hardware prefetch, unaccesed.
*/
bool isPrefetch() const
{
return (status & BlkHWPrefetched) != 0;
}
};
/**
* Output a CacheBlk to the given ostream.
* @param out The stream for the output.
* @param blk The cache block to print.
*
* @return The output stream.
*/
inline std::ostream &
operator<<(std::ostream &out, const CacheBlk &blk)
{
out << std::hex << std::endl;
out << " Tag: " << blk.tag << std::endl;
out << " Status: " << blk.status << std::endl;
return(out << std::dec);
}
#endif //__CACHE_BLK_HH__
<|endoftext|>
|
<commit_before>#include "gameitem.h"
#include <QGraphicsScene>
GameItem::GameItem(QObject *parent) : QObject(parent)
{
}
QPointF GameItem::tryMove(const QPointF &requestedPosition, QLineF *collidedLine,
QGraphicsItem **collidedItem) const
{
QLineF movementPath(pos(), requestedPosition);
qreal cannonLength = 0.0;
{
QPointF p1 = boundingRect().center();
QPointF p2 = QPointF(boundingRect().right() + 10.0, p1.y());
cannonLength = QLineF(mapToScene(p1), mapToScene(p2)).length();
}
movementPath.setLength(movementPath.length() + cannonLength);
QRectF boundingRectPath(QPointF(qMin(movementPath.x1(), movementPath.x2()), qMin(movementPath.y1(), movementPath.y2())),
QPointF(qMax(movementPath.x1(), movementPath.x2()), qMax(movementPath.y1(), movementPath.y2())));
QList<QGraphicsItem *> itemsInRect = scene()->items(boundingRectPath, Qt::IntersectsItemBoundingRect);
QPointF nextPoint = requestedPosition;
QRectF sceneRect = scene()->sceneRect();
foreach (QGraphicsItem *item, itemsInRect) {
if (item == static_cast<const QGraphicsItem *>(this))
continue;
QPolygonF mappedBoundingRect = item->mapToScene(item->boundingRect());
for (int i=0; i<mappedBoundingRect.size(); ++i) {
QPointF p1 = mappedBoundingRect.at(i == 0 ? mappedBoundingRect.size()-1 : i-1);
QPointF p2 = mappedBoundingRect.at(i);
QLineF rectLine(p1, p2);
QPointF intersectionPoint;
QLineF::IntersectType intersectType = movementPath.intersect(rectLine, &intersectionPoint);
if (intersectType == QLineF::BoundedIntersection) {
movementPath.setP2(intersectionPoint);
movementPath.setLength(movementPath.length() - cannonLength);
nextPoint = movementPath.p2();
if (collidedLine != 0)
*collidedLine = rectLine;
if (collidedItem != 0)
*collidedItem = item;
}
}
}
// Don't go outside of map
if (nextPoint.x() < sceneRect.left())
nextPoint.rx() = sceneRect.left();
if (nextPoint.x() > sceneRect.right())
nextPoint.rx() = sceneRect.right();
if (nextPoint.y() < sceneRect.top())
nextPoint.ry() = sceneRect.top();
if (nextPoint.y() > sceneRect.bottom())
nextPoint.ry() = sceneRect.bottom();
return nextPoint;
}
<commit_msg>Set collidedLine for the implicit walls around the scene to allow for collision response.<commit_after>#include "gameitem.h"
#include <QGraphicsScene>
#include <QDebug>
GameItem::GameItem(QObject *parent) : QObject(parent)
{
}
QPointF GameItem::tryMove(const QPointF &requestedPosition, QLineF *collidedLine,
QGraphicsItem **collidedItem) const
{
QLineF movementPath(pos(), requestedPosition);
qreal cannonLength = 0.0;
{
QPointF p1 = boundingRect().center();
QPointF p2 = QPointF(boundingRect().right() + 10.0, p1.y());
cannonLength = QLineF(mapToScene(p1), mapToScene(p2)).length();
}
movementPath.setLength(movementPath.length() + cannonLength);
QRectF boundingRectPath(QPointF(qMin(movementPath.x1(), movementPath.x2()), qMin(movementPath.y1(), movementPath.y2())),
QPointF(qMax(movementPath.x1(), movementPath.x2()), qMax(movementPath.y1(), movementPath.y2())));
QList<QGraphicsItem *> itemsInRect = scene()->items(boundingRectPath, Qt::IntersectsItemBoundingRect);
QPointF nextPoint = requestedPosition;
QRectF sceneRect = scene()->sceneRect();
foreach (QGraphicsItem *item, itemsInRect) {
if (item == static_cast<const QGraphicsItem *>(this))
continue;
QPolygonF mappedBoundingRect = item->mapToScene(item->boundingRect());
for (int i=0; i<mappedBoundingRect.size(); ++i) {
QPointF p1 = mappedBoundingRect.at(i == 0 ? mappedBoundingRect.size()-1 : i-1);
QPointF p2 = mappedBoundingRect.at(i);
QLineF rectLine(p1, p2);
QPointF intersectionPoint;
QLineF::IntersectType intersectType = movementPath.intersect(rectLine, &intersectionPoint);
if (intersectType == QLineF::BoundedIntersection) {
movementPath.setP2(intersectionPoint);
movementPath.setLength(movementPath.length() - cannonLength);
nextPoint = movementPath.p2();
if (collidedLine != 0)
*collidedLine = rectLine;
if (collidedItem != 0)
*collidedItem = item;
}
}
}
// Don't go outside of map
if (nextPoint.x() < sceneRect.left()) {
nextPoint.rx() = sceneRect.left();
if (collidedLine != 0)
*collidedLine = QLineF(scene()->sceneRect().topLeft(), scene()->sceneRect().bottomLeft());
}
if (nextPoint.x() > sceneRect.right()) {
nextPoint.rx() = sceneRect.right();
if (collidedLine != 0)
*collidedLine = QLineF(scene()->sceneRect().topRight(), scene()->sceneRect().bottomRight());
}
if (nextPoint.y() < sceneRect.top()) {
nextPoint.ry() = sceneRect.top();
if (collidedLine != 0)
*collidedLine = QLineF(scene()->sceneRect().topLeft(), scene()->sceneRect().topRight());
}
if (nextPoint.y() > sceneRect.bottom()) {
nextPoint.ry() = sceneRect.bottom();
if (collidedLine != 0)
*collidedLine = QLineF(scene()->sceneRect().bottomLeft(), scene()->sceneRect().bottomRight());
}
return nextPoint;
}
<|endoftext|>
|
<commit_before>/* OpenHoW
* Copyright (C) 2017-2019 Mark Sowden <markelswo@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <PL/platform_graphics_camera.h>
#include "../engine.h"
#include "../frontend.h"
#include "../audio.h"
#include "SPGameMode.h"
#include "ActorManager.h"
SPGameMode::SPGameMode() {
players_.resize(4);
}
SPGameMode::~SPGameMode() {
AudioManager::GetInstance()->FreeSources();
AudioManager::GetInstance()->FreeSamples();
DestroyActors();
}
void SPGameMode::StartRound() {
if(HasRoundStarted()) {
Error("Attempted to change map in the middle of a round, aborting!\n");
}
SpawnActors();
round_started_ = true;
}
void SPGameMode::RestartRound() {
DestroyActors();
SpawnActors();
}
void SPGameMode::EndRound() {
DestroyActors();
}
void SPGameMode::Tick() {
if(!HasRoundStarted()) {
// still setting the game up...
return;
}
Actor* slave = GetCurrentPlayer()->input_target;
if(slave != nullptr) {
slave->HandleInput();
// temp: force the camera at the actor pos
g_state.camera->position = slave->GetPosition();
g_state.camera->angles = slave->GetAngles();
}
ActorManager::GetInstance()->TickActors();
}
void SPGameMode::SpawnActors() {
Map* map = GameManager::GetInstance()->GetCurrentMap();
u_assert(map != nullptr);
std::vector<MapSpawn> spawns = map->GetSpawns();
for(auto spawn : spawns) {
Actor* actor = ActorManager::GetInstance()->SpawnMapActor(spawn.name);
if(actor == nullptr) {
continue;
}
actor->SetPosition(PLVector3(spawn.position[0], spawn.position[1], spawn.position[2]));
actor->SetAngles(PLVector3(spawn.angles[0] / 360, spawn.angles[1] / 360, spawn.angles[2] / 360));
// todo: assign player pigs etc., temp hack
if(strcmp(spawn.name, "GR_ME") == 0) {
players_[0].input_target = actor;
}
}
}
void SPGameMode::DestroyActors() {
ActorManager::GetInstance()->DestroyActors();
}
void SPGameMode::StartTurn() {
Player *player = GetCurrentPlayer();
if(player->input_target == nullptr) {
LogWarn("No valid control target for player \"%s\"!\n", player->name.c_str());
EndTurn();
return;
}
}
void SPGameMode::EndTurn() {
// move onto the next player
if(++current_player_ >= players_.size()) {
current_player_ = 0;
}
}
void SPGameMode::PlayerJoined(Player *player) {
}
void SPGameMode::PlayerLeft(Player *player) {
}
unsigned int SPGameMode::GetMaxSpectators() const {
return 0;
}
void SPGameMode::SpectatorJoined(Player *player) {
}
void SPGameMode::SpectatorLeft(Player *player) {
}
unsigned int SPGameMode::GetMaxPlayers() const {
return 0;
}
<commit_msg>fixed minor warnings<commit_after>/* OpenHoW
* Copyright (C) 2017-2019 Mark Sowden <markelswo@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <PL/platform_graphics_camera.h>
#include "../engine.h"
#include "../frontend.h"
#include "../audio.h"
#include "SPGameMode.h"
#include "ActorManager.h"
SPGameMode::SPGameMode() {
players_.resize(4);
}
SPGameMode::~SPGameMode() {
AudioManager::GetInstance()->FreeSources();
AudioManager::GetInstance()->FreeSamples();
DestroyActors();
}
void SPGameMode::StartRound() {
if(HasRoundStarted()) {
Error("Attempted to change map in the middle of a round, aborting!\n");
}
SpawnActors();
round_started_ = true;
}
void SPGameMode::RestartRound() {
DestroyActors();
SpawnActors();
}
void SPGameMode::EndRound() {
DestroyActors();
}
void SPGameMode::Tick() {
if(!HasRoundStarted()) {
// still setting the game up...
return;
}
Actor* slave = GetCurrentPlayer()->input_target;
if(slave != nullptr) {
slave->HandleInput();
// temp: force the camera at the actor pos
g_state.camera->position = slave->GetPosition();
g_state.camera->angles = slave->GetAngles();
}
ActorManager::GetInstance()->TickActors();
}
void SPGameMode::SpawnActors() {
Map* map = GameManager::GetInstance()->GetCurrentMap();
if(map == nullptr) {
Error("Attempted to spawn actors without having loaded a map!\n");
}
std::vector<MapSpawn> spawns = map->GetSpawns();
for(auto spawn : spawns) {
Actor* actor = ActorManager::GetInstance()->SpawnMapActor(spawn.name);
if(actor == nullptr) {
continue;
}
actor->SetPosition(PLVector3(spawn.position[0], spawn.position[1], spawn.position[2]));
actor->SetAngles(PLVector3(spawn.angles[0] / 360.f, spawn.angles[1] / 360.f, spawn.angles[2] / 360.f));
// todo: assign player pigs etc., temp hack
if(strcmp(spawn.name, "GR_ME") == 0) {
players_[0].input_target = actor;
}
}
}
void SPGameMode::DestroyActors() {
ActorManager::GetInstance()->DestroyActors();
}
void SPGameMode::StartTurn() {
Player *player = GetCurrentPlayer();
if(player->input_target == nullptr) {
LogWarn("No valid control target for player \"%s\"!\n", player->name.c_str());
EndTurn();
return;
}
}
void SPGameMode::EndTurn() {
// move onto the next player
if(++current_player_ >= players_.size()) {
current_player_ = 0;
}
}
void SPGameMode::PlayerJoined(Player *player) {
}
void SPGameMode::PlayerLeft(Player *player) {
}
unsigned int SPGameMode::GetMaxSpectators() const {
return 0;
}
void SPGameMode::SpectatorJoined(Player *player) {
}
void SPGameMode::SpectatorLeft(Player *player) {
}
unsigned int SPGameMode::GetMaxPlayers() const {
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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.
//===- PrepareReductionDispatch.cpp ----------------------------*- C++//-*-===//
//
// Prepare dispatch regions that implement reductions before SPIR-V lowering.
//
//===----------------------------------------------------------------------===//
#include "iree/compiler/IR/Ops.h"
#include "iree/compiler/Utils/DispatchUtils.h"
#include "mlir/IR/Function.h"
#include "mlir/IR/PatternMatch.h"
#include "mlir/Pass/Pass.h"
namespace mlir {
namespace iree_compiler {
namespace {
/// The entry function of the reduction dispatches is empty. This pattern fills
/// the body with an iree.load_input of the reduction input followed by an
/// iree.store_reduce for the later lowering passes to generate the appropriate
/// SPIR-V code.
struct AddReductionEntryFnBody : public OpRewritePattern<FuncOp> {
using OpRewritePattern<FuncOp>::OpRewritePattern;
PatternMatchResult matchAndRewrite(FuncOp fn,
PatternRewriter &rewriter) const override;
};
/// Pass to prepare the reduction dispatch entry functions.
struct PrepareReductionDispatchPass
: public OperationPass<PrepareReductionDispatchPass> {
void runOnOperation() override;
};
} // namespace
PatternMatchResult AddReductionEntryFnBody::matchAndRewrite(
FuncOp fn, PatternRewriter &rewriter) const {
if (!fn.getAttr("iree.executable.reduction") || !fn.empty()) {
return matchFailure();
}
OpBuilder::InsertionGuard guard(rewriter);
rewriter.setInsertionPointToStart(fn.addEntryBlock());
if (fn.getNumArguments() != 3) {
return matchFailure();
}
auto src = fn.getArgument(0);
auto dst = fn.getArgument(2);
fn.setArgAttr(2, "iree.executable.reduction.output",
UnitAttr::get(fn.getContext()));
auto applyFn =
fn.getAttrOfType<FlatSymbolRefAttr>("iree.executable.reduction.apply");
auto srcType = src->getType().cast<MemRefType>();
auto loc = fn.getLoc();
auto loadInputOp = rewriter.create<IREE::LoadInputOp>(
loc, RankedTensorType::get(srcType.getShape(), srcType.getElementType()),
src);
rewriter.create<IREE::StoreReduceOp>(loc, loadInputOp.getResult(), dst,
applyFn);
rewriter.create<IREE::ReturnOp>(fn.getLoc());
// Finally update the workload size to be determined by the size of the input.
auto shape = src->getType().cast<ShapedType>().getShape();
std::array<int32_t, 3> workload = {1, 1, 1};
calculateWorkload(shape, workload);
SmallVector<APInt, 3> workloadAPInt;
workloadAPInt.reserve(3);
for (auto workloadVal : workload) {
workloadAPInt.emplace_back(32, static_cast<uint64_t>(workloadVal), true);
}
fn.setAttr(
"iree.executable.workload",
DenseElementsAttr::get(
RankedTensorType::get(3, IntegerType::get(32, rewriter.getContext())),
workloadAPInt)
.cast<DenseIntElementsAttr>());
rewriter.updatedRootInPlace(fn);
return matchSuccess();
}
void PrepareReductionDispatchPass::runOnOperation() {
OwningRewritePatternList patterns;
patterns.insert<AddReductionEntryFnBody>(&getContext());
Operation *op = getOperation();
applyPatternsGreedily(op->getRegions(), patterns);
}
static PassRegistration<PrepareReductionDispatchPass> pass(
"iree-spirv-prepare-reduction-dispatch",
"Prepare the entry function for generation of reduction dispatches");
std::unique_ptr<Pass> createPrepareReductionDispatchPass() {
return std::make_unique<PrepareReductionDispatchPass>();
}
} // namespace iree_compiler
} // namespace mlir
<commit_msg>Change the `notifyRootUpdated` API to be transaction based.<commit_after>// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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.
//===- PrepareReductionDispatch.cpp ----------------------------*- C++//-*-===//
//
// Prepare dispatch regions that implement reductions before SPIR-V lowering.
//
//===----------------------------------------------------------------------===//
#include "iree/compiler/IR/Ops.h"
#include "iree/compiler/Utils/DispatchUtils.h"
#include "mlir/IR/Function.h"
#include "mlir/IR/PatternMatch.h"
#include "mlir/Pass/Pass.h"
namespace mlir {
namespace iree_compiler {
namespace {
/// The entry function of the reduction dispatches is empty. This pattern fills
/// the body with an iree.load_input of the reduction input followed by an
/// iree.store_reduce for the later lowering passes to generate the appropriate
/// SPIR-V code.
struct AddReductionEntryFnBody : public OpRewritePattern<FuncOp> {
using OpRewritePattern<FuncOp>::OpRewritePattern;
PatternMatchResult matchAndRewrite(FuncOp fn,
PatternRewriter &rewriter) const override;
};
/// Pass to prepare the reduction dispatch entry functions.
struct PrepareReductionDispatchPass
: public OperationPass<PrepareReductionDispatchPass> {
void runOnOperation() override;
};
} // namespace
PatternMatchResult AddReductionEntryFnBody::matchAndRewrite(
FuncOp fn, PatternRewriter &rewriter) const {
if (!fn.getAttr("iree.executable.reduction") || !fn.empty()) {
return matchFailure();
}
OpBuilder::InsertionGuard guard(rewriter);
rewriter.setInsertionPointToStart(fn.addEntryBlock());
if (fn.getNumArguments() != 3) {
return matchFailure();
}
rewriter.startRootUpdate(fn);
auto src = fn.getArgument(0);
auto dst = fn.getArgument(2);
fn.setArgAttr(2, "iree.executable.reduction.output",
UnitAttr::get(fn.getContext()));
auto applyFn =
fn.getAttrOfType<FlatSymbolRefAttr>("iree.executable.reduction.apply");
auto srcType = src->getType().cast<MemRefType>();
auto loc = fn.getLoc();
auto loadInputOp = rewriter.create<IREE::LoadInputOp>(
loc, RankedTensorType::get(srcType.getShape(), srcType.getElementType()),
src);
rewriter.create<IREE::StoreReduceOp>(loc, loadInputOp.getResult(), dst,
applyFn);
rewriter.create<IREE::ReturnOp>(fn.getLoc());
// Finally update the workload size to be determined by the size of the input.
auto shape = src->getType().cast<ShapedType>().getShape();
std::array<int32_t, 3> workload = {1, 1, 1};
calculateWorkload(shape, workload);
SmallVector<APInt, 3> workloadAPInt;
workloadAPInt.reserve(3);
for (auto workloadVal : workload) {
workloadAPInt.emplace_back(32, static_cast<uint64_t>(workloadVal), true);
}
fn.setAttr(
"iree.executable.workload",
DenseElementsAttr::get(
RankedTensorType::get(3, IntegerType::get(32, rewriter.getContext())),
workloadAPInt)
.cast<DenseIntElementsAttr>());
rewriter.finalizeRootUpdate(fn);
return matchSuccess();
}
void PrepareReductionDispatchPass::runOnOperation() {
OwningRewritePatternList patterns;
patterns.insert<AddReductionEntryFnBody>(&getContext());
Operation *op = getOperation();
applyPatternsGreedily(op->getRegions(), patterns);
}
static PassRegistration<PrepareReductionDispatchPass> pass(
"iree-spirv-prepare-reduction-dispatch",
"Prepare the entry function for generation of reduction dispatches");
std::unique_ptr<Pass> createPrepareReductionDispatchPass() {
return std::make_unique<PrepareReductionDispatchPass>();
}
} // namespace iree_compiler
} // namespace mlir
<|endoftext|>
|
<commit_before>#include "file.h"
#include "string.h"
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <memory>
#include <stdexcept>
#include <string>
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__)
#define PLATFORM_WINDOWS
#endif
#ifdef PLATFORM_WINDOWS
#include <direct.h>
#include <shlwapi.h>
#include <windows.h>
#else
#include <fcntl.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
#ifdef PLATFORM_WINDOWS
// This is the only module that requires windows character conversion
std::string to_string(const wchar_t* str = L"")
{
if (!str) {
str = L"";
}
auto length = WideCharToMultiByte(CP_UTF8, 0, str, -1, nullptr, 0, nullptr, nullptr);
std::unique_ptr<char[]> buffer(new char[length + 1]);
WideCharToMultiByte(CP_UTF8, 0, str, -1, buffer.get(), length, nullptr, nullptr);
return std::string(buffer.get());
}
// use unique_ptr to prevent memory leak with exceptions.
inline std::unique_ptr<wchar_t[]> to_wchar(const std::string str)
{
auto length = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, nullptr, 0);
std::unique_ptr<wchar_t[]> buffer(new wchar_t[length + 1]);
MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, buffer.get(), length);
return std::move(buffer);
}
#endif
using namespace UnTech;
std::string File::readUtf8TextFile(const std::string& filename)
{
std::ifstream in(filename, std::ios::in | std::ios::binary);
if (in) {
uint8_t bom[3];
in.read((char*)bom, sizeof(bom));
in.seekg(0, std::ios::end);
size_t size = in.tellg();
// check for BOM
if (size > 3 && bom[0] == 0xEF && bom[1] == 0xBB && bom[2] == 0xBF) {
in.seekg(3, std::ios::beg);
size -= 3;
}
else {
in.seekg(0, std::ios::beg);
}
std::string ret;
ret.reserve(size + 1);
ret.assign((std::istreambuf_iterator<char>(in)), (std::istreambuf_iterator<char>()));
in.close();
if (!String::checkUtf8WellFormed(ret)) {
throw std::runtime_error("File is not UTF-8 Well Formed");
}
return (ret);
}
throw std::runtime_error("Cannot open file");
}
std::pair<std::string, std::string> File::splitFilename(const std::string& filename)
{
if (filename.empty()) {
return { std::string(), std::string() };
}
#ifdef PLATFORM_WINDOWS
// search both types of slash in windows.
auto i = filename.find_last_of("\\/");
#else
auto i = filename.find_last_of('/');
#endif
if (i == std::string::npos) {
return { std::string(), filename };
}
else {
return { filename.substr(0, i + 1), filename.substr(i + 1) };
}
}
std::string File::cwd()
{
#ifdef PLATFORM_WINDOWS
wchar_t wpath[PATH_MAX] = L"";
if (!_wgetcwd(wpath, PATH_MAX)) {
throw std::runtime_error("Error getting working directory");
}
return to_string(wpath);
#else
char* dir = get_current_dir_name();
if (dir) {
std::string ret(dir);
free(dir);
return ret;
}
else {
throw std::runtime_error("Error with path");
}
#endif
}
std::string File::cleanPath(const std::string& path)
{
if (path.empty()) {
return path;
}
#ifdef PLATFORM_WINDOWS
const char SEP = '\\';
std::string newPath = path;
std::replace(newPath.begin(), newPath.end(), '/', '\\');
const char* source = newPath.c_str();
#else
const char SEP = '/';
const char* source = path.c_str();
#endif
char ret[path.length() + 1];
char* pos = ret;
char* dirs[path.length() / 2];
size_t nDirs = 0;
while (*source != '\0') {
// Start of a directory/file
if (source[0] == '.' && source[1] == SEP) {
// ignore all . directories
source += 2;
}
else if (source[0] == '.' && source[1] == '.' && source[2] == SEP) {
if (nDirs > 1) {
// shift pos to previous directory
pos = dirs[nDirs - 2];
nDirs--;
source += 3;
}
else {
pos[0] = source[0];
pos[1] = source[1];
pos[2] = source[2];
pos += 3;
source += 3;
}
}
else {
// loop until end of directory separator
while (*source != '\0' && *source != SEP) {
*(pos++) = *(source++);
}
// include terminator ('/' or '\0').
*(pos++) = *(source++);
if (*(source - 1) == '\0') {
break;
}
else if (*(source - 1) == SEP) {
// remember previous dir position
dirs[nDirs] = pos;
nDirs++;
}
}
#ifndef PLATFORM_WINDOWS
// ignore duplicate separators
while (*source == SEP) {
source++;
}
#endif
}
return std::string(ret);
}
std::string File::joinPath(const std::string& dir, const std::string& path)
{
#ifdef PLATFORM_WINDOWS
auto wdir = to_wchar(dir);
auto wpath = to_wchar(path);
wchar_t wjoined[PATH_MAX] = L"";
PathCombineW(wjoined, wdir.get(), wpath.get());
return to_string(wjoined);
#else
if (path.front() == '/') {
return path;
}
std::string join;
join.reserve(dir.length() + path.length() + 1);
if (!dir.empty() && dir.back() != '/') {
join = dir + '/' + path;
}
else {
join = dir + path;
}
return cleanPath(join);
#endif
}
std::string File::fullPath(const std::string& path)
{
#ifdef PLATFORM_WINDOWS
wchar_t wfullpath[PATH_MAX] = L"";
auto wpath = to_wchar(path);
if (!_wfullpath(wfullpath, wpath.get(), PATH_MAX)) {
throw std::runtime_error("Error expanding path");
}
return to_string(wfullpath);
#else
if (path.front() == '/') {
return path;
}
return joinPath(cwd(), path);
#endif
}
std::string File::relativePath(const std::string& sourceDir, const std::string& destPath)
{
if (sourceDir.empty()) {
return File::fullPath(destPath);
}
#ifdef PLATFORM_WINDOWS
wchar_t wrelpath[PATH_MAX] = L"";
auto wsource = to_wchar(sourceDir);
auto wdest = to_wchar(destPath);
if (!PathRelativePathToW(wrelpath, wsource.get(), FILE_ATTRIBUTE_DIRECTORY, wdest.get(), FILE_ATTRIBUTE_NORMAL)) {
return File::fullPath(destPath);
}
if (wrelpath[0] != L'\\') {
return to_string(wrelpath);
}
else {
return to_string(wrelpath + 1);
}
#else
std::string source = File::fullPath(sourceDir);
std::string dest = File::fullPath(destPath);
if (source.empty() || dest.empty()
|| source.front() != '/' || dest.front() != '/') {
return dest;
}
std::string ret;
// Get common root directories
size_t lastCommonSep = 0;
{
size_t i = 0;
while (i < source.size() && i < dest.size() && source[i] == dest[i]) {
if (source[i] == '/') {
lastCommonSep = i;
}
i++;
}
if (i == source.size() && dest.size() > source.size() && dest[i] == '/') {
lastCommonSep = i;
}
}
if (source.size() > lastCommonSep) {
size_t p = lastCommonSep + 1;
while ((p = source.find('/', p)) != std::string::npos) {
ret += "../";
p += 1;
}
}
ret += dest.substr(lastCommonSep + 1);
return ret;
#endif
}
#ifdef PLATFORM_WINDOWS
void File::atomicWrite(const std::string& filename, const void* data, size_t size)
{
const size_t BLOCK_SIZE = 4096;
// atomically creating a tempfile name is hard
// just simplify it by using a ~ temp file instead.
auto tmpFilename = to_wchar(filename + "~");
// open file normally.
// error out if file exists.
HANDLE hFile = CreateFileW(tmpFilename.get(), GENERIC_WRITE, 0, nullptr,
CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr);
if (hFile == INVALID_HANDLE_VALUE) {
if (GetLastError() == ERROR_FILE_EXISTS) {
throw std::runtime_error("Temporary file already exists: " + filename + "~");
}
else {
throw std::runtime_error("Cannot open temporary file " + filename + "~");
}
}
const uint8_t* ptr = static_cast<const uint8_t*>(data);
size_t todo = size;
while (todo > 0) {
DWORD toWrite = std::min(BLOCK_SIZE, todo);
DWORD written = 0;
auto ret = WriteFile(hFile, ptr, toWrite, &written, NULL);
if (ret == FALSE || written != toWrite) {
CloseHandle(hFile);
throw std::runtime_error("Error writing file");
}
ptr += toWrite;
todo -= toWrite;
}
CloseHandle(hFile);
auto wFilename = to_wchar(filename);
bool s = MoveFileExW(tmpFilename.get(), wFilename.get(),
MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED);
if (!s) {
throw std::runtime_error("MoveFileEx failed");
}
}
#else
void File::atomicWrite(const std::string& filename, const void* data, size_t size)
{
const size_t BLOCK_SIZE = 4096;
int fd;
char tmpFilename[filename.size() + 12];
strncpy(tmpFilename, filename.c_str(), filename.size() + 1);
strncpy(tmpFilename + filename.size(), "-tmpXXXXXX", 12);
struct stat statbuf;
if (stat(filename.c_str(), &statbuf) == 0) {
if (S_ISLNK(statbuf.st_mode)) {
throw std::runtime_error("Cannot write to a symbolic link");
}
// check if we can write to file
bool canWrite = ((getuid() == statbuf.st_uid) && (statbuf.st_mode & S_IWUSR))
|| ((getgid() == statbuf.st_gid) && (statbuf.st_mode & S_IWGRP))
|| (statbuf.st_mode & S_IWOTH);
if (!canWrite) {
throw std::runtime_error("User can not write to " + filename);
}
fd = mkostemp(tmpFilename, O_WRONLY);
if (fd < 0) {
throw std::system_error(errno, std::system_category());
}
// mkostemp sets file permission to 0600
// Set the permissions to match filename
chmod(tmpFilename, statbuf.st_mode);
chown(tmpFilename, statbuf.st_uid, statbuf.st_gid);
}
else {
fd = mkostemp(tmpFilename, O_WRONLY);
if (fd < 0) {
throw std::system_error(errno, std::system_category());
}
// mkostemp sets file permission to 0600
// Set the permissions what user would expect
mode_t mask = umask(0);
umask(mask);
chmod(tmpFilename, 0666 & ~mask);
}
const uint8_t* ptr = static_cast<const uint8_t*>(data);
size_t todo = size;
ssize_t done;
while (todo > 0) {
done = ::write(fd, ptr, std::min(BLOCK_SIZE, todo));
if (done < 0) {
auto err = errno;
close(fd);
throw std::system_error(err, std::system_category());
}
ptr += done;
todo -= done;
}
int r;
r = close(fd);
if (r != 0) {
throw std::system_error(errno, std::system_category());
}
r = rename(tmpFilename, filename.c_str());
if (r != 0) {
throw std::system_error(errno, std::system_category());
}
}
#endif
<commit_msg>ui: include filename in File::readUtf8TextFile exceptions<commit_after>#include "file.h"
#include "string.h"
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <memory>
#include <stdexcept>
#include <string>
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__)
#define PLATFORM_WINDOWS
#endif
#ifdef PLATFORM_WINDOWS
#include <direct.h>
#include <shlwapi.h>
#include <windows.h>
#else
#include <fcntl.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
#ifdef PLATFORM_WINDOWS
// This is the only module that requires windows character conversion
std::string to_string(const wchar_t* str = L"")
{
if (!str) {
str = L"";
}
auto length = WideCharToMultiByte(CP_UTF8, 0, str, -1, nullptr, 0, nullptr, nullptr);
std::unique_ptr<char[]> buffer(new char[length + 1]);
WideCharToMultiByte(CP_UTF8, 0, str, -1, buffer.get(), length, nullptr, nullptr);
return std::string(buffer.get());
}
// use unique_ptr to prevent memory leak with exceptions.
inline std::unique_ptr<wchar_t[]> to_wchar(const std::string str)
{
auto length = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, nullptr, 0);
std::unique_ptr<wchar_t[]> buffer(new wchar_t[length + 1]);
MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, buffer.get(), length);
return std::move(buffer);
}
#endif
using namespace UnTech;
std::string File::readUtf8TextFile(const std::string& filename)
{
std::ifstream in(filename, std::ios::in | std::ios::binary);
if (in) {
uint8_t bom[3];
in.read((char*)bom, sizeof(bom));
in.seekg(0, std::ios::end);
size_t size = in.tellg();
// check for BOM
if (size > 3 && bom[0] == 0xEF && bom[1] == 0xBB && bom[2] == 0xBF) {
in.seekg(3, std::ios::beg);
size -= 3;
}
else {
in.seekg(0, std::ios::beg);
}
std::string ret;
ret.reserve(size + 1);
ret.assign((std::istreambuf_iterator<char>(in)), (std::istreambuf_iterator<char>()));
in.close();
if (!String::checkUtf8WellFormed(ret)) {
throw std::runtime_error("Cannot open file: " + filename + " : Not UTF-8 Well Formed");
}
return (ret);
}
throw std::runtime_error("Cannot open file: " + filename);
}
std::pair<std::string, std::string> File::splitFilename(const std::string& filename)
{
if (filename.empty()) {
return { std::string(), std::string() };
}
#ifdef PLATFORM_WINDOWS
// search both types of slash in windows.
auto i = filename.find_last_of("\\/");
#else
auto i = filename.find_last_of('/');
#endif
if (i == std::string::npos) {
return { std::string(), filename };
}
else {
return { filename.substr(0, i + 1), filename.substr(i + 1) };
}
}
std::string File::cwd()
{
#ifdef PLATFORM_WINDOWS
wchar_t wpath[PATH_MAX] = L"";
if (!_wgetcwd(wpath, PATH_MAX)) {
throw std::runtime_error("Error getting working directory");
}
return to_string(wpath);
#else
char* dir = get_current_dir_name();
if (dir) {
std::string ret(dir);
free(dir);
return ret;
}
else {
throw std::runtime_error("Error with path");
}
#endif
}
std::string File::cleanPath(const std::string& path)
{
if (path.empty()) {
return path;
}
#ifdef PLATFORM_WINDOWS
const char SEP = '\\';
std::string newPath = path;
std::replace(newPath.begin(), newPath.end(), '/', '\\');
const char* source = newPath.c_str();
#else
const char SEP = '/';
const char* source = path.c_str();
#endif
char ret[path.length() + 1];
char* pos = ret;
char* dirs[path.length() / 2];
size_t nDirs = 0;
while (*source != '\0') {
// Start of a directory/file
if (source[0] == '.' && source[1] == SEP) {
// ignore all . directories
source += 2;
}
else if (source[0] == '.' && source[1] == '.' && source[2] == SEP) {
if (nDirs > 1) {
// shift pos to previous directory
pos = dirs[nDirs - 2];
nDirs--;
source += 3;
}
else {
pos[0] = source[0];
pos[1] = source[1];
pos[2] = source[2];
pos += 3;
source += 3;
}
}
else {
// loop until end of directory separator
while (*source != '\0' && *source != SEP) {
*(pos++) = *(source++);
}
// include terminator ('/' or '\0').
*(pos++) = *(source++);
if (*(source - 1) == '\0') {
break;
}
else if (*(source - 1) == SEP) {
// remember previous dir position
dirs[nDirs] = pos;
nDirs++;
}
}
#ifndef PLATFORM_WINDOWS
// ignore duplicate separators
while (*source == SEP) {
source++;
}
#endif
}
return std::string(ret);
}
std::string File::joinPath(const std::string& dir, const std::string& path)
{
#ifdef PLATFORM_WINDOWS
auto wdir = to_wchar(dir);
auto wpath = to_wchar(path);
wchar_t wjoined[PATH_MAX] = L"";
PathCombineW(wjoined, wdir.get(), wpath.get());
return to_string(wjoined);
#else
if (path.front() == '/') {
return path;
}
std::string join;
join.reserve(dir.length() + path.length() + 1);
if (!dir.empty() && dir.back() != '/') {
join = dir + '/' + path;
}
else {
join = dir + path;
}
return cleanPath(join);
#endif
}
std::string File::fullPath(const std::string& path)
{
#ifdef PLATFORM_WINDOWS
wchar_t wfullpath[PATH_MAX] = L"";
auto wpath = to_wchar(path);
if (!_wfullpath(wfullpath, wpath.get(), PATH_MAX)) {
throw std::runtime_error("Error expanding path");
}
return to_string(wfullpath);
#else
if (path.front() == '/') {
return path;
}
return joinPath(cwd(), path);
#endif
}
std::string File::relativePath(const std::string& sourceDir, const std::string& destPath)
{
if (sourceDir.empty()) {
return File::fullPath(destPath);
}
#ifdef PLATFORM_WINDOWS
wchar_t wrelpath[PATH_MAX] = L"";
auto wsource = to_wchar(sourceDir);
auto wdest = to_wchar(destPath);
if (!PathRelativePathToW(wrelpath, wsource.get(), FILE_ATTRIBUTE_DIRECTORY, wdest.get(), FILE_ATTRIBUTE_NORMAL)) {
return File::fullPath(destPath);
}
if (wrelpath[0] != L'\\') {
return to_string(wrelpath);
}
else {
return to_string(wrelpath + 1);
}
#else
std::string source = File::fullPath(sourceDir);
std::string dest = File::fullPath(destPath);
if (source.empty() || dest.empty()
|| source.front() != '/' || dest.front() != '/') {
return dest;
}
std::string ret;
// Get common root directories
size_t lastCommonSep = 0;
{
size_t i = 0;
while (i < source.size() && i < dest.size() && source[i] == dest[i]) {
if (source[i] == '/') {
lastCommonSep = i;
}
i++;
}
if (i == source.size() && dest.size() > source.size() && dest[i] == '/') {
lastCommonSep = i;
}
}
if (source.size() > lastCommonSep) {
size_t p = lastCommonSep + 1;
while ((p = source.find('/', p)) != std::string::npos) {
ret += "../";
p += 1;
}
}
ret += dest.substr(lastCommonSep + 1);
return ret;
#endif
}
#ifdef PLATFORM_WINDOWS
void File::atomicWrite(const std::string& filename, const void* data, size_t size)
{
const size_t BLOCK_SIZE = 4096;
// atomically creating a tempfile name is hard
// just simplify it by using a ~ temp file instead.
auto tmpFilename = to_wchar(filename + "~");
// open file normally.
// error out if file exists.
HANDLE hFile = CreateFileW(tmpFilename.get(), GENERIC_WRITE, 0, nullptr,
CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr);
if (hFile == INVALID_HANDLE_VALUE) {
if (GetLastError() == ERROR_FILE_EXISTS) {
throw std::runtime_error("Temporary file already exists: " + filename + "~");
}
else {
throw std::runtime_error("Cannot open temporary file " + filename + "~");
}
}
const uint8_t* ptr = static_cast<const uint8_t*>(data);
size_t todo = size;
while (todo > 0) {
DWORD toWrite = std::min(BLOCK_SIZE, todo);
DWORD written = 0;
auto ret = WriteFile(hFile, ptr, toWrite, &written, NULL);
if (ret == FALSE || written != toWrite) {
CloseHandle(hFile);
throw std::runtime_error("Error writing file");
}
ptr += toWrite;
todo -= toWrite;
}
CloseHandle(hFile);
auto wFilename = to_wchar(filename);
bool s = MoveFileExW(tmpFilename.get(), wFilename.get(),
MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED);
if (!s) {
throw std::runtime_error("MoveFileEx failed");
}
}
#else
void File::atomicWrite(const std::string& filename, const void* data, size_t size)
{
const size_t BLOCK_SIZE = 4096;
int fd;
char tmpFilename[filename.size() + 12];
strncpy(tmpFilename, filename.c_str(), filename.size() + 1);
strncpy(tmpFilename + filename.size(), "-tmpXXXXXX", 12);
struct stat statbuf;
if (stat(filename.c_str(), &statbuf) == 0) {
if (S_ISLNK(statbuf.st_mode)) {
throw std::runtime_error("Cannot write to a symbolic link");
}
// check if we can write to file
bool canWrite = ((getuid() == statbuf.st_uid) && (statbuf.st_mode & S_IWUSR))
|| ((getgid() == statbuf.st_gid) && (statbuf.st_mode & S_IWGRP))
|| (statbuf.st_mode & S_IWOTH);
if (!canWrite) {
throw std::runtime_error("User can not write to " + filename);
}
fd = mkostemp(tmpFilename, O_WRONLY);
if (fd < 0) {
throw std::system_error(errno, std::system_category());
}
// mkostemp sets file permission to 0600
// Set the permissions to match filename
chmod(tmpFilename, statbuf.st_mode);
chown(tmpFilename, statbuf.st_uid, statbuf.st_gid);
}
else {
fd = mkostemp(tmpFilename, O_WRONLY);
if (fd < 0) {
throw std::system_error(errno, std::system_category());
}
// mkostemp sets file permission to 0600
// Set the permissions what user would expect
mode_t mask = umask(0);
umask(mask);
chmod(tmpFilename, 0666 & ~mask);
}
const uint8_t* ptr = static_cast<const uint8_t*>(data);
size_t todo = size;
ssize_t done;
while (todo > 0) {
done = ::write(fd, ptr, std::min(BLOCK_SIZE, todo));
if (done < 0) {
auto err = errno;
close(fd);
throw std::system_error(err, std::system_category());
}
ptr += done;
todo -= done;
}
int r;
r = close(fd);
if (r != 0) {
throw std::system_error(errno, std::system_category());
}
r = rename(tmpFilename, filename.c_str());
if (r != 0) {
throw std::system_error(errno, std::system_category());
}
}
#endif
<|endoftext|>
|
<commit_before>//===-- LLVMTargetMachine.cpp - Implement the LLVMTargetMachine class -----===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the LLVMTargetMachine class.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Scalar.h"
#include "llvm/PassManager.h"
#include "llvm/Assembly/PrintModulePass.h"
#include "llvm/CodeGen/AsmPrinter.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/MachineFunctionAnalysis.h"
#include "llvm/CodeGen/MachineModuleInfo.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetLowering.h"
#include "llvm/Target/TargetLoweringObjectFile.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Target/TargetSubtargetInfo.h"
#include "llvm/Target/TargetRegisterInfo.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCSubtargetInfo.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/TargetRegistry.h"
using namespace llvm;
// Enable or disable FastISel. Both options are needed, because
// FastISel is enabled by default with -fast, and we wish to be
// able to enable or disable fast-isel independently from -O0.
static cl::opt<cl::boolOrDefault>
EnableFastISelOption("fast-isel", cl::Hidden,
cl::desc("Enable the \"fast\" instruction selector"));
static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
cl::desc("Show encoding in .s output"));
static cl::opt<bool> ShowMCInst("show-mc-inst", cl::Hidden,
cl::desc("Show instruction structure in .s output"));
static cl::opt<cl::boolOrDefault>
AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
cl::init(cl::BOU_UNSET));
static bool getVerboseAsm() {
switch (AsmVerbose) {
case cl::BOU_UNSET: return TargetMachine::getAsmVerbosityDefault();
case cl::BOU_TRUE: return true;
case cl::BOU_FALSE: return false;
}
llvm_unreachable("Invalid verbose asm state");
}
LLVMTargetMachine::LLVMTargetMachine(const Target &T, StringRef Triple,
StringRef CPU, StringRef FS,
TargetOptions Options,
Reloc::Model RM, CodeModel::Model CM,
CodeGenOpt::Level OL)
: TargetMachine(T, Triple, CPU, FS, Options) {
CodeGenInfo = T.createMCCodeGenInfo(Triple, RM, CM, OL);
AsmInfo = T.createMCAsmInfo(Triple);
// TargetSelect.h moved to a different directory between LLVM 2.9 and 3.0,
// and if the old one gets included then MCAsmInfo will be NULL and
// we'll crash later.
// Provide the user with a useful error message about what's wrong.
assert(AsmInfo && "MCAsmInfo not initialized."
"Make sure you include the correct TargetSelect.h"
"and that InitializeAllTargetMCs() is being invoked!");
}
/// addPassesToX helper drives creation and initialization of TargetPassConfig.
static MCContext *addPassesToGenerateCode(LLVMTargetMachine *TM,
PassManagerBase &PM,
bool DisableVerify,
AnalysisID StartAfter,
AnalysisID StopAfter) {
// Targets may override createPassConfig to provide a target-specific sublass.
TargetPassConfig *PassConfig = TM->createPassConfig(PM);
PassConfig->setStartStopPasses(StartAfter, StopAfter);
// Set PassConfig options provided by TargetMachine.
PassConfig->setDisableVerify(DisableVerify);
PM.add(PassConfig);
PassConfig->addIRPasses();
PassConfig->addPassesToHandleExceptions();
PassConfig->addISelPrepare();
// Install a MachineModuleInfo class, which is an immutable pass that holds
// all the per-module stuff we're generating, including MCContext.
MachineModuleInfo *MMI =
new MachineModuleInfo(*TM->getMCAsmInfo(), *TM->getRegisterInfo(),
&TM->getTargetLowering()->getObjFileLowering());
PM.add(MMI);
MCContext *Context = &MMI->getContext(); // Return the MCContext by-ref.
// Set up a MachineFunction for the rest of CodeGen to work on.
PM.add(new MachineFunctionAnalysis(*TM));
// Enable FastISel with -fast, but allow that to be overridden.
if (EnableFastISelOption == cl::BOU_TRUE ||
(TM->getOptLevel() == CodeGenOpt::None &&
EnableFastISelOption != cl::BOU_FALSE))
TM->setFastISel(true);
// Ask the target for an isel.
if (PassConfig->addInstSelector())
return NULL;
PassConfig->addMachinePasses();
PassConfig->setInitialized();
return Context;
}
bool LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
formatted_raw_ostream &Out,
CodeGenFileType FileType,
bool DisableVerify,
AnalysisID StartAfter,
AnalysisID StopAfter) {
// Add common CodeGen passes.
MCContext *Context = addPassesToGenerateCode(this, PM, DisableVerify,
StartAfter, StopAfter);
if (!Context)
return true;
if (StopAfter) {
// FIXME: The intent is that this should eventually write out a YAML file,
// containing the LLVM IR, the machine-level IR (when stopping after a
// machine-level pass), and whatever other information is needed to
// deserialize the code and resume compilation. For now, just write the
// LLVM IR.
PM.add(createPrintModulePass(&Out));
return false;
}
if (hasMCSaveTempLabels())
Context->setAllowTemporaryLabels(false);
const MCAsmInfo &MAI = *getMCAsmInfo();
const MCRegisterInfo &MRI = *getRegisterInfo();
const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
OwningPtr<MCStreamer> AsmStreamer;
switch (FileType) {
case CGFT_AssemblyFile: {
MCInstPrinter *InstPrinter =
getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI,
*getInstrInfo(),
Context->getRegisterInfo(), STI);
// Create a code emitter if asked to show the encoding.
MCCodeEmitter *MCE = 0;
MCAsmBackend *MAB = 0;
if (ShowMCEncoding) {
const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
MCE = getTarget().createMCCodeEmitter(*getInstrInfo(), MRI, STI,
*Context);
MAB = getTarget().createMCAsmBackend(getTargetTriple(), TargetCPU);
}
MCStreamer *S = getTarget().createAsmStreamer(*Context, Out,
getVerboseAsm(),
hasMCUseLoc(),
hasMCUseCFI(),
hasMCUseDwarfDirectory(),
InstPrinter,
MCE, MAB,
ShowMCInst);
AsmStreamer.reset(S);
break;
}
case CGFT_ObjectFile: {
// Create the code emitter for the target if it exists. If not, .o file
// emission fails.
MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(*getInstrInfo(), MRI,
STI, *Context);
MCAsmBackend *MAB = getTarget().createMCAsmBackend(getTargetTriple(), TargetCPU);
if (MCE == 0 || MAB == 0)
return true;
AsmStreamer.reset(getTarget().createMCObjectStreamer(getTargetTriple(),
*Context, *MAB, Out,
MCE, hasMCRelaxAll(),
hasMCNoExecStack()));
AsmStreamer.get()->InitSections();
break;
}
case CGFT_Null:
// The Null output is intended for use for performance analysis and testing,
// not real users.
AsmStreamer.reset(createNullStreamer(*Context));
break;
}
// Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
if (Printer == 0)
return true;
// If successful, createAsmPrinter took ownership of AsmStreamer.
AsmStreamer.take();
PM.add(Printer);
PM.add(createGCInfoDeleter());
return false;
}
/// addPassesToEmitMachineCode - Add passes to the specified pass manager to
/// get machine code emitted. This uses a JITCodeEmitter object to handle
/// actually outputting the machine code and resolving things like the address
/// of functions. This method should returns true if machine code emission is
/// not supported.
///
bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
JITCodeEmitter &JCE,
bool DisableVerify) {
// Add common CodeGen passes.
MCContext *Context = addPassesToGenerateCode(this, PM, DisableVerify, 0, 0);
if (!Context)
return true;
addCodeEmitter(PM, JCE);
PM.add(createGCInfoDeleter());
return false; // success!
}
/// addPassesToEmitMC - Add passes to the specified pass manager to get
/// machine code emitted with the MCJIT. This method returns true if machine
/// code is not supported. It fills the MCContext Ctx pointer which can be
/// used to build custom MCStreamer.
///
bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM,
MCContext *&Ctx,
raw_ostream &Out,
bool DisableVerify) {
// Add common CodeGen passes.
Ctx = addPassesToGenerateCode(this, PM, DisableVerify, 0, 0);
if (!Ctx)
return true;
if (hasMCSaveTempLabels())
Ctx->setAllowTemporaryLabels(false);
// Create the code emitter for the target if it exists. If not, .o file
// emission fails.
const MCRegisterInfo &MRI = *getRegisterInfo();
const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(*getInstrInfo(), MRI,
STI, *Ctx);
MCAsmBackend *MAB = getTarget().createMCAsmBackend(getTargetTriple(), TargetCPU);
if (MCE == 0 || MAB == 0)
return true;
OwningPtr<MCStreamer> AsmStreamer;
AsmStreamer.reset(getTarget().createMCObjectStreamer(getTargetTriple(), *Ctx,
*MAB, Out, MCE,
hasMCRelaxAll(),
hasMCNoExecStack()));
AsmStreamer.get()->InitSections();
// Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
if (Printer == 0)
return true;
// If successful, createAsmPrinter took ownership of AsmStreamer.
AsmStreamer.take();
PM.add(Printer);
return false; // success!
}
<commit_msg>Fix 80-col violation<commit_after>//===-- LLVMTargetMachine.cpp - Implement the LLVMTargetMachine class -----===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the LLVMTargetMachine class.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Scalar.h"
#include "llvm/PassManager.h"
#include "llvm/Assembly/PrintModulePass.h"
#include "llvm/CodeGen/AsmPrinter.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/MachineFunctionAnalysis.h"
#include "llvm/CodeGen/MachineModuleInfo.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetLowering.h"
#include "llvm/Target/TargetLoweringObjectFile.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Target/TargetSubtargetInfo.h"
#include "llvm/Target/TargetRegisterInfo.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCSubtargetInfo.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/TargetRegistry.h"
using namespace llvm;
// Enable or disable FastISel. Both options are needed, because
// FastISel is enabled by default with -fast, and we wish to be
// able to enable or disable fast-isel independently from -O0.
static cl::opt<cl::boolOrDefault>
EnableFastISelOption("fast-isel", cl::Hidden,
cl::desc("Enable the \"fast\" instruction selector"));
static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
cl::desc("Show encoding in .s output"));
static cl::opt<bool> ShowMCInst("show-mc-inst", cl::Hidden,
cl::desc("Show instruction structure in .s output"));
static cl::opt<cl::boolOrDefault>
AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
cl::init(cl::BOU_UNSET));
static bool getVerboseAsm() {
switch (AsmVerbose) {
case cl::BOU_UNSET: return TargetMachine::getAsmVerbosityDefault();
case cl::BOU_TRUE: return true;
case cl::BOU_FALSE: return false;
}
llvm_unreachable("Invalid verbose asm state");
}
LLVMTargetMachine::LLVMTargetMachine(const Target &T, StringRef Triple,
StringRef CPU, StringRef FS,
TargetOptions Options,
Reloc::Model RM, CodeModel::Model CM,
CodeGenOpt::Level OL)
: TargetMachine(T, Triple, CPU, FS, Options) {
CodeGenInfo = T.createMCCodeGenInfo(Triple, RM, CM, OL);
AsmInfo = T.createMCAsmInfo(Triple);
// TargetSelect.h moved to a different directory between LLVM 2.9 and 3.0,
// and if the old one gets included then MCAsmInfo will be NULL and
// we'll crash later.
// Provide the user with a useful error message about what's wrong.
assert(AsmInfo && "MCAsmInfo not initialized."
"Make sure you include the correct TargetSelect.h"
"and that InitializeAllTargetMCs() is being invoked!");
}
/// addPassesToX helper drives creation and initialization of TargetPassConfig.
static MCContext *addPassesToGenerateCode(LLVMTargetMachine *TM,
PassManagerBase &PM,
bool DisableVerify,
AnalysisID StartAfter,
AnalysisID StopAfter) {
// Targets may override createPassConfig to provide a target-specific sublass.
TargetPassConfig *PassConfig = TM->createPassConfig(PM);
PassConfig->setStartStopPasses(StartAfter, StopAfter);
// Set PassConfig options provided by TargetMachine.
PassConfig->setDisableVerify(DisableVerify);
PM.add(PassConfig);
PassConfig->addIRPasses();
PassConfig->addPassesToHandleExceptions();
PassConfig->addISelPrepare();
// Install a MachineModuleInfo class, which is an immutable pass that holds
// all the per-module stuff we're generating, including MCContext.
MachineModuleInfo *MMI =
new MachineModuleInfo(*TM->getMCAsmInfo(), *TM->getRegisterInfo(),
&TM->getTargetLowering()->getObjFileLowering());
PM.add(MMI);
MCContext *Context = &MMI->getContext(); // Return the MCContext by-ref.
// Set up a MachineFunction for the rest of CodeGen to work on.
PM.add(new MachineFunctionAnalysis(*TM));
// Enable FastISel with -fast, but allow that to be overridden.
if (EnableFastISelOption == cl::BOU_TRUE ||
(TM->getOptLevel() == CodeGenOpt::None &&
EnableFastISelOption != cl::BOU_FALSE))
TM->setFastISel(true);
// Ask the target for an isel.
if (PassConfig->addInstSelector())
return NULL;
PassConfig->addMachinePasses();
PassConfig->setInitialized();
return Context;
}
bool LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
formatted_raw_ostream &Out,
CodeGenFileType FileType,
bool DisableVerify,
AnalysisID StartAfter,
AnalysisID StopAfter) {
// Add common CodeGen passes.
MCContext *Context = addPassesToGenerateCode(this, PM, DisableVerify,
StartAfter, StopAfter);
if (!Context)
return true;
if (StopAfter) {
// FIXME: The intent is that this should eventually write out a YAML file,
// containing the LLVM IR, the machine-level IR (when stopping after a
// machine-level pass), and whatever other information is needed to
// deserialize the code and resume compilation. For now, just write the
// LLVM IR.
PM.add(createPrintModulePass(&Out));
return false;
}
if (hasMCSaveTempLabels())
Context->setAllowTemporaryLabels(false);
const MCAsmInfo &MAI = *getMCAsmInfo();
const MCRegisterInfo &MRI = *getRegisterInfo();
const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
OwningPtr<MCStreamer> AsmStreamer;
switch (FileType) {
case CGFT_AssemblyFile: {
MCInstPrinter *InstPrinter =
getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI,
*getInstrInfo(),
Context->getRegisterInfo(), STI);
// Create a code emitter if asked to show the encoding.
MCCodeEmitter *MCE = 0;
MCAsmBackend *MAB = 0;
if (ShowMCEncoding) {
const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
MCE = getTarget().createMCCodeEmitter(*getInstrInfo(), MRI, STI,
*Context);
MAB = getTarget().createMCAsmBackend(getTargetTriple(), TargetCPU);
}
MCStreamer *S = getTarget().createAsmStreamer(*Context, Out,
getVerboseAsm(),
hasMCUseLoc(),
hasMCUseCFI(),
hasMCUseDwarfDirectory(),
InstPrinter,
MCE, MAB,
ShowMCInst);
AsmStreamer.reset(S);
break;
}
case CGFT_ObjectFile: {
// Create the code emitter for the target if it exists. If not, .o file
// emission fails.
MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(*getInstrInfo(), MRI,
STI, *Context);
MCAsmBackend *MAB = getTarget().createMCAsmBackend(getTargetTriple(),
TargetCPU);
if (MCE == 0 || MAB == 0)
return true;
AsmStreamer.reset(getTarget().createMCObjectStreamer(getTargetTriple(),
*Context, *MAB, Out,
MCE, hasMCRelaxAll(),
hasMCNoExecStack()));
AsmStreamer.get()->InitSections();
break;
}
case CGFT_Null:
// The Null output is intended for use for performance analysis and testing,
// not real users.
AsmStreamer.reset(createNullStreamer(*Context));
break;
}
// Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
if (Printer == 0)
return true;
// If successful, createAsmPrinter took ownership of AsmStreamer.
AsmStreamer.take();
PM.add(Printer);
PM.add(createGCInfoDeleter());
return false;
}
/// addPassesToEmitMachineCode - Add passes to the specified pass manager to
/// get machine code emitted. This uses a JITCodeEmitter object to handle
/// actually outputting the machine code and resolving things like the address
/// of functions. This method should returns true if machine code emission is
/// not supported.
///
bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
JITCodeEmitter &JCE,
bool DisableVerify) {
// Add common CodeGen passes.
MCContext *Context = addPassesToGenerateCode(this, PM, DisableVerify, 0, 0);
if (!Context)
return true;
addCodeEmitter(PM, JCE);
PM.add(createGCInfoDeleter());
return false; // success!
}
/// addPassesToEmitMC - Add passes to the specified pass manager to get
/// machine code emitted with the MCJIT. This method returns true if machine
/// code is not supported. It fills the MCContext Ctx pointer which can be
/// used to build custom MCStreamer.
///
bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM,
MCContext *&Ctx,
raw_ostream &Out,
bool DisableVerify) {
// Add common CodeGen passes.
Ctx = addPassesToGenerateCode(this, PM, DisableVerify, 0, 0);
if (!Ctx)
return true;
if (hasMCSaveTempLabels())
Ctx->setAllowTemporaryLabels(false);
// Create the code emitter for the target if it exists. If not, .o file
// emission fails.
const MCRegisterInfo &MRI = *getRegisterInfo();
const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(*getInstrInfo(), MRI,
STI, *Ctx);
MCAsmBackend *MAB = getTarget().createMCAsmBackend(getTargetTriple(), TargetCPU);
if (MCE == 0 || MAB == 0)
return true;
OwningPtr<MCStreamer> AsmStreamer;
AsmStreamer.reset(getTarget().createMCObjectStreamer(getTargetTriple(), *Ctx,
*MAB, Out, MCE,
hasMCRelaxAll(),
hasMCNoExecStack()));
AsmStreamer.get()->InitSections();
// Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
if (Printer == 0)
return true;
// If successful, createAsmPrinter took ownership of AsmStreamer.
AsmStreamer.take();
PM.add(Printer);
return false; // success!
}
<|endoftext|>
|
<commit_before>/***************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of mcompositor.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include <QPropertyAnimation>
#include <QParallelAnimationGroup>
#include <QPointF>
#include <QtDebug>
#include <mcompositewindow.h>
#include <mcompositewindowshadereffect.h>
#include <mstatusbartexture.h>
#include "mpositionanimation.h"
static QRectF screen;
MPositionAnimation::MPositionAnimation(QObject* parent)
:MCompositeWindowAnimation(parent)
{
setReplaceable(false);
// only use the position animation
animationGroup()->removeAnimation(scaleAnimation());
animationGroup()->removeAnimation(opacityAnimation());
position = positionAnimation();
if (screen.isEmpty())
screen = QApplication::desktop()->availableGeometry();
}
MPositionAnimation::~MPositionAnimation()
{
// don't delete externally referenced animation objects
for (int i = 0; i < animationGroup()->animationCount(); ++i)
if (animationGroup()->animationAt(i) != position)
animationGroup()->takeAnimation(i);
}
void MPositionAnimation::setEnabled(bool enabled)
{
if (enabled && (animationGroup()->indexOfAnimation(position) == -1))
animationGroup()->addAnimation(position);
else if (!enabled) {
animationGroup()->stop();
animationGroup()->removeAnimation(position);
}
}
MSheetAnimation::MSheetAnimation(QObject* parent)
:MPositionAnimation(parent)
{
// From the UX specs
positionAnimation()->setDuration(350);
}
void MSheetAnimation::windowShown()
{
setEnabled(true);
targetWindow()->setOpacity(1.0);
bool portrait = targetWindow()->propertyCache()->orientationAngle() % 180;
positionAnimation()->setEasingCurve(QEasingCurve::OutExpo);
if (portrait) {
positionAnimation()->setStartValue(screen.topRight());
positionAnimation()->setEndValue(QPointF(0,0));
} else {
positionAnimation()->setStartValue(screen.bottomLeft());
positionAnimation()->setEndValue(QPointF(0,0));
}
animationGroup()->setDirection(QAbstractAnimation::Forward);
start();
}
void MSheetAnimation::windowClosed()
{
setEnabled(true);
positionAnimation()->setEasingCurve(QEasingCurve::InOutExpo);
animationGroup()->setDirection(QAbstractAnimation::Backward);
animationGroup()->start();
}
class MStatusBarCrop: public MCompositeWindowShaderEffect
{
Q_OBJECT
public:
MStatusBarCrop(QObject* parent)
:MCompositeWindowShaderEffect(parent),
appwindow(0),
portrait(false)
{
p_transform.rotate(90);
p_transform.translate(0, -screen.height());
p_transform = p_transform.inverted();
}
virtual void drawTexture(const QTransform &transform,
const QRectF &drawRect, qreal opacity)
{
const MStatusBarTexture *sbtex = MStatusBarTexture::instance();
QRectF draw_rect(drawRect);
if (appwindow && appwindow->propertyCache()
&& !appwindow->propertyCache()->statusbarGeometry().isEmpty()) {
// subtract statusbar
if (portrait)
draw_rect.setLeft(sbtex->portraitRect().height());
else
draw_rect.setTop(sbtex->landscapeRect().height());
}
// original texture with cropped statusbar
glBindTexture(GL_TEXTURE_2D, texture());
drawSource(transform, draw_rect, opacity, true);
// draw status bar texture
if (!portrait) {
glBindTexture(GL_TEXTURE_2D, sbtex->landscapeTexture());
drawSource(QTransform(),
sbtex->landscapeRect(), 1.0);
} else {
glBindTexture(GL_TEXTURE_2D, sbtex->portraitTexture());
drawSource(p_transform,
sbtex->portraitRect(), 1.0);
}
}
void setAppWindow(MCompositeWindow* a)
{
appwindow = a;
}
void setPortrait(bool p)
{
portrait = p;
}
private:
MCompositeWindow* appwindow;
QTransform p_transform;
bool portrait;
};
MChainedAnimation::MChainedAnimation(QObject* parent)
:MPositionAnimation(parent)
{
// UX subview specs
positionAnimation()->setDuration(500);
positionAnimation()->setEasingCurve(QEasingCurve::InOutExpo);
invoker_pos = new QPropertyAnimation(this);
invoker_pos->setPropertyName("pos");
invoker_pos->setEasingCurve(QEasingCurve::InOutExpo);
invoker_pos->setDuration(500);
animationGroup()->addAnimation(invoker_pos);
connect(animationGroup(), SIGNAL(finished()), SLOT(endAnimation()));
cropper = new MStatusBarCrop(this);
}
void MChainedAnimation::windowShown()
{
qDebug() << __func__;
setEnabled(true);
MStatusBarTexture::instance()->updatePixmap();
// sb geometry is shared by targetwindow and invokerwindow
cropper->setAppWindow(targetWindow());
cropper->installEffect(targetWindow());
cropper->installEffect(invokerWindow());
targetWindow()->setOpacity(1.0);
invokerWindow()->setVisible(true);
invoker_pos->setTargetObject(invokerWindow());
bool portrait = targetWindow()->propertyCache()->orientationAngle() % 180;
cropper->setPortrait(portrait);
if (portrait) {
positionAnimation()->setStartValue(screen.translated(0,-screen.height())
.topLeft());
positionAnimation()->setEndValue(QPointF(0,0));
invoker_pos->setStartValue(QPointF(0,0));
invoker_pos->setEndValue(screen.bottomLeft());
} else {
positionAnimation()->setStartValue(screen.topRight());
positionAnimation()->setEndValue(QPointF(0,0));
invoker_pos->setStartValue(QPointF(0,0));
invoker_pos->setEndValue(screen.translated(0,-screen.width())
.topLeft());
}
animationGroup()->setDirection(QAbstractAnimation::Forward);
start();
}
void MChainedAnimation::windowClosed()
{
qDebug() << __func__;
setEnabled(true);
MStatusBarTexture::instance()->updatePixmap();
cropper->setAppWindow(targetWindow());
cropper->installEffect(targetWindow());
cropper->installEffect(invokerWindow());
invokerWindow()->setVisible(true);
invoker_pos->setTargetObject(invokerWindow());
animationGroup()->setDirection(QAbstractAnimation::Backward);
animationGroup()->start();
}
MCompositeWindow* MChainedAnimation::invokerWindow()
{
if (targetWindow()->propertyCache()->invokedBy() != None)
return MCompositeWindow::compositeWindow(targetWindow()->propertyCache()->invokedBy());
return 0;
}
void MChainedAnimation::endAnimation()
{
cropper->removeEffect(targetWindow());
cropper->removeEffect(invokerWindow());
MStatusBarTexture::instance()->untrackDamages();
}
#include "mpositionanimation.moc"
<commit_msg>remove qDebugs introduced by ad01c67c3b6e3<commit_after>/***************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of mcompositor.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include <QPropertyAnimation>
#include <QParallelAnimationGroup>
#include <QPointF>
#include <QtDebug>
#include <mcompositewindow.h>
#include <mcompositewindowshadereffect.h>
#include <mstatusbartexture.h>
#include "mpositionanimation.h"
static QRectF screen;
MPositionAnimation::MPositionAnimation(QObject* parent)
:MCompositeWindowAnimation(parent)
{
setReplaceable(false);
// only use the position animation
animationGroup()->removeAnimation(scaleAnimation());
animationGroup()->removeAnimation(opacityAnimation());
position = positionAnimation();
if (screen.isEmpty())
screen = QApplication::desktop()->availableGeometry();
}
MPositionAnimation::~MPositionAnimation()
{
// don't delete externally referenced animation objects
for (int i = 0; i < animationGroup()->animationCount(); ++i)
if (animationGroup()->animationAt(i) != position)
animationGroup()->takeAnimation(i);
}
void MPositionAnimation::setEnabled(bool enabled)
{
if (enabled && (animationGroup()->indexOfAnimation(position) == -1))
animationGroup()->addAnimation(position);
else if (!enabled) {
animationGroup()->stop();
animationGroup()->removeAnimation(position);
}
}
MSheetAnimation::MSheetAnimation(QObject* parent)
:MPositionAnimation(parent)
{
// From the UX specs
positionAnimation()->setDuration(350);
}
void MSheetAnimation::windowShown()
{
setEnabled(true);
targetWindow()->setOpacity(1.0);
bool portrait = targetWindow()->propertyCache()->orientationAngle() % 180;
positionAnimation()->setEasingCurve(QEasingCurve::OutExpo);
if (portrait) {
positionAnimation()->setStartValue(screen.topRight());
positionAnimation()->setEndValue(QPointF(0,0));
} else {
positionAnimation()->setStartValue(screen.bottomLeft());
positionAnimation()->setEndValue(QPointF(0,0));
}
animationGroup()->setDirection(QAbstractAnimation::Forward);
start();
}
void MSheetAnimation::windowClosed()
{
setEnabled(true);
positionAnimation()->setEasingCurve(QEasingCurve::InOutExpo);
animationGroup()->setDirection(QAbstractAnimation::Backward);
animationGroup()->start();
}
class MStatusBarCrop: public MCompositeWindowShaderEffect
{
Q_OBJECT
public:
MStatusBarCrop(QObject* parent)
:MCompositeWindowShaderEffect(parent),
appwindow(0),
portrait(false)
{
p_transform.rotate(90);
p_transform.translate(0, -screen.height());
p_transform = p_transform.inverted();
}
virtual void drawTexture(const QTransform &transform,
const QRectF &drawRect, qreal opacity)
{
const MStatusBarTexture *sbtex = MStatusBarTexture::instance();
QRectF draw_rect(drawRect);
if (appwindow && appwindow->propertyCache()
&& !appwindow->propertyCache()->statusbarGeometry().isEmpty()) {
// subtract statusbar
if (portrait)
draw_rect.setLeft(sbtex->portraitRect().height());
else
draw_rect.setTop(sbtex->landscapeRect().height());
}
// original texture with cropped statusbar
glBindTexture(GL_TEXTURE_2D, texture());
drawSource(transform, draw_rect, opacity, true);
// draw status bar texture
if (!portrait) {
glBindTexture(GL_TEXTURE_2D, sbtex->landscapeTexture());
drawSource(QTransform(),
sbtex->landscapeRect(), 1.0);
} else {
glBindTexture(GL_TEXTURE_2D, sbtex->portraitTexture());
drawSource(p_transform,
sbtex->portraitRect(), 1.0);
}
}
void setAppWindow(MCompositeWindow* a)
{
appwindow = a;
}
void setPortrait(bool p)
{
portrait = p;
}
private:
MCompositeWindow* appwindow;
QTransform p_transform;
bool portrait;
};
MChainedAnimation::MChainedAnimation(QObject* parent)
:MPositionAnimation(parent)
{
// UX subview specs
positionAnimation()->setDuration(500);
positionAnimation()->setEasingCurve(QEasingCurve::InOutExpo);
invoker_pos = new QPropertyAnimation(this);
invoker_pos->setPropertyName("pos");
invoker_pos->setEasingCurve(QEasingCurve::InOutExpo);
invoker_pos->setDuration(500);
animationGroup()->addAnimation(invoker_pos);
connect(animationGroup(), SIGNAL(finished()), SLOT(endAnimation()));
cropper = new MStatusBarCrop(this);
}
void MChainedAnimation::windowShown()
{
setEnabled(true);
MStatusBarTexture::instance()->updatePixmap();
// sb geometry is shared by targetwindow and invokerwindow
cropper->setAppWindow(targetWindow());
cropper->installEffect(targetWindow());
cropper->installEffect(invokerWindow());
targetWindow()->setOpacity(1.0);
invokerWindow()->setVisible(true);
invoker_pos->setTargetObject(invokerWindow());
bool portrait = targetWindow()->propertyCache()->orientationAngle() % 180;
cropper->setPortrait(portrait);
if (portrait) {
positionAnimation()->setStartValue(screen.translated(0,-screen.height())
.topLeft());
positionAnimation()->setEndValue(QPointF(0,0));
invoker_pos->setStartValue(QPointF(0,0));
invoker_pos->setEndValue(screen.bottomLeft());
} else {
positionAnimation()->setStartValue(screen.topRight());
positionAnimation()->setEndValue(QPointF(0,0));
invoker_pos->setStartValue(QPointF(0,0));
invoker_pos->setEndValue(screen.translated(0,-screen.width())
.topLeft());
}
animationGroup()->setDirection(QAbstractAnimation::Forward);
start();
}
void MChainedAnimation::windowClosed()
{
setEnabled(true);
MStatusBarTexture::instance()->updatePixmap();
cropper->setAppWindow(targetWindow());
cropper->installEffect(targetWindow());
cropper->installEffect(invokerWindow());
invokerWindow()->setVisible(true);
invoker_pos->setTargetObject(invokerWindow());
animationGroup()->setDirection(QAbstractAnimation::Backward);
animationGroup()->start();
}
MCompositeWindow* MChainedAnimation::invokerWindow()
{
if (targetWindow()->propertyCache()->invokedBy() != None)
return MCompositeWindow::compositeWindow(targetWindow()->propertyCache()->invokedBy());
return 0;
}
void MChainedAnimation::endAnimation()
{
cropper->removeEffect(targetWindow());
cropper->removeEffect(invokerWindow());
MStatusBarTexture::instance()->untrackDamages();
}
#include "mpositionanimation.moc"
<|endoftext|>
|
<commit_before>#include "GramsDisplay.h"
GramsDisplay::GramsDisplay(uint8_t pin_clk, uint8_t pin_dio)
: SevenSegmentTM1637(pin_clk, pin_dio)
{
init();
setBacklight(100);
}
void GramsDisplay::display(float grams)
{
if (tooLargeToDisplay(grams))
print("----");
else
printGrams(grams);
}
bool GramsDisplay::tooLargeToDisplay(float grams)
{
return (grams >= 10000 || grams <= -1000);
}
void GramsDisplay::printGrams(float grams)
{
static char string_buffer[NUM_DIGITS + 1];
static uint8_t display_buffer[NUM_DIGITS];
const auto show_decigrams = shouldShowDecigrams(grams);
createDisplayString(string_buffer, show_decigrams, grams);
addLeadingZeroIfNeeded(string_buffer, show_decigrams, grams);
addMinusSignIfNeeded(string_buffer, grams);
encode(display_buffer, string_buffer, NUM_DIGITS);
addDecimalPointIfNeeded(display_buffer, show_decigrams);
printRaw(display_buffer);
}
bool GramsDisplay::shouldShowDecigrams(float grams)
{
return (grams > -100 && grams < 1000);
}
void GramsDisplay::createDisplayString(char* buffer, bool show_decigrams,
float grams)
{
const long display_value =
lroundf(abs(show_decigrams ? grams * 10 : grams));
sprintf(buffer, "%4li", display_value);
}
void GramsDisplay::addLeadingZeroIfNeeded(char* buffer, bool show_decigrams,
float grams)
{
const auto need_leading_zero = show_decigrams && abs(grams) < 1.0;
if (need_leading_zero)
buffer[2] = '0';
}
void GramsDisplay::addMinusSignIfNeeded(char* buffer, float grams)
{
const auto is_negative = grams < 0;
if (is_negative)
buffer[0] = '-';
}
void GramsDisplay::addDecimalPointIfNeeded(uint8_t* buffer, bool show_decigrams)
{
if (show_decigrams)
buffer[2] += DECIMAL_POINT;
}
<commit_msg>Remove unnecessary parens<commit_after>#include "GramsDisplay.h"
GramsDisplay::GramsDisplay(uint8_t pin_clk, uint8_t pin_dio)
: SevenSegmentTM1637(pin_clk, pin_dio)
{
init();
setBacklight(100);
}
void GramsDisplay::display(float grams)
{
if (tooLargeToDisplay(grams))
print("----");
else
printGrams(grams);
}
bool GramsDisplay::tooLargeToDisplay(float grams)
{
return (grams >= 10000 || grams <= -1000);
}
void GramsDisplay::printGrams(float grams)
{
static char string_buffer[NUM_DIGITS + 1];
static uint8_t display_buffer[NUM_DIGITS];
const auto show_decigrams = shouldShowDecigrams(grams);
createDisplayString(string_buffer, show_decigrams, grams);
addLeadingZeroIfNeeded(string_buffer, show_decigrams, grams);
addMinusSignIfNeeded(string_buffer, grams);
encode(display_buffer, string_buffer, NUM_DIGITS);
addDecimalPointIfNeeded(display_buffer, show_decigrams);
printRaw(display_buffer);
}
bool GramsDisplay::shouldShowDecigrams(float grams)
{
return grams > -100 && grams < 1000;
}
void GramsDisplay::createDisplayString(char* buffer, bool show_decigrams,
float grams)
{
const long display_value =
lroundf(abs(show_decigrams ? grams * 10 : grams));
sprintf(buffer, "%4li", display_value);
}
void GramsDisplay::addLeadingZeroIfNeeded(char* buffer, bool show_decigrams,
float grams)
{
const auto need_leading_zero = show_decigrams && abs(grams) < 1.0;
if (need_leading_zero)
buffer[2] = '0';
}
void GramsDisplay::addMinusSignIfNeeded(char* buffer, float grams)
{
const auto is_negative = grams < 0;
if (is_negative)
buffer[0] = '-';
}
void GramsDisplay::addDecimalPointIfNeeded(uint8_t* buffer, bool show_decigrams)
{
if (show_decigrams)
buffer[2] += DECIMAL_POINT;
}
<|endoftext|>
|
<commit_before>#include "download.h"
Download *Download::self = 0;
Download *Download::instance() {
if(!self)
self = new Download();
return self;
}
QString Download::getError() {
return error;
}
void Download::onTimer() {
if (isReady) {
if (!queue -> isEmpty()) {
isReady = false;
ModelItem * item = queue -> takeFirst();
item -> setDownloadProgress(0);
QNetworkReply * m_http = manager() -> get(QNetworkRequest(item -> toUrl()));
DownloadPosition * pos = downloads -> take(item);
downloads -> insert(m_http, pos);
QObject::connect(m_http, SIGNAL(finished()), this, SLOT(downloadConnectionResponsed()));
emit slotChanged("( Last " + QString::number(queue -> count()) + ") " + item -> data(TITLEID).toString());
} else {
emit slotChanged("(O_o)");
}
}
}
void Download::finishDownload() {
// QFutureWatcher<QNetworkReply *> * curr = (QFutureWatcher<QNetworkReply *>)sender();
delete downloader -> result();
isReady = true;
delete downloader;
downloader = 0;
}
void Download::start(Model * model, ModelItem * item, QUrl savePath) {
queue -> append(item);
downloads -> insert(item, new DownloadPosition(model, item, savePath));
}
void Download::downloadConnectionResponsed() {
QNetworkReply * reply = (QNetworkReply*)QObject::sender();
downloader = new QFutureWatcher<QNetworkReply *>();
connect(downloader, SIGNAL(finished()), this, SLOT(finishDownload()));
downloader -> setFuture(QtConcurrent::run(this, &Download::downloading, reply));
}
QNetworkReply * Download::downloading(QNetworkReply * reply) {
DownloadPosition * position = downloads -> value(reply);
QObject::connect(this, SIGNAL(downloadFinished(ModelItem *, bool)), position -> model, SLOT(itemDownloadFinished(ModelItem *, bool)));
QObject::connect(this, SIGNAL(downloadProgress(ModelItem *, int)), position -> model, SLOT(itemDownloadProgress(ModelItem *, int)));
QFile file(position -> savePath.toLocalFile());
// QIODevice::Append | QIODevice::Unbuffered
if (!file.open(QIODevice::WriteOnly)) {
emit downloadError(position -> item, file.errorString());
emit downloadFinished(position -> item, false);
} else {
if (!file.resize(reply -> bytesAvailable())) {
emit downloadError(position -> item, file.errorString());
emit downloadFinished(position -> item, false);
} else {
QByteArray buffer;
qint64 pos = 0;
double limit = reply -> bytesAvailable();
int bufferLength = 1024 * 1024 * 1; //1 mb
while(!reply -> atEnd()) {
try {
buffer = reply -> read(bufferLength);
pos += buffer.length();
file.write(buffer);
progress = (pos/limit) * 100;
emit downloadProgress(position -> item, progress);
}
catch(...) {
emit downloadError(position -> item, "Some error occured while download...");
emit downloadFinished(position -> item, false);
}
}
file.close();
reply -> close();
emit downloadFinished(position -> item, true);
}
}
QObject::disconnect(this, SIGNAL(downloadFinished(ModelItem *, bool)), position -> model, SLOT(itemDownloadFinished(ModelItem *, bool)));
QObject::disconnect(this, SIGNAL(downloadProgress(ModelItem *, int)), position -> model, SLOT(itemDownloadProgress(ModelItem *, int)));
return reply;
}
CustomNetworkAccessManager * Download::manager() const {
return netManager;
}
int Download::getProgress() const {
return progress;
}
int Download::getQueueLength() const {
return queue -> count();
}
<commit_msg>update message<commit_after>#include "download.h"
Download *Download::self = 0;
Download *Download::instance() {
if(!self)
self = new Download();
return self;
}
QString Download::getError() {
return error;
}
void Download::onTimer() {
if (isReady) {
if (!queue -> isEmpty()) {
isReady = false;
ModelItem * item = queue -> takeFirst();
item -> setDownloadProgress(0);
QNetworkReply * m_http = manager() -> get(QNetworkRequest(item -> toUrl()));
DownloadPosition * pos = downloads -> take(item);
downloads -> insert(m_http, pos);
QObject::connect(m_http, SIGNAL(finished()), this, SLOT(downloadConnectionResponsed()));
emit slotChanged("(Downloads remain: " + QString::number(queue -> count()) + ") " + item -> data(TITLEID).toString());
} else {
emit slotChanged("(O_o)");
}
}
}
void Download::finishDownload() {
// QFutureWatcher<QNetworkReply *> * curr = (QFutureWatcher<QNetworkReply *>)sender();
delete downloader -> result();
isReady = true;
delete downloader;
downloader = 0;
}
void Download::start(Model * model, ModelItem * item, QUrl savePath) {
queue -> append(item);
downloads -> insert(item, new DownloadPosition(model, item, savePath));
}
void Download::downloadConnectionResponsed() {
QNetworkReply * reply = (QNetworkReply*)QObject::sender();
downloader = new QFutureWatcher<QNetworkReply *>();
connect(downloader, SIGNAL(finished()), this, SLOT(finishDownload()));
downloader -> setFuture(QtConcurrent::run(this, &Download::downloading, reply));
}
QNetworkReply * Download::downloading(QNetworkReply * reply) {
DownloadPosition * position = downloads -> value(reply);
QObject::connect(this, SIGNAL(downloadFinished(ModelItem *, bool)), position -> model, SLOT(itemDownloadFinished(ModelItem *, bool)));
QObject::connect(this, SIGNAL(downloadProgress(ModelItem *, int)), position -> model, SLOT(itemDownloadProgress(ModelItem *, int)));
QFile file(position -> savePath.toLocalFile());
// QIODevice::Append | QIODevice::Unbuffered
if (!file.open(QIODevice::WriteOnly)) {
emit downloadError(position -> item, file.errorString());
emit downloadFinished(position -> item, false);
} else {
if (!file.resize(reply -> bytesAvailable())) {
emit downloadError(position -> item, file.errorString());
emit downloadFinished(position -> item, false);
} else {
QByteArray buffer;
qint64 pos = 0;
double limit = reply -> bytesAvailable();
int bufferLength = 1024 * 1024 * 1; //1 mb
while(!reply -> atEnd()) {
try {
buffer = reply -> read(bufferLength);
pos += buffer.length();
file.write(buffer);
progress = (pos/limit) * 100;
emit downloadProgress(position -> item, progress);
}
catch(...) {
emit downloadError(position -> item, "Some error occured while download...");
emit downloadFinished(position -> item, false);
}
}
file.close();
reply -> close();
emit downloadFinished(position -> item, true);
}
}
QObject::disconnect(this, SIGNAL(downloadFinished(ModelItem *, bool)), position -> model, SLOT(itemDownloadFinished(ModelItem *, bool)));
QObject::disconnect(this, SIGNAL(downloadProgress(ModelItem *, int)), position -> model, SLOT(itemDownloadProgress(ModelItem *, int)));
return reply;
}
CustomNetworkAccessManager * Download::manager() const {
return netManager;
}
int Download::getProgress() const {
return progress;
}
int Download::getQueueLength() const {
return queue -> count();
}
<|endoftext|>
|
<commit_before>/**
** \file object/system-class.cc
** \brief Creation of the URBI object system.
*/
//#define ENABLE_DEBUG_TRACES
#include <libport/compiler.hh>
#include "parser/uparser.hh"
#include "kernel/userver.hh"
#include "kernel/uconnection.hh"
#include "runner/runner.hh"
#include "object/alien.hh"
#include "object/system-class.hh"
namespace object
{
rObject system_class;
/*--------------------.
| System primitives. |
`--------------------*/
#define SERVER_FUNCTION(Function) \
static rObject \
system_class_ ## Function (runner::Runner&, objects_type args) \
{ \
CHECK_ARG_COUNT (1); \
::urbiserver->Function(); \
return void_class; \
}
SERVER_FUNCTION(reboot)
SERVER_FUNCTION(shutdown)
#undef SERVER_FUNCTION
static rObject
system_class_sleep (runner::Runner& r, objects_type args)
{
CHECK_ARG_COUNT (2);
FETCH_ARG(1, Float);
libport::utime_t deadline =
::urbiserver->getTime() +
static_cast<libport::utime_t>(arg1->value_get() * 1000.0);
r.yield_until (deadline);
return void_class;
}
static rObject
system_class_time (runner::Runner&, objects_type)
{
return Float::fresh(::urbiserver->getTime() / 1000.0);
}
static rObject
execute_parsed (runner::Runner& r, parser::UParser& p, UrbiException e)
{
ast::Nary errs;
p.process_errors(&errs);
errs.accept(r);
if (ast::Nary* ast = p.ast_get())
{
ast->accept(r);
//FIXME: deleting the tree now causes segv.
//delete p.command_tree_get();
//p.command_tree_set (0);
return r.current_get();
}
else
throw e;
}
static rObject
system_class_assert_(runner::Runner&, objects_type args)
{
CHECK_ARG_COUNT(3);
FETCH_ARG(2, String);
if (!IS_TRUE(args[1]))
throw PrimitiveError
("assert_",
"assertion `" + arg2->value_get().name_get() + "' failed");
return void_class;
}
static rObject
system_class_eval (runner::Runner& r, objects_type args)
{
FETCH_ARG(1, String);
parser::UParser p;
p.parse(arg1->value_get());
return execute_parsed(r, p, PrimitiveError("",
std::string("Error executing command.")));
}
static rObject
system_class_searchFile (runner::Runner& r, objects_type args)
{
CHECK_ARG_COUNT (2);
FETCH_ARG(1, String);
UServer& s = r.lobby_get()->value_get().connection.server_get();
try
{
return String::fresh(libport::Symbol(
s.find_file(arg1->value_get ().name_get ())));
}
catch (libport::file_library::Not_found&)
{
throw
PrimitiveError("searchFile",
"Unable to find file: "
+ arg1->value_get().name_get());
// Never reached
assertion(false);
return 0;
}
}
static rObject
system_class_loadFile (runner::Runner& r, objects_type args)
{
CHECK_ARG_COUNT (2);
FETCH_ARG(1, String);
std::string filename = arg1->value_get().name_get();
if (!libport::path (filename).exists ())
throw PrimitiveError("loadFile",
"No such file: " + filename);
parser::UParser p;
p.parse_file(arg1->value_get());
return
execute_parsed(r, p,
PrimitiveError("", //same message than k1
"Error loading file: " + filename));
}
static rObject
system_class_currentRunner (runner::Runner& r, objects_type args)
{
CHECK_ARG_COUNT (1);
rObject res = object::Object::fresh();
res->proto_add (task_class);
res->slot_set (SYMBOL (runner), box (scheduler::rJob, r.myself_get ()));
return res;
}
static rObject
system_class_cycle (runner::Runner& r, objects_type args)
{
CHECK_ARG_COUNT (1);
return Float::fresh (r.scheduler_get ().cycle_get ());
}
static rObject
system_class_fresh (runner::Runner&, objects_type args)
{
CHECK_ARG_COUNT (1);
return String::fresh(libport::Symbol::fresh());
}
static rObject
system_class_lobby (runner::Runner& r, objects_type args)
{
CHECK_ARG_COUNT (1);
return r.lobby_get();
}
static rObject
system_class_quit (runner::Runner& r, objects_type args)
{
CHECK_ARG_COUNT (1);
r.lobby_get()->value_get().connection.close();
return void_class;
}
#define SERVER_SET_VAR(Function, Variable, Value) \
static rObject \
system_class_ ## Function (runner::Runner&, objects_type args) \
{ \
CHECK_ARG_COUNT (1); \
::urbiserver->Variable = Value; \
return void_class; \
}
SERVER_SET_VAR(debugoff, debugOutput, false)
SERVER_SET_VAR(debugon, debugOutput, true)
SERVER_SET_VAR(stopall, stopall, true)
#undef SERVER_SET_VAR
void
system_class_initialize ()
{
/// \a Call gives the name of the C++ function, and \a Name that in Urbi.
#define DECLARE(Name) \
DECLARE_PRIMITIVE(system, Name)
DECLARE(assert_);
DECLARE(currentRunner);
DECLARE(cycle);
DECLARE(debugoff);
DECLARE(debugon);
DECLARE(eval);
DECLARE(fresh);
DECLARE(loadFile);
DECLARE(lobby);
DECLARE(quit);
DECLARE(reboot);
DECLARE(searchFile);
DECLARE(shutdown);
DECLARE(sleep);
DECLARE(stopall);
DECLARE(time);
#undef DECLARE
}
}; // namespace object
<commit_msg>Use namespace-level parsing functions.<commit_after>/**
** \file object/system-class.cc
** \brief Creation of the URBI object system.
*/
//#define ENABLE_DEBUG_TRACES
#include <libport/compiler.hh>
#include "parser/uparser.hh"
#include "kernel/userver.hh"
#include "kernel/uconnection.hh"
#include "runner/runner.hh"
#include "object/alien.hh"
#include "object/system-class.hh"
namespace object
{
rObject system_class;
/*--------------------.
| System primitives. |
`--------------------*/
#define SERVER_FUNCTION(Function) \
static rObject \
system_class_ ## Function (runner::Runner&, objects_type args) \
{ \
CHECK_ARG_COUNT (1); \
::urbiserver->Function(); \
return void_class; \
}
SERVER_FUNCTION(reboot)
SERVER_FUNCTION(shutdown)
#undef SERVER_FUNCTION
static rObject
system_class_sleep (runner::Runner& r, objects_type args)
{
CHECK_ARG_COUNT (2);
FETCH_ARG(1, Float);
libport::utime_t deadline =
::urbiserver->getTime() +
static_cast<libport::utime_t>(arg1->value_get() * 1000.0);
r.yield_until (deadline);
return void_class;
}
static rObject
system_class_time (runner::Runner&, objects_type)
{
return Float::fresh(::urbiserver->getTime() / 1000.0);
}
static rObject
execute_parsed (runner::Runner& r, parser::UParser& p, UrbiException e)
{
ast::Nary errs;
p.process_errors(&errs);
errs.accept(r);
if (ast::Nary* ast = p.ast_get())
{
ast->accept(r);
//FIXME: deleting the tree now causes segv.
//delete p.command_tree_get();
//p.command_tree_set (0);
return r.current_get();
}
else
throw e;
}
static rObject
system_class_assert_(runner::Runner&, objects_type args)
{
CHECK_ARG_COUNT(3);
FETCH_ARG(2, String);
if (!IS_TRUE(args[1]))
throw PrimitiveError
("assert_",
"assertion `" + arg2->value_get().name_get() + "' failed");
return void_class;
}
static rObject
system_class_eval (runner::Runner& r, objects_type args)
{
FETCH_ARG(1, String);
parser::UParser p = parser::parse(arg1->value_get());
return execute_parsed(r, p, PrimitiveError("",
std::string("Error executing command.")));
}
static rObject
system_class_searchFile (runner::Runner& r, objects_type args)
{
CHECK_ARG_COUNT (2);
FETCH_ARG(1, String);
UServer& s = r.lobby_get()->value_get().connection.server_get();
try
{
return String::fresh(libport::Symbol(
s.find_file(arg1->value_get ().name_get ())));
}
catch (libport::file_library::Not_found&)
{
throw
PrimitiveError("searchFile",
"Unable to find file: "
+ arg1->value_get().name_get());
// Never reached
assertion(false);
return 0;
}
}
static rObject
system_class_loadFile (runner::Runner& r, objects_type args)
{
CHECK_ARG_COUNT (2);
FETCH_ARG(1, String);
std::string filename = arg1->value_get().name_get();
if (!libport::path (filename).exists ())
throw PrimitiveError("loadFile",
"No such file: " + filename);
parser::UParser p = parser::parse_file(filename);
return
execute_parsed(r, p,
PrimitiveError("", //same message than k1
"Error loading file: " + filename));
}
static rObject
system_class_currentRunner (runner::Runner& r, objects_type args)
{
CHECK_ARG_COUNT (1);
rObject res = object::Object::fresh();
res->proto_add (task_class);
res->slot_set (SYMBOL (runner), box (scheduler::rJob, r.myself_get ()));
return res;
}
static rObject
system_class_cycle (runner::Runner& r, objects_type args)
{
CHECK_ARG_COUNT (1);
return Float::fresh (r.scheduler_get ().cycle_get ());
}
static rObject
system_class_fresh (runner::Runner&, objects_type args)
{
CHECK_ARG_COUNT (1);
return String::fresh(libport::Symbol::fresh());
}
static rObject
system_class_lobby (runner::Runner& r, objects_type args)
{
CHECK_ARG_COUNT (1);
return r.lobby_get();
}
static rObject
system_class_quit (runner::Runner& r, objects_type args)
{
CHECK_ARG_COUNT (1);
r.lobby_get()->value_get().connection.close();
return void_class;
}
#define SERVER_SET_VAR(Function, Variable, Value) \
static rObject \
system_class_ ## Function (runner::Runner&, objects_type args) \
{ \
CHECK_ARG_COUNT (1); \
::urbiserver->Variable = Value; \
return void_class; \
}
SERVER_SET_VAR(debugoff, debugOutput, false)
SERVER_SET_VAR(debugon, debugOutput, true)
SERVER_SET_VAR(stopall, stopall, true)
#undef SERVER_SET_VAR
void
system_class_initialize ()
{
/// \a Call gives the name of the C++ function, and \a Name that in Urbi.
#define DECLARE(Name) \
DECLARE_PRIMITIVE(system, Name)
DECLARE(assert_);
DECLARE(currentRunner);
DECLARE(cycle);
DECLARE(debugoff);
DECLARE(debugon);
DECLARE(eval);
DECLARE(fresh);
DECLARE(loadFile);
DECLARE(lobby);
DECLARE(quit);
DECLARE(reboot);
DECLARE(searchFile);
DECLARE(shutdown);
DECLARE(sleep);
DECLARE(stopall);
DECLARE(time);
#undef DECLARE
}
}; // namespace object
<|endoftext|>
|
<commit_before>#include <QDebug>
#include "tangramwidget.h"
#include <tangram.h>
#include <curl/curl.h>
#include <cstdlib>
#include <QOpenGLContext>
#include <QOpenGLFunctions>
#include "platform_qt.h"
#include <GL/gl.h>
#include <GL/glx.h>
#include <QRunnable>
PFNGLBINDVERTEXARRAYPROC glBindVertexArrayOESEXT = 0;
PFNGLDELETEVERTEXARRAYSPROC glDeleteVertexArraysOESEXT = 0;
PFNGLGENVERTEXARRAYSPROC glGenVertexArraysOESEXT = 0;
TangramWidget::TangramWidget(QWidget *parent)
: QOpenGLWidget(parent)
, m_sceneFile("scene.yaml")
, m_lastMousePos(-1, -1)
{
// Initialize cURL
curl_global_init(CURL_GLOBAL_DEFAULT);
grabGesture(Qt::PanGesture);
}
TangramWidget::~TangramWidget()
{
curl_global_cleanup();
}
void TangramWidget::initializeGL()
{
qDebug() << Q_FUNC_INFO << ".--------------";
glBindVertexArrayOESEXT = (PFNGLBINDVERTEXARRAYPROC)context()->getProcAddress("glBindVertexArray");
glDeleteVertexArraysOESEXT = (PFNGLDELETEVERTEXARRAYSPROC)context()->getProcAddress("glDeleteVertexArrays");
glGenVertexArraysOESEXT = (PFNGLGENVERTEXARRAYSPROC)context()->getProcAddress("glGenVertexArrays");
qDebug() << Q_FUNC_INFO << glBindVertexArrayOESEXT << glDeleteVertexArraysOESEXT << glGenVertexArraysOESEXT;
QOpenGLFunctions *f = QOpenGLContext::currentContext()->functions();
qDebug() << "Version:" << f->glGetString(GL_VERSION);
f->glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
Tangram::initialize(m_sceneFile.fileName().toStdString().c_str());
Tangram::setupGL();
Tangram::resize(width(),
height());
data_source = std::make_shared<Tangram::ClientGeoJsonSource>("touch", "");
Tangram::addDataSource(data_source);
}
void TangramWidget::paintGL()
{
QDateTime now = QDateTime::currentDateTime();
Tangram::update(1.f);
Tangram::render();
m_lastRendering = now;
}
void TangramWidget::resizeGL(int w, int h)
{
Tangram::resize(w,
h);
}
void TangramWidget::mousePressEvent(QMouseEvent *event)
{
Tangram::handlePanGesture(0.0f, 0.0f, 0.0f, 0.0f);
m_lastMousePos = event->pos();
}
void TangramWidget::mouseMoveEvent(QMouseEvent *event)
{
Tangram::handlePanGesture(m_lastMousePos.x(), m_lastMousePos.y(),
event->x(), event->y());
m_lastMousePos = event->pos();
}
void TangramWidget::grabGestures(const QList<Qt::GestureType> &gestures)
{
foreach (Qt::GestureType gesture, gestures)
grabGesture(gesture);
}
bool TangramWidget::event(QEvent *e)
{
if (e->type() == QEvent::Gesture)
return gestureEvent(static_cast<QGestureEvent*>(e));
else if (e->type() == QEvent::Wheel)
return mouseWheelEvent(static_cast<QWheelEvent*>(e));
else if (e->type() == TANGRAM_REQ_RENDER_EVENT_TYPE)
return renderRequestEvent();
return QWidget::event(e);
}
bool TangramWidget::renderRequestEvent()
{
qDebug() << Q_FUNC_INFO;
processNetworkQueue();
update();
return true;
}
bool TangramWidget::mouseWheelEvent(QWheelEvent *ev)
{
}
bool TangramWidget::gestureEvent(QGestureEvent *ev)
{
if (QGesture *swipe = ev->gesture(Qt::SwipeGesture))
swipeTriggered(static_cast<QSwipeGesture*>(swipe));
else if (QGesture *pan = ev->gesture(Qt::PanGesture))
panTriggered(static_cast<QPanGesture *>(pan));
if (QGesture *pinch = ev->gesture(Qt::PinchGesture))
pinchTriggered(static_cast<QPinchGesture *>(pinch));
return true;
}
void TangramWidget::panTriggered(QPanGesture *gesture)
{
#ifndef QT_NO_CURSOR
switch (gesture->state()) {
case Qt::GestureStarted:
case Qt::GestureUpdated:
setCursor(Qt::SizeAllCursor);
break;
default:
setCursor(Qt::ArrowCursor);
}
#endif
QPointF delta = gesture->delta();
qDebug() << "panTriggered():" << gesture;
horizontalOffset += delta.x();
verticalOffset += delta.y();
update();
}
void TangramWidget::pinchTriggered(QPinchGesture *gesture)
{
QPinchGesture::ChangeFlags changeFlags = gesture->changeFlags();
if (changeFlags & QPinchGesture::RotationAngleChanged) {
qreal rotationDelta = gesture->rotationAngle() - gesture->lastRotationAngle();
rotationAngle += rotationDelta;
qDebug() << "pinchTriggered(): rotate by" <<
rotationDelta << "->" << rotationAngle;
}
if (changeFlags & QPinchGesture::ScaleFactorChanged) {
currentStepScaleFactor = gesture->totalScaleFactor();
qDebug() << "pinchTriggered(): zoom by" <<
gesture->scaleFactor() << "->" << currentStepScaleFactor;
}
if (gesture->state() == Qt::GestureFinished) {
scaleFactor *= currentStepScaleFactor;
currentStepScaleFactor = 1;
}
update();
}
void TangramWidget::swipeTriggered(QSwipeGesture *gesture)
{
if (gesture->state() == Qt::GestureFinished) {
if (gesture->horizontalDirection() == QSwipeGesture::Left
|| gesture->verticalDirection() == QSwipeGesture::Up) {
qDebug() << "swipeTriggered(): swipe to previous";
} else {
qDebug() << "swipeTriggered(): swipe to next";
}
update();
}
}
class UrlRunner : public QRunnable
{
public:
UrlRunner(QUrl url, UrlCallback callback) {
m_url = url;
m_callback = callback;
}
void run() {
}
private:
QUrl m_url;
UrlCallback m_callback;
};
void TangramWidget::startUrlRequest(const std::__cxx11::string &url, UrlCallback callback)
{
}
void TangramWidget::cancelUrlRequest(const std::__cxx11::string &url)
{
}
void TangramWidget::handleCallback(UrlCallback callback)
{
}
<commit_msg>Add rotate, shov and zoom to scroll wheel events.<commit_after>#include <QDebug>
#include "tangramwidget.h"
#include <tangram.h>
#include <curl/curl.h>
#include <cstdlib>
#include <QOpenGLContext>
#include <QOpenGLFunctions>
#include "platform_qt.h"
#include <GL/gl.h>
#include <GL/glx.h>
#include <QRunnable>
PFNGLBINDVERTEXARRAYPROC glBindVertexArrayOESEXT = 0;
PFNGLDELETEVERTEXARRAYSPROC glDeleteVertexArraysOESEXT = 0;
PFNGLGENVERTEXARRAYSPROC glGenVertexArraysOESEXT = 0;
TangramWidget::TangramWidget(QWidget *parent)
: QOpenGLWidget(parent)
, m_sceneFile("scene.yaml")
, m_lastMousePos(-1, -1)
{
// Initialize cURL
curl_global_init(CURL_GLOBAL_DEFAULT);
grabGesture(Qt::PanGesture);
}
TangramWidget::~TangramWidget()
{
curl_global_cleanup();
}
void TangramWidget::initializeGL()
{
qDebug() << Q_FUNC_INFO << ".--------------";
glBindVertexArrayOESEXT = (PFNGLBINDVERTEXARRAYPROC)context()->getProcAddress("glBindVertexArray");
glDeleteVertexArraysOESEXT = (PFNGLDELETEVERTEXARRAYSPROC)context()->getProcAddress("glDeleteVertexArrays");
glGenVertexArraysOESEXT = (PFNGLGENVERTEXARRAYSPROC)context()->getProcAddress("glGenVertexArrays");
qDebug() << Q_FUNC_INFO << glBindVertexArrayOESEXT << glDeleteVertexArraysOESEXT << glGenVertexArraysOESEXT;
QOpenGLFunctions *f = QOpenGLContext::currentContext()->functions();
qDebug() << "Version:" << f->glGetString(GL_VERSION);
f->glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
Tangram::initialize(m_sceneFile.fileName().toStdString().c_str());
Tangram::setupGL();
Tangram::resize(width(),
height());
data_source = std::make_shared<Tangram::ClientGeoJsonSource>("touch", "");
Tangram::addDataSource(data_source);
}
void TangramWidget::paintGL()
{
QDateTime now = QDateTime::currentDateTime();
Tangram::update(1.f);
Tangram::render();
m_lastRendering = now;
}
void TangramWidget::resizeGL(int w, int h)
{
Tangram::resize(w,
h);
}
void TangramWidget::mousePressEvent(QMouseEvent *event)
{
Tangram::handlePanGesture(0.0f, 0.0f, 0.0f, 0.0f);
m_lastMousePos = event->pos();
}
void TangramWidget::mouseMoveEvent(QMouseEvent *event)
{
Tangram::handlePanGesture(m_lastMousePos.x(), m_lastMousePos.y(),
event->x(), event->y());
m_lastMousePos = event->pos();
}
void TangramWidget::grabGestures(const QList<Qt::GestureType> &gestures)
{
foreach (Qt::GestureType gesture, gestures)
grabGesture(gesture);
}
bool TangramWidget::event(QEvent *e)
{
if (e->type() == QEvent::Gesture)
return gestureEvent(static_cast<QGestureEvent*>(e));
else if (e->type() == QEvent::Wheel)
return mouseWheelEvent(static_cast<QWheelEvent*>(e));
else if (e->type() == TANGRAM_REQ_RENDER_EVENT_TYPE)
return renderRequestEvent();
return QWidget::event(e);
}
bool TangramWidget::renderRequestEvent()
{
processNetworkQueue();
update();
return true;
}
bool TangramWidget::mouseWheelEvent(QWheelEvent *ev)
{
double x = ev->posF().x();
double y = ev->posF().y();
if (ev->modifiers() & Qt::ControlModifier)
Tangram::handleShoveGesture(0.05 * ev->angleDelta().y());
else if (ev->modifiers() & Qt::AltModifier) {
Tangram::handleRotateGesture(x, y, 0.0005 * ev->angleDelta().y());
} else
Tangram::handlePinchGesture(x, y, 1.0 + 0.0005 * ev->angleDelta().y(), 0.f);
}
bool TangramWidget::gestureEvent(QGestureEvent *ev)
{
if (QGesture *swipe = ev->gesture(Qt::SwipeGesture))
swipeTriggered(static_cast<QSwipeGesture*>(swipe));
else if (QGesture *pan = ev->gesture(Qt::PanGesture))
panTriggered(static_cast<QPanGesture *>(pan));
if (QGesture *pinch = ev->gesture(Qt::PinchGesture))
pinchTriggered(static_cast<QPinchGesture *>(pinch));
return true;
}
void TangramWidget::panTriggered(QPanGesture *gesture)
{
#ifndef QT_NO_CURSOR
switch (gesture->state()) {
case Qt::GestureStarted:
case Qt::GestureUpdated:
setCursor(Qt::SizeAllCursor);
break;
default:
setCursor(Qt::ArrowCursor);
}
#endif
QPointF delta = gesture->delta();
qDebug() << "panTriggered():" << gesture;
horizontalOffset += delta.x();
verticalOffset += delta.y();
update();
}
void TangramWidget::pinchTriggered(QPinchGesture *gesture)
{
QPinchGesture::ChangeFlags changeFlags = gesture->changeFlags();
if (changeFlags & QPinchGesture::RotationAngleChanged) {
qreal rotationDelta = gesture->rotationAngle() - gesture->lastRotationAngle();
rotationAngle += rotationDelta;
qDebug() << "pinchTriggered(): rotate by" <<
rotationDelta << "->" << rotationAngle;
}
if (changeFlags & QPinchGesture::ScaleFactorChanged) {
currentStepScaleFactor = gesture->totalScaleFactor();
qDebug() << "pinchTriggered(): zoom by" <<
gesture->scaleFactor() << "->" << currentStepScaleFactor;
}
if (gesture->state() == Qt::GestureFinished) {
scaleFactor *= currentStepScaleFactor;
currentStepScaleFactor = 1;
}
update();
}
void TangramWidget::swipeTriggered(QSwipeGesture *gesture)
{
if (gesture->state() == Qt::GestureFinished) {
if (gesture->horizontalDirection() == QSwipeGesture::Left
|| gesture->verticalDirection() == QSwipeGesture::Up) {
qDebug() << "swipeTriggered(): swipe to previous";
} else {
qDebug() << "swipeTriggered(): swipe to next";
}
update();
}
}
class UrlRunner : public QRunnable
{
public:
UrlRunner(QUrl url, UrlCallback callback) {
m_url = url;
m_callback = callback;
}
void run() {
}
private:
QUrl m_url;
UrlCallback m_callback;
};
void TangramWidget::startUrlRequest(const std::__cxx11::string &url, UrlCallback callback)
{
}
void TangramWidget::cancelUrlRequest(const std::__cxx11::string &url)
{
}
void TangramWidget::handleCallback(UrlCallback callback)
{
}
<|endoftext|>
|
<commit_before>//******************************************************************************************************
// CompactMeasurementParser.cpp - Gbtc
//
// Copyright 2018, Grid Protection Alliance. All Rights Reserved.
//
// Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
// the NOTICE file distributed with this work for additional information regarding copyright ownership.
// The GPA licenses this file to you under the MIT License (MIT), the "License"; you may not use this
// file except in compliance with the License. You may obtain a copy of the License at:
//
// http://opensource.org/licenses/MIT
//
// Unless agreed to in writing, the subject software distributed under the License is distributed on an
// "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
// License for the specific language governing permissions and limitations.
//
// Code Modification History:
// ----------------------------------------------------------------------------------------------------
// 03/09/2012 - Stephen C. Wills
// Generated original version of source code.
//
//******************************************************************************************************
#include "CompactMeasurement.h"
#include "../Common/EndianConverter.h"
using namespace std;
using namespace GSF::TimeSeries;
using namespace GSF::TimeSeries::Transport;
// These constants represent each flag in the 8-bit compact measurement state flags.
static const uint8_t CompactDataRangeFlag = 0x01;
static const uint8_t CompactDataQualityFlag = 0x02;
static const uint8_t CompactTimeQualityFlag = 0x04;
static const uint8_t CompactSystemIssueFlag = 0x08;
static const uint8_t CompactCalculatedValueFlag = 0x10;
static const uint8_t CompactDiscardedValueFlag = 0x20;
static const uint8_t CompactBaseTimeOffsetFlag = 0x40;
static const uint8_t CompactTimeIndexFlag = 0x80;
// These constants are masks used to set flags within the full 32-bit measurement state flags.
static const uint32_t DataRangeMask = 0x000000FC;
static const uint32_t DataQualityMask = 0x0000EF03;
static const uint32_t TimeQualityMask = 0x00BF0000;
static const uint32_t SystemIssueMask = 0xE0000000;
static const uint32_t CalculatedValueMask = 0x00001000;
static const uint32_t DiscardedValueMask = 0x00400000;
// Takes the 8-bit compact measurement flags and maps
// them to the full 32-bit measurement flags format.
inline uint32_t MapToFullFlags(uint8_t compactFlags)
{
uint32_t fullFlags = 0U;
if ((compactFlags & CompactDataRangeFlag) > 0)
fullFlags |= DataRangeMask;
if ((compactFlags & CompactDataQualityFlag) > 0)
fullFlags |= DataQualityMask;
if ((compactFlags & CompactTimeQualityFlag) > 0)
fullFlags |= TimeQualityMask;
if ((compactFlags & CompactSystemIssueFlag) > 0)
fullFlags |= SystemIssueMask;
if ((compactFlags & CompactCalculatedValueFlag) > 0)
fullFlags |= CalculatedValueMask;
if ((compactFlags & CompactDiscardedValueFlag) > 0)
fullFlags |= DiscardedValueMask;
return fullFlags;
}
// Takes the full 32-bit measurement flags format and
// maps them to the 8-bit compact measurement flags.
inline uint32_t MapToCompactFlags(uint32_t fullFlags)
{
uint32_t compactFlags = 0U;
if ((fullFlags & DataRangeMask) > 0)
compactFlags |= CompactDataRangeFlag;
if ((fullFlags & DataQualityMask) > 0)
compactFlags |= CompactDataQualityFlag;
if ((fullFlags & TimeQualityMask) > 0)
compactFlags |= CompactTimeQualityFlag;
if ((fullFlags & SystemIssueMask) > 0)
compactFlags |= CompactSystemIssueFlag;
if ((fullFlags & CalculatedValueMask) > 0)
compactFlags |= CompactCalculatedValueFlag;
if ((fullFlags & DiscardedValueMask) > 0)
compactFlags |= CompactDiscardedValueFlag;
return compactFlags;
}
CompactMeasurement::CompactMeasurement(SignalIndexCache& signalIndexCache, int64_t* baseTimeOffsets, bool includeTime, bool useMillisecondResolution, int32_t timeIndex) :
m_signalIndexCache(signalIndexCache),
m_baseTimeOffsets(baseTimeOffsets),
m_includeTime(includeTime),
m_useMillisecondResolution(useMillisecondResolution),
m_timeIndex(timeIndex)
{
}
// Gets the byte length of measurements parsed by this parser.
uint32_t CompactMeasurement::GetMeasurementByteLength(const bool usingBaseTimeOffset) const
{
uint32_t byteLength = 7;
if (m_includeTime)
{
if (usingBaseTimeOffset)
{
if (m_useMillisecondResolution)
byteLength += 2; // Use two bytes for millisecond resolution timestamp with valid offset
else
byteLength += 4; // Use four bytes for tick resolution timestamp with valid offset
}
else
{
byteLength += 8; // Use eight bytes for full fidelity time
}
}
return byteLength;
}
// Attempts to parse a measurement from the buffer. Return value of false indicates
// that there is not enough data to parse the measurement. Offset and length will be
// updated by this method to indicate how many bytes were used when parsing.
bool CompactMeasurement::TryParseMeasurement(uint8_t* data, uint32_t& offset, uint32_t length, MeasurementPtr& measurement) const
{
// Ensure that we at least have enough
// data to read the compact state flags
if (length - offset < 1)
return false;
// Read the compact state flags to determine
// the size of the measurement being parsed
const uint8_t compactFlags = data[offset] & 0xFF;
const int32_t timeIndex = compactFlags & CompactTimeIndexFlag ? 1 : 0;
const bool usingBaseTimeOffset = (compactFlags & CompactBaseTimeOffsetFlag) != 0;
// If we are using base time offsets, ensure that it is defined
if (usingBaseTimeOffset && (m_baseTimeOffsets == nullptr || m_baseTimeOffsets[timeIndex] == 0))
return false;
// Ensure that we have enough data to read the rest of the measurement
if (length - offset < GetMeasurementByteLength(usingBaseTimeOffset))
return false;
// Read the signal index from the buffer
const uint16_t signalIndex = EndianConverter::ToBigEndian<uint16_t>(data, offset + 1);
// If the signal index is not found in the cache, we cannot parse the measurement
if (!m_signalIndexCache.Contains(signalIndex))
return false;
Guid signalID;
string measurementSource;
uint32_t measurementID;
int64_t timestamp = 0;
// Now that we've validated our failure conditions we can safely start advancing the offset
m_signalIndexCache.GetMeasurementKey(signalIndex, signalID, measurementSource, measurementID);
offset += 3;
// Read the measurement value from the buffer
const float32_t measurementValue = EndianConverter::ToBigEndian<float32_t>(data, offset);
offset += 4;
if (m_includeTime)
{
if (!usingBaseTimeOffset)
{
// Read full 8-byte timestamp from the buffer
timestamp = EndianConverter::ToBigEndian<int64_t>(data, offset);
offset += 8;
}
else if (!m_useMillisecondResolution)
{
// Read 4-byte offset from the buffer and apply the appropriate base time offset
timestamp = EndianConverter::ToBigEndian<uint32_t>(data, offset);
timestamp += m_baseTimeOffsets[timeIndex]; //-V522
offset += 4;
}
else
{
// Read 2-byte offset from the buffer, convert from milliseconds to ticks, and apply the appropriate base time offset
timestamp = EndianConverter::ToBigEndian<uint16_t>(data, offset);
timestamp *= 10000;
timestamp += m_baseTimeOffsets[timeIndex];
offset += 2;
}
}
measurement = NewSharedPtr<Measurement>();
measurement->Flags = MapToFullFlags(compactFlags);
measurement->SignalID = signalID;
measurement->Source = measurementSource;
measurement->ID = measurementID;
measurement->Value = measurementValue;
measurement->Timestamp = timestamp;
return true;
}
void CompactMeasurement::SerializeMeasurement(const MeasurementPtr& measurement, vector<uint8_t>& buffer) const
{
// Define the compact state flags
uint8_t compactFlags = MapToCompactFlags(measurement->Flags);
int64_t difference = 0L;
bool usingBaseTimeOffset = false;
if (m_baseTimeOffsets != nullptr)
{
// See if timestamp will fit within space allowed for active base offset. We cache result so that post call
// to binary length, result will speed other subsequent parsing operations by not having to reevaluate.
difference = measurement->Timestamp - m_baseTimeOffsets[m_timeIndex];
usingBaseTimeOffset = difference > 0 ?
(m_useMillisecondResolution ? difference / Ticks::PerMillisecond < UInt16::MaxValue : difference < UInt16::MaxValue) : false;
}
if (usingBaseTimeOffset)
compactFlags |= CompactBaseTimeOffsetFlag;
if (m_timeIndex != 0)
compactFlags |= CompactTimeIndexFlag;
// Added encoded compact state flags to beginning of buffer
buffer.push_back(compactFlags);
// Encode runtime ID
EndianConverter::WriteBigEndianBytes(buffer, m_signalIndexCache.GetSignalIndex(measurement->SignalID));
// Encode adjusted value (accounts for adder and multiplier)
EndianConverter::WriteBigEndianBytes(buffer, static_cast<float32_t>(measurement->AdjustedValue()));
if (!m_includeTime)
return;
if (usingBaseTimeOffset)
{
if (m_useMillisecondResolution)
{
// Encode 2-byte millisecond offset timestamp
EndianConverter::WriteBigEndianBytes(buffer, static_cast<uint16_t>(difference / Ticks::PerMillisecond));
}
else
{
// Encode 4-byte ticks offset timestamp
EndianConverter::WriteBigEndianBytes(buffer, static_cast<uint32_t>(difference));
}
}
else
{
// Encode 8-byte full fidelity timestamp
EndianConverter::WriteBigEndianBytes(buffer, measurement->Timestamp);
}
}
<commit_msg>Update CompactMeasurement.cpp<commit_after>//******************************************************************************************************
// CompactMeasurement.cpp - Gbtc
//
// Copyright © 2018, Grid Protection Alliance. All Rights Reserved.
//
// Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
// the NOTICE file distributed with this work for additional information regarding copyright ownership.
// The GPA licenses this file to you under the MIT License (MIT), the "License"; you may not use this
// file except in compliance with the License. You may obtain a copy of the License at:
//
// http://opensource.org/licenses/MIT
//
// Unless agreed to in writing, the subject software distributed under the License is distributed on an
// "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
// License for the specific language governing permissions and limitations.
//
// Code Modification History:
// ----------------------------------------------------------------------------------------------------
// 03/09/2012 - Stephen C. Wills
// Generated original version of source code.
//
//******************************************************************************************************
#include "CompactMeasurement.h"
#include "../Common/EndianConverter.h"
using namespace std;
using namespace GSF::TimeSeries;
using namespace GSF::TimeSeries::Transport;
// These constants represent each flag in the 8-bit compact measurement state flags.
static const uint8_t CompactDataRangeFlag = 0x01;
static const uint8_t CompactDataQualityFlag = 0x02;
static const uint8_t CompactTimeQualityFlag = 0x04;
static const uint8_t CompactSystemIssueFlag = 0x08;
static const uint8_t CompactCalculatedValueFlag = 0x10;
static const uint8_t CompactDiscardedValueFlag = 0x20;
static const uint8_t CompactBaseTimeOffsetFlag = 0x40;
static const uint8_t CompactTimeIndexFlag = 0x80;
// These constants are masks used to set flags within the full 32-bit measurement state flags.
static const uint32_t DataRangeMask = 0x000000FC;
static const uint32_t DataQualityMask = 0x0000EF03;
static const uint32_t TimeQualityMask = 0x00BF0000;
static const uint32_t SystemIssueMask = 0xE0000000;
static const uint32_t CalculatedValueMask = 0x00001000;
static const uint32_t DiscardedValueMask = 0x00400000;
// Takes the 8-bit compact measurement flags and maps
// them to the full 32-bit measurement flags format.
inline uint32_t MapToFullFlags(uint8_t compactFlags)
{
uint32_t fullFlags = 0U;
if ((compactFlags & CompactDataRangeFlag) > 0)
fullFlags |= DataRangeMask;
if ((compactFlags & CompactDataQualityFlag) > 0)
fullFlags |= DataQualityMask;
if ((compactFlags & CompactTimeQualityFlag) > 0)
fullFlags |= TimeQualityMask;
if ((compactFlags & CompactSystemIssueFlag) > 0)
fullFlags |= SystemIssueMask;
if ((compactFlags & CompactCalculatedValueFlag) > 0)
fullFlags |= CalculatedValueMask;
if ((compactFlags & CompactDiscardedValueFlag) > 0)
fullFlags |= DiscardedValueMask;
return fullFlags;
}
// Takes the full 32-bit measurement flags format and
// maps them to the 8-bit compact measurement flags.
inline uint32_t MapToCompactFlags(uint32_t fullFlags)
{
uint32_t compactFlags = 0U;
if ((fullFlags & DataRangeMask) > 0)
compactFlags |= CompactDataRangeFlag;
if ((fullFlags & DataQualityMask) > 0)
compactFlags |= CompactDataQualityFlag;
if ((fullFlags & TimeQualityMask) > 0)
compactFlags |= CompactTimeQualityFlag;
if ((fullFlags & SystemIssueMask) > 0)
compactFlags |= CompactSystemIssueFlag;
if ((fullFlags & CalculatedValueMask) > 0)
compactFlags |= CompactCalculatedValueFlag;
if ((fullFlags & DiscardedValueMask) > 0)
compactFlags |= CompactDiscardedValueFlag;
return compactFlags;
}
CompactMeasurement::CompactMeasurement(SignalIndexCache& signalIndexCache, int64_t* baseTimeOffsets, bool includeTime, bool useMillisecondResolution, int32_t timeIndex) :
m_signalIndexCache(signalIndexCache),
m_baseTimeOffsets(baseTimeOffsets),
m_includeTime(includeTime),
m_useMillisecondResolution(useMillisecondResolution),
m_timeIndex(timeIndex)
{
}
// Gets the byte length of measurements parsed by this parser.
uint32_t CompactMeasurement::GetMeasurementByteLength(const bool usingBaseTimeOffset) const
{
uint32_t byteLength = 7;
if (m_includeTime)
{
if (usingBaseTimeOffset)
{
if (m_useMillisecondResolution)
byteLength += 2; // Use two bytes for millisecond resolution timestamp with valid offset
else
byteLength += 4; // Use four bytes for tick resolution timestamp with valid offset
}
else
{
byteLength += 8; // Use eight bytes for full fidelity time
}
}
return byteLength;
}
// Attempts to parse a measurement from the buffer. Return value of false indicates
// that there is not enough data to parse the measurement. Offset and length will be
// updated by this method to indicate how many bytes were used when parsing.
bool CompactMeasurement::TryParseMeasurement(uint8_t* data, uint32_t& offset, uint32_t length, MeasurementPtr& measurement) const
{
// Ensure that we at least have enough
// data to read the compact state flags
if (length - offset < 1)
return false;
// Read the compact state flags to determine
// the size of the measurement being parsed
const uint8_t compactFlags = data[offset] & 0xFF;
const int32_t timeIndex = compactFlags & CompactTimeIndexFlag ? 1 : 0;
const bool usingBaseTimeOffset = (compactFlags & CompactBaseTimeOffsetFlag) != 0;
// If we are using base time offsets, ensure that it is defined
if (usingBaseTimeOffset && (m_baseTimeOffsets == nullptr || m_baseTimeOffsets[timeIndex] == 0))
return false;
// Ensure that we have enough data to read the rest of the measurement
if (length - offset < GetMeasurementByteLength(usingBaseTimeOffset))
return false;
// Read the signal index from the buffer
const uint16_t signalIndex = EndianConverter::ToBigEndian<uint16_t>(data, offset + 1);
// If the signal index is not found in the cache, we cannot parse the measurement
if (!m_signalIndexCache.Contains(signalIndex))
return false;
Guid signalID;
string measurementSource;
uint32_t measurementID;
int64_t timestamp = 0;
// Now that we've validated our failure conditions we can safely start advancing the offset
m_signalIndexCache.GetMeasurementKey(signalIndex, signalID, measurementSource, measurementID);
offset += 3;
// Read the measurement value from the buffer
const float32_t measurementValue = EndianConverter::ToBigEndian<float32_t>(data, offset);
offset += 4;
if (m_includeTime)
{
if (!usingBaseTimeOffset)
{
// Read full 8-byte timestamp from the buffer
timestamp = EndianConverter::ToBigEndian<int64_t>(data, offset);
offset += 8;
}
else if (!m_useMillisecondResolution)
{
// Read 4-byte offset from the buffer and apply the appropriate base time offset
timestamp = EndianConverter::ToBigEndian<uint32_t>(data, offset);
timestamp += m_baseTimeOffsets[timeIndex]; //-V522
offset += 4;
}
else
{
// Read 2-byte offset from the buffer, convert from milliseconds to ticks, and apply the appropriate base time offset
timestamp = EndianConverter::ToBigEndian<uint16_t>(data, offset);
timestamp *= 10000;
timestamp += m_baseTimeOffsets[timeIndex];
offset += 2;
}
}
measurement = NewSharedPtr<Measurement>();
measurement->Flags = MapToFullFlags(compactFlags);
measurement->SignalID = signalID;
measurement->Source = measurementSource;
measurement->ID = measurementID;
measurement->Value = measurementValue;
measurement->Timestamp = timestamp;
return true;
}
void CompactMeasurement::SerializeMeasurement(const MeasurementPtr& measurement, vector<uint8_t>& buffer) const
{
// Define the compact state flags
uint8_t compactFlags = MapToCompactFlags(measurement->Flags);
int64_t difference = 0L;
bool usingBaseTimeOffset = false;
if (m_baseTimeOffsets != nullptr)
{
// See if timestamp will fit within space allowed for active base offset. We cache result so that post call
// to binary length, result will speed other subsequent parsing operations by not having to reevaluate.
difference = measurement->Timestamp - m_baseTimeOffsets[m_timeIndex];
usingBaseTimeOffset = difference > 0 ?
(m_useMillisecondResolution ? difference / Ticks::PerMillisecond < UInt16::MaxValue : difference < UInt16::MaxValue) : false;
}
if (usingBaseTimeOffset)
compactFlags |= CompactBaseTimeOffsetFlag;
if (m_timeIndex != 0)
compactFlags |= CompactTimeIndexFlag;
// Added encoded compact state flags to beginning of buffer
buffer.push_back(compactFlags);
// Encode runtime ID
EndianConverter::WriteBigEndianBytes(buffer, m_signalIndexCache.GetSignalIndex(measurement->SignalID));
// Encode adjusted value (accounts for adder and multiplier)
EndianConverter::WriteBigEndianBytes(buffer, static_cast<float32_t>(measurement->AdjustedValue()));
if (!m_includeTime)
return;
if (usingBaseTimeOffset)
{
if (m_useMillisecondResolution)
{
// Encode 2-byte millisecond offset timestamp
EndianConverter::WriteBigEndianBytes(buffer, static_cast<uint16_t>(difference / Ticks::PerMillisecond));
}
else
{
// Encode 4-byte ticks offset timestamp
EndianConverter::WriteBigEndianBytes(buffer, static_cast<uint32_t>(difference));
}
}
else
{
// Encode 8-byte full fidelity timestamp
EndianConverter::WriteBigEndianBytes(buffer, measurement->Timestamp);
}
}
<|endoftext|>
|
<commit_before>// A C++ Program to generate test cases for
// an unweighted tree
#include<bits/stdc++.h>
using namespace std;
// Define the number of runs for the test data
// generated
#define RUN 10000
// Define the maximum number of nodes of the tree
#define MAXNODE 100
int main()
{
set<pair<int, int>> container;
set<pair<int, int>>::iterator it;
freopen ("Test_Cases_Unweighted_Tree.in", "w", stdout);
//For random values every time
srand(time(NULL));
int NUM; // Number of Vertices/Nodes
for (int i=1; i<=RUN; i++)
{
NUM = 1 + rand() % MAXNODE;
// First print the number of vertices/nodes
printf("%d\n", NUM);
// Then print the edges of the form (a b)
// where 'a' is connected to 'b'
for (int j=1; j<=NUM-1; j++)
{
int a = 1 + rand() % NUM;
int b = 1 + rand() % NUM;
pair<int, int> p = make_pair(a, b);
pair<int, int> reverse_p = make_pair(b, a);
// Search for a random "new" edge everytime
// Note - In a tree the edge (a, b) is same
// as the edge (b, a)
while (container.find(p) != container.end() ||
container.find(reverse_p) != container.end())
{
a = 1 + rand() % NUM;
b = 1 + rand() % NUM;
p = make_pair(a, b);
reverse_p = make_pair(b, a);
}
container.insert(p);
}
for (it=container.begin(); it!=container.end(); ++it)
printf("%d %d\n", it->first, it->second);
container.clear();
printf("\n");
}
fclose(stdout);
return(0);
}
<commit_msg>Delete Test_Case_Generator_Unweighted_Tree.cpp<commit_after><|endoftext|>
|
<commit_before>#include "./qimage_drawer.h"
#include <QPainter>
#include <vector>
namespace Graphics
{
QImageDrawer::QImageDrawer(int width, int height)
{
image = std::make_shared<QImage>(width, height, QImage::Format_Grayscale8);
}
void drawPolygon(QPainter &painter, std::vector<QPointF> &points)
{
if (points.size() < 3)
return;
QPointF triangle[3];
triangle[0] = points[0];
for (size_t i = 2; i < points.size(); ++i)
{
triangle[1] = points[i - 1];
triangle[2] = points[i];
painter.drawConvexPolygon(triangle, 3);
}
points.clear();
}
void QImageDrawer::drawElementVector(std::vector<float> positions, float color)
{
QPainter painter;
painter.begin(image.get());
QColor brushColor = QColor::fromRgbF(color, color, color, color);
painter.setBrush(QBrush(brushColor));
painter.setPen(brushColor);
std::vector<QPointF> points;
size_t i = 0;
if (positions[0] == positions[2] && positions[1] == positions[3])
i = 1;
for (; i < positions.size() / 2; ++i)
{
float x = positions[i * 2];
float y = image->height() - positions[i * 2 + 1];
if (i * 2 + 3 < positions.size() && x == positions[i * 2 + 2] &&
y == positions[i * 2 + 3])
{
drawPolygon(painter, points);
points.clear();
i += 2;
}
points.push_back(QPointF(x, y));
}
drawPolygon(painter, points);
painter.end();
}
void QImageDrawer::clear()
{
image->fill(Qt::GlobalColor::black);
}
} // namespace Graphics
<commit_msg>Don't use transparency in QImageDrawer.<commit_after>#include "./qimage_drawer.h"
#include <QPainter>
#include <vector>
namespace Graphics
{
QImageDrawer::QImageDrawer(int width, int height)
{
image = std::make_shared<QImage>(width, height, QImage::Format_Grayscale8);
}
void drawPolygon(QPainter &painter, std::vector<QPointF> &points)
{
if (points.size() < 3)
return;
QPointF triangle[3];
triangle[0] = points[0];
for (size_t i = 2; i < points.size(); ++i)
{
triangle[1] = points[i - 1];
triangle[2] = points[i];
painter.drawConvexPolygon(triangle, 3);
}
points.clear();
}
void QImageDrawer::drawElementVector(std::vector<float> positions, float color)
{
QPainter painter;
painter.begin(image.get());
QColor brushColor = QColor::fromRgbF(color, color, color, 1.0f);
painter.setBrush(QBrush(brushColor));
painter.setPen(brushColor);
std::vector<QPointF> points;
size_t i = 0;
if (positions[0] == positions[2] && positions[1] == positions[3])
i = 1;
for (; i < positions.size() / 2; ++i)
{
float x = positions[i * 2];
float y = image->height() - positions[i * 2 + 1];
if (i * 2 + 3 < positions.size() && x == positions[i * 2 + 2] &&
y == positions[i * 2 + 3])
{
drawPolygon(painter, points);
points.clear();
i += 2;
}
points.push_back(QPointF(x, y));
}
drawPolygon(painter, points);
painter.end();
}
void QImageDrawer::clear()
{
image->fill(Qt::GlobalColor::black);
}
} // namespace Graphics
<|endoftext|>
|
<commit_before>///
/// @file l1d_cache_size.cpp
/// @brief Get the L1 cache size in kilobytes on Windows
/// and most Unix-like operating systems.
///
/// Copyright (C) 2015 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License.
///
#include <cstdlib>
#if defined(_WIN32) || defined(_WIN64)
#include <windows.h>
typedef BOOL (WINAPI *LPFN_GLPI)(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION, PDWORD);
/// Get the CPU's L1 data cache size (per core) in kilobytes.
/// Successfully tested on Windows x64.
/// @return L1 data cache size in kilobytes or -1 if an error occurred.
///
int get_l1d_cache_size()
{
LPFN_GLPI glpi = (LPFN_GLPI) GetProcAddress(GetModuleHandle(TEXT("kernel32")), "GetLogicalProcessorInformation");
// GetLogicalProcessorInformation not supported
if (glpi == NULL)
return -1;
DWORD buffer_bytes = 0;
int cache_size = 0;
glpi(0, &buffer_bytes);
std::size_t size = buffer_bytes / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
SYSTEM_LOGICAL_PROCESSOR_INFORMATION* buffer = new SYSTEM_LOGICAL_PROCESSOR_INFORMATION[size];
glpi(buffer, &buffer_bytes);
for (std::size_t i = 0; i < size; i++)
{
if (buffer[i].Relationship == RelationCache &&
buffer[i].Cache.Level == 1)
{
cache_size = (int) buffer[i].Cache.Size;
break;
}
}
delete buffer;
return cache_size / 1024;
}
#else
/// Get the CPU's L1 data cache size (per core) in kilobytes.
/// Successfully tested on Linux and Mac OS X.
/// @return L1 data cache size in kilobytes or -1 if an error occurred.
///
int get_l1d_cache_size()
{
// Posix shell script for UNIX like OSes,
// Returns log2 of L1_DCACHE_SIZE in kilobytes.
// The script tries to get the L1 cache size using 3 different approaches:
// 1) getconf LEVEL1_DCACHE_SIZE
// 2) cat /sys/devices/system/cpu/cpu0/cache/index0/size
// 3) sysctl hw.l1dcachesize
const char* shell_script =
"command -v getconf >/dev/null 2>/dev/null; \n"
"if [ $? -eq 0 ]; \n"
"then \n"
" # Returns L1 cache size in bytes \n"
" L1_DCACHE_BYTES=$(getconf LEVEL1_DCACHE_SIZE 2>/dev/null); \n"
"fi; \n"
" \n"
"if test \"x$L1_DCACHE_BYTES\" = \"x\" || test \"$L1_DCACHE_BYTES\" = \"0\"; \n"
"then \n"
" # Returns L1 cache size like e.g. 32K, 1M \n"
" L1_DCACHE_BYTES=$(cat /sys/devices/system/cpu/cpu0/cache/index0/size 2>/dev/null); \n"
" \n"
" if test \"x$L1_DCACHE_BYTES\" != \"x\"; \n"
" then \n"
" is_kilobytes=$(echo $L1_DCACHE_BYTES | grep K); \n"
" if test \"x$is_kilobytes\" != \"x\"; \n"
" then \n"
" L1_DCACHE_BYTES=$(expr $(echo $L1_DCACHE_BYTES | sed -e s'/K$//') '*' 1024); \n"
" fi; \n"
" is_megabytes=$(echo $L1_DCACHE_BYTES | grep M); \n"
" if test \"x$is_megabytes\" != \"x\"; \n"
" then \n"
" L1_DCACHE_BYTES=$(expr $(echo $L1_DCACHE_BYTES | sed -e s'/M$//') '*' 1024 '*' 1024); \n"
" fi; \n"
" else \n"
" # This method works on OS X \n"
" command -v sysctl >/dev/null 2>/dev/null; \n"
" if [ $? -eq 0 ]; \n"
" then \n"
" # Returns L1 cache size in bytes \n"
" L1_DCACHE_BYTES=$(sysctl hw.l1dcachesize 2>/dev/null | sed -e 's/^.* //'); \n"
" fi; \n"
" fi; \n"
"fi; \n"
" \n"
"if test \"x$L1_DCACHE_BYTES\" != \"x\"; \n"
"then \n"
" if [ $L1_DCACHE_BYTES -ge 1024 2>/dev/null ]; \n"
" then \n"
" # Convert to kilobytes \n"
" L1_DCACHE_SIZE=$(expr $L1_DCACHE_BYTES '/' 1024); \n"
" fi; \n"
"fi; \n"
" \n"
"if test \"x$L1_DCACHE_SIZE\" = \"x\"; \n"
"then \n"
" exit 1; \n"
"fi; \n"
" \n"
"LOG2_L1_DCACHE_SIZE=0; \n"
"while [ $L1_DCACHE_SIZE -ge 2 ]; \n"
"do \n"
" L1_DCACHE_SIZE=$(expr $L1_DCACHE_SIZE '/' 2); \n"
" LOG2_L1_DCACHE_SIZE=$(expr $LOG2_L1_DCACHE_SIZE '+' 1); \n"
"done; \n"
" \n"
"exit $LOG2_L1_DCACHE_SIZE; \n";
int exit_code = std::system(shell_script);
exit_code = WEXITSTATUS(exit_code);
// check if shell script executed without any errors
if (exit_code <= 2)
return -1;
int l1d_cache_size = 1 << exit_code;
return l1d_cache_size;
}
#endif
<commit_msg>Fix delete bug<commit_after>///
/// @file l1d_cache_size.cpp
/// @brief Get the L1 cache size in kilobytes on Windows
/// and most Unix-like operating systems.
///
/// Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License.
///
#include <cstdlib>
#if defined(_WIN32) || defined(_WIN64)
#include <windows.h>
typedef BOOL (WINAPI *LPFN_GLPI)(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION, PDWORD);
/// Get the CPU's L1 data cache size (per core) in kilobytes.
/// Successfully tested on Windows x64.
/// @return L1 data cache size in kilobytes or -1 if an error occurred.
///
int get_l1d_cache_size()
{
LPFN_GLPI glpi = (LPFN_GLPI) GetProcAddress(GetModuleHandle(TEXT("kernel32")), "GetLogicalProcessorInformation");
// GetLogicalProcessorInformation not supported
if (glpi == NULL)
return -1;
DWORD buffer_bytes = 0;
int cache_size = 0;
glpi(0, &buffer_bytes);
std::size_t size = buffer_bytes / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
SYSTEM_LOGICAL_PROCESSOR_INFORMATION* buffer = new SYSTEM_LOGICAL_PROCESSOR_INFORMATION[size];
glpi(buffer, &buffer_bytes);
for (std::size_t i = 0; i < size; i++)
{
if (buffer[i].Relationship == RelationCache &&
buffer[i].Cache.Level == 1)
{
cache_size = (int) buffer[i].Cache.Size;
break;
}
}
delete[] buffer;
return cache_size / 1024;
}
#else
/// Get the CPU's L1 data cache size (per core) in kilobytes.
/// Successfully tested on Linux and Mac OS X.
/// @return L1 data cache size in kilobytes or -1 if an error occurred.
///
int get_l1d_cache_size()
{
// Posix shell script for UNIX like OSes,
// Returns log2 of L1_DCACHE_SIZE in kilobytes.
// The script tries to get the L1 cache size using 3 different approaches:
// 1) getconf LEVEL1_DCACHE_SIZE
// 2) cat /sys/devices/system/cpu/cpu0/cache/index0/size
// 3) sysctl hw.l1dcachesize
const char* shell_script =
"command -v getconf >/dev/null 2>/dev/null; \n"
"if [ $? -eq 0 ]; \n"
"then \n"
" # Returns L1 cache size in bytes \n"
" L1_DCACHE_BYTES=$(getconf LEVEL1_DCACHE_SIZE 2>/dev/null); \n"
"fi; \n"
" \n"
"if test \"x$L1_DCACHE_BYTES\" = \"x\" || test \"$L1_DCACHE_BYTES\" = \"0\"; \n"
"then \n"
" # Returns L1 cache size like e.g. 32K, 1M \n"
" L1_DCACHE_BYTES=$(cat /sys/devices/system/cpu/cpu0/cache/index0/size 2>/dev/null); \n"
" \n"
" if test \"x$L1_DCACHE_BYTES\" != \"x\"; \n"
" then \n"
" is_kilobytes=$(echo $L1_DCACHE_BYTES | grep K); \n"
" if test \"x$is_kilobytes\" != \"x\"; \n"
" then \n"
" L1_DCACHE_BYTES=$(expr $(echo $L1_DCACHE_BYTES | sed -e s'/K$//') '*' 1024); \n"
" fi; \n"
" is_megabytes=$(echo $L1_DCACHE_BYTES | grep M); \n"
" if test \"x$is_megabytes\" != \"x\"; \n"
" then \n"
" L1_DCACHE_BYTES=$(expr $(echo $L1_DCACHE_BYTES | sed -e s'/M$//') '*' 1024 '*' 1024); \n"
" fi; \n"
" else \n"
" # This method works on OS X \n"
" command -v sysctl >/dev/null 2>/dev/null; \n"
" if [ $? -eq 0 ]; \n"
" then \n"
" # Returns L1 cache size in bytes \n"
" L1_DCACHE_BYTES=$(sysctl hw.l1dcachesize 2>/dev/null | sed -e 's/^.* //'); \n"
" fi; \n"
" fi; \n"
"fi; \n"
" \n"
"if test \"x$L1_DCACHE_BYTES\" != \"x\"; \n"
"then \n"
" if [ $L1_DCACHE_BYTES -ge 1024 2>/dev/null ]; \n"
" then \n"
" # Convert to kilobytes \n"
" L1_DCACHE_SIZE=$(expr $L1_DCACHE_BYTES '/' 1024); \n"
" fi; \n"
"fi; \n"
" \n"
"if test \"x$L1_DCACHE_SIZE\" = \"x\"; \n"
"then \n"
" exit 1; \n"
"fi; \n"
" \n"
"LOG2_L1_DCACHE_SIZE=0; \n"
"while [ $L1_DCACHE_SIZE -ge 2 ]; \n"
"do \n"
" L1_DCACHE_SIZE=$(expr $L1_DCACHE_SIZE '/' 2); \n"
" LOG2_L1_DCACHE_SIZE=$(expr $LOG2_L1_DCACHE_SIZE '+' 1); \n"
"done; \n"
" \n"
"exit $LOG2_L1_DCACHE_SIZE; \n";
int exit_code = std::system(shell_script);
exit_code = WEXITSTATUS(exit_code);
// check if shell script executed without any errors
if (exit_code <= 2)
return -1;
int l1d_cache_size = 1 << exit_code;
return l1d_cache_size;
}
#endif
<|endoftext|>
|
<commit_before>/*
*
* $Id$
*
* History:
*
* Bernd Wuebben, wuebben@math.cornell.edu:
*
* Much of this is taken from the pppd sources in particular
* /pppstat/pppstat.c, and modified to suit the needs of kppp.
*
*
* Here the original history of pppstat.c:
*
* perkins@cps.msu.edu: Added compression statistics and alternate
* display. 11/94
*
* Brad Parker (brad@cayman.com) 6/92
*
* from the original "slstats" by Van Jaconson
*
* Copyright (c) 1989 Regents of the University of California.
* All rights reserved.
*
* Redistribution and use in source and binary forms are permitted
* provided that the above copyright notice and this paragraph are
* duplicated in all such forms and that any documentation,
* advertising materials, and other materials related to such
* distribution and use acknowledge that the software was developed
* by the University of California, Berkeley. The name of the
* University may not be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* Van Jacobson (van@helios.ee.lbl.gov), Dec 31, 1989:
* - Initial distribution.
*/
#include "pppstats.h"
#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <signal.h>
#include <fcntl.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netinet/in.h>
#ifndef STREAMS
#if defined(__linux__) && defined(__powerpc__) \
&& (__GLIBC__ == 2 && __GLIBC_MINOR__ == 0)
/* kludge alert! */
#undef __GLIBC__
#endif
#include <sys/socket.h> /* *BSD, Linux, NeXT, Ultrix etc. */
#ifndef HAVE_NET_IF_PPP_H
#ifdef HAVE_LINUX_IF_PPP_H
#include <linux/if_ppp.h>
#endif
#else
#include <net/ppp_defs.h>
#include <net/if.h>
#include <net/if_ppp.h>
#endif
#else /* STREAMS */
#include <sys/socket.h>
#include <sys/stropts.h> /* SVR4, Solaris 2, SunOS 4, OSF/1, etc. */
#include <net/ppp_defs.h>
#include <net/pppio.h>
#include <net/if.h>
#include <sys/sockio.h>
#endif /* STREAMS */
#include <qtimer.h>
#include <kdebug.h>
#include "pppstats.h"
PPPStats::PPPStats() {
timer = new QTimer;
connect(timer, SIGNAL(timeout()), SLOT(timerClick()));
}
PPPStats::~PPPStats() {
stop();
delete timer;
}
void PPPStats::timerClick() {
enum IOStatus newStatus;
doStats();
if((ibytes != ibytes_last) && (obytes != obytes_last))
newStatus = BytesBoth;
else if(ibytes != ibytes_last)
newStatus = BytesIn;
else if(obytes != obytes_last)
newStatus = BytesOut;
else
newStatus = BytesNone;
if(newStatus != ioStatus)
emit statsChanged(ioStatus = newStatus);
ibytes_last = ibytes;
obytes_last = obytes;
}
void PPPStats::setUnit(int u) {
unit = u;
sprintf(unitName, "ppp%d", unit);
}
void PPPStats::start() {
timer->start(PPP_STATS_INTERVAL);
}
void PPPStats::stop() {
emit statsChanged(BytesNone);
timer->stop();
}
bool PPPStats::ifIsUp() {
bool is_up;
struct ifreq ifr;
#if defined(__svr4__ )
usleep(500000); // Needed for Solaris ?!
#endif
#ifdef STREAMS
if ((t = open("/dev/ppp", O_RDONLY)) < 0) {
perror("pppstats: Couldn't open /dev/ppp: ");
return false;
}
if (!strioctl(t, PPPIO_ATTACH, (char*)&unit, sizeof(int), 0)) {
fprintf(stderr, "pppstats: ppp%d is not available\n", unit);
::close(t);
return false;
}
// TODO: close t somewhere again
#endif
if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
perror("Couldn't create IP socket");
return false;
}
strncpy(ifr.ifr_name, unitName, sizeof(ifr.ifr_name));
if(ioctl(s, SIOCGIFFLAGS, (caddr_t) &ifr) < 0) {
if (errno)
fprintf(stderr, "Couldn't find interface %s: %s\n",
unitName, strerror(errno));
::close(s);
s = 0;
return 0;
}
if ((ifr.ifr_flags & (IFF_UP|IFF_RUNNING)) != 0) {
is_up = true;
kdDebug(5002) << "Interface is up" << endl;
}
else{
is_up = false;
::close(s);
s = 0;
kdDebug(5002) << "Interface is down" << endl;
}
return is_up;
}
bool PPPStats::initStats() {
struct sockaddr_in *sinp;
struct ifreq ifr;
ibytes = 0;
ipackets = 0;
ibytes_last = 0;
obytes_last = 0;
compressedin = 0;
uncompressedin = 0;
errorin = 0;
obytes = 0;
opackets = 0;
compressed = 0;
packetsunc = 0;
packetsoutunc = 0;
ioStatus = BytesNone;
strcpy(ifr.ifr_name, unitName);
if (ioctl(s, SIOCGIFADDR, &ifr) < 0) {
}
sinp = (struct sockaddr_in*)&ifr.ifr_addr;
if(sinp->sin_addr.s_addr)
local_ip_address = inet_ntoa(sinp->sin_addr);
else
local_ip_address = "";
kdDebug(5002) << "Local IP: " << local_ip_address << endl;
if (ioctl(s, SIOCGIFDSTADDR, &ifr) < 0)
;
sinp = (struct sockaddr_in*)&ifr.ifr_dstaddr;
if(sinp->sin_addr.s_addr)
remote_ip_address = inet_ntoa(sinp->sin_addr);
else
remote_ip_address = "";
kdDebug(5002) << "Remote IP: " << remote_ip_address << endl;
return true;
}
bool PPPStats::doStats() {
struct ppp_stats cur;
if(! get_ppp_stats(&cur)){
return false;
}
// "in" "pack" "comp" "uncomp" "err"
// IN PACK VJCOMP VJUNC VJERR
ibytes = cur.p.ppp_ibytes; // bytes received
ipackets = cur.p.ppp_ipackets; // packets recieved
compressedin = cur.vj.vjs_compressedin; // inbound compressed packets
uncompressedin = cur.vj.vjs_uncompressedin; // inbound uncompressed packets
errorin = cur.vj.vjs_errorin; //receive errors
// "out" "pack" "comp" "uncomp" "ip"
// OUT PACK JCOMP VJUNC NON-VJ
obytes = cur.p.ppp_obytes; // raw bytes sent
opackets = cur.p.ppp_opackets; // packets sent
compressed = cur.vj.vjs_compressed; //outbound compressed packets
// outbound packets - outbound compressed packets
packetsunc = cur.vj.vjs_packets - cur.vj.vjs_compressed;
// packets sent - oubount compressed
packetsoutunc = cur.p.ppp_opackets - cur.vj.vjs_packets;
return true;
}
#ifndef STREAMS
bool PPPStats::get_ppp_stats(struct ppp_stats *curp){
struct ifpppstatsreq req;
if(s==0)
return false;
#ifdef __linux__
req.stats_ptr = (caddr_t) &req.stats;
sprintf(req.ifr__name, "ppp%d", unit);
#else
sprintf(req.ifr_name, "ppp%d", unit);
#endif
if (ioctl(s, SIOCGPPPSTATS, &req) < 0) {
if (errno == ENOTTY)
fprintf(stderr, "pppstats: kernel support missing\n");
else
perror("ioctl(SIOCGPPPSTATS)");
return false;
}
*curp = req.stats;
return true;
}
#else /* STREAMS */
bool PPPStats::get_ppp_stats( struct ppp_stats *curp){
if (!strioctl(t, PPPIO_GETSTAT, (char*)curp, 0, sizeof(*curp))) {
if (errno == EINVAL)
fprintf(stderr, "pppstats: kernel support missing\n");
else
perror("pppstats: Couldn't get statistics");
return false;
}
return true;
}
bool PPPStats::strioctl(int fd, int cmd, char* ptr, int ilen, int olen){
struct strioctl str;
str.ic_cmd = cmd;
str.ic_timout = 0;
str.ic_len = ilen;
str.ic_dp = ptr;
if (ioctl(fd, I_STR, &str) == -1)
return false;
if (str.ic_len != olen)
fprintf(stderr, "strioctl: expected %d bytes, got %d for cmd %x\n",
olen, str.ic_len, cmd);
return true;
}
#endif /* STREAMS */
#include "pppstats.moc"
<commit_msg>#include <net/ppp_defs.h> for every system. Didn't get any feedback from a tester, yet, but I saw this in older versions in the cvs, too.<commit_after>/*
*
* $Id$
*
* History:
*
* Bernd Wuebben, wuebben@math.cornell.edu:
*
* Much of this is taken from the pppd sources in particular
* /pppstat/pppstat.c, and modified to suit the needs of kppp.
*
*
* Here the original history of pppstat.c:
*
* perkins@cps.msu.edu: Added compression statistics and alternate
* display. 11/94
*
* Brad Parker (brad@cayman.com) 6/92
*
* from the original "slstats" by Van Jaconson
*
* Copyright (c) 1989 Regents of the University of California.
* All rights reserved.
*
* Redistribution and use in source and binary forms are permitted
* provided that the above copyright notice and this paragraph are
* duplicated in all such forms and that any documentation,
* advertising materials, and other materials related to such
* distribution and use acknowledge that the software was developed
* by the University of California, Berkeley. The name of the
* University may not be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* Van Jacobson (van@helios.ee.lbl.gov), Dec 31, 1989:
* - Initial distribution.
*/
#include "pppstats.h"
#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <signal.h>
#include <fcntl.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netinet/in.h>
#include <net/ppp_defs.h>
#ifndef STREAMS
#if defined(__linux__) && defined(__powerpc__) \
&& (__GLIBC__ == 2 && __GLIBC_MINOR__ == 0)
/* kludge alert! */
#undef __GLIBC__
#endif
#include <sys/socket.h> /* *BSD, Linux, NeXT, Ultrix etc. */
#ifndef HAVE_NET_IF_PPP_H
#ifdef HAVE_LINUX_IF_PPP_H
#include <linux/if.h>
#include <linux/if_ppp.h>
#endif
#else
#include <net/if.h>
#include <net/if_ppp.h>
#endif
#else /* STREAMS */
#include <sys/socket.h>
#include <sys/stropts.h> /* SVR4, Solaris 2, SunOS 4, OSF/1, etc. */
#include <net/ppp_defs.h>
#include <net/pppio.h>
#include <net/if.h>
#include <sys/sockio.h>
#endif /* STREAMS */
#include <qtimer.h>
#include <kdebug.h>
#include "pppstats.h"
PPPStats::PPPStats() {
timer = new QTimer;
connect(timer, SIGNAL(timeout()), SLOT(timerClick()));
}
PPPStats::~PPPStats() {
stop();
delete timer;
}
void PPPStats::timerClick() {
enum IOStatus newStatus;
doStats();
if((ibytes != ibytes_last) && (obytes != obytes_last))
newStatus = BytesBoth;
else if(ibytes != ibytes_last)
newStatus = BytesIn;
else if(obytes != obytes_last)
newStatus = BytesOut;
else
newStatus = BytesNone;
if(newStatus != ioStatus)
emit statsChanged(ioStatus = newStatus);
ibytes_last = ibytes;
obytes_last = obytes;
}
void PPPStats::setUnit(int u) {
unit = u;
sprintf(unitName, "ppp%d", unit);
}
void PPPStats::start() {
timer->start(PPP_STATS_INTERVAL);
}
void PPPStats::stop() {
emit statsChanged(BytesNone);
timer->stop();
}
bool PPPStats::ifIsUp() {
bool is_up;
struct ifreq ifr;
#if defined(__svr4__ )
usleep(500000); // Needed for Solaris ?!
#endif
#ifdef STREAMS
if ((t = open("/dev/ppp", O_RDONLY)) < 0) {
perror("pppstats: Couldn't open /dev/ppp: ");
return false;
}
if (!strioctl(t, PPPIO_ATTACH, (char*)&unit, sizeof(int), 0)) {
fprintf(stderr, "pppstats: ppp%d is not available\n", unit);
::close(t);
return false;
}
// TODO: close t somewhere again
#endif
if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
perror("Couldn't create IP socket");
return false;
}
strncpy(ifr.ifr_name, unitName, sizeof(ifr.ifr_name));
if(ioctl(s, SIOCGIFFLAGS, (caddr_t) &ifr) < 0) {
if (errno)
fprintf(stderr, "Couldn't find interface %s: %s\n",
unitName, strerror(errno));
::close(s);
s = 0;
return 0;
}
if ((ifr.ifr_flags & (IFF_UP|IFF_RUNNING)) != 0) {
is_up = true;
kdDebug(5002) << "Interface is up" << endl;
}
else{
is_up = false;
::close(s);
s = 0;
kdDebug(5002) << "Interface is down" << endl;
}
return is_up;
}
bool PPPStats::initStats() {
struct sockaddr_in *sinp;
struct ifreq ifr;
ibytes = 0;
ipackets = 0;
ibytes_last = 0;
obytes_last = 0;
compressedin = 0;
uncompressedin = 0;
errorin = 0;
obytes = 0;
opackets = 0;
compressed = 0;
packetsunc = 0;
packetsoutunc = 0;
ioStatus = BytesNone;
strcpy(ifr.ifr_name, unitName);
if (ioctl(s, SIOCGIFADDR, &ifr) < 0) {
}
sinp = (struct sockaddr_in*)&ifr.ifr_addr;
if(sinp->sin_addr.s_addr)
local_ip_address = inet_ntoa(sinp->sin_addr);
else
local_ip_address = "";
kdDebug(5002) << "Local IP: " << local_ip_address << endl;
if (ioctl(s, SIOCGIFDSTADDR, &ifr) < 0)
;
sinp = (struct sockaddr_in*)&ifr.ifr_dstaddr;
if(sinp->sin_addr.s_addr)
remote_ip_address = inet_ntoa(sinp->sin_addr);
else
remote_ip_address = "";
kdDebug(5002) << "Remote IP: " << remote_ip_address << endl;
return true;
}
bool PPPStats::doStats() {
struct ppp_stats cur;
if(! get_ppp_stats(&cur)){
return false;
}
// "in" "pack" "comp" "uncomp" "err"
// IN PACK VJCOMP VJUNC VJERR
ibytes = cur.p.ppp_ibytes; // bytes received
ipackets = cur.p.ppp_ipackets; // packets recieved
compressedin = cur.vj.vjs_compressedin; // inbound compressed packets
uncompressedin = cur.vj.vjs_uncompressedin; // inbound uncompressed packets
errorin = cur.vj.vjs_errorin; //receive errors
// "out" "pack" "comp" "uncomp" "ip"
// OUT PACK JCOMP VJUNC NON-VJ
obytes = cur.p.ppp_obytes; // raw bytes sent
opackets = cur.p.ppp_opackets; // packets sent
compressed = cur.vj.vjs_compressed; //outbound compressed packets
// outbound packets - outbound compressed packets
packetsunc = cur.vj.vjs_packets - cur.vj.vjs_compressed;
// packets sent - oubount compressed
packetsoutunc = cur.p.ppp_opackets - cur.vj.vjs_packets;
return true;
}
#ifndef STREAMS
bool PPPStats::get_ppp_stats(struct ppp_stats *curp){
struct ifpppstatsreq req;
if(s==0)
return false;
#ifdef __linux__
req.stats_ptr = (caddr_t) &req.stats;
sprintf(req.ifr__name, "ppp%d", unit);
#else
sprintf(req.ifr_name, "ppp%d", unit);
#endif
if (ioctl(s, SIOCGPPPSTATS, &req) < 0) {
if (errno == ENOTTY)
fprintf(stderr, "pppstats: kernel support missing\n");
else
perror("ioctl(SIOCGPPPSTATS)");
return false;
}
*curp = req.stats;
return true;
}
#else /* STREAMS */
bool PPPStats::get_ppp_stats( struct ppp_stats *curp){
if (!strioctl(t, PPPIO_GETSTAT, (char*)curp, 0, sizeof(*curp))) {
if (errno == EINVAL)
fprintf(stderr, "pppstats: kernel support missing\n");
else
perror("pppstats: Couldn't get statistics");
return false;
}
return true;
}
bool PPPStats::strioctl(int fd, int cmd, char* ptr, int ilen, int olen){
struct strioctl str;
str.ic_cmd = cmd;
str.ic_timout = 0;
str.ic_len = ilen;
str.ic_dp = ptr;
if (ioctl(fd, I_STR, &str) == -1)
return false;
if (str.ic_len != olen)
fprintf(stderr, "strioctl: expected %d bytes, got %d for cmd %x\n",
olen, str.ic_len, cmd);
return true;
}
#endif /* STREAMS */
#include "pppstats.moc"
<|endoftext|>
|
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <osgSim/MultiSwitch>
#include <algorithm>
using namespace osgSim;
MultiSwitch::MultiSwitch():
_newChildDefaultValue(true),
_activeSwitchSet(0)
{
}
MultiSwitch::MultiSwitch(const MultiSwitch& sw,const osg::CopyOp& copyop):
osg::Group(sw,copyop),
_newChildDefaultValue(sw._newChildDefaultValue),
_values(sw._values)
{
}
void MultiSwitch::traverse(osg::NodeVisitor& nv)
{
if (nv.getTraversalMode()==osg::NodeVisitor::TRAVERSE_ACTIVE_CHILDREN)
{
if (_activeSwitchSet<_values.size())
{
for(unsigned int pos=0;pos<_children.size();++pos)
{
if (_values[_activeSwitchSet][pos]) _children[pos]->accept(nv);
}
}
}
else
{
Group::traverse(nv);
}
}
bool MultiSwitch::addChild( osg::Node *child)
{
unsigned int childPosition = _children.size();
if (Group::addChild(child))
{
for(SwitchSetList::iterator itr=_values.begin();
itr!=_values.end();
++itr)
{
ValueList& values = *itr;
if (_children.size()>_values.size())
{
values.resize(_children.size(),_newChildDefaultValue);
values[childPosition]=_newChildDefaultValue;
}
}
return true;
}
return false;
}
bool MultiSwitch::insertChild( unsigned int index, osg::Node *child)
{
if (Group::insertChild(index,child))
{
for(SwitchSetList::iterator itr=_values.begin();
itr!=_values.end();
++itr)
{
ValueList& values = *itr;
if (index>=_values.size())
{
values.push_back(_newChildDefaultValue);
}
else
{
values.insert(values.begin()+index, _newChildDefaultValue);
}
}
return true;
}
return false;
}
bool MultiSwitch::removeChild( osg::Node *child )
{
// find the child's position.
unsigned int pos=getChildIndex(child);
if (pos==_children.size()) return false;
for(SwitchSetList::iterator itr=_values.begin();
itr!=_values.end();
++itr)
{
ValueList& values = *itr;
values.erase(values.begin()+pos);
}
return Group::removeChild(child);
}
void MultiSwitch::setValue(unsigned int switchSet, unsigned int pos,bool value)
{
expandToEncompassSwitchSet(switchSet);
ValueList& values = _values[switchSet];
if (pos>=values.size()) values.resize(pos+1,_newChildDefaultValue);
values[pos]=value;
}
void MultiSwitch::setChildValue(const osg::Node* child,unsigned int switchSet, bool value)
{
expandToEncompassSwitchSet(switchSet);
// find the child's position.
unsigned int pos=getChildIndex(child);
if (pos==_children.size()) return;
ValueList& values = _values[switchSet];
values[pos]=value;
}
bool MultiSwitch::getValue(unsigned int switchSet, unsigned int pos) const
{
if (switchSet>=_values.size()) return false;
const ValueList& values = _values[switchSet];
if (pos>=values.size()) return false;
return values[pos];
}
bool MultiSwitch::getChildValue(const osg::Node* child, unsigned int switchSet) const
{
if (switchSet>=_values.size()) return false;
// find the child's position.
unsigned int pos=getChildIndex(child);
if (pos==_children.size()) return false;
const ValueList& values = _values[switchSet];
return values[pos];
}
void MultiSwitch::expandToEncompassSwitchSet(unsigned int switchSet)
{
if (switchSet>=_values.size())
{
// need to expand arrays.
unsigned int originalSize = _values.size();
_values.resize(switchSet+1);
for(unsigned int i=originalSize;i<=switchSet;++i)
{
ValueList& values = _values[switchSet];
values.resize(_children.size(),_newChildDefaultValue);
}
}
}
bool MultiSwitch::setAllChildrenOff(unsigned int switchSet)
{
_newChildDefaultValue = false;
expandToEncompassSwitchSet(switchSet);
ValueList& values = _values[switchSet];
for(ValueList::iterator itr=values.begin();
itr!=values.end();
++itr)
{
*itr = false;
}
return true;
}
bool MultiSwitch::setAllChildrenOn(unsigned int switchSet)
{
_newChildDefaultValue = true;
expandToEncompassSwitchSet(switchSet);
ValueList& values = _values[switchSet];
for(ValueList::iterator itr=values.begin();
itr!=values.end();
++itr)
{
*itr = true;
}
return true;
}
bool MultiSwitch::setSingleChildOn(unsigned int switchSet, unsigned int pos)
{
expandToEncompassSwitchSet(switchSet);
ValueList& values = _values[switchSet];
for(ValueList::iterator itr=values.begin();
itr!=values.end();
++itr)
{
*itr = false;
}
setValue(switchSet, pos,true);
return true;
}
<commit_msg>Added _activeSwitchSet(sw._activeSwitchSet) into the copy constructor.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <osgSim/MultiSwitch>
#include <algorithm>
using namespace osgSim;
MultiSwitch::MultiSwitch():
_newChildDefaultValue(true),
_activeSwitchSet(0)
{
}
MultiSwitch::MultiSwitch(const MultiSwitch& sw,const osg::CopyOp& copyop):
osg::Group(sw,copyop),
_newChildDefaultValue(sw._newChildDefaultValue),
_activeSwitchSet(sw._activeSwitchSet),
_values(sw._values)
{
}
void MultiSwitch::traverse(osg::NodeVisitor& nv)
{
if (nv.getTraversalMode()==osg::NodeVisitor::TRAVERSE_ACTIVE_CHILDREN)
{
if (_activeSwitchSet<_values.size())
{
for(unsigned int pos=0;pos<_children.size();++pos)
{
if (_values[_activeSwitchSet][pos]) _children[pos]->accept(nv);
}
}
}
else
{
Group::traverse(nv);
}
}
bool MultiSwitch::addChild( osg::Node *child)
{
unsigned int childPosition = _children.size();
if (Group::addChild(child))
{
for(SwitchSetList::iterator itr=_values.begin();
itr!=_values.end();
++itr)
{
ValueList& values = *itr;
if (_children.size()>_values.size())
{
values.resize(_children.size(),_newChildDefaultValue);
values[childPosition]=_newChildDefaultValue;
}
}
return true;
}
return false;
}
bool MultiSwitch::insertChild( unsigned int index, osg::Node *child)
{
if (Group::insertChild(index,child))
{
for(SwitchSetList::iterator itr=_values.begin();
itr!=_values.end();
++itr)
{
ValueList& values = *itr;
if (index>=_values.size())
{
values.push_back(_newChildDefaultValue);
}
else
{
values.insert(values.begin()+index, _newChildDefaultValue);
}
}
return true;
}
return false;
}
bool MultiSwitch::removeChild( osg::Node *child )
{
// find the child's position.
unsigned int pos=getChildIndex(child);
if (pos==_children.size()) return false;
for(SwitchSetList::iterator itr=_values.begin();
itr!=_values.end();
++itr)
{
ValueList& values = *itr;
values.erase(values.begin()+pos);
}
return Group::removeChild(child);
}
void MultiSwitch::setValue(unsigned int switchSet, unsigned int pos,bool value)
{
expandToEncompassSwitchSet(switchSet);
ValueList& values = _values[switchSet];
if (pos>=values.size()) values.resize(pos+1,_newChildDefaultValue);
values[pos]=value;
}
void MultiSwitch::setChildValue(const osg::Node* child,unsigned int switchSet, bool value)
{
expandToEncompassSwitchSet(switchSet);
// find the child's position.
unsigned int pos=getChildIndex(child);
if (pos==_children.size()) return;
ValueList& values = _values[switchSet];
values[pos]=value;
}
bool MultiSwitch::getValue(unsigned int switchSet, unsigned int pos) const
{
if (switchSet>=_values.size()) return false;
const ValueList& values = _values[switchSet];
if (pos>=values.size()) return false;
return values[pos];
}
bool MultiSwitch::getChildValue(const osg::Node* child, unsigned int switchSet) const
{
if (switchSet>=_values.size()) return false;
// find the child's position.
unsigned int pos=getChildIndex(child);
if (pos==_children.size()) return false;
const ValueList& values = _values[switchSet];
return values[pos];
}
void MultiSwitch::expandToEncompassSwitchSet(unsigned int switchSet)
{
if (switchSet>=_values.size())
{
// need to expand arrays.
unsigned int originalSize = _values.size();
_values.resize(switchSet+1);
for(unsigned int i=originalSize;i<=switchSet;++i)
{
ValueList& values = _values[switchSet];
values.resize(_children.size(),_newChildDefaultValue);
}
}
}
bool MultiSwitch::setAllChildrenOff(unsigned int switchSet)
{
_newChildDefaultValue = false;
expandToEncompassSwitchSet(switchSet);
ValueList& values = _values[switchSet];
for(ValueList::iterator itr=values.begin();
itr!=values.end();
++itr)
{
*itr = false;
}
return true;
}
bool MultiSwitch::setAllChildrenOn(unsigned int switchSet)
{
_newChildDefaultValue = true;
expandToEncompassSwitchSet(switchSet);
ValueList& values = _values[switchSet];
for(ValueList::iterator itr=values.begin();
itr!=values.end();
++itr)
{
*itr = true;
}
return true;
}
bool MultiSwitch::setSingleChildOn(unsigned int switchSet, unsigned int pos)
{
expandToEncompassSwitchSet(switchSet);
ValueList& values = _values[switchSet];
for(ValueList::iterator itr=values.begin();
itr!=values.end();
++itr)
{
*itr = false;
}
setValue(switchSet, pos,true);
return true;
}
<|endoftext|>
|
<commit_before>/*
* ProbeActivityLinear.cpp
*
* Created on: Mar 7, 2009
* Author: rasmussn
*/
#include "LinearActivityProbe.hpp"
namespace PV {
/**
* @hc
* @dim
* @kLoc
* @f
*/
LinearActivityProbe::LinearActivityProbe(HyPerCol * hc, PVDimType dim, int linePos, int f)
: PVLayerProbe()
{
this->parent = hc;
this->dim = dim;
this->linePos = linePos;
this->f = f;
}
/**
* @filename
* @hc
* @dim
* @kLoc
* @f
*/
LinearActivityProbe::LinearActivityProbe(const char * filename, HyPerCol * hc, PVDimType dim, int linePos, int f)
: PVLayerProbe(filename)
{
this->parent = hc;
this->dim = dim;
this->linePos = linePos;
this->f = f;
}
/**
* @time
* @l
*/
int LinearActivityProbe::outputState(float time, PVLayer * l)
{
int width, sLine, k, kex;
float * line;
float * activity = l->activity->data;
const int nx = l->loc.nx;
const int ny = l->loc.ny;
const int nf = l->numFeatures;
const int marginWidth = l->loc.nPad;
float dt = parent->getDeltaTime();
double sum = 0.0;
float freq;
if (dim == DimX) {
width = nx + 2*marginWidth;
line = l->activity->data + (linePos+marginWidth) * width * nf;
sLine = nf;
}
else {
width = ny + 2*marginWidth;
line = l->activity->data + (linePos+marginWidth)*nf;
sLine = nf * (nx + 2*marginWidth);
}
for (int k = 0; k < width; k++) {
float a = line[f + k * sLine];
sum += a;
}
freq = sum / (width * dt * 0.001);
fprintf(fp, "t=%6.1f sum=%3d f=%6.1f Hz :", time, (int)sum, freq);
for (int k = 0; k < width; k++) {
float a = line[f + k * sLine];
if (a > 0.0) fprintf(fp, "*");
else fprintf(fp, " ");
}
fprintf(fp, ":\n");
fflush(fp);
return 0;
}
} // namespace PV
<commit_msg>LayerProbe now uses HyPerLayer rather than just PVLayer. Also renamed PVLayerProbe to LayerProbe.<commit_after>/*
* ProbeActivityLinear.cpp
*
* Created on: Mar 7, 2009
* Author: rasmussn
*/
#include "LinearActivityProbe.hpp"
namespace PV {
/**
* @hc
* @dim
* @kLoc
* @f
*/
LinearActivityProbe::LinearActivityProbe(HyPerCol * hc, PVDimType dim, int linePos, int f)
: LayerProbe()
{
this->parent = hc;
this->dim = dim;
this->linePos = linePos;
this->f = f;
}
/**
* @filename
* @hc
* @dim
* @kLoc
* @f
*/
LinearActivityProbe::LinearActivityProbe(const char * filename, HyPerCol * hc, PVDimType dim, int linePos, int f)
: LayerProbe(filename)
{
this->parent = hc;
this->dim = dim;
this->linePos = linePos;
this->f = f;
}
/**
* @time
* @l
*/
int LinearActivityProbe::outputState(float time, HyPerLayer * l)
{
int width, sLine, k, kex;
float * line;
const PVLayer * clayer = l->clayer;
float * activity = clayer->activity->data;
const int nx = clayer->loc.nx;
const int ny = clayer->loc.ny;
const int nf = clayer->numFeatures;
const int marginWidth = clayer->loc.nPad;
float dt = parent->getDeltaTime();
double sum = 0.0;
float freq;
if (dim == DimX) {
width = nx + 2*marginWidth;
line = clayer->activity->data + (linePos+marginWidth) * width * nf;
sLine = nf;
}
else {
width = ny + 2*marginWidth;
line = clayer->activity->data + (linePos+marginWidth)*nf;
sLine = nf * (nx + 2*marginWidth);
}
for (int k = 0; k < width; k++) {
float a = line[f + k * sLine];
sum += a;
}
freq = sum / (width * dt * 0.001);
fprintf(fp, "t=%6.1f sum=%3d f=%6.1f Hz :", time, (int)sum, freq);
for (int k = 0; k < width; k++) {
float a = line[f + k * sLine];
if (a > 0.0) fprintf(fp, "*");
else fprintf(fp, " ");
}
fprintf(fp, ":\n");
fflush(fp);
return 0;
}
} // namespace PV
<|endoftext|>
|
<commit_before>/*
* this file is part of the oxygen gtk engine
* Copyright (c) 2010 Hugo Pereira Da Costa <hugo@oxygen-icons.org>
* Copyright (c) 2010 Ruslan Kabatsayev <b7.10110111@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or( at your option ) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include "oxygenwindowshadow.h"
#include "oxygencachekey.h"
#include "oxygencairoutils.h"
#include "oxygencolorutils.h"
namespace Oxygen
{
//________________________________________________________________________________
void WindowShadow::render(cairo_t* cr, gint x, gint y, gint w, gint h)
{
ColorUtils::Rgba background = settings().palette().color(Palette::Window);
WindowShadowKey key;
key.active=_wopt&WinDeco::Active;
tileSet( background, key).render( cr, x, y, w, h, TileSet::Full );
}
//________________________________________________________________________________
const TileSet& WindowShadow::tileSet(const ColorUtils::Rgba& color, WindowShadowKey key)
{
// check if tileset already in cache
const TileSet& tileSet( helper().windowShadowCache().value(key) );
if( tileSet.isValid() ) return tileSet;
const double size( shadowSize() );
return helper().windowShadowCache().insert(key, TileSet( shadowPixmap( color, key ), int(size), int(size), 1, 1 ) );
}
//________________________________________________________________________________
Cairo::Surface WindowShadow::shadowPixmap(const ColorUtils::Rgba& color, const WindowShadowKey& key )
{
const bool active( key.active );
ShadowConfiguration& shadowConfiguration( active ? activeShadowConfiguration_ : inactiveShadowConfiguration_ );
static const double fixedSize=25.5;
double size( shadowSize() );
double shadowSize( shadowConfiguration.isEnabled() ? shadowConfiguration.shadowSize() : 0 );
Cairo::Surface shadow( helper().createSurface( int(size*2), int(size*2) ) );
Cairo::Context p(shadow);
// some gradients rendering are different at bottom corners if client has no border
bool hasBorder( true || _wopt&WinDeco::Shaded ); // TODO: true -> hasBorder
if( shadowSize )
{
if( active && true ) // TODO: true -> useOxygenShadows
{
{
// inner (shark) gradient
const double gradientSize = std::min( shadowSize, (shadowSize+fixedSize)/2 );
const double hoffset = shadowConfiguration.horizontalOffset()*gradientSize/fixedSize;
const double voffset = shadowConfiguration.verticalOffset()*gradientSize/fixedSize;
Cairo::Pattern rg( cairo_pattern_create_radial( size+12.0*hoffset, size+12.0*voffset, gradientSize ) );
cairo_pattern_add_color_stop( rg, 1, ColorUtils::Rgba::transparent() );
// gaussian shadow is used
int nPoints( int( (10*gradientSize)/fixedSize ) );
Gaussian f( 0.85, 0.17 );
ColorUtils::Rgba c(shadowConfiguration.innerColor());
for( double i=0; i < nPoints; i++ )
{
double x = i/nPoints;
c.setAlpha( f(x) );
cairo_pattern_add_color_stop( rg, x, c );
}
cairo_set_source(p, rg);
GdkRectangle rect={0,0,int(size*2),int(size*2)};
renderGradient(p, rect, rg, hasBorder);
}
{
// outer (spread) gradient
const double gradientSize = shadowSize;
const double hoffset = shadowConfiguration.horizontalOffset()*gradientSize/fixedSize;
const double voffset = shadowConfiguration.verticalOffset()*gradientSize/fixedSize;
Cairo::Pattern rg( cairo_pattern_create_radial( size+12.0*hoffset, size+12.0*voffset, gradientSize ) );
cairo_pattern_add_color_stop( rg, 1, ColorUtils::Rgba::transparent() );
// gaussian shadow is used
int nPoints( int( (10*gradientSize)/fixedSize ) );
Gaussian f( 0.46, 0.34 );
ColorUtils::Rgba c(shadowConfiguration.outerColor());
for( double i=0; i < nPoints; i++ )
{
double x = i/nPoints;
c.setAlpha( f(x) );
cairo_pattern_add_color_stop( rg, x, c );
}
cairo_set_source(p, rg);
cairo_rectangle(p, 0,0,size*2,size*2);
cairo_fill(p);
}
} else {
{
// inner (sharp) gradient
const double gradientSize = std::min( shadowSize, fixedSize );
const double hoffset = shadowConfiguration.horizontalOffset()*gradientSize/fixedSize;
const double voffset = shadowConfiguration.verticalOffset()*gradientSize/fixedSize;
Cairo::Pattern rg( cairo_pattern_create_radial( size+hoffset, size+voffset, gradientSize ) );
cairo_pattern_add_color_stop( rg, 1, ColorUtils::Rgba::transparent() );
// parabolic shadow is used
int nPoints( int( (10*gradientSize)/fixedSize ) );
Parabolic f( 1, 0.22 );
ColorUtils::Rgba c(shadowConfiguration.outerColor());
for( double i=0; i < nPoints; i++ )
{
double x = i/nPoints;
c.setAlpha( f(x) );
cairo_pattern_add_color_stop( rg, x, c );
}
cairo_set_source(p, rg);
GdkRectangle rect={0,0,int(size*2),int(size*2)};
renderGradient(p, rect, rg, hasBorder);
}
{
// mid gradient
const double gradientSize = std::min( shadowSize, (shadowSize+2*fixedSize)/3 );
const double hoffset = shadowConfiguration.horizontalOffset()*gradientSize/fixedSize;
const double voffset = shadowConfiguration.verticalOffset()*gradientSize/fixedSize;
Cairo::Pattern rg( cairo_pattern_create_radial( size+8.0*hoffset, size+8.0*voffset, gradientSize ) );
cairo_pattern_add_color_stop( rg, 1, ColorUtils::Rgba::transparent() );
// gaussian shadow is used
int nPoints( int( (10*gradientSize)/fixedSize ) );
Gaussian f( 0.54, 0.21 );
ColorUtils::Rgba c(shadowConfiguration.outerColor());
for( double i=0; i < nPoints; i++ )
{
double x = i/nPoints;
c.setAlpha( f(x) );
cairo_pattern_add_color_stop( rg, x, c );
}
cairo_set_source(p, rg);
cairo_rectangle(p, 0,0,size*2,size*2);
cairo_fill(p);
}
{
// outer (spread) gradient
const double gradientSize = shadowSize;
const double hoffset = shadowConfiguration.horizontalOffset()*gradientSize/fixedSize;
const double voffset = shadowConfiguration.verticalOffset()*gradientSize/fixedSize;
Cairo::Pattern rg( cairo_pattern_create_radial( size+20.0*hoffset, size+20.0*voffset, gradientSize ) );
cairo_pattern_add_color_stop( rg, 1, ColorUtils::Rgba::transparent() );
// gaussian shadow is used
int nPoints( int( (20*gradientSize)/fixedSize ) );
Gaussian f( 0.155, 0.445 );
ColorUtils::Rgba c(shadowConfiguration.outerColor());
for( double i=0; i < nPoints; i++ )
{
double x = i/nPoints;
c.setAlpha( f(x) );
cairo_pattern_add_color_stop( rg, x, c );
}
cairo_set_source(p, rg);
cairo_rectangle(p, 0,0,size*2,size*2);
cairo_fill(p);
}
}
cairo_set_source_rgb(p,0,0,0);
cairo_set_operator(p,CAIRO_OPERATOR_CLEAR);
cairo_ellipse(p, size-3,size-3,6,6);
cairo_fill(p);
}
return shadow;
}
//________________________________________________________________________________
void WindowShadow::renderGradient( cairo_t* p, const GdkRectangle& rect, cairo_pattern_t* rg, bool hasBorder ) const
{
if( hasBorder )
{
cairo_set_source(p,rg);
gdk_cairo_rectangle(p, &rect);
cairo_fill(p);
return;
}
double size( rect.width/2.0 );
// get pattern definition
double x0(0), y0(0), r0(0);
double x1(0), y1(0), r1(0);
const cairo_status_t status( cairo_pattern_get_radial_circles( rg, &x0, &y0, &r0, &x1, &y1, &r1 ) );
assert( status == CAIRO_STATUS_SUCCESS );
const double hoffset( x0 - size );
const double voffset( y0 - size );
const double radius( r1 );
ColorStop::List stops( cairo_pattern_get_color_stops( rg ) );
// draw ellipse for the upper rect
{
cairo_set_source( p, rg );
cairo_rectangle( p, hoffset, voffset, 2*size-hoffset, size );
cairo_fill( p );
}
// draw square gradients for the lower rect
{
// vertical lines
Cairo::Pattern pattern( cairo_pattern_create_linear( hoffset, 0.0, 2*size+hoffset, 0.0 ) );
for( unsigned int i = 0; i < stops.size(); ++i )
{
const ColorUtils::Rgba c( stops[i]._color );
const double x( stops[i]._x * radius );
cairo_pattern_add_color_stop( pattern, (size-x)/(2.0*size), c );
cairo_pattern_add_color_stop( pattern, (size+x)/(2.0*size), c );
}
cairo_set_source( p, pattern );
cairo_rectangle( p, hoffset, size+voffset, 2*size-hoffset, 4 );
cairo_fill( p );
}
{
// horizontal line
Cairo::Pattern pattern( cairo_pattern_create_linear( 0, voffset, 0, 2*size+voffset ) );
for( unsigned int i = 0; i < stops.size(); ++i )
{
const ColorUtils::Rgba c( stops[i]._color );
const double x( stops[i]._x * radius );
cairo_pattern_add_color_stop( pattern, (size+x)/(2.0*size), c );
}
cairo_set_source( p, pattern );
cairo_rectangle( p, size-4+hoffset, size+voffset, 8, size );
cairo_fill( p );
}
{
// bottom-left corner
Cairo::Pattern pattern( cairo_pattern_create_radial( size+hoffset-4, size+voffset+4, radius ) );
for( unsigned int i = 0; i < stops.size(); ++i )
{
ColorUtils::Rgba c( stops[i]._color );
double x( stops[i]._x -4.0/radius );
if( x<0 )
{
if( i < stops.size()-1 )
{
const double x1( stops[i+1]._x - 4.0/radius );
c = ColorUtils::mix( c, stops[i+1]._color, -x/(x1-x) );
}
x = 0;
}
cairo_pattern_add_color_stop( pattern, x, c );
}
cairo_set_source( p, pattern );
cairo_rectangle( p, hoffset, size+voffset+4, size-4, size );
cairo_fill( p );
}
{
// bottom-right corner
Cairo::Pattern pattern( cairo_pattern_create_radial( size+hoffset+4, size+voffset+4, radius ) );
for( unsigned int i = 0; i < stops.size(); ++i )
{
ColorUtils::Rgba c( stops[i]._color );
double x( stops[i]._x -4.0/radius );
if( x<0 )
{
if( i < stops.size()-1 )
{
const double x1( stops[i+1]._x - 4.0/radius );
c = ColorUtils::mix( c, stops[i+1]._color, -x/(x1-x) );
}
x = 0;
}
cairo_pattern_add_color_stop( pattern, x, c );
}
cairo_set_source( p, pattern );
cairo_rectangle( p, size+hoffset+4, size+voffset+4, size-4, size );
cairo_fill( p );
}
}
}
<commit_msg>use "key" values to set flags in shadowPixmap.<commit_after>/*
* this file is part of the oxygen gtk engine
* Copyright (c) 2010 Hugo Pereira Da Costa <hugo@oxygen-icons.org>
* Copyright (c) 2010 Ruslan Kabatsayev <b7.10110111@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or( at your option ) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include "oxygenwindowshadow.h"
#include "oxygencachekey.h"
#include "oxygencairoutils.h"
#include "oxygencolorutils.h"
namespace Oxygen
{
//________________________________________________________________________________
void WindowShadow::render(cairo_t* cr, gint x, gint y, gint w, gint h)
{
ColorUtils::Rgba background = settings().palette().color(Palette::Window);
WindowShadowKey key;
key.active=_wopt&WinDeco::Active;
tileSet( background, key).render( cr, x, y, w, h, TileSet::Full );
}
//________________________________________________________________________________
const TileSet& WindowShadow::tileSet(const ColorUtils::Rgba& color, WindowShadowKey key)
{
// check if tileset already in cache
const TileSet& tileSet( helper().windowShadowCache().value(key) );
if( tileSet.isValid() ) return tileSet;
const double size( shadowSize() );
return helper().windowShadowCache().insert(key, TileSet( shadowPixmap( color, key ), int(size), int(size), 1, 1 ) );
}
//________________________________________________________________________________
Cairo::Surface WindowShadow::shadowPixmap(const ColorUtils::Rgba& color, const WindowShadowKey& key )
{
const bool active( key.active );
ShadowConfiguration& shadowConfiguration( active ? activeShadowConfiguration_ : inactiveShadowConfiguration_ );
static const double fixedSize=25.5;
double size( shadowSize() );
double shadowSize( shadowConfiguration.isEnabled() ? shadowConfiguration.shadowSize() : 0 );
Cairo::Surface shadow( helper().createSurface( int(size*2), int(size*2) ) );
Cairo::Context p(shadow);
// some gradients rendering are different at bottom corners if client has no border
// TODO: true -> hasBorder
bool hasBorder( key.hasBorder );
if( shadowSize )
{
if( active )
{
{
// inner (shark) gradient
const double gradientSize = std::min( shadowSize, (shadowSize+fixedSize)/2 );
const double hoffset = shadowConfiguration.horizontalOffset()*gradientSize/fixedSize;
const double voffset = shadowConfiguration.verticalOffset()*gradientSize/fixedSize;
Cairo::Pattern rg( cairo_pattern_create_radial( size+12.0*hoffset, size+12.0*voffset, gradientSize ) );
cairo_pattern_add_color_stop( rg, 1, ColorUtils::Rgba::transparent() );
// gaussian shadow is used
int nPoints( int( (10*gradientSize)/fixedSize ) );
Gaussian f( 0.85, 0.17 );
ColorUtils::Rgba c(shadowConfiguration.innerColor());
for( double i=0; i < nPoints; i++ )
{
double x = i/nPoints;
c.setAlpha( f(x) );
cairo_pattern_add_color_stop( rg, x, c );
}
cairo_set_source(p, rg);
GdkRectangle rect={0,0,int(size*2),int(size*2)};
renderGradient(p, rect, rg, hasBorder);
}
{
// outer (spread) gradient
const double gradientSize = shadowSize;
const double hoffset = shadowConfiguration.horizontalOffset()*gradientSize/fixedSize;
const double voffset = shadowConfiguration.verticalOffset()*gradientSize/fixedSize;
Cairo::Pattern rg( cairo_pattern_create_radial( size+12.0*hoffset, size+12.0*voffset, gradientSize ) );
cairo_pattern_add_color_stop( rg, 1, ColorUtils::Rgba::transparent() );
// gaussian shadow is used
int nPoints( int( (10*gradientSize)/fixedSize ) );
Gaussian f( 0.46, 0.34 );
ColorUtils::Rgba c(shadowConfiguration.outerColor());
for( double i=0; i < nPoints; i++ )
{
double x = i/nPoints;
c.setAlpha( f(x) );
cairo_pattern_add_color_stop( rg, x, c );
}
cairo_set_source(p, rg);
cairo_rectangle(p, 0,0,size*2,size*2);
cairo_fill(p);
}
} else {
{
// inner (sharp) gradient
const double gradientSize = std::min( shadowSize, fixedSize );
const double hoffset = shadowConfiguration.horizontalOffset()*gradientSize/fixedSize;
const double voffset = shadowConfiguration.verticalOffset()*gradientSize/fixedSize;
Cairo::Pattern rg( cairo_pattern_create_radial( size+hoffset, size+voffset, gradientSize ) );
cairo_pattern_add_color_stop( rg, 1, ColorUtils::Rgba::transparent() );
// parabolic shadow is used
int nPoints( int( (10*gradientSize)/fixedSize ) );
Parabolic f( 1, 0.22 );
ColorUtils::Rgba c(shadowConfiguration.outerColor());
for( double i=0; i < nPoints; i++ )
{
double x = i/nPoints;
c.setAlpha( f(x) );
cairo_pattern_add_color_stop( rg, x, c );
}
cairo_set_source(p, rg);
GdkRectangle rect={0,0,int(size*2),int(size*2)};
renderGradient(p, rect, rg, hasBorder);
}
{
// mid gradient
const double gradientSize = std::min( shadowSize, (shadowSize+2*fixedSize)/3 );
const double hoffset = shadowConfiguration.horizontalOffset()*gradientSize/fixedSize;
const double voffset = shadowConfiguration.verticalOffset()*gradientSize/fixedSize;
Cairo::Pattern rg( cairo_pattern_create_radial( size+8.0*hoffset, size+8.0*voffset, gradientSize ) );
cairo_pattern_add_color_stop( rg, 1, ColorUtils::Rgba::transparent() );
// gaussian shadow is used
int nPoints( int( (10*gradientSize)/fixedSize ) );
Gaussian f( 0.54, 0.21 );
ColorUtils::Rgba c(shadowConfiguration.outerColor());
for( double i=0; i < nPoints; i++ )
{
double x = i/nPoints;
c.setAlpha( f(x) );
cairo_pattern_add_color_stop( rg, x, c );
}
cairo_set_source(p, rg);
cairo_rectangle(p, 0,0,size*2,size*2);
cairo_fill(p);
}
{
// outer (spread) gradient
const double gradientSize = shadowSize;
const double hoffset = shadowConfiguration.horizontalOffset()*gradientSize/fixedSize;
const double voffset = shadowConfiguration.verticalOffset()*gradientSize/fixedSize;
Cairo::Pattern rg( cairo_pattern_create_radial( size+20.0*hoffset, size+20.0*voffset, gradientSize ) );
cairo_pattern_add_color_stop( rg, 1, ColorUtils::Rgba::transparent() );
// gaussian shadow is used
int nPoints( int( (20*gradientSize)/fixedSize ) );
Gaussian f( 0.155, 0.445 );
ColorUtils::Rgba c(shadowConfiguration.outerColor());
for( double i=0; i < nPoints; i++ )
{
double x = i/nPoints;
c.setAlpha( f(x) );
cairo_pattern_add_color_stop( rg, x, c );
}
cairo_set_source(p, rg);
cairo_rectangle(p, 0,0,size*2,size*2);
cairo_fill(p);
}
}
cairo_set_source_rgb(p,0,0,0);
cairo_set_operator(p,CAIRO_OPERATOR_CLEAR);
cairo_ellipse(p, size-3,size-3,6,6);
cairo_fill(p);
}
return shadow;
}
//________________________________________________________________________________
void WindowShadow::renderGradient( cairo_t* p, const GdkRectangle& rect, cairo_pattern_t* rg, bool hasBorder ) const
{
if( hasBorder )
{
cairo_set_source(p,rg);
gdk_cairo_rectangle(p, &rect);
cairo_fill(p);
return;
}
double size( rect.width/2.0 );
// get pattern definition
double x0(0), y0(0), r0(0);
double x1(0), y1(0), r1(0);
const cairo_status_t status( cairo_pattern_get_radial_circles( rg, &x0, &y0, &r0, &x1, &y1, &r1 ) );
assert( status == CAIRO_STATUS_SUCCESS );
const double hoffset( x0 - size );
const double voffset( y0 - size );
const double radius( r1 );
ColorStop::List stops( cairo_pattern_get_color_stops( rg ) );
// draw ellipse for the upper rect
{
cairo_set_source( p, rg );
cairo_rectangle( p, hoffset, voffset, 2*size-hoffset, size );
cairo_fill( p );
}
// draw square gradients for the lower rect
{
// vertical lines
Cairo::Pattern pattern( cairo_pattern_create_linear( hoffset, 0.0, 2*size+hoffset, 0.0 ) );
for( unsigned int i = 0; i < stops.size(); ++i )
{
const ColorUtils::Rgba c( stops[i]._color );
const double x( stops[i]._x * radius );
cairo_pattern_add_color_stop( pattern, (size-x)/(2.0*size), c );
cairo_pattern_add_color_stop( pattern, (size+x)/(2.0*size), c );
}
cairo_set_source( p, pattern );
cairo_rectangle( p, hoffset, size+voffset, 2*size-hoffset, 4 );
cairo_fill( p );
}
{
// horizontal line
Cairo::Pattern pattern( cairo_pattern_create_linear( 0, voffset, 0, 2*size+voffset ) );
for( unsigned int i = 0; i < stops.size(); ++i )
{
const ColorUtils::Rgba c( stops[i]._color );
const double x( stops[i]._x * radius );
cairo_pattern_add_color_stop( pattern, (size+x)/(2.0*size), c );
}
cairo_set_source( p, pattern );
cairo_rectangle( p, size-4+hoffset, size+voffset, 8, size );
cairo_fill( p );
}
{
// bottom-left corner
Cairo::Pattern pattern( cairo_pattern_create_radial( size+hoffset-4, size+voffset+4, radius ) );
for( unsigned int i = 0; i < stops.size(); ++i )
{
ColorUtils::Rgba c( stops[i]._color );
double x( stops[i]._x -4.0/radius );
if( x<0 )
{
if( i < stops.size()-1 )
{
const double x1( stops[i+1]._x - 4.0/radius );
c = ColorUtils::mix( c, stops[i+1]._color, -x/(x1-x) );
}
x = 0;
}
cairo_pattern_add_color_stop( pattern, x, c );
}
cairo_set_source( p, pattern );
cairo_rectangle( p, hoffset, size+voffset+4, size-4, size );
cairo_fill( p );
}
{
// bottom-right corner
Cairo::Pattern pattern( cairo_pattern_create_radial( size+hoffset+4, size+voffset+4, radius ) );
for( unsigned int i = 0; i < stops.size(); ++i )
{
ColorUtils::Rgba c( stops[i]._color );
double x( stops[i]._x -4.0/radius );
if( x<0 )
{
if( i < stops.size()-1 )
{
const double x1( stops[i+1]._x - 4.0/radius );
c = ColorUtils::mix( c, stops[i+1]._color, -x/(x1-x) );
}
x = 0;
}
cairo_pattern_add_color_stop( pattern, x, c );
}
cairo_set_source( p, pattern );
cairo_rectangle( p, size+hoffset+4, size+voffset+4, size-4, size );
cairo_fill( p );
}
}
}
<|endoftext|>
|
<commit_before>/** Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License */
#include "pathOrderOptimizer.h"
#include "utils/logoutput.h"
#include "utils/BucketGrid2D.h"
#define INLINE static inline
namespace cura {
/**
*
*/
void PathOrderOptimizer::optimize()
{
bool picked[polygons.size()];
memset(picked, false, sizeof(bool) * polygons.size());/// initialized as falses
for (PolygonRef poly : polygons) /// find closest point to initial starting point within each polygon +initialize picked
{
int best = -1;
float bestDist = std::numeric_limits<float>::infinity();
for (unsigned int point_idx = 0; point_idx < poly.size(); point_idx++) /// get closest point in polygon
{
float dist = vSize2f(poly[point_idx] - startPoint);
if (dist < bestDist)
{
best = point_idx;
bestDist = dist;
}
}
polyStart.push_back(best);
//picked.push_back(false); /// initialize all picked values as false
assert(poly.size() != 2);
}
Point prev_point = startPoint;
for (unsigned int poly_order_idx = 0; poly_order_idx < polygons.size(); poly_order_idx++) /// actual path order optimizer
{
int best_poly_idx = -1;
float bestDist = std::numeric_limits<float>::infinity();
for (unsigned int poly_idx = 0; poly_idx < polygons.size(); poly_idx++)
{
if (picked[poly_idx] || polygons[poly_idx].size() < 1) /// skip single-point-polygons
{
continue;
}
assert (polygons[poly_idx].size() != 2);
float dist = vSize2f(polygons[poly_idx][polyStart[poly_idx]] - prev_point);
if (dist < bestDist)
{
best_poly_idx = poly_idx;
bestDist = dist;
}
}
if (best_poly_idx > -1) /// should always be true; we should have been able to identify the best next polygon
{
assert(polygons[best_poly_idx].size() != 2);
prev_point = polygons[best_poly_idx][polyStart[best_poly_idx]];
picked[best_poly_idx] = true;
polyOrder.push_back(best_poly_idx);
}
else
{
logError("Failed to find next closest polygon.\n");
}
}
prev_point = startPoint;
for (unsigned int poly_idx = 0; poly_idx < polyOrder.size(); poly_idx++) /// decide final starting points in each polygon
{
int ordered_poly_idx = polyOrder[poly_idx];
int point_idx = getPolyStart(prev_point, ordered_poly_idx);
polyStart[poly_idx] = point_idx;
prev_point = polygons[ordered_poly_idx][point_idx];
}
}
int PathOrderOptimizer::getPolyStart(Point prev_point, int poly_idx)
{
switch (type)
{
case EZSeamType::BACK: return getFarthestPointInPolygon(poly_idx);
case EZSeamType::RANDOM: return getRandomPointInPolygon(poly_idx);
case EZSeamType::SHORTEST: return getClosestPointInPolygon(prev_point, poly_idx);
default: return getClosestPointInPolygon(prev_point, poly_idx);
}
}
int PathOrderOptimizer::getClosestPointInPolygon(Point prev_point, int poly_idx)
{
PolygonRef poly = polygons[poly_idx];
int best_point_idx = -1;
float bestDist = std::numeric_limits<float>::infinity();
bool orientation = poly.orientation();
for (unsigned int point_idx = 0; point_idx < poly.size(); point_idx++)
{
float dist = vSize2f(poly[point_idx] - prev_point);
Point n0 = normal(poly[(point_idx-1+poly.size())%poly.size()] - poly[point_idx], 2000);
Point n1 = normal(poly[point_idx] - poly[(point_idx + 1) % poly.size()], 2000);
float dot_score = dot(n0, n1) - dot(crossZ(n0), n1); /// prefer binnenbocht
if (orientation)
dot_score = -dot_score;
if (dist + dot_score < bestDist)
{
best_point_idx = point_idx;
bestDist = dist;
}
}
return best_point_idx;
}
int PathOrderOptimizer::getRandomPointInPolygon(int poly_idx)
{
return rand() % polygons[poly_idx].size();
}
int PathOrderOptimizer::getFarthestPointInPolygon(int poly_idx)
{
PolygonRef poly = polygons[poly_idx];
int best_point_idx = -1;
float best_y = std::numeric_limits<float>::min();
for(unsigned int point_idx=0 ; point_idx<poly.size() ; point_idx++)
{
if (poly[point_idx].Y > best_y)
{
best_point_idx = point_idx;
best_y = poly[point_idx].Y;
}
}
return best_point_idx;
}
/**
*
*/
void LineOrderOptimizer::optimize()
{
int gridSize = 5000; // the size of the cells in the hash grid.
BucketGrid2D<unsigned int> line_bucket_grid(gridSize);
bool picked[polygons.size()];
memset(picked, false, sizeof(bool) * polygons.size());/// initialized as falses
for (unsigned int poly_idx = 0; poly_idx < polygons.size(); poly_idx++) /// find closest point to initial starting point within each polygon +initialize picked
{
int best_point_idx = -1;
float best_point_dist = std::numeric_limits<float>::infinity();
PolygonRef poly = polygons[poly_idx];
for (unsigned int point_idx = 0; point_idx < poly.size(); point_idx++) /// get closest point from polygon
{
float dist = vSize2f(poly[point_idx] - startPoint);
if (dist < best_point_dist)
{
best_point_idx = point_idx;
best_point_dist = dist;
}
}
polyStart.push_back(best_point_idx);
assert(poly.size() == 2);
line_bucket_grid.insert(poly[0], poly_idx);
line_bucket_grid.insert(poly[1], poly_idx);
}
Point incommingPerpundicularNormal(0, 0);
Point prev_point = startPoint;
for (unsigned int order_idx = 0; order_idx < polygons.size(); order_idx++) /// actual path order optimizer
{
int best_line_idx = -1;
float bestDist = std::numeric_limits<float>::infinity();
for(unsigned int close_line_poly_idx : line_bucket_grid.findNearbyObjects(prev_point)) /// check if single-line-polygon is close to last point
{
if (picked[close_line_poly_idx] || polygons[close_line_poly_idx].size() < 1)
{
continue;
}
checkIfLineIsBest(close_line_poly_idx, best_line_idx, bestDist, prev_point, incommingPerpundicularNormal);
}
if (best_line_idx == -1) /// if single-line-polygon hasn't been found yet
{
for (unsigned int poly_idx = 0; poly_idx < polygons.size(); poly_idx++)
{
if (picked[poly_idx] || polygons[poly_idx].size() < 1) /// skip single-point-polygons
{
continue;
}
assert(polygons[poly_idx].size() == 2);
checkIfLineIsBest(poly_idx, best_line_idx, bestDist, prev_point, incommingPerpundicularNormal);
}
}
if (best_line_idx > -1) /// should always be true; we should have been able to identify the best next polygon
{
assert(polygons[best_line_idx].size() == 2);
int endIdx = polyStart[best_line_idx] * -1 + 1; /// 1 -> 0 , 0 -> 1
prev_point = polygons[best_line_idx][endIdx];
incommingPerpundicularNormal = crossZ(normal(polygons[best_line_idx][endIdx] - polygons[best_line_idx][polyStart[best_line_idx]], 1000));
picked[best_line_idx] = true;
polyOrder.push_back(best_line_idx);
}
else
{
logError("Failed to find next closest line.\n");
}
}
prev_point = startPoint;
for (int poly_idx : polyOrder)
{
PolygonRef poly = polygons[poly_idx];
int best = -1;
float bestDist = std::numeric_limits<float>::infinity();
bool orientation = poly.orientation();
for (unsigned int point_idx = 0; point_idx < poly.size(); point_idx++)
{
float dist = vSize2f(polygons[poly_idx][point_idx] - prev_point);
Point n0 = normal(poly[(point_idx+poly.size()-1)%poly.size()] - poly[point_idx], 2000);
Point n1 = normal(poly[point_idx] - poly[(point_idx + 1) % poly.size()], 2000);
float dot_score = dot(n0, n1) - dot(crossZ(n0), n1);
if (orientation)
dot_score = -dot_score;
if (dist + dot_score < bestDist)
{
best = point_idx;
bestDist = dist + dot_score;
}
}
polyStart[poly_idx] = best;
assert(poly.size() == 2);
prev_point = poly[best *-1 + 1]; /// 1 -> 0 , 0 -> 1
}
}
inline void LineOrderOptimizer::checkIfLineIsBest(unsigned int i_line_polygon, int& best, float& bestDist, Point& prev_point, Point& incommingPerpundicularNormal)
{
{ /// check distance to first point on line (0)
float dist = vSize2f(polygons[i_line_polygon][0] - prev_point);
dist += abs(dot(incommingPerpundicularNormal, normal(polygons[i_line_polygon][1] - polygons[i_line_polygon][0], 1000))) * 0.0001f; /// penalize sharp corners
if (dist < bestDist)
{
best = i_line_polygon;
bestDist = dist;
polyStart[i_line_polygon] = 0;
}
}
{ /// check distance to second point on line (1)
float dist = vSize2f(polygons[i_line_polygon][1] - prev_point);
dist += abs(dot(incommingPerpundicularNormal, normal(polygons[i_line_polygon][0] - polygons[i_line_polygon][1], 1000) )) * 0.0001f; /// penalize sharp corners
if (dist < bestDist)
{
best = i_line_polygon;
bestDist = dist;
polyStart[i_line_polygon] = 1;
}
}
}
}//namespace cura
<commit_msg>refactor: more cleanup of pathOrderOptimizer (CURA-1170)<commit_after>/** Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License */
#include "pathOrderOptimizer.h"
#include "utils/logoutput.h"
#include "utils/BucketGrid2D.h"
#define INLINE static inline
namespace cura {
/**
*
*/
void PathOrderOptimizer::optimize()
{
bool picked[polygons.size()];
memset(picked, false, sizeof(bool) * polygons.size());/// initialized as falses
for (PolygonRef poly : polygons) /// find closest point to initial starting point within each polygon +initialize picked
{
int best = -1;
float bestDist = std::numeric_limits<float>::infinity();
for (unsigned int point_idx = 0; point_idx < poly.size(); point_idx++) /// get closest point in polygon
{
float dist = vSize2f(poly[point_idx] - startPoint);
if (dist < bestDist)
{
best = point_idx;
bestDist = dist;
}
}
polyStart.push_back(best);
//picked.push_back(false); /// initialize all picked values as false
assert(poly.size() != 2);
}
Point prev_point = startPoint;
for (unsigned int poly_order_idx = 0; poly_order_idx < polygons.size(); poly_order_idx++) /// actual path order optimizer
{
int best_poly_idx = -1;
float bestDist = std::numeric_limits<float>::infinity();
for (unsigned int poly_idx = 0; poly_idx < polygons.size(); poly_idx++)
{
if (picked[poly_idx] || polygons[poly_idx].size() < 1) /// skip single-point-polygons
{
continue;
}
assert (polygons[poly_idx].size() != 2);
float dist = vSize2f(polygons[poly_idx][polyStart[poly_idx]] - prev_point);
if (dist < bestDist)
{
best_poly_idx = poly_idx;
bestDist = dist;
}
}
if (best_poly_idx > -1) /// should always be true; we should have been able to identify the best next polygon
{
assert(polygons[best_poly_idx].size() != 2);
prev_point = polygons[best_poly_idx][polyStart[best_poly_idx]];
picked[best_poly_idx] = true;
polyOrder.push_back(best_poly_idx);
}
else
{
logError("Failed to find next closest polygon.\n");
}
}
prev_point = startPoint;
for (unsigned int poly_idx = 0; poly_idx < polyOrder.size(); poly_idx++) /// decide final starting points in each polygon
{
int ordered_poly_idx = polyOrder[poly_idx];
int point_idx = getPolyStart(prev_point, ordered_poly_idx);
polyStart[poly_idx] = point_idx;
prev_point = polygons[ordered_poly_idx][point_idx];
}
}
int PathOrderOptimizer::getPolyStart(Point prev_point, int poly_idx)
{
switch (type)
{
case EZSeamType::BACK: return getFarthestPointInPolygon(poly_idx);
case EZSeamType::RANDOM: return getRandomPointInPolygon(poly_idx);
case EZSeamType::SHORTEST: return getClosestPointInPolygon(prev_point, poly_idx);
default: return getClosestPointInPolygon(prev_point, poly_idx);
}
}
int PathOrderOptimizer::getClosestPointInPolygon(Point prev_point, int poly_idx)
{
PolygonRef poly = polygons[poly_idx];
int best_point_idx = -1;
float bestDist = std::numeric_limits<float>::infinity();
bool orientation = poly.orientation();
Point p0 = poly.back();
for (unsigned int point_idx = 0; point_idx < poly.size(); point_idx++)
{
Point& p1 = poly[point_idx];
Point& p2 = poly[(point_idx + 1) % poly.size()];
float dist = vSize2f(p1 - prev_point);
Point n0 = normal(p0 - p1, 2000);
Point n1 = normal(p1 - p2, 2000);
float dot_score = dot(n0, n1) - dot(crossZ(n0), n1); /// prefer binnenbocht
if (orientation)
{
dot_score = -dot_score;
}
if (dist + dot_score < bestDist)
{
best_point_idx = point_idx;
bestDist = dist;
}
p0 = p1;
}
return best_point_idx;
}
int PathOrderOptimizer::getRandomPointInPolygon(int poly_idx)
{
return rand() % polygons[poly_idx].size();
}
int PathOrderOptimizer::getFarthestPointInPolygon(int poly_idx)
{
PolygonRef poly = polygons[poly_idx];
int best_point_idx = -1;
float best_y = std::numeric_limits<float>::min();
for(unsigned int point_idx=0 ; point_idx<poly.size() ; point_idx++)
{
if (poly[point_idx].Y > best_y)
{
best_point_idx = point_idx;
best_y = poly[point_idx].Y;
}
}
return best_point_idx;
}
/**
*
*/
void LineOrderOptimizer::optimize()
{
int gridSize = 5000; // the size of the cells in the hash grid.
BucketGrid2D<unsigned int> line_bucket_grid(gridSize);
bool picked[polygons.size()];
memset(picked, false, sizeof(bool) * polygons.size());/// initialized as falses
for (unsigned int poly_idx = 0; poly_idx < polygons.size(); poly_idx++) /// find closest point to initial starting point within each polygon +initialize picked
{
int best_point_idx = -1;
float best_point_dist = std::numeric_limits<float>::infinity();
PolygonRef poly = polygons[poly_idx];
for (unsigned int point_idx = 0; point_idx < poly.size(); point_idx++) /// get closest point from polygon
{
float dist = vSize2f(poly[point_idx] - startPoint);
if (dist < best_point_dist)
{
best_point_idx = point_idx;
best_point_dist = dist;
}
}
polyStart.push_back(best_point_idx);
assert(poly.size() == 2);
line_bucket_grid.insert(poly[0], poly_idx);
line_bucket_grid.insert(poly[1], poly_idx);
}
Point incommingPerpundicularNormal(0, 0);
Point prev_point = startPoint;
for (unsigned int order_idx = 0; order_idx < polygons.size(); order_idx++) /// actual path order optimizer
{
int best_line_idx = -1;
float bestDist = std::numeric_limits<float>::infinity();
for(unsigned int close_line_poly_idx : line_bucket_grid.findNearbyObjects(prev_point)) /// check if single-line-polygon is close to last point
{
if (picked[close_line_poly_idx] || polygons[close_line_poly_idx].size() < 1)
{
continue;
}
checkIfLineIsBest(close_line_poly_idx, best_line_idx, bestDist, prev_point, incommingPerpundicularNormal);
}
if (best_line_idx == -1) /// if single-line-polygon hasn't been found yet
{
for (unsigned int poly_idx = 0; poly_idx < polygons.size(); poly_idx++)
{
if (picked[poly_idx] || polygons[poly_idx].size() < 1) /// skip single-point-polygons
{
continue;
}
assert(polygons[poly_idx].size() == 2);
checkIfLineIsBest(poly_idx, best_line_idx, bestDist, prev_point, incommingPerpundicularNormal);
}
}
if (best_line_idx > -1) /// should always be true; we should have been able to identify the best next polygon
{
assert(polygons[best_line_idx].size() == 2);
int endIdx = polyStart[best_line_idx] * -1 + 1; /// 1 -> 0 , 0 -> 1
prev_point = polygons[best_line_idx][endIdx];
incommingPerpundicularNormal = crossZ(normal(polygons[best_line_idx][endIdx] - polygons[best_line_idx][polyStart[best_line_idx]], 1000));
picked[best_line_idx] = true;
polyOrder.push_back(best_line_idx);
}
else
{
logError("Failed to find next closest line.\n");
}
}
prev_point = startPoint;
for (int poly_idx : polyOrder)
{
PolygonRef poly = polygons[poly_idx];
int best = -1;
float bestDist = std::numeric_limits<float>::infinity();
bool orientation = poly.orientation();
for (unsigned int point_idx = 0; point_idx < poly.size(); point_idx++)
{
float dist = vSize2f(polygons[poly_idx][point_idx] - prev_point);
Point n0 = normal(poly[(point_idx+poly.size()-1)%poly.size()] - poly[point_idx], 2000);
Point n1 = normal(poly[point_idx] - poly[(point_idx + 1) % poly.size()], 2000);
float dot_score = dot(n0, n1) - dot(crossZ(n0), n1);
if (orientation)
dot_score = -dot_score;
if (dist + dot_score < bestDist)
{
best = point_idx;
bestDist = dist + dot_score;
}
}
polyStart[poly_idx] = best;
assert(poly.size() == 2);
prev_point = poly[best *-1 + 1]; /// 1 -> 0 , 0 -> 1
}
}
inline void LineOrderOptimizer::checkIfLineIsBest(unsigned int poly_idx, int& best, float& best_dist, Point& prev_point, Point& incomming_perpundicular_normal)
{
{ /// check distance to first point on line (0)
float dist = vSize2f(polygons[poly_idx][0] - prev_point);
dist += abs(dot(incomming_perpundicular_normal, normal(polygons[poly_idx][1] - polygons[poly_idx][0], 1000))) * 0.0001f; /// penalize sharp corners
if (dist < best_dist)
{
best = poly_idx;
best_dist = dist;
polyStart[poly_idx] = 0;
}
}
{ /// check distance to second point on line (1)
float dist = vSize2f(polygons[poly_idx][1] - prev_point);
dist += abs(dot(incomming_perpundicular_normal, normal(polygons[poly_idx][0] - polygons[poly_idx][1], 1000) )) * 0.0001f; /// penalize sharp corners
if (dist < best_dist)
{
best = poly_idx;
best_dist = dist;
polyStart[poly_idx] = 1;
}
}
}
}//namespace cura
<|endoftext|>
|
<commit_before>#include "interface/usb.h"
#include "util/bytebuffer.h"
#include "util/log.h"
#include "gpio.h"
#ifdef CHIPKIT
#define USB_VBUS_ANALOG_INPUT A0
#endif
#define USB_HANDLE_MAX_WAIT_COUNT 35000
namespace gpio = openxc::gpio;
using openxc::util::log::debug;
using openxc::interface::usb::UsbDevice;
using openxc::interface::usb::UsbEndpoint;
using openxc::interface::usb::UsbEndpointDirection;
using openxc::gpio::GPIO_DIRECTION_INPUT;
using openxc::util::bytebuffer::processQueue;
// This is a reference to the last packet read
extern volatile CTRL_TRF_SETUP SetupPkt;
extern UsbDevice USB_DEVICE;
extern bool handleControlRequest(uint8_t);
boolean usbCallback(USB_EVENT event, void *pdata, word size) {
// initial connection up to configure will be handled by the default
// callback routine.
USB_DEVICE.device.DefaultCBEventHandler(event, pdata, size);
// TODO why can't we use USB_EVENT as the type anymore? rejects
// EVENT_EP0_REQUEST as a switch case
switch((int)event) {
case EVENT_CONFIGURED:
debug("USB Configured");
USB_DEVICE.configured = true;
for(int i = 0; i < ENDPOINT_COUNT; i++) {
UsbEndpoint* endpoint = &USB_DEVICE.endpoints[i];
if(endpoint->direction == UsbEndpointDirection::USB_ENDPOINT_DIRECTION_OUT) {
USB_DEVICE.device.EnableEndpoint(endpoint->address,
USB_OUT_ENABLED|USB_HANDSHAKE_ENABLED|USB_DISALLOW_SETUP);
} else {
USB_DEVICE.device.EnableEndpoint(endpoint->address,
USB_IN_ENABLED|USB_HANDSHAKE_ENABLED|USB_DISALLOW_SETUP);
}
}
break;
case EVENT_EP0_REQUEST:
handleControlRequest(SetupPkt.bRequest);
break;
default:
break;
}
return true;
}
void openxc::interface::usb::sendControlMessage(uint8_t* data, uint8_t length) {
USB_DEVICE.device.EP0SendRAMPtr(data, length, USB_EP0_INCLUDE_ZERO);
}
bool vbusEnabled() {
#ifdef USB_VBUS_ANALOG_INPUT
return analogRead(USB_VBUS_ANALOG_INPUT) > 100;
#else
return true;
#endif
}
bool waitForHandle(UsbDevice* usbDevice, UsbEndpoint* endpoint) {
int i = 0;
while(usbDevice->configured &&
usbDevice->device.HandleBusy(endpoint->deviceToHostHandle)) {
++i;
if(i > USB_HANDLE_MAX_WAIT_COUNT) {
// The reason we want to exit this loop early is that if USB is
// attached and configured, but the host isn't sending an IN
// requests, we will block here forever. As it is, it still slows
// down UART transfers quite a bit, so setting configured = false
// ASAP is important.
// This can get really noisy when running but I want to leave it in
// because it' useful to enable when debugging.
// debug("USB most likely not connected or at least not requesting "
// "IN transfers - bailing out of handle waiting");
return false;
}
}
return true;
}
void openxc::interface::usb::processSendQueue(UsbDevice* usbDevice) {
if(usbDevice->configured && !vbusEnabled()) {
debug("USB no longer detected - marking unconfigured");
usbDevice->configured = false;
return;
}
for(int i = 0; i < ENDPOINT_COUNT; i++) {
UsbEndpoint* endpoint = &usbDevice->endpoints[i];
// Don't touch usbDevice->sendBuffer if there's still a pending transfer
if(!waitForHandle(usbDevice, endpoint)) {
return;
}
while(usbDevice->configured &&
!QUEUE_EMPTY(uint8_t, &endpoint->queue)) {
int byteCount = 0;
while(!QUEUE_EMPTY(uint8_t, &endpoint->queue) &&
byteCount < USB_SEND_BUFFER_SIZE) {
endpoint->sendBuffer[byteCount++] = QUEUE_POP(uint8_t,
&endpoint->queue);
}
int nextByteIndex = 0;
while(nextByteIndex < byteCount) {
// Make sure the USB write is 100% complete before messing with this
// buffer after we copy the message into it - the Microchip library
// doesn't copy the data to its own internal buffer. See #171 for
// background on this issue.
// TODO instead of dropping, replace POP above with a SNAPSHOT
// and POP off only exactly how many bytes were sent after the
// fact.
// TODO in order for this not to fail too often I had to increase
// the USB_HANDLE_MAX_WAIT_COUNT. that may be OK since now we have
// VBUS detection.
if(!waitForHandle(usbDevice, endpoint)) {
debug("USB not responding in a timely fashion, dropped data");
return;
}
int bytesToTransfer = min(MAX_USB_PACKET_SIZE_BYTES,
byteCount - nextByteIndex);
endpoint->deviceToHostHandle = usbDevice->device.GenWrite(
endpoint->address,
&endpoint->sendBuffer[nextByteIndex], bytesToTransfer);
nextByteIndex += bytesToTransfer;
}
}
}
}
void openxc::interface::usb::initialize(UsbDevice* usbDevice) {
usb::initializeCommon(usbDevice);
usbDevice->device = USBDevice(usbCallback);
usbDevice->device.InitializeSystem(false);
#ifdef USB_VBUS_ANALOG_INPUT
gpio::setDirection(0, USB_VBUS_ANALOG_INPUT, GPIO_DIRECTION_INPUT);
#endif
debug("Done.");
}
void openxc::interface::usb::deinitialize(UsbDevice* usbDevice) {
// disable USB (notifies stack we are disabling)
USBModuleDisable();
// power off the USB peripheral
// TODO could not find a ready-made function or macro
// in the USB library to actually turn off the module.
// USBModuleDisable() is close to what we want, but it
// sets the ON bit to 1 for some reason.
// so, easy solution is just go right to the control register, for now
U1PWRCCLR = (1 << 0);
}
/* Private: Arm the given endpoint for a read from the device to host.
*
* This also puts a NUL char in the beginning of the buffer so you don't get
* confused that it's still a valid message.
*
* device - the CAN USB device to arm the endpoint on
* endpoint - the endpoint to arm.
* buffer - the destination buffer for the next OUT transfer.
*/
void armForRead(UsbDevice* usbDevice, UsbEndpoint* endpoint) {
endpoint->receiveBuffer[0] = 0;
endpoint->hostToDeviceHandle = usbDevice->device.GenRead(
endpoint->address, (uint8_t*)endpoint->receiveBuffer,
endpoint->size);
}
void openxc::interface::usb::read(UsbDevice* device, UsbEndpoint* endpoint,
bool (*callback)(uint8_t*)) {
if(!device->device.HandleBusy(endpoint->hostToDeviceHandle)) {
if(endpoint->receiveBuffer[0] != '\0') {
for(int i = 0; i < endpoint->size; i++) {
if(!QUEUE_PUSH(uint8_t, &endpoint->queue,
endpoint->receiveBuffer[i])) {
debug("Dropped write from host -- queue is full");
}
}
processQueue(&endpoint->queue, callback);
}
armForRead(device, endpoint);
}
}
<commit_msg>Remove a TODO resolved by Makefile improvements.<commit_after>#include "interface/usb.h"
#include "util/bytebuffer.h"
#include "util/log.h"
#include "gpio.h"
#ifdef CHIPKIT
#define USB_VBUS_ANALOG_INPUT A0
#endif
#define USB_HANDLE_MAX_WAIT_COUNT 35000
namespace gpio = openxc::gpio;
using openxc::util::log::debug;
using openxc::interface::usb::UsbDevice;
using openxc::interface::usb::UsbEndpoint;
using openxc::interface::usb::UsbEndpointDirection;
using openxc::gpio::GPIO_DIRECTION_INPUT;
using openxc::util::bytebuffer::processQueue;
// This is a reference to the last packet read
extern volatile CTRL_TRF_SETUP SetupPkt;
extern UsbDevice USB_DEVICE;
extern bool handleControlRequest(uint8_t);
boolean usbCallback(USB_EVENT event, void *pdata, word size) {
// initial connection up to configure will be handled by the default
// callback routine.
USB_DEVICE.device.DefaultCBEventHandler(event, pdata, size);
switch(event) {
case EVENT_CONFIGURED:
debug("USB Configured");
USB_DEVICE.configured = true;
for(int i = 0; i < ENDPOINT_COUNT; i++) {
UsbEndpoint* endpoint = &USB_DEVICE.endpoints[i];
if(endpoint->direction == UsbEndpointDirection::USB_ENDPOINT_DIRECTION_OUT) {
USB_DEVICE.device.EnableEndpoint(endpoint->address,
USB_OUT_ENABLED|USB_HANDSHAKE_ENABLED|USB_DISALLOW_SETUP);
} else {
USB_DEVICE.device.EnableEndpoint(endpoint->address,
USB_IN_ENABLED|USB_HANDSHAKE_ENABLED|USB_DISALLOW_SETUP);
}
}
break;
case EVENT_EP0_REQUEST:
handleControlRequest(SetupPkt.bRequest);
break;
default:
break;
}
return true;
}
void openxc::interface::usb::sendControlMessage(uint8_t* data, uint8_t length) {
USB_DEVICE.device.EP0SendRAMPtr(data, length, USB_EP0_INCLUDE_ZERO);
}
bool vbusEnabled() {
#ifdef USB_VBUS_ANALOG_INPUT
return analogRead(USB_VBUS_ANALOG_INPUT) > 100;
#else
return true;
#endif
}
bool waitForHandle(UsbDevice* usbDevice, UsbEndpoint* endpoint) {
int i = 0;
while(usbDevice->configured &&
usbDevice->device.HandleBusy(endpoint->deviceToHostHandle)) {
++i;
if(i > USB_HANDLE_MAX_WAIT_COUNT) {
// The reason we want to exit this loop early is that if USB is
// attached and configured, but the host isn't sending an IN
// requests, we will block here forever. As it is, it still slows
// down UART transfers quite a bit, so setting configured = false
// ASAP is important.
// This can get really noisy when running but I want to leave it in
// because it' useful to enable when debugging.
// debug("USB most likely not connected or at least not requesting "
// "IN transfers - bailing out of handle waiting");
return false;
}
}
return true;
}
void openxc::interface::usb::processSendQueue(UsbDevice* usbDevice) {
if(usbDevice->configured && !vbusEnabled()) {
debug("USB no longer detected - marking unconfigured");
usbDevice->configured = false;
return;
}
for(int i = 0; i < ENDPOINT_COUNT; i++) {
UsbEndpoint* endpoint = &usbDevice->endpoints[i];
// Don't touch usbDevice->sendBuffer if there's still a pending transfer
if(!waitForHandle(usbDevice, endpoint)) {
return;
}
while(usbDevice->configured &&
!QUEUE_EMPTY(uint8_t, &endpoint->queue)) {
int byteCount = 0;
while(!QUEUE_EMPTY(uint8_t, &endpoint->queue) &&
byteCount < USB_SEND_BUFFER_SIZE) {
endpoint->sendBuffer[byteCount++] = QUEUE_POP(uint8_t,
&endpoint->queue);
}
int nextByteIndex = 0;
while(nextByteIndex < byteCount) {
// Make sure the USB write is 100% complete before messing with this
// buffer after we copy the message into it - the Microchip library
// doesn't copy the data to its own internal buffer. See #171 for
// background on this issue.
// TODO instead of dropping, replace POP above with a SNAPSHOT
// and POP off only exactly how many bytes were sent after the
// fact.
// TODO in order for this not to fail too often I had to increase
// the USB_HANDLE_MAX_WAIT_COUNT. that may be OK since now we have
// VBUS detection.
if(!waitForHandle(usbDevice, endpoint)) {
debug("USB not responding in a timely fashion, dropped data");
return;
}
int bytesToTransfer = min(MAX_USB_PACKET_SIZE_BYTES,
byteCount - nextByteIndex);
endpoint->deviceToHostHandle = usbDevice->device.GenWrite(
endpoint->address,
&endpoint->sendBuffer[nextByteIndex], bytesToTransfer);
nextByteIndex += bytesToTransfer;
}
}
}
}
void openxc::interface::usb::initialize(UsbDevice* usbDevice) {
usb::initializeCommon(usbDevice);
usbDevice->device = USBDevice(usbCallback);
usbDevice->device.InitializeSystem(false);
#ifdef USB_VBUS_ANALOG_INPUT
gpio::setDirection(0, USB_VBUS_ANALOG_INPUT, GPIO_DIRECTION_INPUT);
#endif
debug("Done.");
}
void openxc::interface::usb::deinitialize(UsbDevice* usbDevice) {
// disable USB (notifies stack we are disabling)
USBModuleDisable();
// power off the USB peripheral
// TODO could not find a ready-made function or macro
// in the USB library to actually turn off the module.
// USBModuleDisable() is close to what we want, but it
// sets the ON bit to 1 for some reason.
// so, easy solution is just go right to the control register, for now
U1PWRCCLR = (1 << 0);
}
/* Private: Arm the given endpoint for a read from the device to host.
*
* This also puts a NUL char in the beginning of the buffer so you don't get
* confused that it's still a valid message.
*
* device - the CAN USB device to arm the endpoint on
* endpoint - the endpoint to arm.
* buffer - the destination buffer for the next OUT transfer.
*/
void armForRead(UsbDevice* usbDevice, UsbEndpoint* endpoint) {
endpoint->receiveBuffer[0] = 0;
endpoint->hostToDeviceHandle = usbDevice->device.GenRead(
endpoint->address, (uint8_t*)endpoint->receiveBuffer,
endpoint->size);
}
void openxc::interface::usb::read(UsbDevice* device, UsbEndpoint* endpoint,
bool (*callback)(uint8_t*)) {
if(!device->device.HandleBusy(endpoint->hostToDeviceHandle)) {
if(endpoint->receiveBuffer[0] != '\0') {
for(int i = 0; i < endpoint->size; i++) {
if(!QUEUE_PUSH(uint8_t, &endpoint->queue,
endpoint->receiveBuffer[i])) {
debug("Dropped write from host -- queue is full");
}
}
processQueue(&endpoint->queue, callback);
}
armForRead(device, endpoint);
}
}
<|endoftext|>
|
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2017 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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.
//#define DEBUG
#define MYINFO(X,...) INFO("Kernel", X, ##__VA_ARGS__)
#include <boot/multiboot.h>
#include <hw/cmos.hpp>
#include <kernel/os.hpp>
#include <kernel/events.hpp>
#include <kprint>
#include <service>
#include <statman>
#include <cstdio>
#include <cinttypes>
//#define ENABLE_PROFILERS
#ifdef ENABLE_PROFILERS
#include <profile>
#define PROFILE(name) ScopedProfiler __CONCAT(sp, __COUNTER__){name};
#else
#define PROFILE(name) /* name */
#endif
extern "C" void* get_cpu_esp();
extern "C" void __libc_init_array();
extern uintptr_t heap_begin;
extern uintptr_t heap_end;
extern uintptr_t _start;
extern uintptr_t _end;
extern uintptr_t _ELF_START_;
extern uintptr_t _TEXT_START_;
extern uintptr_t _LOAD_START_;
extern uintptr_t _ELF_END_;
struct alignas(SMP_ALIGN) OS_CPU {
uint64_t cycles_hlt = 0;
};
static SMP_ARRAY<OS_CPU> os_per_cpu;
int64_t OS::micros_since_boot() noexcept {
return cycles_since_boot() / cpu_freq().count();
}
RTC::timestamp_t OS::boot_timestamp()
{
return RTC::boot_timestamp();
}
RTC::timestamp_t OS::uptime()
{
return RTC::time_since_boot();
}
uint64_t OS::cycles_asleep() noexcept {
return PER_CPU(os_per_cpu).cycles_hlt;
}
uint64_t OS::micros_asleep() noexcept {
return PER_CPU(os_per_cpu).cycles_hlt / cpu_freq().count();
}
__attribute__((noinline))
void OS::halt()
{
uint64_t cycles_before = __arch_cpu_cycles();
asm volatile("hlt");
// add a global symbol here so we can quickly discard
// event loop from stack sampling
asm volatile(
".global _irq_cb_return_location;\n"
"_irq_cb_return_location:" );
// Count sleep cycles
PER_CPU(os_per_cpu).cycles_hlt += __arch_cpu_cycles() - cycles_before;
}
void OS::default_stdout(const char* str, const size_t len)
{
__serial_print(str, len);
}
void OS::start(uint32_t boot_magic, uint32_t boot_addr)
{
OS::cmdline = Service::binary_name();
// Initialize stdout handlers
OS::add_stdout(&OS::default_stdout);
PROFILE("OS::start");
// Print a fancy header
CAPTION("#include<os> // Literally");
void* esp = get_cpu_esp();
MYINFO("Stack: %p", esp);
MYINFO("Boot magic: 0x%x, addr: 0x%x", boot_magic, boot_addr);
/// STATMAN ///
PROFILE("Statman");
/// initialize on page 7, 3 pages in size
Statman::get().init(0x6000, 0x3000);
// Call global ctors
PROFILE("Global constructors");
__libc_init_array();
// BOOT METHOD //
PROFILE("Multiboot / legacy");
OS::memory_end_ = 0;
// Detect memory limits etc. depending on boot type
if (boot_magic == MULTIBOOT_BOOTLOADER_MAGIC) {
OS::multiboot(boot_addr);
} else {
if (is_softreset_magic(boot_magic) && boot_addr != 0)
OS::resume_softreset(boot_addr);
OS::legacy_boot();
}
Expects(OS::memory_end_ != 0);
// Give the rest of physical memory to heap
OS::heap_max_ = OS::memory_end_;
PROFILE("Memory map");
// Assign memory ranges used by the kernel
auto& memmap = memory_map();
MYINFO("Assigning fixed memory ranges (Memory map)");
memmap.assign_range({0x6000, 0x8fff, "Statman", "Statistics"});
#if defined(ARCH_x86_64)
memmap.assign_range({0x100000, 0x8fffff, "Pagetables", "System page tables"});
memmap.assign_range({0x900000, 0x9fffff, "Stack", "System main stack"});
#elif defined(ARCH_i686)
memmap.assign_range({0xA000, 0x9fbff, "Stack", "System main stack"});
#endif
memmap.assign_range({(uintptr_t)&_LOAD_START_, (uintptr_t)&_end - 1,
"ELF", "Your service binary including OS"});
Expects(::heap_begin and heap_max_);
// @note for security we don't want to expose this
memmap.assign_range({(uintptr_t)&_end, ::heap_begin - 1,
"Pre-heap", "Heap randomization area"});
uintptr_t span_max = std::numeric_limits<std::ptrdiff_t>::max();
uintptr_t heap_range_max_ = std::min(span_max, heap_max_);
MYINFO("Assigning heap");
memmap.assign_range({::heap_begin, heap_range_max_,
"Heap", "Dynamic memory", heap_usage });
MYINFO("Printing memory map");
for (const auto &i : memmap)
INFO2("* %s",i.second.to_string().c_str());
PROFILE("Platform init");
extern void __platform_init();
__platform_init();
PROFILE("RTC init");
// Realtime/monotonic clock
RTC::init();
}
void OS::event_loop()
{
Events::get(0).process_events();
do {
OS::halt();
Events::get(0).process_events();
} while (power_);
MYINFO("Stopping service");
Service::stop();
MYINFO("Powering off");
extern void __arch_poweroff();
__arch_poweroff();
}
void OS::legacy_boot()
{
// Fetch CMOS memory info (unfortunately this is maximally 10^16 kb)
auto mem = hw::CMOS::meminfo();
//uintptr_t low_memory_size = mem.base.total * 1024;
INFO2("* Low memory: %i Kib", mem.base.total);
uintptr_t high_memory_size = mem.extended.total * 1024;
INFO2("* High memory (from cmos): %i Kib", mem.extended.total);
auto& memmap = memory_map();
// No guarantees without multiboot, but we assume standard memory layout
memmap.assign_range({0x0009FC00, 0x0009FFFF,
"EBDA", "Extended BIOS data area"});
memmap.assign_range({0x000A0000, 0x000FFFFF,
"VGA/ROM", "Memory mapped video memory"});
// @note : since the maximum size of a span is unsigned (ptrdiff_t) we may need more than one
uintptr_t addr_max = std::numeric_limits<std::size_t>::max();
uintptr_t span_max = std::numeric_limits<std::ptrdiff_t>::max();
uintptr_t unavail_start = 0x100000 + high_memory_size;
size_t interval = std::min(span_max, addr_max - unavail_start) - 1;
uintptr_t unavail_end = unavail_start + interval;
while (unavail_end < addr_max){
INFO2("* Unavailable memory: 0x%" PRIxPTR" - 0x%" PRIxPTR, unavail_start, unavail_end);
memmap.assign_range({unavail_start, unavail_end,
"N/A", "Reserved / outside physical range" });
unavail_start = unavail_end + 1;
interval = std::min(span_max, addr_max - unavail_start);
// Increment might wrapped around
if (unavail_start > unavail_end + interval or unavail_start + interval == addr_max){
INFO2("* Last chunk of memory: 0x%" PRIxPTR" - 0x%" PRIxPTR, unavail_start, addr_max);
memmap.assign_range({unavail_start, addr_max,
"N/A", "Reserved / outside physical range" });
break;
}
unavail_end += interval;
}
}
<commit_msg>x86: Initialize legacy heap properly<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2017 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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.
//#define DEBUG
#define MYINFO(X,...) INFO("Kernel", X, ##__VA_ARGS__)
#include <boot/multiboot.h>
#include <hw/cmos.hpp>
#include <kernel/os.hpp>
#include <kernel/events.hpp>
#include <kprint>
#include <service>
#include <statman>
#include <cstdio>
#include <cinttypes>
//#define ENABLE_PROFILERS
#ifdef ENABLE_PROFILERS
#include <profile>
#define PROFILE(name) ScopedProfiler __CONCAT(sp, __COUNTER__){name};
#else
#define PROFILE(name) /* name */
#endif
extern "C" void* get_cpu_esp();
extern "C" void __libc_init_array();
extern uintptr_t heap_begin;
extern uintptr_t heap_end;
extern uintptr_t _start;
extern uintptr_t _end;
extern uintptr_t _ELF_START_;
extern uintptr_t _TEXT_START_;
extern uintptr_t _LOAD_START_;
extern uintptr_t _ELF_END_;
struct alignas(SMP_ALIGN) OS_CPU {
uint64_t cycles_hlt = 0;
};
static SMP_ARRAY<OS_CPU> os_per_cpu;
int64_t OS::micros_since_boot() noexcept {
return cycles_since_boot() / cpu_freq().count();
}
RTC::timestamp_t OS::boot_timestamp()
{
return RTC::boot_timestamp();
}
RTC::timestamp_t OS::uptime()
{
return RTC::time_since_boot();
}
uint64_t OS::cycles_asleep() noexcept {
return PER_CPU(os_per_cpu).cycles_hlt;
}
uint64_t OS::micros_asleep() noexcept {
return PER_CPU(os_per_cpu).cycles_hlt / cpu_freq().count();
}
__attribute__((noinline))
void OS::halt()
{
uint64_t cycles_before = __arch_cpu_cycles();
asm volatile("hlt");
// add a global symbol here so we can quickly discard
// event loop from stack sampling
asm volatile(
".global _irq_cb_return_location;\n"
"_irq_cb_return_location:" );
// Count sleep cycles
PER_CPU(os_per_cpu).cycles_hlt += __arch_cpu_cycles() - cycles_before;
}
void OS::default_stdout(const char* str, const size_t len)
{
__serial_print(str, len);
}
void OS::start(uint32_t boot_magic, uint32_t boot_addr)
{
OS::cmdline = Service::binary_name();
// Initialize stdout handlers
OS::add_stdout(&OS::default_stdout);
PROFILE("OS::start");
// Print a fancy header
CAPTION("#include<os> // Literally");
MYINFO("Stack: %p", get_cpu_esp());
MYINFO("Boot magic: 0x%x, addr: 0x%x", boot_magic, boot_addr);
/// STATMAN ///
PROFILE("Statman");
/// initialize on page 7, 3 pages in size
Statman::get().init(0x6000, 0x3000);
// Call global ctors
PROFILE("Global constructors");
__libc_init_array();
// BOOT METHOD //
PROFILE("Multiboot / legacy");
OS::memory_end_ = 0;
// Detect memory limits etc. depending on boot type
if (boot_magic == MULTIBOOT_BOOTLOADER_MAGIC) {
OS::multiboot(boot_addr);
} else {
if (is_softreset_magic(boot_magic) && boot_addr != 0)
OS::resume_softreset(boot_addr);
OS::legacy_boot();
}
assert(OS::memory_end_ != 0);
// Give the rest of physical memory to heap
OS::heap_max_ = OS::memory_end_;
PROFILE("Memory map");
// Assign memory ranges used by the kernel
auto& memmap = memory_map();
MYINFO("Assigning fixed memory ranges (Memory map)");
memmap.assign_range({0x6000, 0x8fff, "Statman", "Statistics"});
#if defined(ARCH_x86_64)
memmap.assign_range({0x100000, 0x8fffff, "Pagetables", "System page tables"});
memmap.assign_range({0x900000, 0x9fffff, "Stack", "System main stack"});
#elif defined(ARCH_i686)
memmap.assign_range({0xA000, 0x9fbff, "Stack", "System main stack"});
#endif
memmap.assign_range({(uintptr_t)&_LOAD_START_, (uintptr_t)&_end - 1,
"ELF", "Your service binary including OS"});
assert(::heap_begin != 0x0 and OS::heap_max_ != 0x0);
// @note for security we don't want to expose this
memmap.assign_range({(uintptr_t)&_end, ::heap_begin - 1,
"Pre-heap", "Heap randomization area"});
uintptr_t span_max = std::numeric_limits<std::ptrdiff_t>::max();
uintptr_t heap_range_max_ = std::min(span_max, OS::heap_max_-1);
MYINFO("Assigning heap");
memmap.assign_range({::heap_begin, heap_range_max_,
"Heap", "Dynamic memory", heap_usage });
MYINFO("Printing memory map");
for (const auto &i : memmap)
INFO2("* %s",i.second.to_string().c_str());
PROFILE("Platform init");
extern void __platform_init();
__platform_init();
PROFILE("RTC init");
// Realtime/monotonic clock
RTC::init();
}
void OS::event_loop()
{
Events::get(0).process_events();
do {
OS::halt();
Events::get(0).process_events();
} while (power_);
MYINFO("Stopping service");
Service::stop();
MYINFO("Powering off");
extern void __arch_poweroff();
__arch_poweroff();
}
void OS::legacy_boot()
{
// Fetch CMOS memory info (unfortunately this is maximally 10^16 kb)
auto mem = hw::CMOS::meminfo();
if (OS::memory_end_ == 0)
{
//uintptr_t low_memory_size = mem.base.total * 1024;
INFO2("* Low memory: %i Kib", mem.base.total);
uintptr_t high_memory_size = mem.extended.total * 1024;
INFO2("* High memory (from cmos): %i Kib", mem.extended.total);
OS::memory_end_ = 0x100000 + high_memory_size;
}
auto& memmap = memory_map();
// No guarantees without multiboot, but we assume standard memory layout
memmap.assign_range({0x0009FC00, 0x0009FFFF,
"EBDA", "Extended BIOS data area"});
memmap.assign_range({0x000A0000, 0x000FFFFF,
"VGA/ROM", "Memory mapped video memory"});
// @note : since the maximum size of a span is unsigned (ptrdiff_t) we may need more than one
uintptr_t addr_max = std::numeric_limits<std::size_t>::max();
uintptr_t span_max = std::numeric_limits<std::ptrdiff_t>::max();
uintptr_t unavail_start = OS::memory_end_;
size_t interval = std::min(span_max, addr_max - unavail_start) - 1;
uintptr_t unavail_end = unavail_start + interval;
while (unavail_end < addr_max)
{
INFO2("* Unavailable memory: 0x%" PRIxPTR" - 0x%" PRIxPTR, unavail_start, unavail_end);
memmap.assign_range({unavail_start, unavail_end,
"N/A", "Reserved / outside physical range" });
unavail_start = unavail_end + 1;
interval = std::min(span_max, addr_max - unavail_start);
// Increment might wrapped around
if (unavail_start > unavail_end + interval or unavail_start + interval == addr_max){
INFO2("* Last chunk of memory: 0x%" PRIxPTR" - 0x%" PRIxPTR, unavail_start, addr_max);
memmap.assign_range({unavail_start, addr_max,
"N/A", "Reserved / outside physical range" });
break;
}
unavail_end += interval;
}
}
<|endoftext|>
|
<commit_before><commit_msg>Fix comment.<commit_after><|endoftext|>
|
<commit_before>/*
Copyright (c) 2006, Arvid Norberg & Daniel Wallin
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#include <libtorrent/kademlia/closest_nodes.hpp>
#include <libtorrent/kademlia/routing_table.hpp>
#include <libtorrent/kademlia/rpc_manager.hpp>
#include "libtorrent/assert.hpp"
namespace libtorrent { namespace dht
{
using asio::ip::udp;
closest_nodes_observer::~closest_nodes_observer()
{
if (m_algorithm) m_algorithm->failed(m_self, true);
}
void closest_nodes_observer::reply(msg const& in)
{
if (!m_algorithm)
{
TORRENT_ASSERT(false);
return;
}
if (!in.nodes.empty())
{
for (msg::nodes_t::const_iterator i = in.nodes.begin()
, end(in.nodes.end()); i != end; ++i)
{
m_algorithm->traverse(i->id, i->addr);
}
}
m_algorithm->finished(m_self);
m_algorithm = 0;
}
void closest_nodes_observer::timeout()
{
if (!m_algorithm) return;
m_algorithm->failed(m_self);
m_algorithm = 0;
}
closest_nodes::closest_nodes(
node_id target
, int branch_factor
, int max_results
, routing_table& table
, rpc_manager& rpc
, done_callback const& callback
)
: traversal_algorithm(
target
, branch_factor
, max_results
, table
, rpc
, table.begin()
, table.end()
)
, m_done_callback(callback)
{
boost::intrusive_ptr<closest_nodes> self(this);
add_requests();
}
void closest_nodes::invoke(node_id const& id, udp::endpoint addr)
{
TORRENT_ASSERT(m_rpc.allocation_size() >= sizeof(closest_nodes_observer));
observer_ptr o(new (m_rpc.allocator().malloc()) closest_nodes_observer(this, id, m_target));
#ifndef NDEBUG
o->m_in_constructor = false;
#endif
m_rpc.invoke(messages::find_node, addr, o);
}
void closest_nodes::done()
{
std::vector<node_entry> results;
int num_results = m_max_results;
for (std::vector<result>::iterator i = m_results.begin()
, end(m_results.end()); i != end && num_results >= 0; ++i)
{
if (i->flags & result::no_id) continue;
if ((i->flags & result::queried) == 0) continue;
results.push_back(node_entry(i->id, i->addr));
--num_results;
}
m_done_callback(results);
}
void closest_nodes::initiate(
node_id target
, int branch_factor
, int max_results
, routing_table& table
, rpc_manager& rpc
, done_callback const& callback
)
{
new closest_nodes(target, branch_factor, max_results, table, rpc, callback);
}
} } // namespace libtorrent::dht
<commit_msg>minor dht fix<commit_after>/*
Copyright (c) 2006, Arvid Norberg & Daniel Wallin
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#include <libtorrent/kademlia/closest_nodes.hpp>
#include <libtorrent/kademlia/routing_table.hpp>
#include <libtorrent/kademlia/rpc_manager.hpp>
#include "libtorrent/assert.hpp"
namespace libtorrent { namespace dht
{
using asio::ip::udp;
closest_nodes_observer::~closest_nodes_observer()
{
if (m_algorithm) m_algorithm->failed(m_self, true);
}
void closest_nodes_observer::reply(msg const& in)
{
if (!m_algorithm)
{
TORRENT_ASSERT(false);
return;
}
if (!in.nodes.empty())
{
for (msg::nodes_t::const_iterator i = in.nodes.begin()
, end(in.nodes.end()); i != end; ++i)
{
m_algorithm->traverse(i->id, i->addr);
}
}
m_algorithm->finished(m_self);
m_algorithm = 0;
}
void closest_nodes_observer::timeout()
{
if (!m_algorithm) return;
m_algorithm->failed(m_self);
m_algorithm = 0;
}
closest_nodes::closest_nodes(
node_id target
, int branch_factor
, int max_results
, routing_table& table
, rpc_manager& rpc
, done_callback const& callback
)
: traversal_algorithm(
target
, branch_factor
, max_results
, table
, rpc
, table.begin()
, table.end()
)
, m_done_callback(callback)
{
boost::intrusive_ptr<closest_nodes> self(this);
add_requests();
}
void closest_nodes::invoke(node_id const& id, udp::endpoint addr)
{
TORRENT_ASSERT(m_rpc.allocation_size() >= sizeof(closest_nodes_observer));
observer_ptr o(new (m_rpc.allocator().malloc()) closest_nodes_observer(this, id, m_target));
#ifndef NDEBUG
o->m_in_constructor = false;
#endif
m_rpc.invoke(messages::find_node, addr, o);
}
void closest_nodes::done()
{
std::vector<node_entry> results;
int num_results = m_max_results;
for (std::vector<result>::iterator i = m_results.begin()
, end(m_results.end()); i != end && num_results > 0; ++i)
{
if (i->flags & result::no_id) continue;
if ((i->flags & result::queried) == 0) continue;
results.push_back(node_entry(i->id, i->addr));
--num_results;
}
m_done_callback(results);
}
void closest_nodes::initiate(
node_id target
, int branch_factor
, int max_results
, routing_table& table
, rpc_manager& rpc
, done_callback const& callback
)
{
new closest_nodes(target, branch_factor, max_results, table, rpc, callback);
}
} } // namespace libtorrent::dht
<|endoftext|>
|
<commit_before>#include "balancer.hpp"
#include <net/tcp/stream.hpp>
#define READQ_PER_CLIENT 4096
#define MAX_READQ_PER_NODE 8192
#define READQ_FOR_NODES 8192
#define MAX_OUTGOING_ATTEMPTS 100
// checking if nodes are dead or not
#define ACTIVE_INITIAL_PERIOD 8s
#define ACTIVE_CHECK_PERIOD 30s
// connection attempt timeouts
#define CONNECT_TIMEOUT 10s
#define CONNECT_THROW_PERIOD 20s
#define LB_VERBOSE 0
#if LB_VERBOSE
#define LBOUT(fmt, ...) printf(fmt, ##__VA_ARGS__)
#else
#define LBOUT(fmt, ...) /** **/
#endif
using namespace std::chrono;
namespace microLB
{
Balancer::Balancer(
netstack_t& incoming, uint16_t in_port,
netstack_t& outgoing, bool active_check)
: nodes(active_check),
netin(incoming), netout(outgoing),
signal({this, &Balancer::handle_queue})
{
netin.tcp().listen(in_port,
[this] (auto conn) {
if (conn != nullptr) {
this->incoming(std::make_unique<net::tcp::Stream> (conn));
}
});
this->init_liveupdate();
}
int Balancer::wait_queue() const {
return this->queue.size();
}
int Balancer::connect_throws() const {
return this->throw_counter;
}
netstack_t& Balancer::get_client_network() noexcept
{
return this->netin;
}
netstack_t& Balancer::get_nodes_network() noexcept
{
return this->netout;
}
const pool_signal_t& Balancer::get_pool_signal() const
{
return this->signal;
}
void Balancer::incoming(net::Stream_ptr conn)
{
assert(conn != nullptr);
queue.emplace_back(std::move(conn));
LBOUT("Queueing connection (q=%lu)\n", queue.size());
// IMPORTANT: try to handle queue, in case its ready
// don't directly call handle_connections() from here!
this->handle_queue();
}
void Balancer::handle_queue()
{
// check waitq
while (nodes.pool_size() > 0 && queue.empty() == false)
{
auto& client = queue.front();
assert(client.conn != nullptr);
if (client.conn->is_connected()) {
// NOTE: explicitly want to copy buffers
net::Stream_ptr rval =
nodes.assign(std::move(client.conn), client.readq);
if (rval == nullptr) {
// done with this queue item
queue.pop_front();
}
else {
// put connection back in queue item
client.conn = std::move(rval);
}
}
else {
queue.pop_front();
}
} // waitq check
// check if we need to create more connections
this->handle_connections();
}
void Balancer::handle_connections()
{
LBOUT("Handle_connections. %i waiting \n", queue.size());
// stop any rethrow timer since this is a de-facto retry
if (this->throw_retry_timer != Timers::UNUSED_ID) {
Timers::stop(this->throw_retry_timer);
this->throw_retry_timer = Timers::UNUSED_ID;
}
// prune dead clients because the "number of clients" is being
// used in a calculation right after this to determine how many
// nodes to connect to
auto new_end = std::remove_if(queue.begin(), queue.end(),
[](Waiting& client) {
return client.conn == nullptr || client.conn->is_connected() == false;
});
queue.erase(new_end, queue.end());
// calculating number of connection attempts to create
int np_connecting = nodes.pool_connecting();
int estimate = queue.size() - (np_connecting + nodes.pool_size());
estimate = std::min(estimate, MAX_OUTGOING_ATTEMPTS);
estimate = std::max(0, estimate - np_connecting);
// create more outgoing connections
LBOUT("Estimated connections needed: %d\n", estimate);
if (estimate > 0)
{
try {
nodes.create_connections(estimate);
}
catch (std::exception& e)
{
this->throw_counter++;
// assuming the failure is due to not enough eph. ports
this->throw_retry_timer = Timers::oneshot(CONNECT_THROW_PERIOD,
[this] (int) {
this->throw_retry_timer = Timers::UNUSED_ID;
this->handle_connections();
});
}
} // estimate
} // handle_connections()
Waiting::Waiting(net::Stream_ptr incoming)
: conn(std::move(incoming)), total(0)
{
assert(this->conn != nullptr);
assert(this->conn->is_connected());
// Release connection if it closes before it's assigned to a node.
this->conn->on_close([this](){
if (this->conn != nullptr)
this->conn->reset_callbacks();
this->conn = nullptr;
});
// queue incoming data from clients not yet
// assigned to a node
this->conn->on_read(READQ_PER_CLIENT,
[this] (auto buf) {
// prevent buffer bloat attack
this->total += buf->size();
if (this->total > MAX_READQ_PER_NODE) {
this->conn->close();
}
else {
LBOUT("*** Queued %lu bytes\n", buf->size());
readq.push_back(buf);
}
});
}
void Nodes::create_connections(int total)
{
// temporary iterator
for (int i = 0; i < total; i++)
{
bool dest_found = false;
// look for next active node up to *size* times
for (size_t i = 0; i < nodes.size(); i++)
{
const int iter = conn_iterator;
conn_iterator = (conn_iterator + 1) % nodes.size();
// if the node is active, connect immediately
auto& dest_node = nodes[iter];
if (dest_node.is_active()) {
dest_node.connect();
dest_found = true;
break;
}
}
// if no active node found, simply delegate to the next node
if (dest_found == false)
{
// with active-checks we can return here later when we get a connection
if (this->do_active_check) return;
const int iter = conn_iterator;
conn_iterator = (conn_iterator + 1) % nodes.size();
nodes[iter].connect();
}
}
}
net::Stream_ptr Nodes::assign(net::Stream_ptr conn, queue_vector_t& readq)
{
for (size_t i = 0; i < nodes.size(); i++)
{
auto outgoing = nodes[algo_iterator].get_connection();
// algorithm here //
algo_iterator = (algo_iterator + 1) % nodes.size();
// check if connection was retrieved
if (outgoing != nullptr)
{
assert(outgoing->is_connected());
LBOUT("Assigning client to node %d (%s)\n",
algo_iterator, outgoing->to_string().c_str());
auto& session = this->create_session(
std::move(conn), std::move(outgoing));
// flush readq to session.outgoing
for (auto buffer : readq) {
LBOUT("*** Flushing %lu bytes\n", buffer->size());
session.outgoing->write(buffer);
}
return nullptr;
}
}
return conn;
}
size_t Nodes::size() const noexcept {
return nodes.size();
}
Nodes::const_iterator Nodes::begin() const {
return nodes.cbegin();
}
Nodes::const_iterator Nodes::end() const {
return nodes.cend();
}
int Nodes::pool_connecting() const {
int count = 0;
for (auto& node : nodes) count += node.connection_attempts();
return count;
}
int Nodes::pool_size() const {
int count = 0;
for (auto& node : nodes) count += node.pool_size();
return count;
}
int32_t Nodes::open_sessions() const {
return session_cnt;
}
int64_t Nodes::total_sessions() const {
return session_total;
}
int32_t Nodes::timed_out_sessions() const {
return 0;
}
Session& Nodes::create_session(net::Stream_ptr client, net::Stream_ptr outgoing)
{
int idx = -1;
if (free_sessions.empty()) {
idx = sessions.size();
sessions.emplace_back(*this, idx, std::move(client), std::move(outgoing));
} else {
idx = free_sessions.back();
new (&sessions[idx]) Session(*this, idx, std::move(client), std::move(outgoing));
free_sessions.pop_back();
}
session_total++;
session_cnt++;
LBOUT("New session %d (current = %d, total = %ld)\n",
idx, session_cnt, session_total);
return sessions[idx];
}
Session& Nodes::get_session(int idx)
{
auto& session = sessions.at(idx);
assert(session.is_alive());
return session;
}
void Nodes::close_session(int idx)
{
auto& session = get_session(idx);
// remove connections
session.incoming->reset_callbacks();
session.incoming = nullptr;
session.outgoing->reset_callbacks();
session.outgoing = nullptr;
// free session
free_sessions.push_back(session.self);
session_cnt--;
LBOUT("Session %d closed (total = %d)\n", session.self, session_cnt);
}
Node::Node(netstack_t& stk, net::Socket a, const pool_signal_t& sig, bool da)
: stack(stk), pool_signal(sig), addr(a), do_active_check(da)
{
if (this->do_active_check)
{
// periodically connect to node and determine if active
// however, perform first check immediately
this->active_timer = Timers::periodic(0s, ACTIVE_CHECK_PERIOD,
{this, &Node::perform_active_check});
}
}
void Node::perform_active_check(int)
{
assert(this->do_active_check);
try {
this->stack.tcp().connect(this->addr,
[this] (auto conn) {
this->active = (conn != nullptr);
// if we are connected, its alive
if (conn != nullptr)
{
// hopefully put this to good use
pool.push_back(std::make_unique<net::tcp::Stream>(conn));
// stop any active check
this->stop_active_check();
// signal change in pool
this->pool_signal();
}
else {
// if no periodic check is being done right now,
// start doing it (after initial delay)
this->restart_active_check();
}
});
} catch (std::exception& e) {
// do nothing, because might just be eph.ports used up
}
}
void Node::restart_active_check()
{
// set as inactive
this->active = false;
if (this->do_active_check)
{
// begin checking active again
if (this->active_timer == Timers::UNUSED_ID)
{
this->active_timer = Timers::periodic(
ACTIVE_INITIAL_PERIOD, ACTIVE_CHECK_PERIOD,
{this, &Node::perform_active_check});
LBOUT("Node %s restarting active check (and is inactive)\n",
this->addr.to_string().c_str());
}
else
{
LBOUT("Node %s still trying to connect...\n",
this->addr.to_string().c_str());
}
}
}
void Node::stop_active_check()
{
// set as active
this->active = true;
if (this->do_active_check)
{
// stop active checking for now
if (this->active_timer != Timers::UNUSED_ID) {
Timers::stop(this->active_timer);
this->active_timer = Timers::UNUSED_ID;
}
}
}
void Node::connect()
{
auto outgoing = this->stack.tcp().connect(this->addr);
// connecting to node atm.
this->connecting++;
// retry timer when connect takes too long
int fail_timer = Timers::oneshot(CONNECT_TIMEOUT,
[this, outgoing] (int)
{
// close connection
outgoing->abort();
// no longer connecting
assert(this->connecting > 0);
this->connecting --;
// restart active check
this->restart_active_check();
// signal change in pool
this->pool_signal();
});
// add connection to pool on success, otherwise.. retry
outgoing->on_connect(
[this, fail_timer] (auto conn)
{
// stop retry timer
Timers::stop(fail_timer);
// no longer connecting
assert(this->connecting > 0);
this->connecting --;
// connection may be null, apparently
if (conn != nullptr && conn->is_connected())
{
LBOUT("Connected to %s (%ld total)\n",
addr.to_string().c_str(), pool.size());
this->pool.push_back(std::make_unique<net::tcp::Stream>(conn));
// stop any active check
this->stop_active_check();
// signal change in pool
this->pool_signal();
}
else {
this->restart_active_check();
}
});
}
net::Stream_ptr Node::get_connection()
{
while (pool.empty() == false) {
auto conn = std::move(pool.back());
assert(conn != nullptr);
pool.pop_back();
if (conn->is_connected()) return conn;
else conn->close();
}
return nullptr;
}
// use indexing to access Session because std::vector
Session::Session(Nodes& n, int idx,
net::Stream_ptr inc, net::Stream_ptr out)
: parent(n), self(idx), incoming(std::move(inc)),
outgoing(std::move(out))
{
incoming->on_read(READQ_PER_CLIENT,
[this] (auto buf) {
assert(this->is_alive());
this->outgoing->write(buf);
});
incoming->on_close(
[&nodes = n, idx] () {
nodes.close_session(idx);
});
outgoing->on_read(READQ_FOR_NODES,
[this] (auto buf) {
assert(this->is_alive());
this->incoming->write(buf);
});
outgoing->on_close(
[&nodes = n, idx] () {
nodes.close_session(idx);
});
}
bool Session::is_alive() const {
return incoming != nullptr;
}
}
<commit_msg>microlb: Add try/catch to avoid silently invalidating the client queue<commit_after>#include "balancer.hpp"
#include <net/tcp/stream.hpp>
#define READQ_PER_CLIENT 4096
#define MAX_READQ_PER_NODE 8192
#define READQ_FOR_NODES 8192
#define MAX_OUTGOING_ATTEMPTS 100
// checking if nodes are dead or not
#define ACTIVE_INITIAL_PERIOD 8s
#define ACTIVE_CHECK_PERIOD 30s
// connection attempt timeouts
#define CONNECT_TIMEOUT 10s
#define CONNECT_THROW_PERIOD 20s
#define LB_VERBOSE 0
#if LB_VERBOSE
#define LBOUT(fmt, ...) printf(fmt, ##__VA_ARGS__)
#else
#define LBOUT(fmt, ...) /** **/
#endif
using namespace std::chrono;
namespace microLB
{
Balancer::Balancer(
netstack_t& incoming, uint16_t in_port,
netstack_t& outgoing, bool active_check)
: nodes(active_check),
netin(incoming), netout(outgoing),
signal({this, &Balancer::handle_queue})
{
netin.tcp().listen(in_port,
[this] (auto conn) {
if (conn != nullptr) {
this->incoming(std::make_unique<net::tcp::Stream> (conn));
}
});
this->init_liveupdate();
}
int Balancer::wait_queue() const {
return this->queue.size();
}
int Balancer::connect_throws() const {
return this->throw_counter;
}
netstack_t& Balancer::get_client_network() noexcept
{
return this->netin;
}
netstack_t& Balancer::get_nodes_network() noexcept
{
return this->netout;
}
const pool_signal_t& Balancer::get_pool_signal() const
{
return this->signal;
}
void Balancer::incoming(net::Stream_ptr conn)
{
assert(conn != nullptr);
queue.emplace_back(std::move(conn));
LBOUT("Queueing connection (q=%lu)\n", queue.size());
// IMPORTANT: try to handle queue, in case its ready
// don't directly call handle_connections() from here!
this->handle_queue();
}
void Balancer::handle_queue()
{
// check waitq
while (nodes.pool_size() > 0 && queue.empty() == false)
{
auto& client = queue.front();
assert(client.conn != nullptr);
if (client.conn->is_connected()) {
try {
// NOTE: explicitly want to copy buffers
net::Stream_ptr rval =
nodes.assign(std::move(client.conn), client.readq);
if (rval == nullptr) {
// done with this queue item
queue.pop_front();
}
else {
// put connection back in queue item
client.conn = std::move(rval);
}
} catch (...) {
queue.pop_front(); // we have no choice
throw;
}
}
else {
queue.pop_front();
}
} // waitq check
// check if we need to create more connections
this->handle_connections();
}
void Balancer::handle_connections()
{
LBOUT("Handle_connections. %i waiting \n", queue.size());
// stop any rethrow timer since this is a de-facto retry
if (this->throw_retry_timer != Timers::UNUSED_ID) {
Timers::stop(this->throw_retry_timer);
this->throw_retry_timer = Timers::UNUSED_ID;
}
// prune dead clients because the "number of clients" is being
// used in a calculation right after this to determine how many
// nodes to connect to
auto new_end = std::remove_if(queue.begin(), queue.end(),
[](Waiting& client) {
return client.conn == nullptr || client.conn->is_connected() == false;
});
queue.erase(new_end, queue.end());
// calculating number of connection attempts to create
int np_connecting = nodes.pool_connecting();
int estimate = queue.size() - (np_connecting + nodes.pool_size());
estimate = std::min(estimate, MAX_OUTGOING_ATTEMPTS);
estimate = std::max(0, estimate - np_connecting);
// create more outgoing connections
LBOUT("Estimated connections needed: %d\n", estimate);
if (estimate > 0)
{
try {
nodes.create_connections(estimate);
}
catch (std::exception& e)
{
this->throw_counter++;
// assuming the failure is due to not enough eph. ports
this->throw_retry_timer = Timers::oneshot(CONNECT_THROW_PERIOD,
[this] (int) {
this->throw_retry_timer = Timers::UNUSED_ID;
this->handle_connections();
});
}
} // estimate
} // handle_connections()
Waiting::Waiting(net::Stream_ptr incoming)
: conn(std::move(incoming)), total(0)
{
assert(this->conn != nullptr);
assert(this->conn->is_connected());
// Release connection if it closes before it's assigned to a node.
this->conn->on_close([this](){
if (this->conn != nullptr)
this->conn->reset_callbacks();
this->conn = nullptr;
});
// queue incoming data from clients not yet
// assigned to a node
this->conn->on_read(READQ_PER_CLIENT,
[this] (auto buf) {
// prevent buffer bloat attack
this->total += buf->size();
if (this->total > MAX_READQ_PER_NODE) {
this->conn->close();
}
else {
LBOUT("*** Queued %lu bytes\n", buf->size());
readq.push_back(buf);
}
});
}
void Nodes::create_connections(int total)
{
// temporary iterator
for (int i = 0; i < total; i++)
{
bool dest_found = false;
// look for next active node up to *size* times
for (size_t i = 0; i < nodes.size(); i++)
{
const int iter = conn_iterator;
conn_iterator = (conn_iterator + 1) % nodes.size();
// if the node is active, connect immediately
auto& dest_node = nodes[iter];
if (dest_node.is_active()) {
dest_node.connect();
dest_found = true;
break;
}
}
// if no active node found, simply delegate to the next node
if (dest_found == false)
{
// with active-checks we can return here later when we get a connection
if (this->do_active_check) return;
const int iter = conn_iterator;
conn_iterator = (conn_iterator + 1) % nodes.size();
nodes[iter].connect();
}
}
}
net::Stream_ptr Nodes::assign(net::Stream_ptr conn, queue_vector_t& readq)
{
for (size_t i = 0; i < nodes.size(); i++)
{
auto outgoing = nodes[algo_iterator].get_connection();
// algorithm here //
algo_iterator = (algo_iterator + 1) % nodes.size();
// check if connection was retrieved
if (outgoing != nullptr)
{
assert(outgoing->is_connected());
LBOUT("Assigning client to node %d (%s)\n",
algo_iterator, outgoing->to_string().c_str());
auto& session = this->create_session(
std::move(conn), std::move(outgoing));
// flush readq to session.outgoing
for (auto buffer : readq) {
LBOUT("*** Flushing %lu bytes\n", buffer->size());
session.outgoing->write(buffer);
}
return nullptr;
}
}
return conn;
}
size_t Nodes::size() const noexcept {
return nodes.size();
}
Nodes::const_iterator Nodes::begin() const {
return nodes.cbegin();
}
Nodes::const_iterator Nodes::end() const {
return nodes.cend();
}
int Nodes::pool_connecting() const {
int count = 0;
for (auto& node : nodes) count += node.connection_attempts();
return count;
}
int Nodes::pool_size() const {
int count = 0;
for (auto& node : nodes) count += node.pool_size();
return count;
}
int32_t Nodes::open_sessions() const {
return session_cnt;
}
int64_t Nodes::total_sessions() const {
return session_total;
}
int32_t Nodes::timed_out_sessions() const {
return 0;
}
Session& Nodes::create_session(net::Stream_ptr client, net::Stream_ptr outgoing)
{
int idx = -1;
if (free_sessions.empty()) {
idx = sessions.size();
sessions.emplace_back(*this, idx, std::move(client), std::move(outgoing));
} else {
idx = free_sessions.back();
new (&sessions[idx]) Session(*this, idx, std::move(client), std::move(outgoing));
free_sessions.pop_back();
}
session_total++;
session_cnt++;
LBOUT("New session %d (current = %d, total = %ld)\n",
idx, session_cnt, session_total);
return sessions[idx];
}
Session& Nodes::get_session(int idx)
{
auto& session = sessions.at(idx);
assert(session.is_alive());
return session;
}
void Nodes::close_session(int idx)
{
auto& session = get_session(idx);
// remove connections
session.incoming->reset_callbacks();
session.incoming = nullptr;
session.outgoing->reset_callbacks();
session.outgoing = nullptr;
// free session
free_sessions.push_back(session.self);
session_cnt--;
LBOUT("Session %d closed (total = %d)\n", session.self, session_cnt);
}
Node::Node(netstack_t& stk, net::Socket a, const pool_signal_t& sig, bool da)
: stack(stk), pool_signal(sig), addr(a), do_active_check(da)
{
if (this->do_active_check)
{
// periodically connect to node and determine if active
// however, perform first check immediately
this->active_timer = Timers::periodic(0s, ACTIVE_CHECK_PERIOD,
{this, &Node::perform_active_check});
}
}
void Node::perform_active_check(int)
{
assert(this->do_active_check);
try {
this->stack.tcp().connect(this->addr,
[this] (auto conn) {
this->active = (conn != nullptr);
// if we are connected, its alive
if (conn != nullptr)
{
// hopefully put this to good use
pool.push_back(std::make_unique<net::tcp::Stream>(conn));
// stop any active check
this->stop_active_check();
// signal change in pool
this->pool_signal();
}
else {
// if no periodic check is being done right now,
// start doing it (after initial delay)
this->restart_active_check();
}
});
} catch (std::exception& e) {
// do nothing, because might just be eph.ports used up
}
}
void Node::restart_active_check()
{
// set as inactive
this->active = false;
if (this->do_active_check)
{
// begin checking active again
if (this->active_timer == Timers::UNUSED_ID)
{
this->active_timer = Timers::periodic(
ACTIVE_INITIAL_PERIOD, ACTIVE_CHECK_PERIOD,
{this, &Node::perform_active_check});
LBOUT("Node %s restarting active check (and is inactive)\n",
this->addr.to_string().c_str());
}
else
{
LBOUT("Node %s still trying to connect...\n",
this->addr.to_string().c_str());
}
}
}
void Node::stop_active_check()
{
// set as active
this->active = true;
if (this->do_active_check)
{
// stop active checking for now
if (this->active_timer != Timers::UNUSED_ID) {
Timers::stop(this->active_timer);
this->active_timer = Timers::UNUSED_ID;
}
}
}
void Node::connect()
{
auto outgoing = this->stack.tcp().connect(this->addr);
// connecting to node atm.
this->connecting++;
// retry timer when connect takes too long
int fail_timer = Timers::oneshot(CONNECT_TIMEOUT,
[this, outgoing] (int)
{
// close connection
outgoing->abort();
// no longer connecting
assert(this->connecting > 0);
this->connecting --;
// restart active check
this->restart_active_check();
// signal change in pool
this->pool_signal();
});
// add connection to pool on success, otherwise.. retry
outgoing->on_connect(
[this, fail_timer] (auto conn)
{
// stop retry timer
Timers::stop(fail_timer);
// no longer connecting
assert(this->connecting > 0);
this->connecting --;
// connection may be null, apparently
if (conn != nullptr && conn->is_connected())
{
LBOUT("Connected to %s (%ld total)\n",
addr.to_string().c_str(), pool.size());
this->pool.push_back(std::make_unique<net::tcp::Stream>(conn));
// stop any active check
this->stop_active_check();
// signal change in pool
this->pool_signal();
}
else {
this->restart_active_check();
}
});
}
net::Stream_ptr Node::get_connection()
{
while (pool.empty() == false) {
auto conn = std::move(pool.back());
assert(conn != nullptr);
pool.pop_back();
if (conn->is_connected()) return conn;
else conn->close();
}
return nullptr;
}
// use indexing to access Session because std::vector
Session::Session(Nodes& n, int idx,
net::Stream_ptr inc, net::Stream_ptr out)
: parent(n), self(idx), incoming(std::move(inc)),
outgoing(std::move(out))
{
incoming->on_read(READQ_PER_CLIENT,
[this] (auto buf) {
assert(this->is_alive());
this->outgoing->write(buf);
});
incoming->on_close(
[&nodes = n, idx] () {
nodes.close_session(idx);
});
outgoing->on_read(READQ_FOR_NODES,
[this] (auto buf) {
assert(this->is_alive());
this->incoming->write(buf);
});
outgoing->on_close(
[&nodes = n, idx] () {
nodes.close_session(idx);
});
}
bool Session::is_alive() const {
return incoming != nullptr;
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2008-2014 The Communi Project
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include "textdocument.h"
#include "messageformatter.h"
#include <QAbstractTextDocumentLayout>
#include <QTextDocumentFragment>
#include <QTextBlockUserData>
#include <IrcConnection>
#include <QStylePainter>
#include <QApplication>
#include <QStyleOption>
#include <QTextCursor>
#include <QTextBlock>
#include <IrcBuffer>
#include <QPalette>
#include <QPointer>
#include <QPainter>
#include <QFrame>
#include <qmath.h>
static int delay = 1000;
class TextBlockUserData : public QTextBlockUserData
{
public:
QString line;
};
class TextFrame : public QFrame
{
public:
TextFrame(QWidget* parent = 0) : QFrame(parent)
{
setVisible(false);
setAttribute(Qt::WA_TranslucentBackground);
setAttribute(Qt::WA_NoSystemBackground);
}
void paintEvent(QPaintEvent*)
{
QStyleOption option;
option.init(this);
QStylePainter painter(this);
painter.drawPrimitive(QStyle::PE_Widget, option);
}
};
class TextHighlight : public TextFrame
{
Q_OBJECT
public:
TextHighlight(QWidget* parent = 0) : TextFrame(parent) { }
};
class TextLowlight : public TextFrame
{
Q_OBJECT
public:
TextLowlight(QWidget* parent = 0) : TextFrame(parent) { }
};
TextDocument::TextDocument(IrcBuffer* buffer) : QTextDocument(buffer)
{
qRegisterMetaType<TextDocument*>();
d.ub = -1;
d.dirty = -1;
d.lowlight = -1;
d.clone = false;
d.drawUb = false;
d.buffer = buffer;
d.visible = false;
d.formatter = new MessageFormatter(this);
d.formatter->setBuffer(buffer);
setUndoRedoEnabled(false);
setMaximumBlockCount(1000);
connect(buffer, SIGNAL(messageReceived(IrcMessage*)), this, SLOT(receiveMessage(IrcMessage*)));
}
QString TextDocument::styleSheet() const
{
return d.css;
}
void TextDocument::setStyleSheet(const QString& css)
{
if (d.css != css) {
d.css = css;
setDefaultStyleSheet(css);
rebuild();
}
}
TextDocument* TextDocument::clone()
{
if (d.dirty > 0)
flushLines();
TextDocument* doc = new TextDocument(d.buffer);
doc->setDefaultStyleSheet(defaultStyleSheet());
QTextCursor(doc).insertFragment(QTextDocumentFragment(this));
doc->rootFrame()->setFrameFormat(rootFrame()->frameFormat());
// TODO:
doc->d.ub = d.ub;
doc->d.css = d.css;
doc->d.lowlight = d.lowlight;
doc->d.buffer = d.buffer;
doc->d.highlights = d.highlights;
doc->d.lowlights = d.lowlights;
doc->d.clone = true;
return doc;
}
bool TextDocument::isClone() const
{
return d.clone;
}
IrcBuffer* TextDocument::buffer() const
{
return d.buffer;
}
MessageFormatter* TextDocument::formatter() const
{
return d.formatter;
}
int TextDocument::totalCount() const
{
int count = d.lines.count();
if (!isEmpty())
count += blockCount();
return count;
}
bool TextDocument::isVisible() const
{
return d.visible;
}
void TextDocument::setVisible(bool visible)
{
if (d.visible != visible) {
if (visible) {
if (d.dirty > 0)
flushLines();
} else {
d.ub = -1;
}
d.visible = visible;
}
}
void TextDocument::beginLowlight()
{
d.lowlight = totalCount();
d.lowlights.insert(d.lowlight, -1);
}
void TextDocument::endLowlight()
{
d.lowlights.insert(d.lowlight, totalCount());
d.lowlight = -1;
}
void TextDocument::addHighlight(int block)
{
const int max = totalCount() - 1;
if (block == -1)
block = max;
if (block >= 0 && block <= max) {
QList<int>::iterator it = qLowerBound(d.highlights.begin(), d.highlights.end(), block);
d.highlights.insert(it, block);
updateBlock(block);
}
}
void TextDocument::removeHighlight(int block)
{
if (d.highlights.removeOne(block) && block >= 0 && block < totalCount())
updateBlock(block);
}
void TextDocument::reset()
{
d.ub = -1;
d.lowlight = -1;
d.lowlights.clear();
d.highlights.clear();
}
void TextDocument::append(const QString& text)
{
if (!text.isEmpty()) {
if (d.dirty == 0 || d.visible) {
QTextCursor cursor(this);
cursor.beginEditBlock();
appendLine(cursor, text);
cursor.endEditBlock();
} else {
if (d.dirty <= 0) {
d.dirty = startTimer(delay);
delay += 1000;
}
d.lines += text;
}
}
}
void TextDocument::drawForeground(QPainter* painter, const QRect& bounds)
{
if (d.drawUb) {
const QPen oldPen = painter->pen();
const QBrush oldBrush = painter->brush();
painter->setBrush(Qt::NoBrush);
painter->setPen(QPen(QPalette().color(QPalette::Mid), 1, Qt::DashLine));
QTextBlock block = findBlockByNumber(d.ub);
if (block.isValid()) {
QRect br = documentLayout()->blockBoundingRect(block).toAlignedRect();
if (bounds.intersects(br))
painter->drawLine(br.topLeft(), br.topRight());
}
painter->setPen(oldPen);
painter->setBrush(oldBrush);
}
}
void TextDocument::drawBackground(QPainter* painter, const QRect& bounds)
{
if (d.highlights.isEmpty() && d.lowlights.isEmpty())
return;
const int margin = qCeil(documentMargin());
const QAbstractTextDocumentLayout* layout = documentLayout();
static QPointer<TextLowlight> lowlightFrame = 0;
if (!lowlightFrame)
lowlightFrame = new TextLowlight(static_cast<QWidget*>(painter->device()));
static QPointer<TextHighlight> highlightFrame = 0;
if (!highlightFrame)
highlightFrame = new TextHighlight(static_cast<QWidget*>(painter->device()));
d.drawUb = d.ub > 1;
if (!d.lowlights.isEmpty()) {
const QAbstractTextDocumentLayout* layout = documentLayout();
const int margin = qCeil(documentMargin());
QMap<int, int>::const_iterator it;
for (it = d.lowlights.begin(); it != d.lowlights.end(); ++it) {
const QTextBlock from = findBlockByNumber(it.key());
const QTextBlock to = findBlockByNumber(it.value());
if (from.isValid() && to.isValid()) {
const QRect fr = layout->blockBoundingRect(from).toAlignedRect();
const QRect tr = layout->blockBoundingRect(to).toAlignedRect();
QRect br = fr.united(tr);
if (bounds.intersects(br)) {
bool atBottom = false;
if (to == lastBlock()) {
if (qAbs(bounds.bottom() - br.bottom()) < qMin(fr.height(), tr.height()))
atBottom = true;
}
if (atBottom)
br.setBottom(bounds.bottom() + 1);
br.adjust(-margin - 1, 0, margin + 1, 0);
painter->translate(br.topLeft());
lowlightFrame->setGeometry(br);
lowlightFrame->render(painter);
painter->translate(-br.topLeft());
if (d.drawUb && d.ub - 1 >= it.key() && (it.value() == -1 || d.ub - 1 <= it.value()))
d.drawUb = false;
}
}
}
}
foreach (int highlight, d.highlights) {
QTextBlock block = findBlockByNumber(highlight);
if (block.isValid()) {
QRect br = layout->blockBoundingRect(block).toAlignedRect();
if (bounds.intersects(br)) {
br.adjust(-margin - 1, -margin / 2, margin + 1, margin / 2 + 1);
painter->translate(br.topLeft());
highlightFrame->setGeometry(br);
highlightFrame->render(painter);
painter->translate(-br.topLeft());
}
}
}
}
void TextDocument::updateBlock(int number)
{
if (d.visible) {
QTextBlock block = findBlockByNumber(number);
if (block.isValid())
QMetaObject::invokeMethod(documentLayout(), "updateBlock", Q_ARG(QTextBlock, block));
}
}
void TextDocument::timerEvent(QTimerEvent* event)
{
QTextDocument::timerEvent(event);
if (event->timerId() == d.dirty) {
delay -= 1000;
flushLines();
}
}
void TextDocument::flushLines()
{
if (!d.lines.isEmpty()) {
QTextCursor cursor(this);
cursor.beginEditBlock();
foreach (const QString& line, d.lines)
appendLine(cursor, line);
cursor.endEditBlock();
d.lines.clear();
}
if (d.dirty > 0) {
killTimer(d.dirty);
d.dirty = 0;
}
}
void TextDocument::receiveMessage(IrcMessage* message)
{
append(d.formatter->formatMessage(message));
emit messageReceived(message);
if (message->type() == IrcMessage::Private || message->type() == IrcMessage::Notice) {
if (!(message->flags() & IrcMessage::Own)) {
const bool contains = message->property("content").toString().contains(message->connection()->nickName(), Qt::CaseInsensitive);
if (contains) {
addHighlight(totalCount() - 1);
emit messageHighlighted(message);
}
}
}
}
void TextDocument::rebuild()
{
QStringList lines;
QTextBlock block = begin();
while (block.isValid()) {
TextBlockUserData* data = static_cast<TextBlockUserData*>(block.userData());
if (data)
lines += data->line;
block = block.next();
}
clear();
foreach (const QString& line, lines)
append(line);
}
void TextDocument::appendLine(QTextCursor& cursor, const QString& line)
{
const int count = blockCount();
cursor.movePosition(QTextCursor::End);
if (!isEmpty()) {
const int max = maximumBlockCount();
cursor.insertBlock();
if (count >= max) {
const int diff = max - count + 1;
if (d.ub > 0)
d.ub -= diff;
QList<int>::iterator i;
for (i = d.highlights.begin(); i != d.highlights.end(); ++i) {
*i -= diff;
if (*i < 0)
i = d.highlights.erase(i);
}
QMap<int, int> ll;
QMap<int, int>::const_iterator j;
for (j = d.lowlights.begin(); j != d.lowlights.end(); ++j) {
int from = j.key() - diff;
int to = j.value() - diff;
if (to > 0)
ll.insert(qMax(0, from), to);
}
d.lowlights = ll;
}
}
QTextBlockFormat format = cursor.blockFormat();
format.setLineHeight(150, QTextBlockFormat::ProportionalHeight);
cursor.setBlockFormat(format);
cursor.insertHtml(line);
TextBlockUserData* data = new TextBlockUserData;
data->line = line;
QTextBlock block = cursor.block();
block.setUserData(data);
if (d.ub == -1 && !d.visible)
d.ub = count;
}
#include "textdocument.moc"
<commit_msg>Tweak and fix row height<commit_after>/*
* Copyright (C) 2008-2014 The Communi Project
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include "textdocument.h"
#include "messageformatter.h"
#include <QAbstractTextDocumentLayout>
#include <QTextDocumentFragment>
#include <QTextBlockUserData>
#include <IrcConnection>
#include <QStylePainter>
#include <QApplication>
#include <QStyleOption>
#include <QTextCursor>
#include <QTextBlock>
#include <IrcBuffer>
#include <QPalette>
#include <QPointer>
#include <QPainter>
#include <QFrame>
#include <qmath.h>
static int delay = 1000;
class TextBlockUserData : public QTextBlockUserData
{
public:
QString line;
};
class TextFrame : public QFrame
{
public:
TextFrame(QWidget* parent = 0) : QFrame(parent)
{
setVisible(false);
setAttribute(Qt::WA_TranslucentBackground);
setAttribute(Qt::WA_NoSystemBackground);
}
void paintEvent(QPaintEvent*)
{
QStyleOption option;
option.init(this);
QStylePainter painter(this);
painter.drawPrimitive(QStyle::PE_Widget, option);
}
};
class TextHighlight : public TextFrame
{
Q_OBJECT
public:
TextHighlight(QWidget* parent = 0) : TextFrame(parent) { }
};
class TextLowlight : public TextFrame
{
Q_OBJECT
public:
TextLowlight(QWidget* parent = 0) : TextFrame(parent) { }
};
TextDocument::TextDocument(IrcBuffer* buffer) : QTextDocument(buffer)
{
qRegisterMetaType<TextDocument*>();
d.ub = -1;
d.dirty = -1;
d.lowlight = -1;
d.clone = false;
d.drawUb = false;
d.buffer = buffer;
d.visible = false;
d.formatter = new MessageFormatter(this);
d.formatter->setBuffer(buffer);
setUndoRedoEnabled(false);
setMaximumBlockCount(1000);
connect(buffer, SIGNAL(messageReceived(IrcMessage*)), this, SLOT(receiveMessage(IrcMessage*)));
}
QString TextDocument::styleSheet() const
{
return d.css;
}
void TextDocument::setStyleSheet(const QString& css)
{
if (d.css != css) {
d.css = css;
setDefaultStyleSheet(css);
rebuild();
}
}
TextDocument* TextDocument::clone()
{
if (d.dirty > 0)
flushLines();
TextDocument* doc = new TextDocument(d.buffer);
doc->setDefaultStyleSheet(defaultStyleSheet());
QTextCursor(doc).insertFragment(QTextDocumentFragment(this));
doc->rootFrame()->setFrameFormat(rootFrame()->frameFormat());
// TODO:
doc->d.ub = d.ub;
doc->d.css = d.css;
doc->d.lowlight = d.lowlight;
doc->d.buffer = d.buffer;
doc->d.highlights = d.highlights;
doc->d.lowlights = d.lowlights;
doc->d.clone = true;
return doc;
}
bool TextDocument::isClone() const
{
return d.clone;
}
IrcBuffer* TextDocument::buffer() const
{
return d.buffer;
}
MessageFormatter* TextDocument::formatter() const
{
return d.formatter;
}
int TextDocument::totalCount() const
{
int count = d.lines.count();
if (!isEmpty())
count += blockCount();
return count;
}
bool TextDocument::isVisible() const
{
return d.visible;
}
void TextDocument::setVisible(bool visible)
{
if (d.visible != visible) {
if (visible) {
if (d.dirty > 0)
flushLines();
} else {
d.ub = -1;
}
d.visible = visible;
}
}
void TextDocument::beginLowlight()
{
d.lowlight = totalCount();
d.lowlights.insert(d.lowlight, -1);
}
void TextDocument::endLowlight()
{
d.lowlights.insert(d.lowlight, totalCount());
d.lowlight = -1;
}
void TextDocument::addHighlight(int block)
{
const int max = totalCount() - 1;
if (block == -1)
block = max;
if (block >= 0 && block <= max) {
QList<int>::iterator it = qLowerBound(d.highlights.begin(), d.highlights.end(), block);
d.highlights.insert(it, block);
updateBlock(block);
}
}
void TextDocument::removeHighlight(int block)
{
if (d.highlights.removeOne(block) && block >= 0 && block < totalCount())
updateBlock(block);
}
void TextDocument::reset()
{
d.ub = -1;
d.lowlight = -1;
d.lowlights.clear();
d.highlights.clear();
}
void TextDocument::append(const QString& text)
{
if (!text.isEmpty()) {
if (d.dirty == 0 || d.visible) {
QTextCursor cursor(this);
cursor.beginEditBlock();
appendLine(cursor, text);
cursor.endEditBlock();
} else {
if (d.dirty <= 0) {
d.dirty = startTimer(delay);
delay += 1000;
}
d.lines += text;
}
}
}
void TextDocument::drawForeground(QPainter* painter, const QRect& bounds)
{
if (d.drawUb) {
const QPen oldPen = painter->pen();
const QBrush oldBrush = painter->brush();
painter->setBrush(Qt::NoBrush);
painter->setPen(QPen(QPalette().color(QPalette::Mid), 1, Qt::DashLine));
QTextBlock block = findBlockByNumber(d.ub);
if (block.isValid()) {
QRect br = documentLayout()->blockBoundingRect(block).toAlignedRect();
if (bounds.intersects(br))
painter->drawLine(br.topLeft(), br.topRight());
}
painter->setPen(oldPen);
painter->setBrush(oldBrush);
}
}
void TextDocument::drawBackground(QPainter* painter, const QRect& bounds)
{
if (d.highlights.isEmpty() && d.lowlights.isEmpty())
return;
const int margin = qCeil(documentMargin());
const QAbstractTextDocumentLayout* layout = documentLayout();
static QPointer<TextLowlight> lowlightFrame = 0;
if (!lowlightFrame)
lowlightFrame = new TextLowlight(static_cast<QWidget*>(painter->device()));
static QPointer<TextHighlight> highlightFrame = 0;
if (!highlightFrame)
highlightFrame = new TextHighlight(static_cast<QWidget*>(painter->device()));
d.drawUb = d.ub > 1;
if (!d.lowlights.isEmpty()) {
const QAbstractTextDocumentLayout* layout = documentLayout();
const int margin = qCeil(documentMargin());
QMap<int, int>::const_iterator it;
for (it = d.lowlights.begin(); it != d.lowlights.end(); ++it) {
const QTextBlock from = findBlockByNumber(it.key());
const QTextBlock to = findBlockByNumber(it.value());
if (from.isValid() && to.isValid()) {
const QRect fr = layout->blockBoundingRect(from).toAlignedRect();
const QRect tr = layout->blockBoundingRect(to).toAlignedRect();
QRect br = fr.united(tr);
if (bounds.intersects(br)) {
bool atBottom = false;
if (to == lastBlock()) {
if (qAbs(bounds.bottom() - br.bottom()) < qMin(fr.height(), tr.height()))
atBottom = true;
}
if (atBottom)
br.setBottom(bounds.bottom() + 1);
br.adjust(-margin - 1, 0, margin + 1, 0);
painter->translate(br.topLeft());
lowlightFrame->setGeometry(br);
lowlightFrame->render(painter);
painter->translate(-br.topLeft());
if (d.drawUb && d.ub - 1 >= it.key() && (it.value() == -1 || d.ub - 1 <= it.value()))
d.drawUb = false;
}
}
}
}
foreach (int highlight, d.highlights) {
QTextBlock block = findBlockByNumber(highlight);
if (block.isValid()) {
QRect br = layout->blockBoundingRect(block).toAlignedRect();
if (bounds.intersects(br)) {
br.adjust(-margin - 1, 0, margin + 1, 2);
painter->translate(br.topLeft());
highlightFrame->setGeometry(br);
highlightFrame->render(painter);
painter->translate(-br.topLeft());
}
}
}
}
void TextDocument::updateBlock(int number)
{
if (d.visible) {
QTextBlock block = findBlockByNumber(number);
if (block.isValid())
QMetaObject::invokeMethod(documentLayout(), "updateBlock", Q_ARG(QTextBlock, block));
}
}
void TextDocument::timerEvent(QTimerEvent* event)
{
QTextDocument::timerEvent(event);
if (event->timerId() == d.dirty) {
delay -= 1000;
flushLines();
}
}
void TextDocument::flushLines()
{
if (!d.lines.isEmpty()) {
QTextCursor cursor(this);
cursor.beginEditBlock();
foreach (const QString& line, d.lines)
appendLine(cursor, line);
cursor.endEditBlock();
d.lines.clear();
}
if (d.dirty > 0) {
killTimer(d.dirty);
d.dirty = 0;
}
}
void TextDocument::receiveMessage(IrcMessage* message)
{
append(d.formatter->formatMessage(message));
emit messageReceived(message);
if (message->type() == IrcMessage::Private || message->type() == IrcMessage::Notice) {
if (!(message->flags() & IrcMessage::Own)) {
const bool contains = message->property("content").toString().contains(message->connection()->nickName(), Qt::CaseInsensitive);
if (contains) {
addHighlight(totalCount() - 1);
emit messageHighlighted(message);
}
}
}
}
void TextDocument::rebuild()
{
QStringList lines;
QTextBlock block = begin();
while (block.isValid()) {
TextBlockUserData* data = static_cast<TextBlockUserData*>(block.userData());
if (data)
lines += data->line;
block = block.next();
}
clear();
foreach (const QString& line, lines)
append(line);
}
void TextDocument::appendLine(QTextCursor& cursor, const QString& line)
{
const int count = blockCount();
cursor.movePosition(QTextCursor::End);
if (!isEmpty()) {
const int max = maximumBlockCount();
cursor.insertBlock();
if (count >= max) {
const int diff = max - count + 1;
if (d.ub > 0)
d.ub -= diff;
QList<int>::iterator i;
for (i = d.highlights.begin(); i != d.highlights.end(); ++i) {
*i -= diff;
if (*i < 0)
i = d.highlights.erase(i);
}
QMap<int, int> ll;
QMap<int, int>::const_iterator j;
for (j = d.lowlights.begin(); j != d.lowlights.end(); ++j) {
int from = j.key() - diff;
int to = j.value() - diff;
if (to > 0)
ll.insert(qMax(0, from), to);
}
d.lowlights = ll;
}
}
cursor.insertHtml(line);
TextBlockUserData* data = new TextBlockUserData;
data->line = line;
QTextBlock block = cursor.block();
block.setUserData(data);
QTextBlockFormat format = cursor.blockFormat();
format.setLineHeight(130, QTextBlockFormat::ProportionalHeight);
cursor.setBlockFormat(format);
if (d.ub == -1 && !d.visible)
d.ub = count;
}
#include "textdocument.moc"
<|endoftext|>
|
<commit_before>#ifndef _prusaslicer_technologies_h_
#define _prusaslicer_technologies_h_
//=============
// debug techs
//=============
// Shows camera target in the 3D scene
#define ENABLE_SHOW_CAMERA_TARGET 0
// Log debug messages to console when changing selection
#define ENABLE_SELECTION_DEBUG_OUTPUT 0
// Renders a small sphere in the center of the bounding box of the current selection when no gizmo is active
#define ENABLE_RENDER_SELECTION_CENTER 0
// Shows an imgui dialog with camera related data
#define ENABLE_CAMERA_STATISTICS 0
// Render the picking pass instead of the main scene (use [T] key to toggle between regular rendering and picking pass only rendering)
#define ENABLE_RENDER_PICKING_PASS 0
// Enable extracting thumbnails from selected gcode and save them as png files
#define ENABLE_THUMBNAIL_GENERATOR_DEBUG 0
// Disable synchronization of unselected instances
#define DISABLE_INSTANCES_SYNCH 0
// Use wxDataViewRender instead of wxDataViewCustomRenderer
#define ENABLE_NONCUSTOM_DATA_VIEW_RENDERING 0
// Enable G-Code viewer statistics imgui dialog
#define ENABLE_GCODE_VIEWER_STATISTICS 0
// Enable G-Code viewer comparison between toolpaths height and width detected from gcode and calculated at gcode generation
#define ENABLE_GCODE_VIEWER_DATA_CHECKING 0
// Enable project dirty state manager debug window
#define ENABLE_PROJECT_DIRTY_STATE_DEBUG_WINDOW 0
// Enable rendering of objects using environment map
#define ENABLE_ENVIRONMENT_MAP 0
// Enable smoothing of objects normals
#define ENABLE_SMOOTH_NORMALS 0
// Enable rendering markers for options in preview as fixed screen size points
#define ENABLE_FIXED_SCREEN_SIZE_POINT_MARKERS 1
//====================
// 2.4.0.alpha1 techs
//====================
#define ENABLE_2_4_0_ALPHA1 1
// Enable drawing contours, at cut level, for sinking volumes
#define ENABLE_SINKING_CONTOURS (1 && ENABLE_2_4_0_ALPHA1)
// Enable implementation of retract acceleration in gcode processor
#define ENABLE_RETRACT_ACCELERATION (1 && ENABLE_2_4_0_ALPHA1)
// Enable the fix for exporting and importing to/from 3mf file of mirrored volumes
#define ENABLE_FIX_MIRRORED_VOLUMES_3MF_IMPORT_EXPORT (1 && ENABLE_2_4_0_ALPHA1)
// Enable rendering seams (and other options) in preview using models
#define ENABLE_SEAMS_USING_MODELS (1 && ENABLE_2_4_0_ALPHA1)
// Enable save and save as commands to be enabled also when the plater is empty and allow to load empty projects
#define ENABLE_SAVE_COMMANDS_ALWAYS_ENABLED (1 && ENABLE_2_4_0_ALPHA1)
//====================
// 2.4.0.alpha2 techs
//====================
#define ENABLE_2_4_0_ALPHA2 1
// Enable rendering seams (and other options) in preview using batched models on systems not supporting OpenGL 3.3
#define ENABLE_SEAMS_USING_BATCHED_MODELS (1 && ENABLE_SEAMS_USING_MODELS && ENABLE_2_4_0_ALPHA2)
// Enable fixing the z position of color change, pause print and custom gcode markers in preview
#define ENABLE_FIX_PREVIEW_OPTIONS_Z (1 && ENABLE_SEAMS_USING_MODELS && ENABLE_FIX_IMPORTING_COLOR_PRINT_VIEW_INTO_GCODEVIEWER && ENABLE_2_4_0_ALPHA2)
// Enable replacing a missing file during reload from disk command
#define ENABLE_RELOAD_FROM_DISK_REPLACE_FILE (1 && ENABLE_2_4_0_ALPHA2)
#endif // _prusaslicer_technologies_h_
<commit_msg>Follow-up of d52ee52098a144a0a68a0721b6d2e7dce8d70a46 - Removed forgotten tech key<commit_after>#ifndef _prusaslicer_technologies_h_
#define _prusaslicer_technologies_h_
//=============
// debug techs
//=============
// Shows camera target in the 3D scene
#define ENABLE_SHOW_CAMERA_TARGET 0
// Log debug messages to console when changing selection
#define ENABLE_SELECTION_DEBUG_OUTPUT 0
// Renders a small sphere in the center of the bounding box of the current selection when no gizmo is active
#define ENABLE_RENDER_SELECTION_CENTER 0
// Shows an imgui dialog with camera related data
#define ENABLE_CAMERA_STATISTICS 0
// Render the picking pass instead of the main scene (use [T] key to toggle between regular rendering and picking pass only rendering)
#define ENABLE_RENDER_PICKING_PASS 0
// Enable extracting thumbnails from selected gcode and save them as png files
#define ENABLE_THUMBNAIL_GENERATOR_DEBUG 0
// Disable synchronization of unselected instances
#define DISABLE_INSTANCES_SYNCH 0
// Use wxDataViewRender instead of wxDataViewCustomRenderer
#define ENABLE_NONCUSTOM_DATA_VIEW_RENDERING 0
// Enable G-Code viewer statistics imgui dialog
#define ENABLE_GCODE_VIEWER_STATISTICS 0
// Enable G-Code viewer comparison between toolpaths height and width detected from gcode and calculated at gcode generation
#define ENABLE_GCODE_VIEWER_DATA_CHECKING 0
// Enable project dirty state manager debug window
#define ENABLE_PROJECT_DIRTY_STATE_DEBUG_WINDOW 0
// Enable rendering of objects using environment map
#define ENABLE_ENVIRONMENT_MAP 0
// Enable smoothing of objects normals
#define ENABLE_SMOOTH_NORMALS 0
// Enable rendering markers for options in preview as fixed screen size points
#define ENABLE_FIXED_SCREEN_SIZE_POINT_MARKERS 1
//====================
// 2.4.0.alpha1 techs
//====================
#define ENABLE_2_4_0_ALPHA1 1
// Enable drawing contours, at cut level, for sinking volumes
#define ENABLE_SINKING_CONTOURS (1 && ENABLE_2_4_0_ALPHA1)
// Enable implementation of retract acceleration in gcode processor
#define ENABLE_RETRACT_ACCELERATION (1 && ENABLE_2_4_0_ALPHA1)
// Enable the fix for exporting and importing to/from 3mf file of mirrored volumes
#define ENABLE_FIX_MIRRORED_VOLUMES_3MF_IMPORT_EXPORT (1 && ENABLE_2_4_0_ALPHA1)
// Enable rendering seams (and other options) in preview using models
#define ENABLE_SEAMS_USING_MODELS (1 && ENABLE_2_4_0_ALPHA1)
// Enable save and save as commands to be enabled also when the plater is empty and allow to load empty projects
#define ENABLE_SAVE_COMMANDS_ALWAYS_ENABLED (1 && ENABLE_2_4_0_ALPHA1)
//====================
// 2.4.0.alpha2 techs
//====================
#define ENABLE_2_4_0_ALPHA2 1
// Enable rendering seams (and other options) in preview using batched models on systems not supporting OpenGL 3.3
#define ENABLE_SEAMS_USING_BATCHED_MODELS (1 && ENABLE_SEAMS_USING_MODELS && ENABLE_2_4_0_ALPHA2)
// Enable fixing the z position of color change, pause print and custom gcode markers in preview
#define ENABLE_FIX_PREVIEW_OPTIONS_Z (1 && ENABLE_SEAMS_USING_MODELS && ENABLE_2_4_0_ALPHA2)
// Enable replacing a missing file during reload from disk command
#define ENABLE_RELOAD_FROM_DISK_REPLACE_FILE (1 && ENABLE_2_4_0_ALPHA2)
#endif // _prusaslicer_technologies_h_
<|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_IO_TYPED_BROKER_HPP
#define CAF_IO_TYPED_BROKER_HPP
#include <map>
#include <vector>
#include "caf/none.hpp"
#include "caf/config.hpp"
#include "caf/make_counted.hpp"
#include "caf/spawn.hpp"
#include "caf/extend.hpp"
#include "caf/typed_behavior.hpp"
#include "caf/local_actor.hpp"
#include "caf/detail/logging.hpp"
#include "caf/detail/singletons.hpp"
#include "caf/detail/scope_guard.hpp"
#include "caf/detail/actor_registry.hpp"
#include "caf/detail/sync_request_bouncer.hpp"
#include "caf/mixin/typed_functor_based.hpp"
#include "caf/io/middleman.hpp"
#include "caf/io/abstract_broker.hpp"
namespace caf {
namespace io {
template <class... Sigs>
class typed_broker;
/// Infers the appropriate base class for a functor-based typed actor
/// from the result and the first argument of the functor.
template <class Result, class FirstArg>
struct infer_typed_broker_base;
template <class... Sigs, class FirstArg>
struct infer_typed_broker_base<typed_behavior<Sigs...>, FirstArg> {
using type = typed_broker<Sigs...>;
};
template <class... Sigs>
struct infer_typed_broker_base<void, typed_event_based_actor<Sigs...>*> {
using type = typed_broker<Sigs...>;
};
/// A typed broker mediates between actor systems and other components in
/// the network.
/// @extends local_actor
template <class... Sigs>
class typed_broker : public abstract_event_based_actor<typed_behavior<Sigs...>,
false, abstract_broker> {
public:
using signatures = detail::type_list<Sigs...>;
using behavior_type = typed_behavior<Sigs...>;
using super = abstract_event_based_actor<behavior_type, false,
abstract_broker>;
using pointer = intrusive_ptr<typed_broker>;
// friend with all possible instantiations
template <class...>
friend class typed_broker;
using super::send;
using super::delayed_send;
template <class... DestSigs, class... Ts>
void send(message_priority mp, const typed_actor<Sigs...>& dest, Ts&&... xs) {
detail::sender_signature_checker<
detail::type_list<Sigs...>,
detail::type_list<DestSigs...>,
detail::type_list<
typename detail::implicit_conversions<
typename std::decay<Ts>::type
>::type...
>
>::check();
super::send(mp, dest, std::forward<Ts>(xs)...);
}
template <class... DestSigs, class... Ts>
void send(const typed_actor<DestSigs...>& dest, Ts&&... xs) {
detail::sender_signature_checker<
detail::type_list<Sigs...>,
detail::type_list<DestSigs...>,
detail::type_list<
typename detail::implicit_conversions<
typename std::decay<Ts>::type
>::type...
>
>::check();
super::send(dest, std::forward<Ts>(xs)...);
}
template <class... DestSigs, class... Ts>
void delayed_send(message_priority mp, const typed_actor<Sigs...>& dest,
const duration& rtime, Ts&&... xs) {
detail::sender_signature_checker<
detail::type_list<Sigs...>,
detail::type_list<DestSigs...>,
detail::type_list<
typename detail::implicit_conversions<
typename std::decay<Ts>::type
>::type...
>
>::check();
super::delayed_send(mp, dest, rtime, std::forward<Ts>(xs)...);
}
template <class... DestSigs, class... Ts>
void delayed_send(const typed_actor<Sigs...>& dest,
const duration& rtime, Ts&&... xs) {
detail::sender_signature_checker<
detail::type_list<Sigs...>,
detail::type_list<DestSigs...>,
detail::type_list<
typename detail::implicit_conversions<
typename std::decay<Ts>::type
>::type...
>
>::check();
super::delayed_send(dest, rtime, std::forward<Ts>(xs)...);
}
/// @cond PRIVATE
std::set<std::string> message_types() const override {
return {Sigs::static_type_name()...};
}
void initialize() override {
this->is_initialized(true);
auto bhvr = make_behavior();
CAF_LOG_DEBUG_IF(! bhvr, "make_behavior() did not return a behavior, "
<< "has_behavior() = "
<< std::boolalpha << this->has_behavior());
if (bhvr) {
// make_behavior() did return a behavior instead of using become()
CAF_LOG_DEBUG("make_behavior() did return a valid behavior");
this->do_become(std::move(bhvr.unbox()), true);
}
}
template <class F, class... Ts>
typename infer_typed_actor_handle<
typename detail::get_callable_trait<F>::result_type,
typename detail::tl_head<
typename detail::get_callable_trait<F>::arg_types
>::type
>::type
fork(F fun, connection_handle hdl, Ts&&... xs) {
auto i = this->scribes_.find(hdl);
if (i == this->scribes_.end()) {
CAF_LOG_ERROR("invalid handle");
throw std::invalid_argument("invalid handle");
}
auto sptr = i->second;
CAF_ASSERT(sptr->hdl() == hdl);
this->scribes_.erase(i);
using impl =
typename infer_typed_broker_base<
typename detail::get_callable_trait<F>::result_type,
typename detail::tl_head<
typename detail::get_callable_trait<F>::arg_types
>::type
>::type;
return spawn_functor_impl<no_spawn_options, impl>(
nullptr, [&sptr](abstract_broker* forked) {
sptr->set_broker(forked);
forked->add_scribe(sptr);
},
std::move(fun), hdl, std::forward<Ts>(xs)...);
}
protected:
typed_broker() {
// nop
}
typed_broker(middleman& parent_ref) : abstract_broker(parent_ref) {
// nop
}
virtual behavior_type make_behavior() {
if (this->initial_behavior_fac_) {
auto bhvr = this->initial_behavior_fac_(this);
this->initial_behavior_fac_ = nullptr;
if (bhvr)
this->do_become(std::move(bhvr), true);
}
return behavior_type::make_empty_behavior();
}
};
} // namespace io
} // namespace caf
#endif // CAF_IO_TYPED_BROKER_HPP
<commit_msg>Remove dead code from `typed_broker`<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_IO_TYPED_BROKER_HPP
#define CAF_IO_TYPED_BROKER_HPP
#include <map>
#include <vector>
#include "caf/none.hpp"
#include "caf/config.hpp"
#include "caf/make_counted.hpp"
#include "caf/spawn.hpp"
#include "caf/extend.hpp"
#include "caf/typed_behavior.hpp"
#include "caf/local_actor.hpp"
#include "caf/detail/logging.hpp"
#include "caf/detail/singletons.hpp"
#include "caf/detail/scope_guard.hpp"
#include "caf/detail/actor_registry.hpp"
#include "caf/detail/sync_request_bouncer.hpp"
#include "caf/mixin/typed_functor_based.hpp"
#include "caf/io/middleman.hpp"
#include "caf/io/abstract_broker.hpp"
namespace caf {
namespace io {
template <class... Sigs>
class typed_broker;
/// Infers the appropriate base class for a functor-based typed actor
/// from the result and the first argument of the functor.
template <class Result, class FirstArg>
struct infer_typed_broker_base;
template <class... Sigs, class FirstArg>
struct infer_typed_broker_base<typed_behavior<Sigs...>, FirstArg> {
using type = typed_broker<Sigs...>;
};
template <class... Sigs>
struct infer_typed_broker_base<void, typed_event_based_actor<Sigs...>*> {
using type = typed_broker<Sigs...>;
};
/// A typed broker mediates between actor systems and other components in
/// the network.
/// @extends local_actor
template <class... Sigs>
class typed_broker : public abstract_event_based_actor<typed_behavior<Sigs...>,
false, abstract_broker> {
public:
using signatures = detail::type_list<Sigs...>;
using behavior_type = typed_behavior<Sigs...>;
using super = abstract_event_based_actor<behavior_type, false,
abstract_broker>;
using super::send;
using super::delayed_send;
template <class... DestSigs, class... Ts>
void send(message_priority mp, const typed_actor<Sigs...>& dest, Ts&&... xs) {
detail::sender_signature_checker<
detail::type_list<Sigs...>,
detail::type_list<DestSigs...>,
detail::type_list<
typename detail::implicit_conversions<
typename std::decay<Ts>::type
>::type...
>
>::check();
super::send(mp, dest, std::forward<Ts>(xs)...);
}
template <class... DestSigs, class... Ts>
void send(const typed_actor<DestSigs...>& dest, Ts&&... xs) {
detail::sender_signature_checker<
detail::type_list<Sigs...>,
detail::type_list<DestSigs...>,
detail::type_list<
typename detail::implicit_conversions<
typename std::decay<Ts>::type
>::type...
>
>::check();
super::send(dest, std::forward<Ts>(xs)...);
}
template <class... DestSigs, class... Ts>
void delayed_send(message_priority mp, const typed_actor<Sigs...>& dest,
const duration& rtime, Ts&&... xs) {
detail::sender_signature_checker<
detail::type_list<Sigs...>,
detail::type_list<DestSigs...>,
detail::type_list<
typename detail::implicit_conversions<
typename std::decay<Ts>::type
>::type...
>
>::check();
super::delayed_send(mp, dest, rtime, std::forward<Ts>(xs)...);
}
template <class... DestSigs, class... Ts>
void delayed_send(const typed_actor<Sigs...>& dest,
const duration& rtime, Ts&&... xs) {
detail::sender_signature_checker<
detail::type_list<Sigs...>,
detail::type_list<DestSigs...>,
detail::type_list<
typename detail::implicit_conversions<
typename std::decay<Ts>::type
>::type...
>
>::check();
super::delayed_send(dest, rtime, std::forward<Ts>(xs)...);
}
/// @cond PRIVATE
std::set<std::string> message_types() const override {
return {Sigs::static_type_name()...};
}
void initialize() override {
this->is_initialized(true);
auto bhvr = make_behavior();
CAF_LOG_DEBUG_IF(! bhvr, "make_behavior() did not return a behavior, "
<< "has_behavior() = "
<< std::boolalpha << this->has_behavior());
if (bhvr) {
// make_behavior() did return a behavior instead of using become()
CAF_LOG_DEBUG("make_behavior() did return a valid behavior");
this->do_become(std::move(bhvr.unbox()), true);
}
}
template <class F, class... Ts>
typename infer_typed_actor_handle<
typename detail::get_callable_trait<F>::result_type,
typename detail::tl_head<
typename detail::get_callable_trait<F>::arg_types
>::type
>::type
fork(F fun, connection_handle hdl, Ts&&... xs) {
auto i = this->scribes_.find(hdl);
if (i == this->scribes_.end()) {
CAF_LOG_ERROR("invalid handle");
throw std::invalid_argument("invalid handle");
}
auto sptr = i->second;
CAF_ASSERT(sptr->hdl() == hdl);
this->scribes_.erase(i);
using impl =
typename infer_typed_broker_base<
typename detail::get_callable_trait<F>::result_type,
typename detail::tl_head<
typename detail::get_callable_trait<F>::arg_types
>::type
>::type;
return spawn_functor_impl<no_spawn_options, impl>(
nullptr, [&sptr](abstract_broker* forked) {
sptr->set_broker(forked);
forked->add_scribe(sptr);
},
std::move(fun), hdl, std::forward<Ts>(xs)...);
}
protected:
typed_broker() {
// nop
}
typed_broker(middleman& parent_ref) : abstract_broker(parent_ref) {
// nop
}
virtual behavior_type make_behavior() {
if (this->initial_behavior_fac_) {
auto bhvr = this->initial_behavior_fac_(this);
this->initial_behavior_fac_ = nullptr;
if (bhvr)
this->do_become(std::move(bhvr), true);
}
return behavior_type::make_empty_behavior();
}
};
} // namespace io
} // namespace caf
#endif // CAF_IO_TYPED_BROKER_HPP
<|endoftext|>
|
<commit_before>/**************************************************************************
*
* Copyright 2011 Jose Fonseca
* Copyright (C) 2013 Intel Corporation. All rights reversed.
* Author: Shuang He <shuang.he@intel.com>
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
**************************************************************************/
#include <string.h>
#include "retrace.hpp"
#include "glproc.hpp"
#include "glstate.hpp"
#include "glretrace.hpp"
#include "os_time.hpp"
#include "os_memory.hpp"
/* Synchronous debug output may reduce performance however,
* without it the callNo in the callback may be inaccurate
* as the callback may be called at any time.
*/
#define DEBUG_OUTPUT_SYNCHRONOUS 0
namespace glretrace {
glws::Profile defaultProfile = glws::PROFILE_COMPAT;
bool insideList = false;
bool insideGlBeginEnd = false;
bool supportsARBShaderObjects = false;
enum {
GPU_START = 0,
GPU_DURATION,
OCCLUSION,
NUM_QUERIES,
};
struct CallQuery
{
GLuint ids[NUM_QUERIES];
unsigned call;
bool isDraw;
GLuint program;
const trace::FunctionSig *sig;
int64_t cpuStart;
int64_t cpuEnd;
int64_t vsizeStart;
int64_t vsizeEnd;
int64_t rssStart;
int64_t rssEnd;
};
static bool supportsElapsed = true;
static bool supportsTimestamp = true;
static bool supportsOcclusion = true;
static bool supportsDebugOutput = true;
static std::list<CallQuery> callQueries;
static void APIENTRY
debugOutputCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam);
void
checkGlError(trace::Call &call) {
GLenum error = glGetError();
while (error != GL_NO_ERROR) {
std::ostream & os = retrace::warning(call);
os << "glGetError(";
os << call.name();
os << ") = ";
switch (error) {
case GL_INVALID_ENUM:
os << "GL_INVALID_ENUM";
break;
case GL_INVALID_VALUE:
os << "GL_INVALID_VALUE";
break;
case GL_INVALID_OPERATION:
os << "GL_INVALID_OPERATION";
break;
case GL_STACK_OVERFLOW:
os << "GL_STACK_OVERFLOW";
break;
case GL_STACK_UNDERFLOW:
os << "GL_STACK_UNDERFLOW";
break;
case GL_OUT_OF_MEMORY:
os << "GL_OUT_OF_MEMORY";
break;
case GL_INVALID_FRAMEBUFFER_OPERATION:
os << "GL_INVALID_FRAMEBUFFER_OPERATION";
break;
case GL_TABLE_TOO_LARGE:
os << "GL_TABLE_TOO_LARGE";
break;
default:
os << error;
break;
}
os << "\n";
error = glGetError();
}
}
static inline int64_t
getCurrentTime(void) {
if (retrace::profilingGpuTimes && supportsTimestamp) {
/* Get the current GL time without stalling */
GLint64 timestamp = 0;
glGetInteger64v(GL_TIMESTAMP, ×tamp);
return timestamp;
} else {
return os::getTime();
}
}
static inline int64_t
getTimeFrequency(void) {
if (retrace::profilingGpuTimes && supportsTimestamp) {
return 1000000000;
} else {
return os::timeFrequency;
}
}
static inline void
getCurrentVsize(int64_t& vsize) {
vsize = os::getVsize();
}
static inline void
getCurrentRss(int64_t& rss) {
rss = os::getRss();
}
static void
completeCallQuery(CallQuery& query) {
/* Get call start and duration */
int64_t gpuStart = 0, gpuDuration = 0, cpuDuration = 0, pixels = 0, vsizeDuration = 0, rssDuration = 0;
if (query.isDraw) {
if (retrace::profilingGpuTimes) {
if (supportsTimestamp) {
glGetQueryObjecti64vEXT(query.ids[GPU_START], GL_QUERY_RESULT, &gpuStart);
}
glGetQueryObjecti64vEXT(query.ids[GPU_DURATION], GL_QUERY_RESULT, &gpuDuration);
}
if (retrace::profilingPixelsDrawn) {
glGetQueryObjecti64vEXT(query.ids[OCCLUSION], GL_QUERY_RESULT, &pixels);
}
} else {
pixels = -1;
}
if (retrace::profilingCpuTimes) {
double cpuTimeScale = 1.0E9 / getTimeFrequency();
cpuDuration = (query.cpuEnd - query.cpuStart) * cpuTimeScale;
query.cpuStart *= cpuTimeScale;
}
if (retrace::profilingMemoryUsage) {
vsizeDuration = query.vsizeEnd - query.vsizeStart;
rssDuration = query.rssEnd - query.rssStart;
}
glDeleteQueries(NUM_QUERIES, query.ids);
/* Add call to profile */
retrace::profiler.addCall(query.call, query.sig->name, query.program, pixels, gpuStart, gpuDuration, query.cpuStart, cpuDuration, query.vsizeStart, vsizeDuration, query.rssStart, rssDuration);
}
void
flushQueries() {
for (std::list<CallQuery>::iterator itr = callQueries.begin(); itr != callQueries.end(); ++itr) {
completeCallQuery(*itr);
}
callQueries.clear();
}
void
beginProfile(trace::Call &call, bool isDraw) {
glretrace::Context *currentContext = glretrace::getCurrentContext();
/* Create call query */
CallQuery query;
query.isDraw = isDraw;
query.call = call.no;
query.sig = call.sig;
query.program = currentContext ? currentContext->activeProgram : 0;
glGenQueries(NUM_QUERIES, query.ids);
/* GPU profiling only for draw calls */
if (isDraw) {
if (retrace::profilingGpuTimes) {
if (supportsTimestamp) {
glQueryCounter(query.ids[GPU_START], GL_TIMESTAMP);
}
glBeginQuery(GL_TIME_ELAPSED, query.ids[GPU_DURATION]);
}
if (retrace::profilingPixelsDrawn) {
glBeginQuery(GL_SAMPLES_PASSED, query.ids[OCCLUSION]);
}
}
callQueries.push_back(query);
/* CPU profiling for all calls */
if (retrace::profilingCpuTimes) {
CallQuery& query = callQueries.back();
query.cpuStart = getCurrentTime();
}
if (retrace::profilingMemoryUsage) {
CallQuery& query = callQueries.back();
query.vsizeStart = os::getVsize();
query.rssStart = os::getRss();
}
}
void
endProfile(trace::Call &call, bool isDraw) {
/* CPU profiling for all calls */
if (retrace::profilingCpuTimes) {
CallQuery& query = callQueries.back();
query.cpuEnd = getCurrentTime();
}
/* GPU profiling only for draw calls */
if (isDraw) {
if (retrace::profilingGpuTimes) {
glEndQuery(GL_TIME_ELAPSED);
}
if (retrace::profilingPixelsDrawn) {
glEndQuery(GL_SAMPLES_PASSED);
}
}
if (retrace::profilingMemoryUsage) {
CallQuery& query = callQueries.back();
query.vsizeEnd = os::getVsize();
query.rssEnd = os::getRss();
}
}
void
initContext() {
glretrace::Context *currentContext = glretrace::getCurrentContext();
/* Ensure we have adequate extension support */
assert(currentContext);
supportsTimestamp = currentContext->hasExtension("GL_ARB_timer_query");
supportsElapsed = currentContext->hasExtension("GL_EXT_timer_query") || supportsTimestamp;
supportsOcclusion = currentContext->hasExtension("GL_ARB_occlusion_query");
supportsDebugOutput = currentContext->hasExtension("GL_ARB_debug_output");
supportsARBShaderObjects = currentContext->hasExtension("GL_ARB_shader_objects");
/* Check for timer query support */
if (retrace::profilingGpuTimes) {
if (!supportsTimestamp && !supportsElapsed) {
std::cout << "Error: Cannot run profile, GL_EXT_timer_query extension is not supported." << std::endl;
exit(-1);
}
GLint bits = 0;
glGetQueryiv(GL_TIME_ELAPSED, GL_QUERY_COUNTER_BITS, &bits);
if (!bits) {
std::cout << "Error: Cannot run profile, GL_QUERY_COUNTER_BITS == 0." << std::endl;
exit(-1);
}
}
/* Check for occlusion query support */
if (retrace::profilingPixelsDrawn && !supportsOcclusion) {
std::cout << "Error: Cannot run profile, GL_ARB_occlusion_query extension is not supported." << std::endl;
exit(-1);
}
/* Setup debug message call back */
if (retrace::debug && supportsDebugOutput) {
glretrace::Context *currentContext = glretrace::getCurrentContext();
glDebugMessageCallbackARB(&debugOutputCallback, currentContext);
if (DEBUG_OUTPUT_SYNCHRONOUS) {
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
}
}
/* Sync the gpu and cpu start times */
if (retrace::profilingCpuTimes || retrace::profilingGpuTimes) {
if (!retrace::profiler.hasBaseTimes()) {
double cpuTimeScale = 1.0E9 / getTimeFrequency();
GLint64 currentTime = getCurrentTime() * cpuTimeScale;
retrace::profiler.setBaseCpuTime(currentTime);
retrace::profiler.setBaseGpuTime(currentTime);
}
}
if (retrace::profilingMemoryUsage) {
GLint64 currentVsize, currentRss;
getCurrentVsize(currentVsize);
retrace::profiler.setBaseVsizeUsage(currentVsize);
getCurrentRss(currentRss);
retrace::profiler.setBaseRssUsage(currentRss);
}
}
void
frame_complete(trace::Call &call) {
if (retrace::profiling) {
/* Complete any remaining queries */
flushQueries();
/* Indicate end of current frame */
retrace::profiler.addFrameEnd();
}
retrace::frameComplete(call);
glretrace::Context *currentContext = glretrace::getCurrentContext();
if (!currentContext) {
return;
}
assert(currentContext->drawable);
if (retrace::debug && !currentContext->drawable->visible) {
retrace::warning(call) << "could not infer drawable size (glViewport never called)\n";
}
}
static const char*
getDebugOutputSource(GLenum source) {
switch(source) {
case GL_DEBUG_SOURCE_API_ARB:
return "API";
case GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB:
return "Window System";
case GL_DEBUG_SOURCE_SHADER_COMPILER_ARB:
return "Shader Compiler";
case GL_DEBUG_SOURCE_THIRD_PARTY_ARB:
return "Third Party";
case GL_DEBUG_SOURCE_APPLICATION_ARB:
return "Application";
case GL_DEBUG_SOURCE_OTHER_ARB:
default:
return "";
}
}
static const char*
getDebugOutputType(GLenum type) {
switch(type) {
case GL_DEBUG_TYPE_ERROR_ARB:
return "error";
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB:
return "deprecated behaviour";
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB:
return "undefined behaviour";
case GL_DEBUG_TYPE_PORTABILITY_ARB:
return "portability issue";
case GL_DEBUG_TYPE_PERFORMANCE_ARB:
return "performance issue";
case GL_DEBUG_TYPE_OTHER_ARB:
default:
return "unknown issue";
}
}
static const char*
getDebugOutputSeverity(GLenum severity) {
switch(severity) {
case GL_DEBUG_SEVERITY_HIGH_ARB:
return "High";
case GL_DEBUG_SEVERITY_MEDIUM_ARB:
return "Medium";
case GL_DEBUG_SEVERITY_LOW_ARB:
return "Low";
default:
return "usnknown";
}
}
static void APIENTRY
debugOutputCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam) {
std::cerr << retrace::callNo << ": ";
std::cerr << "glDebugOutputCallback: ";
std::cerr << getDebugOutputSeverity(severity) << " severity ";
std::cerr << getDebugOutputSource(source) << " " << getDebugOutputType(type);
std::cerr << " " << id;
std::cerr << ", " << message;
std::cerr << std::endl;
}
} /* namespace glretrace */
class GLDumper : public retrace::Dumper {
public:
image::Image *
getSnapshot(void) {
if (!glretrace::getCurrentContext()) {
return NULL;
}
return glstate::getDrawBufferImage();
}
bool
dumpState(std::ostream &os) {
glretrace::Context *currentContext = glretrace::getCurrentContext();
if (glretrace::insideGlBeginEnd ||
!currentContext) {
return false;
}
glstate::dumpCurrentContext(os);
return true;
}
};
static GLDumper glDumper;
void
retrace::setFeatureLevel(const char *featureLevel)
{
glretrace::defaultProfile = glws::PROFILE_3_2_CORE;
}
void
retrace::setUp(void) {
glws::init();
dumper = &glDumper;
}
void
retrace::addCallbacks(retrace::Retracer &retracer)
{
retracer.addCallbacks(glretrace::gl_callbacks);
retracer.addCallbacks(glretrace::glx_callbacks);
retracer.addCallbacks(glretrace::wgl_callbacks);
retracer.addCallbacks(glretrace::cgl_callbacks);
retracer.addCallbacks(glretrace::egl_callbacks);
}
void
retrace::flushRendering(void) {
glretrace::Context *currentContext = glretrace::getCurrentContext();
if (currentContext) {
glretrace::flushQueries();
}
}
void
retrace::finishRendering(void) {
glretrace::Context *currentContext = glretrace::getCurrentContext();
if (currentContext) {
glFinish();
}
}
void
retrace::waitForInput(void) {
flushRendering();
while (glws::processEvents()) {
os::sleep(100*1000);
}
}
void
retrace::cleanUp(void) {
glws::cleanup();
}
<commit_msg>glretrace: Enable all debug output.<commit_after>/**************************************************************************
*
* Copyright 2011 Jose Fonseca
* Copyright (C) 2013 Intel Corporation. All rights reversed.
* Author: Shuang He <shuang.he@intel.com>
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
**************************************************************************/
#include <string.h>
#include "retrace.hpp"
#include "glproc.hpp"
#include "glstate.hpp"
#include "glretrace.hpp"
#include "os_time.hpp"
#include "os_memory.hpp"
/* Synchronous debug output may reduce performance however,
* without it the callNo in the callback may be inaccurate
* as the callback may be called at any time.
*/
#define DEBUG_OUTPUT_SYNCHRONOUS 0
namespace glretrace {
glws::Profile defaultProfile = glws::PROFILE_COMPAT;
bool insideList = false;
bool insideGlBeginEnd = false;
bool supportsARBShaderObjects = false;
enum {
GPU_START = 0,
GPU_DURATION,
OCCLUSION,
NUM_QUERIES,
};
struct CallQuery
{
GLuint ids[NUM_QUERIES];
unsigned call;
bool isDraw;
GLuint program;
const trace::FunctionSig *sig;
int64_t cpuStart;
int64_t cpuEnd;
int64_t vsizeStart;
int64_t vsizeEnd;
int64_t rssStart;
int64_t rssEnd;
};
static bool supportsElapsed = true;
static bool supportsTimestamp = true;
static bool supportsOcclusion = true;
static bool supportsDebugOutput = true;
static std::list<CallQuery> callQueries;
static void APIENTRY
debugOutputCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam);
void
checkGlError(trace::Call &call) {
GLenum error = glGetError();
while (error != GL_NO_ERROR) {
std::ostream & os = retrace::warning(call);
os << "glGetError(";
os << call.name();
os << ") = ";
switch (error) {
case GL_INVALID_ENUM:
os << "GL_INVALID_ENUM";
break;
case GL_INVALID_VALUE:
os << "GL_INVALID_VALUE";
break;
case GL_INVALID_OPERATION:
os << "GL_INVALID_OPERATION";
break;
case GL_STACK_OVERFLOW:
os << "GL_STACK_OVERFLOW";
break;
case GL_STACK_UNDERFLOW:
os << "GL_STACK_UNDERFLOW";
break;
case GL_OUT_OF_MEMORY:
os << "GL_OUT_OF_MEMORY";
break;
case GL_INVALID_FRAMEBUFFER_OPERATION:
os << "GL_INVALID_FRAMEBUFFER_OPERATION";
break;
case GL_TABLE_TOO_LARGE:
os << "GL_TABLE_TOO_LARGE";
break;
default:
os << error;
break;
}
os << "\n";
error = glGetError();
}
}
static inline int64_t
getCurrentTime(void) {
if (retrace::profilingGpuTimes && supportsTimestamp) {
/* Get the current GL time without stalling */
GLint64 timestamp = 0;
glGetInteger64v(GL_TIMESTAMP, ×tamp);
return timestamp;
} else {
return os::getTime();
}
}
static inline int64_t
getTimeFrequency(void) {
if (retrace::profilingGpuTimes && supportsTimestamp) {
return 1000000000;
} else {
return os::timeFrequency;
}
}
static inline void
getCurrentVsize(int64_t& vsize) {
vsize = os::getVsize();
}
static inline void
getCurrentRss(int64_t& rss) {
rss = os::getRss();
}
static void
completeCallQuery(CallQuery& query) {
/* Get call start and duration */
int64_t gpuStart = 0, gpuDuration = 0, cpuDuration = 0, pixels = 0, vsizeDuration = 0, rssDuration = 0;
if (query.isDraw) {
if (retrace::profilingGpuTimes) {
if (supportsTimestamp) {
glGetQueryObjecti64vEXT(query.ids[GPU_START], GL_QUERY_RESULT, &gpuStart);
}
glGetQueryObjecti64vEXT(query.ids[GPU_DURATION], GL_QUERY_RESULT, &gpuDuration);
}
if (retrace::profilingPixelsDrawn) {
glGetQueryObjecti64vEXT(query.ids[OCCLUSION], GL_QUERY_RESULT, &pixels);
}
} else {
pixels = -1;
}
if (retrace::profilingCpuTimes) {
double cpuTimeScale = 1.0E9 / getTimeFrequency();
cpuDuration = (query.cpuEnd - query.cpuStart) * cpuTimeScale;
query.cpuStart *= cpuTimeScale;
}
if (retrace::profilingMemoryUsage) {
vsizeDuration = query.vsizeEnd - query.vsizeStart;
rssDuration = query.rssEnd - query.rssStart;
}
glDeleteQueries(NUM_QUERIES, query.ids);
/* Add call to profile */
retrace::profiler.addCall(query.call, query.sig->name, query.program, pixels, gpuStart, gpuDuration, query.cpuStart, cpuDuration, query.vsizeStart, vsizeDuration, query.rssStart, rssDuration);
}
void
flushQueries() {
for (std::list<CallQuery>::iterator itr = callQueries.begin(); itr != callQueries.end(); ++itr) {
completeCallQuery(*itr);
}
callQueries.clear();
}
void
beginProfile(trace::Call &call, bool isDraw) {
glretrace::Context *currentContext = glretrace::getCurrentContext();
/* Create call query */
CallQuery query;
query.isDraw = isDraw;
query.call = call.no;
query.sig = call.sig;
query.program = currentContext ? currentContext->activeProgram : 0;
glGenQueries(NUM_QUERIES, query.ids);
/* GPU profiling only for draw calls */
if (isDraw) {
if (retrace::profilingGpuTimes) {
if (supportsTimestamp) {
glQueryCounter(query.ids[GPU_START], GL_TIMESTAMP);
}
glBeginQuery(GL_TIME_ELAPSED, query.ids[GPU_DURATION]);
}
if (retrace::profilingPixelsDrawn) {
glBeginQuery(GL_SAMPLES_PASSED, query.ids[OCCLUSION]);
}
}
callQueries.push_back(query);
/* CPU profiling for all calls */
if (retrace::profilingCpuTimes) {
CallQuery& query = callQueries.back();
query.cpuStart = getCurrentTime();
}
if (retrace::profilingMemoryUsage) {
CallQuery& query = callQueries.back();
query.vsizeStart = os::getVsize();
query.rssStart = os::getRss();
}
}
void
endProfile(trace::Call &call, bool isDraw) {
/* CPU profiling for all calls */
if (retrace::profilingCpuTimes) {
CallQuery& query = callQueries.back();
query.cpuEnd = getCurrentTime();
}
/* GPU profiling only for draw calls */
if (isDraw) {
if (retrace::profilingGpuTimes) {
glEndQuery(GL_TIME_ELAPSED);
}
if (retrace::profilingPixelsDrawn) {
glEndQuery(GL_SAMPLES_PASSED);
}
}
if (retrace::profilingMemoryUsage) {
CallQuery& query = callQueries.back();
query.vsizeEnd = os::getVsize();
query.rssEnd = os::getRss();
}
}
void
initContext() {
glretrace::Context *currentContext = glretrace::getCurrentContext();
/* Ensure we have adequate extension support */
assert(currentContext);
supportsTimestamp = currentContext->hasExtension("GL_ARB_timer_query");
supportsElapsed = currentContext->hasExtension("GL_EXT_timer_query") || supportsTimestamp;
supportsOcclusion = currentContext->hasExtension("GL_ARB_occlusion_query");
supportsDebugOutput = currentContext->hasExtension("GL_ARB_debug_output");
supportsARBShaderObjects = currentContext->hasExtension("GL_ARB_shader_objects");
/* Check for timer query support */
if (retrace::profilingGpuTimes) {
if (!supportsTimestamp && !supportsElapsed) {
std::cout << "Error: Cannot run profile, GL_EXT_timer_query extension is not supported." << std::endl;
exit(-1);
}
GLint bits = 0;
glGetQueryiv(GL_TIME_ELAPSED, GL_QUERY_COUNTER_BITS, &bits);
if (!bits) {
std::cout << "Error: Cannot run profile, GL_QUERY_COUNTER_BITS == 0." << std::endl;
exit(-1);
}
}
/* Check for occlusion query support */
if (retrace::profilingPixelsDrawn && !supportsOcclusion) {
std::cout << "Error: Cannot run profile, GL_ARB_occlusion_query extension is not supported." << std::endl;
exit(-1);
}
/* Setup debug message call back */
if (retrace::debug && supportsDebugOutput) {
glretrace::Context *currentContext = glretrace::getCurrentContext();
glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, 0, GL_TRUE);
glDebugMessageCallbackARB(&debugOutputCallback, currentContext);
if (DEBUG_OUTPUT_SYNCHRONOUS) {
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
}
}
/* Sync the gpu and cpu start times */
if (retrace::profilingCpuTimes || retrace::profilingGpuTimes) {
if (!retrace::profiler.hasBaseTimes()) {
double cpuTimeScale = 1.0E9 / getTimeFrequency();
GLint64 currentTime = getCurrentTime() * cpuTimeScale;
retrace::profiler.setBaseCpuTime(currentTime);
retrace::profiler.setBaseGpuTime(currentTime);
}
}
if (retrace::profilingMemoryUsage) {
GLint64 currentVsize, currentRss;
getCurrentVsize(currentVsize);
retrace::profiler.setBaseVsizeUsage(currentVsize);
getCurrentRss(currentRss);
retrace::profiler.setBaseRssUsage(currentRss);
}
}
void
frame_complete(trace::Call &call) {
if (retrace::profiling) {
/* Complete any remaining queries */
flushQueries();
/* Indicate end of current frame */
retrace::profiler.addFrameEnd();
}
retrace::frameComplete(call);
glretrace::Context *currentContext = glretrace::getCurrentContext();
if (!currentContext) {
return;
}
assert(currentContext->drawable);
if (retrace::debug && !currentContext->drawable->visible) {
retrace::warning(call) << "could not infer drawable size (glViewport never called)\n";
}
}
static const char*
getDebugOutputSource(GLenum source) {
switch(source) {
case GL_DEBUG_SOURCE_API_ARB:
return "API";
case GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB:
return "Window System";
case GL_DEBUG_SOURCE_SHADER_COMPILER_ARB:
return "Shader Compiler";
case GL_DEBUG_SOURCE_THIRD_PARTY_ARB:
return "Third Party";
case GL_DEBUG_SOURCE_APPLICATION_ARB:
return "Application";
case GL_DEBUG_SOURCE_OTHER_ARB:
default:
return "";
}
}
static const char*
getDebugOutputType(GLenum type) {
switch(type) {
case GL_DEBUG_TYPE_ERROR_ARB:
return "error";
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB:
return "deprecated behaviour";
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB:
return "undefined behaviour";
case GL_DEBUG_TYPE_PORTABILITY_ARB:
return "portability issue";
case GL_DEBUG_TYPE_PERFORMANCE_ARB:
return "performance issue";
case GL_DEBUG_TYPE_OTHER_ARB:
default:
return "unknown issue";
}
}
static const char*
getDebugOutputSeverity(GLenum severity) {
switch(severity) {
case GL_DEBUG_SEVERITY_HIGH_ARB:
return "High";
case GL_DEBUG_SEVERITY_MEDIUM_ARB:
return "Medium";
case GL_DEBUG_SEVERITY_LOW_ARB:
return "Low";
default:
return "usnknown";
}
}
static void APIENTRY
debugOutputCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam) {
std::cerr << retrace::callNo << ": ";
std::cerr << "glDebugOutputCallback: ";
std::cerr << getDebugOutputSeverity(severity) << " severity ";
std::cerr << getDebugOutputSource(source) << " " << getDebugOutputType(type);
std::cerr << " " << id;
std::cerr << ", " << message;
std::cerr << std::endl;
}
} /* namespace glretrace */
class GLDumper : public retrace::Dumper {
public:
image::Image *
getSnapshot(void) {
if (!glretrace::getCurrentContext()) {
return NULL;
}
return glstate::getDrawBufferImage();
}
bool
dumpState(std::ostream &os) {
glretrace::Context *currentContext = glretrace::getCurrentContext();
if (glretrace::insideGlBeginEnd ||
!currentContext) {
return false;
}
glstate::dumpCurrentContext(os);
return true;
}
};
static GLDumper glDumper;
void
retrace::setFeatureLevel(const char *featureLevel)
{
glretrace::defaultProfile = glws::PROFILE_3_2_CORE;
}
void
retrace::setUp(void) {
glws::init();
dumper = &glDumper;
}
void
retrace::addCallbacks(retrace::Retracer &retracer)
{
retracer.addCallbacks(glretrace::gl_callbacks);
retracer.addCallbacks(glretrace::glx_callbacks);
retracer.addCallbacks(glretrace::wgl_callbacks);
retracer.addCallbacks(glretrace::cgl_callbacks);
retracer.addCallbacks(glretrace::egl_callbacks);
}
void
retrace::flushRendering(void) {
glretrace::Context *currentContext = glretrace::getCurrentContext();
if (currentContext) {
glretrace::flushQueries();
}
}
void
retrace::finishRendering(void) {
glretrace::Context *currentContext = glretrace::getCurrentContext();
if (currentContext) {
glFinish();
}
}
void
retrace::waitForInput(void) {
flushRendering();
while (glws::processEvents()) {
os::sleep(100*1000);
}
}
void
retrace::cleanUp(void) {
glws::cleanup();
}
<|endoftext|>
|
<commit_before>/*
This file is part of khmer, https://github.com/dib-lab/khmer/, and is
Copyright (C) 2010-2015, Michigan State University.
Copyright (C) 2015-2016, The Regents of the University of California.
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 Michigan State University 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
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.
LICENSE (END)
Contact: khmer-project@idyll.org
*/
#ifndef KMER_HASH_HH
#define KMER_HASH_HH
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include "khmer.hh"
// test validity
#ifdef KHMER_EXTRA_SANITY_CHECKS
# define is_valid_dna(ch) ((toupper(ch)) == 'A' || (toupper(ch)) == 'C' || \
(toupper(ch)) == 'G' || (toupper(ch)) == 'T')
#else
// NOTE: Assumes data is already sanitized as it should be by parsers.
// This assumption eliminates 4 function calls.
# define is_valid_dna(ch) ((ch) == 'A' || (ch) == 'C' || \
(ch) == 'G' || (ch) == 'T')
#endif
// bit representation of A/T/C/G.
#ifdef KHMER_EXTRA_SANITY_CHECKS
# define twobit_repr(ch) ((toupper(ch)) == 'A' ? 0LL : \
(toupper(ch)) == 'T' ? 1LL : \
(toupper(ch)) == 'C' ? 2LL : 3LL)
#else
// NOTE: Assumes data is already sanitized as it should be by parsers.
// This assumption eliminates 4 function calls.
# define twobit_repr(ch) ((ch) == 'A' ? 0LL : \
(ch) == 'T' ? 1LL : \
(ch) == 'C' ? 2LL : 3LL)
#endif
#define revtwobit_repr(n) ((n) == 0 ? 'A' : \
(n) == 1 ? 'T' : \
(n) == 2 ? 'C' : 'G')
#ifdef KHMER_EXTRA_SANITY_CHECKS
# define twobit_comp(ch) ((toupper(ch)) == 'A' ? 1LL : \
(toupper(ch)) == 'T' ? 0LL : \
(toupper(ch)) == 'C' ? 3LL : 2LL)
#else
// NOTE: Assumes data is already sanitized as it should be by parsers.
// This assumption eliminates 4 function calls.
# define twobit_comp(ch) ((ch) == 'A' ? 1LL : \
(ch) == 'T' ? 0LL : \
(ch) == 'C' ? 3LL : 2LL)
#endif
// choose wisely between forward and rev comp.
#ifndef NO_UNIQUE_RC
#define uniqify_rc(f, r) ((f) < (r) ? (f) : (r))
#else
#define uniqify_rc(f,r)(f)
#endif
namespace khmer
{
// two-way hash functions.
HashIntoType _hash(const char * kmer, const WordLength k);
HashIntoType _hash(const char * kmer, const WordLength k,
HashIntoType& h, HashIntoType& r);
HashIntoType _hash(const std::string kmer, const WordLength k);
HashIntoType _hash(const std::string kmer, const WordLength k,
HashIntoType& h, HashIntoType& r);
HashIntoType _hash_forward(const char * kmer, WordLength k);
std::string _revhash(HashIntoType hash, WordLength k);
std::string _revcomp(const std::string& kmer);
// two-way hash functions, MurmurHash3.
HashIntoType _hash_murmur(const std::string& kmer);
HashIntoType _hash_murmur(const std::string& kmer,
HashIntoType& h, HashIntoType& r);
HashIntoType _hash_murmur_forward(const std::string& kmer);
/**
* \class Kmer
*
* \brief Hold the hash values corresponding to a single k-mer.
*
* This class stores the forward, reverse complement, and
* uniqified hash values for a given k-mer. It also defines
* some basic operators and a utility function for getting
* the string representation of the sequence. This is meant
* to replace the original inelegant macros used for hashing.
*
* \author Camille Scott
*
* Contact: camille.scott.w@gmail.com
*
*/
class Kmer
{
public:
/// The forward hash
HashIntoType kmer_f;
/// The reverse (complement) hash
HashIntoType kmer_r;
/// The uniqified hash
HashIntoType kmer_u;
/** @param[in] f forward hash.
* @param[in] r reverse (complement) hash.
* @param[in] u uniqified hash.
*/
Kmer(HashIntoType f, HashIntoType r, HashIntoType u)
{
kmer_f = f;
kmer_r = r;
kmer_u = u;
}
/** @param[in] s DNA k-mer
@param[in] ksize k-mer size
*/
Kmer(const std::string s, WordLength ksize)
{
kmer_u = _hash(s.c_str(), ksize, kmer_f, kmer_r);
}
/// @warning The default constructor builds an invalid k-mer.
Kmer()
{
kmer_f = kmer_r = kmer_u = 0;
}
void set_from_unique_hash(HashIntoType h, WordLength ksize)
{
std::string s = _revhash(h, ksize);
kmer_u = _hash(s.c_str(), ksize, kmer_f, kmer_r);
}
/// Allows complete backwards compatibility
operator HashIntoType() const
{
return kmer_u;
}
bool operator< (const Kmer &other) const
{
return kmer_u < other.kmer_u;
}
std::string get_string_rep(WordLength K) const
{
return _revhash(kmer_u, K);
}
char get_last_base() const
{
return revtwobit_repr(kmer_f & 3);
}
std::string repr(WordLength K) const
{
std::string s = "<Us=" + _revhash(kmer_u, K) + ", Fs=" +
_revhash(kmer_f, K) + ", Rs=" + _revhash(kmer_r, K) + ">";
//", U=" + std::to_string(kmer_u) + ", F=" + std::to_string(kmer_f) +
//", R=" + std::to_string(kmer_r) + ">";
return s;
}
bool is_forward() const
{
return kmer_f == kmer_u;
}
};
/**
* \class KmerFactory
*
* \brief Build complete Kmer objects.
*
* The KmerFactory is a simple construct to emit complete
* Kmer objects. The design decision leading to this class
* stems from the issue of overloading the Kmer constructor
* while also giving it a K size: you get ambiguous signatures
* between the (kmer_u, K) and (kmer_f, kmer_r) cases. This
* implementation also allows a logical architecture wherein
* KmerIterator and Hashtable inherit directly from KmerFactory,
* extending the latter's purpose of "create k-mers" to
* "emit k-mers from a sequence" and "create and store k-mers".
*
* \author Camille Scott
*
* Contact: camille.scott.w@gmail.com
*
*/
class KmerFactory
{
protected:
WordLength _ksize;
public:
explicit KmerFactory(WordLength K): _ksize(K) {}
/** @param[in] kmer_u Uniqified hash value.
* @return A complete Kmer object.
*/
Kmer build_kmer(HashIntoType kmer_u)
const
{
HashIntoType kmer_f, kmer_r;
std:: string kmer_s = _revhash(kmer_u, _ksize);
_hash(kmer_s.c_str(), _ksize, kmer_f, kmer_r);
return Kmer(kmer_f, kmer_r, kmer_u);
}
/** Call the uniqify function and build a complete Kmer.
*
* @param[in] kmer_f Forward hash value.
* @param[in] kmer_r Reverse complement hash value.
* @return A complete Kmer object.
*/
Kmer build_kmer(HashIntoType kmer_f, HashIntoType kmer_r)
const
{
HashIntoType kmer_u = uniqify_rc(kmer_f, kmer_r);
return Kmer(kmer_f, kmer_r, kmer_u);
}
/** Hash the given sequence and call the uniqify function
* on its results to build a complete Kmer.
*
* @param[in] kmer_s String representation of a k-mer.
* @return A complete Kmer object hashed from the given string.
*/
Kmer build_kmer(std::string kmer_s) const
{
HashIntoType kmer_f, kmer_r, kmer_u;
kmer_u = _hash(kmer_s.c_str(), _ksize, kmer_f, kmer_r);
return Kmer(kmer_f, kmer_r, kmer_u);
}
/** Hash the given sequence and call the uniqify function
* on its results to build a complete Kmer.
*
* @param[in] kmer_c The character array representation of a k-mer.
* @return A complete Kmer object hashed from the given char array.
*/
Kmer build_kmer(const char * kmer_c) const
{
HashIntoType kmer_f, kmer_r, kmer_u;
kmer_u = _hash(kmer_c, _ksize, kmer_f, kmer_r);
return Kmer(kmer_f, kmer_r, kmer_u);
}
};
/**
* \class KmerIterator
*
* \brief Emit Kmer objects generated from the given sequence.
*
* Given a string \f$S\f$ and a length \f$K > 0\f$, we define
* the k-mers of \f$S\f$ as the set \f$S_{i..i+K} \forall i \in \{0..|S|-K+1\}\f$,
* where \f$|S|\f$ is the length and \f$S_{j..k}\f$ is the half-open
* substring starting at \f$j\f$ and terminating at \f$k\f$.
*
* KmerIterator mimics a python-style generator function which
* emits the k-mers of the given sequence, in order, as Kmer objects.
*
* @warning This is not actually a valid C++ iterator, though it is close.
*
* \author Camille Scott
*
* Contact: camille.scott.w@gmail.com
*
*/
class KmerIterator: public KmerFactory
{
protected:
const char * _seq;
HashIntoType _kmer_f, _kmer_r;
HashIntoType bitmask;
unsigned int _nbits_sub_1;
unsigned int index;
size_t length;
bool initialized;
public:
KmerIterator(const char * seq, unsigned char k);
/** @param[in] f The forward hash value.
* @param[in] r The reverse complement hash value.
* @return The first Kmer of the sequence.
*/
Kmer first(HashIntoType& f, HashIntoType& r);
/** @param[in] f The current forward hash value
* @param[in] r The current reverse complement hash value
* @return The next Kmer in the sequence
*/
Kmer next(HashIntoType& f, HashIntoType& r);
Kmer first()
{
return first(_kmer_f, _kmer_r);
}
Kmer next()
{
return next(_kmer_f, _kmer_r);
}
/// @return Whether or not the iterator has completed.
bool done() const
{
return index >= length;
}
unsigned int get_start_pos() const
{
return index - _ksize;
}
unsigned int get_end_pos() const
{
return index;
}
}; // class KmerIterator
//
// KmerHashIterator - analogous to KmerIterator classes, but returns only
// only HashIntoType hashes, not full Kmer objects. This supports irreversible
// hashing.
//
class KmerHashIterator {
public:
virtual HashIntoType first() = 0;
virtual HashIntoType next() = 0;
virtual bool done() const = 0;
virtual unsigned int get_start_pos() const = 0;
virtual unsigned int get_end_pos() const = 0;
virtual ~KmerHashIterator() { };
};
// TwoBitKmerHashIterator -- just wrap KmerIterator.
class TwoBitKmerHashIterator : public KmerHashIterator {
protected:
KmerIterator iter;
public:
TwoBitKmerHashIterator(const char * seq, WordLength k) :
iter(seq, k) { } ;
HashIntoType first() { return iter.first(); }
HashIntoType next() { return iter.next(); }
bool done() const { return iter.done(); }
virtual unsigned int get_start_pos() const {
return iter.get_start_pos();
}
virtual unsigned int get_end_pos() const {
return iter.get_end_pos();
}
};
}
#endif // KMER_HASH_HH
<commit_msg>fix dupl only<commit_after>/*
This file is part of khmer, https://github.com/dib-lab/khmer/, and is
Copyright (C) 2010-2015, Michigan State University.
Copyright (C) 2015-2016, The Regents of the University of California.
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 Michigan State University 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
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.
LICENSE (END)
Contact: khmer-project@idyll.org
*/
#ifndef KMER_HASH_HH
#define KMER_HASH_HH
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include "khmer.hh"
// test validity
#ifdef KHMER_EXTRA_SANITY_CHECKS
# define is_valid_dna(ch) ((toupper(ch)) == 'A' || (toupper(ch)) == 'C' || \
(toupper(ch)) == 'G' || (toupper(ch)) == 'T')
#else
// NOTE: Assumes data is already sanitized as it should be by parsers.
// This assumption eliminates 4 function calls.
# define is_valid_dna(ch) ((ch) == 'A' || (ch) == 'C' || \
(ch) == 'G' || (ch) == 'T')
#endif
// bit representation of A/T/C/G.
#ifdef KHMER_EXTRA_SANITY_CHECKS
# define twobit_repr(ch) ((toupper(ch)) == 'A' ? 0LL : \
(toupper(ch)) == 'T' ? 1LL : \
(toupper(ch)) == 'C' ? 2LL : 3LL)
#else
// NOTE: Assumes data is already sanitized as it should be by parsers.
// This assumption eliminates 4 function calls.
# define twobit_repr(ch) ((ch) == 'A' ? 0LL : \
(ch) == 'T' ? 1LL : \
(ch) == 'C' ? 2LL : 3LL)
#endif
#define revtwobit_repr(n) ((n) == 0 ? 'A' : \
(n) == 1 ? 'T' : \
(n) == 2 ? 'C' : 'G')
#ifdef KHMER_EXTRA_SANITY_CHECKS
# define twobit_comp(ch) ((toupper(ch)) == 'A' ? 1LL : \
(toupper(ch)) == 'T' ? 0LL : \
(toupper(ch)) == 'C' ? 3LL : 2LL)
#else
// NOTE: Assumes data is already sanitized as it should be by parsers.
// This assumption eliminates 4 function calls.
# define twobit_comp(ch) ((ch) == 'A' ? 1LL : \
(ch) == 'T' ? 0LL : \
(ch) == 'C' ? 3LL : 2LL)
#endif
// choose wisely between forward and rev comp.
#ifndef NO_UNIQUE_RC
#define uniqify_rc(f, r) ((f) < (r) ? (f) : (r))
#else
#define uniqify_rc(f,r)(f)
#endif
namespace khmer
{
// two-way hash functions.
HashIntoType _hash(const char * kmer, const WordLength k);
HashIntoType _hash(const char * kmer, const WordLength k,
HashIntoType& h, HashIntoType& r);
HashIntoType _hash(const std::string kmer, const WordLength k);
HashIntoType _hash(const std::string kmer, const WordLength k,
HashIntoType& h, HashIntoType& r);
HashIntoType _hash_forward(const char * kmer, WordLength k);
std::string _revhash(HashIntoType hash, WordLength k);
std::string _revcomp(const std::string& kmer);
// two-way hash functions, MurmurHash3.
HashIntoType _hash_murmur(const std::string& kmer);
HashIntoType _hash_murmur(const std::string& kmer,
HashIntoType& h, HashIntoType& r);
HashIntoType _hash_murmur_forward(const std::string& kmer);
/**
* \class Kmer
*
* \brief Hold the hash values corresponding to a single k-mer.
*
* This class stores the forward, reverse complement, and
* uniqified hash values for a given k-mer. It also defines
* some basic operators and a utility function for getting
* the string representation of the sequence. This is meant
* to replace the original inelegant macros used for hashing.
*
* \author Camille Scott
*
* Contact: camille.scott.w@gmail.com
*
*/
class Kmer
{
public:
/// The forward hash
HashIntoType kmer_f;
/// The reverse (complement) hash
HashIntoType kmer_r;
/// The uniqified hash
HashIntoType kmer_u;
/** @param[in] f forward hash.
* @param[in] r reverse (complement) hash.
* @param[in] u uniqified hash.
*/
Kmer(HashIntoType f, HashIntoType r, HashIntoType u)
{
kmer_f = f;
kmer_r = r;
kmer_u = u;
}
/** @param[in] s DNA k-mer
@param[in] ksize k-mer size
*/
Kmer(const std::string s, WordLength ksize)
{
kmer_u = _hash(s.c_str(), ksize, kmer_f, kmer_r);
}
/// @warning The default constructor builds an invalid k-mer.
Kmer()
{
kmer_f = kmer_r = kmer_u = 0;
}
void set_from_unique_hash(HashIntoType h, WordLength ksize)
{
std::string s = _revhash(h, ksize);
kmer_u = _hash(s.c_str(), ksize, kmer_f, kmer_r);
}
/// Allows complete backwards compatibility
operator HashIntoType() const
{
return kmer_u;
}
bool operator< (const Kmer &other) const
{
return kmer_u < other.kmer_u;
}
std::string get_string_rep(WordLength K) const
{
return _revhash(kmer_u, K);
}
char get_last_base() const
{
return revtwobit_repr(kmer_f & 3);
}
std::string repr(WordLength K) const
{
std::string s = "<Us=" + _revhash(kmer_u, K) + ", Fs=" +
_revhash(kmer_f, K) + ", Rs=" + _revhash(kmer_r, K) + ">";
//", U=" + std::to_string(kmer_u) + ", F=" + std::to_string(kmer_f) +
//", R=" + std::to_string(kmer_r) + ">";
return s;
}
bool is_forward() const
{
return kmer_f == kmer_u;
}
};
/**
* \class KmerFactory
*
* \brief Build complete Kmer objects.
*
* The KmerFactory is a simple construct to emit complete
* Kmer objects. The design decision leading to this class
* stems from the issue of overloading the Kmer constructor
* while also giving it a K size: you get ambiguous signatures
* between the (kmer_u, K) and (kmer_f, kmer_r) cases. This
* implementation also allows a logical architecture wherein
* KmerIterator and Hashtable inherit directly from KmerFactory,
* extending the latter's purpose of "create k-mers" to
* "emit k-mers from a sequence" and "create and store k-mers".
*
* \author Camille Scott
*
* Contact: camille.scott.w@gmail.com
*
*/
class KmerFactory
{
protected:
WordLength _ksize;
public:
explicit KmerFactory(WordLength K): _ksize(K) {}
/** @param[in] kmer_u Uniqified hash value.
* @return A complete Kmer object.
*/
Kmer build_kmer(HashIntoType kmer_u)
const
{
HashIntoType kmer_f, kmer_r;
std:: string kmer_s = _revhash(kmer_u, _ksize);
_hash(kmer_s.c_str(), _ksize, kmer_f, kmer_r);
return Kmer(kmer_f, kmer_r, kmer_u);
}
/** Call the uniqify function and build a complete Kmer.
*
* @param[in] kmer_f Forward hash value.
* @param[in] kmer_r Reverse complement hash value.
* @return A complete Kmer object.
*/
Kmer build_kmer(HashIntoType kmer_f, HashIntoType kmer_r)
const
{
HashIntoType kmer_u = uniqify_rc(kmer_f, kmer_r);
return Kmer(kmer_f, kmer_r, kmer_u);
}
/** Hash the given sequence and call the uniqify function
* on its results to build a complete Kmer.
*
* @param[in] kmer_s String representation of a k-mer.
* @return A complete Kmer object hashed from the given string.
*/
Kmer build_kmer(std::string kmer_s) const
{
HashIntoType kmer_f, kmer_r, kmer_u;
kmer_u = _hash(kmer_s.c_str(), _ksize, kmer_f, kmer_r);
return Kmer(kmer_f, kmer_r, kmer_u);
}
/** Hash the given sequence and call the uniqify function
* on its results to build a complete Kmer.
*
* @param[in] kmer_c The character array representation of a k-mer.
* @return A complete Kmer object hashed from the given char array.
*/
Kmer build_kmer(const char * kmer_c) const
{
HashIntoType kmer_f, kmer_r, kmer_u;
kmer_u = _hash(kmer_c, _ksize, kmer_f, kmer_r);
return Kmer(kmer_f, kmer_r, kmer_u);
}
};
/**
* \class KmerIterator
*
* \brief Emit Kmer objects generated from the given sequence.
*
* Given a string \f$S\f$ and a length \f$K > 0\f$, we define
* the k-mers of \f$S\f$ as the set \f$S_{i..i+K} \forall i \in \{0..|S|-K+1\}\f$,
* where \f$|S|\f$ is the length and \f$S_{j..k}\f$ is the half-open
* substring starting at \f$j\f$ and terminating at \f$k\f$.
*
* KmerIterator mimics a python-style generator function which
* emits the k-mers of the given sequence, in order, as Kmer objects.
*
* @warning This is not actually a valid C++ iterator, though it is close.
*
* \author Camille Scott
*
* Contact: camille.scott.w@gmail.com
*
*/
class KmerIterator: public KmerFactory
{
protected:
const char * _seq;
HashIntoType _kmer_f, _kmer_r;
HashIntoType bitmask;
unsigned int _nbits_sub_1;
unsigned int index;
size_t length;
bool initialized;
public:
KmerIterator(const char * seq, unsigned char k);
/** @param[in] f The forward hash value.
* @param[in] r The reverse complement hash value.
* @return The first Kmer of the sequence.
*/
Kmer first(HashIntoType& f, HashIntoType& r);
/** @param[in] f The current forward hash value
* @param[in] r The current reverse complement hash value
* @return The next Kmer in the sequence
*/
Kmer next(HashIntoType& f, HashIntoType& r);
Kmer first()
{
return first(_kmer_f, _kmer_r);
}
Kmer next()
{
return next(_kmer_f, _kmer_r);
}
/// @return Whether or not the iterator has completed.
bool done() const
{
return index >= length;
}
unsigned int get_start_pos() const
{
return index - _ksize;
}
unsigned int get_end_pos() const
{
return index;
}
}; // class KmerIterator
//
// KmerHashIterator - analogous to KmerIterator classes, but returns only
// HashIntoType hashes, not full Kmer objects. This supports irreversible
// hashing.
//
class KmerHashIterator {
public:
virtual HashIntoType first() = 0;
virtual HashIntoType next() = 0;
virtual bool done() const = 0;
virtual unsigned int get_start_pos() const = 0;
virtual unsigned int get_end_pos() const = 0;
virtual ~KmerHashIterator() { };
};
// TwoBitKmerHashIterator -- just wrap KmerIterator.
class TwoBitKmerHashIterator : public KmerHashIterator {
protected:
KmerIterator iter;
public:
TwoBitKmerHashIterator(const char * seq, WordLength k) :
iter(seq, k) { } ;
HashIntoType first() { return iter.first(); }
HashIntoType next() { return iter.next(); }
bool done() const { return iter.done(); }
virtual unsigned int get_start_pos() const {
return iter.get_start_pos();
}
virtual unsigned int get_end_pos() const {
return iter.get_end_pos();
}
};
}
#endif // KMER_HASH_HH
<|endoftext|>
|
<commit_before><commit_msg>DDF don't overwrite legacy values with default value if already set<commit_after><|endoftext|>
|
<commit_before>// Copyright 2013, Kay Hayen, mailto:kay.hayen@gmail.com
//
// Part of "Nuitka", an optimizing Python compiler that is compatible and
// integrates with CPython, but also works on its own.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef __NUITKA_HELPER_RAISING_H__
#define __NUITKA_HELPER_RAISING_H__
#if PYTHON_VERSION < 300
#define WRONG_EXCEPTION_TYPE_ERROR_MESSAGE "exceptions must be old-style classes or derived from BaseException, not %s"
#else
#define WRONG_EXCEPTION_TYPE_ERROR_MESSAGE "exceptions must derive from BaseException"
#endif
#if PYTHON_VERSION >= 300
static void CHAIN_EXCEPTION( PyObject *exception_type, PyObject *exception_value )
{
// Implicit chain of exception already existing.
PyThreadState *thread_state = PyThreadState_GET();
// Normalize existing exception first.
PyErr_NormalizeException( &thread_state->exc_type, &thread_state->exc_value, &thread_state->exc_traceback );
PyObject *old_exc_value = thread_state->exc_value;
if ( old_exc_value != NULL && old_exc_value != Py_None && old_exc_value != exception_value )
{
Py_INCREF( old_exc_value );
PyObject *o = old_exc_value, *context;
while (( context = PyException_GetContext(o) ))
{
Py_DECREF( context );
if ( context == exception_value )
{
PyException_SetContext( o, NULL );
break;
}
o = context;
}
PyException_SetContext( exception_value, old_exc_value );
PyException_SetTraceback( old_exc_value, thread_state->exc_traceback );
}
}
#endif
NUITKA_NO_RETURN NUITKA_MAY_BE_UNUSED static void RAISE_EXCEPTION_WITH_TYPE( PyObject *exception_type, PyObject *exception_tb )
{
PyTracebackObject *traceback = (PyTracebackObject *)exception_tb;
assertObject( traceback );
assert( PyTraceBack_Check( traceback ) );
assertObject( exception_type );
if ( PyExceptionClass_Check( exception_type ) )
{
PyObject *value = NULL;
Py_INCREF( exception_type );
Py_XINCREF( traceback );
NORMALIZE_EXCEPTION( &exception_type, &value, &traceback );
#if PYTHON_VERSION >= 270
if (unlikely( !PyExceptionInstance_Check( value ) ))
{
Py_DECREF( exception_type );
Py_DECREF( value );
Py_XDECREF( traceback );
PyErr_Format(
PyExc_TypeError,
"calling %s() should have returned an instance of BaseException, not '%s'",
((PyTypeObject *)exception_type)->tp_name,
Py_TYPE( value )->tp_name
);
throw PythonException();
}
#endif
#if PYTHON_VERSION >= 300
CHAIN_EXCEPTION( exception_type, value );
#endif
throw PythonException(
exception_type,
value,
traceback
);
}
else if ( PyExceptionInstance_Check( exception_type ) )
{
PyObject *value = exception_type;
exception_type = PyExceptionInstance_Class( exception_type );
#if PYTHON_VERSION >= 300
CHAIN_EXCEPTION( exception_type, value );
PyTracebackObject *prev = (PyTracebackObject *)PyException_GetTraceback( value );
if ( prev != NULL )
{
assert( traceback->tb_next == NULL );
traceback->tb_next = prev;
}
PyException_SetTraceback( value, (PyObject *)traceback );
#endif
throw PythonException(
INCREASE_REFCOUNT( exception_type ),
INCREASE_REFCOUNT( value ),
INCREASE_REFCOUNT( traceback )
);
}
else
{
PyErr_Format( PyExc_TypeError, WRONG_EXCEPTION_TYPE_ERROR_MESSAGE, Py_TYPE( exception_type )->tp_name );
PythonException to_throw;
to_throw.setTraceback( INCREASE_REFCOUNT( traceback ) );
throw to_throw;
}
}
#if PYTHON_VERSION >= 300
NUITKA_NO_RETURN NUITKA_MAY_BE_UNUSED static void RAISE_EXCEPTION_WITH_CAUSE( PyObject *exception_type, PyObject *exception_cause, PyObject *exception_tb )
{
PyTracebackObject *traceback = (PyTracebackObject *)exception_tb;
assertObject( exception_type );
assertObject( exception_cause );
#if PYTHON_VERSION >= 330
// None is not a cause.
if ( exception_cause == Py_None )
{
exception_cause = NULL;
}
else
#endif
if ( PyExceptionClass_Check( exception_cause ) )
{
exception_cause = PyObject_CallObject( exception_cause, NULL );
if (unlikely( exception_cause == NULL ))
{
throw PythonException();
}
}
else
{
Py_INCREF( exception_cause );
}
#if PYTHON_VERSION >= 330
if (unlikely( exception_cause != NULL && !PyExceptionInstance_Check( exception_cause ) ))
#else
if (unlikely( !PyExceptionInstance_Check( exception_cause ) ))
#endif
{
Py_XDECREF( exception_cause );
PyErr_Format( PyExc_TypeError, "exception causes must derive from BaseException" );
throw PythonException();
}
if ( PyExceptionClass_Check( exception_type ) )
{
PyObject *value = NULL;
Py_INCREF( exception_type );
Py_INCREF( traceback );
NORMALIZE_EXCEPTION( &exception_type, &value, &traceback );
if (unlikely( !PyExceptionInstance_Check( value ) ))
{
Py_DECREF( exception_type );
Py_XDECREF( value );
Py_DECREF( traceback );
Py_XDECREF( exception_cause );
PyErr_Format(
PyExc_TypeError,
"calling %s() should have returned an instance of BaseException, not '%s'",
((PyTypeObject *)exception_type)->tp_name,
Py_TYPE( value )->tp_name
);
throw PythonException();
}
PythonException to_throw( exception_type, value, traceback );
to_throw.setCause( exception_cause );
throw to_throw;
}
else if ( PyExceptionInstance_Check( exception_type ) )
{
Py_XDECREF( exception_cause );
throw PythonException(
INCREASE_REFCOUNT( PyExceptionInstance_Class( exception_type ) ),
INCREASE_REFCOUNT( exception_type ),
INCREASE_REFCOUNT( traceback )
);
}
else
{
Py_XDECREF( exception_cause );
PyErr_Format( PyExc_TypeError, WRONG_EXCEPTION_TYPE_ERROR_MESSAGE, Py_TYPE( exception_type )->tp_name );
PythonException to_throw;
to_throw.setTraceback( INCREASE_REFCOUNT( traceback ) );
throw to_throw;
}
}
#endif
NUITKA_NO_RETURN NUITKA_MAY_BE_UNUSED static void RAISE_EXCEPTION_WITH_VALUE( PyObject *exception_type, PyObject *value, PyObject *exception_tb )
{
assertObject( exception_type );
PyTracebackObject *traceback = (PyTracebackObject *)exception_tb;
// Non-empty tuple exceptions are the first element.
while (unlikely( PyTuple_Check( exception_type ) && PyTuple_Size( exception_type ) > 0 ))
{
exception_type = PyTuple_GET_ITEM( exception_type, 0 );
}
if ( PyExceptionClass_Check( exception_type ) )
{
Py_INCREF( exception_type );
Py_XINCREF( value );
Py_XINCREF( traceback );
NORMALIZE_EXCEPTION( &exception_type, &value, &traceback );
#if PYTHON_VERSION >= 270
if (unlikely( !PyExceptionInstance_Check( value ) ))
{
PyErr_Format(
PyExc_TypeError,
"calling %s() should have returned an instance of BaseException, not '%s'",
((PyTypeObject *)exception_type)->tp_name,
Py_TYPE( value )->tp_name
);
Py_DECREF( exception_type );
Py_XDECREF( value );
Py_XDECREF( traceback );
throw PythonException();
}
#endif
throw PythonException(
exception_type,
value,
traceback
);
}
else if ( PyExceptionInstance_Check( exception_type ) )
{
if (unlikely( value != NULL && value != Py_None ))
{
PyErr_Format(
PyExc_TypeError,
"instance exception may not have a separate value"
);
throw PythonException();
}
// The type is rather a value, so we are overriding it here.
value = exception_type;
exception_type = PyExceptionInstance_Class( exception_type );
throw PythonException(
INCREASE_REFCOUNT( exception_type ),
INCREASE_REFCOUNT( value ),
INCREASE_REFCOUNT_X( traceback )
);
}
else
{
PyErr_Format( PyExc_TypeError, WRONG_EXCEPTION_TYPE_ERROR_MESSAGE, Py_TYPE( exception_type )->tp_name );
throw PythonException();
}
}
NUITKA_NO_RETURN NUITKA_MAY_BE_UNUSED static void RAISE_EXCEPTION_WITH_VALUE_NO_NORMALIZE( PyObject *exception_type, PyObject *value, PyObject *tb )
{
PyTracebackObject *traceback = (PyTracebackObject *)tb;
assertObject( exception_type );
assert( !PyTuple_Check( exception_type ) );
if ( PyExceptionClass_Check( exception_type ) )
{
throw PythonException(
INCREASE_REFCOUNT( exception_type ),
INCREASE_REFCOUNT( value ),
INCREASE_REFCOUNT_X( traceback )
);
}
else if ( PyExceptionInstance_Check( exception_type ) )
{
assert ( value == NULL || value == Py_None );
// The type is rather a value, so we are overriding it here.
value = exception_type;
exception_type = PyExceptionInstance_Class( exception_type );
throw PythonException(
INCREASE_REFCOUNT( exception_type ),
INCREASE_REFCOUNT( value ),
INCREASE_REFCOUNT_X( traceback )
);
}
else
{
assert( false );
PyErr_Format( PyExc_TypeError, WRONG_EXCEPTION_TYPE_ERROR_MESSAGE, Py_TYPE( exception_type )->tp_name );
throw PythonException();
}
}
NUITKA_NO_RETURN NUITKA_MAY_BE_UNUSED static inline void RAISE_EXCEPTION_WITH_TRACEBACK( PyObject *exception_type, PyObject *value, PyObject *traceback )
{
if ( traceback == Py_None )
{
traceback = NULL;
}
// Check traceback
if( traceback != NULL && !PyTraceBack_Check( traceback ) )
{
PyErr_Format( PyExc_TypeError, "raise: arg 3 must be a traceback or None" );
throw PythonException();
}
RAISE_EXCEPTION_WITH_VALUE( exception_type, value, traceback );
}
NUITKA_NO_RETURN NUITKA_MAY_BE_UNUSED static void RERAISE_EXCEPTION( void )
{
PyThreadState *tstate = PyThreadState_GET();
assert( tstate );
PyObject *type = tstate->exc_type != NULL ? tstate->exc_type : Py_None;
PyObject *value = tstate->exc_value;
PyObject *tb = tstate->exc_traceback;
assertObject( type );
#if PYTHON_VERSION >= 300
if ( type == Py_None )
{
PyErr_Format( PyExc_RuntimeError, "No active exception to reraise" );
throw PythonException();
}
#endif
RAISE_EXCEPTION_WITH_TRACEBACK( type, value, tb );
}
// Throw an exception from within an expression, this is without normalization. Note:
// There is also a form for use as a statement, and also doesn't do it, seeing this used
// normally means, the implicit exception was not propagated.
NUITKA_NO_RETURN NUITKA_MAY_BE_UNUSED static PyObject *THROW_EXCEPTION( PyObject *exception_type, PyObject *exception_value, PyObject *traceback )
{
RAISE_EXCEPTION_WITH_VALUE_NO_NORMALIZE(
exception_type,
exception_value,
traceback
);
}
NUITKA_MAY_BE_UNUSED static void THROW_IF_ERROR_OCCURED( void )
{
if ( ERROR_OCCURED() )
{
throw PythonException();
}
}
NUITKA_MAY_BE_UNUSED static void THROW_IF_ERROR_OCCURED_NOT( PyObject *ignored )
{
if ( ERROR_OCCURED() )
{
if ( PyErr_ExceptionMatches( ignored ))
{
PyErr_Clear();
}
else
{
throw PythonException();
}
}
}
#endif
<commit_msg>Python3: Fix, need to chain exceptions raised with causes too.<commit_after>// Copyright 2013, Kay Hayen, mailto:kay.hayen@gmail.com
//
// Part of "Nuitka", an optimizing Python compiler that is compatible and
// integrates with CPython, but also works on its own.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef __NUITKA_HELPER_RAISING_H__
#define __NUITKA_HELPER_RAISING_H__
#if PYTHON_VERSION < 300
#define WRONG_EXCEPTION_TYPE_ERROR_MESSAGE "exceptions must be old-style classes or derived from BaseException, not %s"
#else
#define WRONG_EXCEPTION_TYPE_ERROR_MESSAGE "exceptions must derive from BaseException"
#endif
#if PYTHON_VERSION >= 300
static void CHAIN_EXCEPTION( PyObject *exception_type, PyObject *exception_value )
{
// Implicit chain of exception already existing.
PyThreadState *thread_state = PyThreadState_GET();
// Normalize existing exception first.
PyErr_NormalizeException( &thread_state->exc_type, &thread_state->exc_value, &thread_state->exc_traceback );
PyObject *old_exc_value = thread_state->exc_value;
if ( old_exc_value != NULL && old_exc_value != Py_None && old_exc_value != exception_value )
{
Py_INCREF( old_exc_value );
PyObject *o = old_exc_value, *context;
while (( context = PyException_GetContext(o) ))
{
Py_DECREF( context );
if ( context == exception_value )
{
PyException_SetContext( o, NULL );
break;
}
o = context;
}
PyException_SetContext( exception_value, old_exc_value );
PyException_SetTraceback( old_exc_value, thread_state->exc_traceback );
}
}
#endif
NUITKA_NO_RETURN NUITKA_MAY_BE_UNUSED static void RAISE_EXCEPTION_WITH_TYPE( PyObject *exception_type, PyObject *exception_tb )
{
PyTracebackObject *traceback = (PyTracebackObject *)exception_tb;
assertObject( traceback );
assert( PyTraceBack_Check( traceback ) );
assertObject( exception_type );
if ( PyExceptionClass_Check( exception_type ) )
{
PyObject *value = NULL;
Py_INCREF( exception_type );
Py_XINCREF( traceback );
NORMALIZE_EXCEPTION( &exception_type, &value, &traceback );
#if PYTHON_VERSION >= 270
if (unlikely( !PyExceptionInstance_Check( value ) ))
{
Py_DECREF( exception_type );
Py_DECREF( value );
Py_XDECREF( traceback );
PyErr_Format(
PyExc_TypeError,
"calling %s() should have returned an instance of BaseException, not '%s'",
((PyTypeObject *)exception_type)->tp_name,
Py_TYPE( value )->tp_name
);
throw PythonException();
}
#endif
#if PYTHON_VERSION >= 300
CHAIN_EXCEPTION( exception_type, value );
#endif
throw PythonException(
exception_type,
value,
traceback
);
}
else if ( PyExceptionInstance_Check( exception_type ) )
{
PyObject *value = exception_type;
exception_type = PyExceptionInstance_Class( exception_type );
#if PYTHON_VERSION >= 300
CHAIN_EXCEPTION( exception_type, value );
PyTracebackObject *prev = (PyTracebackObject *)PyException_GetTraceback( value );
if ( prev != NULL )
{
assert( traceback->tb_next == NULL );
traceback->tb_next = prev;
}
PyException_SetTraceback( value, (PyObject *)traceback );
#endif
throw PythonException(
INCREASE_REFCOUNT( exception_type ),
INCREASE_REFCOUNT( value ),
INCREASE_REFCOUNT( traceback )
);
}
else
{
PyErr_Format( PyExc_TypeError, WRONG_EXCEPTION_TYPE_ERROR_MESSAGE, Py_TYPE( exception_type )->tp_name );
PythonException to_throw;
to_throw.setTraceback( INCREASE_REFCOUNT( traceback ) );
throw to_throw;
}
}
#if PYTHON_VERSION >= 300
NUITKA_NO_RETURN NUITKA_MAY_BE_UNUSED static void RAISE_EXCEPTION_WITH_CAUSE( PyObject *exception_type, PyObject *exception_cause, PyObject *exception_tb )
{
PyTracebackObject *traceback = (PyTracebackObject *)exception_tb;
assertObject( exception_type );
assertObject( exception_cause );
#if PYTHON_VERSION >= 330
// None is not a cause.
if ( exception_cause == Py_None )
{
exception_cause = NULL;
}
else
#endif
if ( PyExceptionClass_Check( exception_cause ) )
{
exception_cause = PyObject_CallObject( exception_cause, NULL );
if (unlikely( exception_cause == NULL ))
{
throw PythonException();
}
}
else
{
Py_INCREF( exception_cause );
}
#if PYTHON_VERSION >= 330
if (unlikely( exception_cause != NULL && !PyExceptionInstance_Check( exception_cause ) ))
#else
if (unlikely( !PyExceptionInstance_Check( exception_cause ) ))
#endif
{
Py_XDECREF( exception_cause );
PyErr_Format( PyExc_TypeError, "exception causes must derive from BaseException" );
throw PythonException();
}
if ( PyExceptionClass_Check( exception_type ) )
{
PyObject *value = NULL;
Py_INCREF( exception_type );
Py_INCREF( traceback );
NORMALIZE_EXCEPTION( &exception_type, &value, &traceback );
if (unlikely( !PyExceptionInstance_Check( value ) ))
{
Py_DECREF( exception_type );
Py_XDECREF( value );
Py_DECREF( traceback );
Py_XDECREF( exception_cause );
PyErr_Format(
PyExc_TypeError,
"calling %s() should have returned an instance of BaseException, not '%s'",
((PyTypeObject *)exception_type)->tp_name,
Py_TYPE( value )->tp_name
);
throw PythonException();
}
#if PYTHON_VERSION >= 300
CHAIN_EXCEPTION( exception_type, value );
#endif
PythonException to_throw( exception_type, value, traceback );
to_throw.setCause( exception_cause );
throw to_throw;
}
else if ( PyExceptionInstance_Check( exception_type ) )
{
PyObject *value = exception_type;
exception_type = PyExceptionInstance_Class( value );
#if PYTHON_VERSION >= 300
CHAIN_EXCEPTION( exception_type, value );
#endif
PythonException to_throw(
INCREASE_REFCOUNT( exception_type ),
INCREASE_REFCOUNT( value ),
INCREASE_REFCOUNT( traceback )
);
to_throw.setCause( exception_cause );
throw to_throw;
}
else
{
Py_XDECREF( exception_cause );
PyErr_Format( PyExc_TypeError, WRONG_EXCEPTION_TYPE_ERROR_MESSAGE, Py_TYPE( exception_type )->tp_name );
PythonException to_throw;
to_throw.setTraceback( INCREASE_REFCOUNT( traceback ) );
throw to_throw;
}
}
#endif
NUITKA_NO_RETURN NUITKA_MAY_BE_UNUSED static void RAISE_EXCEPTION_WITH_VALUE( PyObject *exception_type, PyObject *value, PyObject *exception_tb )
{
assertObject( exception_type );
PyTracebackObject *traceback = (PyTracebackObject *)exception_tb;
// Non-empty tuple exceptions are the first element.
while (unlikely( PyTuple_Check( exception_type ) && PyTuple_Size( exception_type ) > 0 ))
{
exception_type = PyTuple_GET_ITEM( exception_type, 0 );
}
if ( PyExceptionClass_Check( exception_type ) )
{
Py_INCREF( exception_type );
Py_XINCREF( value );
Py_XINCREF( traceback );
NORMALIZE_EXCEPTION( &exception_type, &value, &traceback );
#if PYTHON_VERSION >= 270
if (unlikely( !PyExceptionInstance_Check( value ) ))
{
PyErr_Format(
PyExc_TypeError,
"calling %s() should have returned an instance of BaseException, not '%s'",
((PyTypeObject *)exception_type)->tp_name,
Py_TYPE( value )->tp_name
);
Py_DECREF( exception_type );
Py_XDECREF( value );
Py_XDECREF( traceback );
throw PythonException();
}
#endif
throw PythonException(
exception_type,
value,
traceback
);
}
else if ( PyExceptionInstance_Check( exception_type ) )
{
if (unlikely( value != NULL && value != Py_None ))
{
PyErr_Format(
PyExc_TypeError,
"instance exception may not have a separate value"
);
throw PythonException();
}
// The type is rather a value, so we are overriding it here.
value = exception_type;
exception_type = PyExceptionInstance_Class( exception_type );
throw PythonException(
INCREASE_REFCOUNT( exception_type ),
INCREASE_REFCOUNT( value ),
INCREASE_REFCOUNT_X( traceback )
);
}
else
{
PyErr_Format( PyExc_TypeError, WRONG_EXCEPTION_TYPE_ERROR_MESSAGE, Py_TYPE( exception_type )->tp_name );
throw PythonException();
}
}
NUITKA_NO_RETURN NUITKA_MAY_BE_UNUSED static void RAISE_EXCEPTION_WITH_VALUE_NO_NORMALIZE( PyObject *exception_type, PyObject *value, PyObject *tb )
{
PyTracebackObject *traceback = (PyTracebackObject *)tb;
assertObject( exception_type );
assert( !PyTuple_Check( exception_type ) );
if ( PyExceptionClass_Check( exception_type ) )
{
throw PythonException(
INCREASE_REFCOUNT( exception_type ),
INCREASE_REFCOUNT( value ),
INCREASE_REFCOUNT_X( traceback )
);
}
else if ( PyExceptionInstance_Check( exception_type ) )
{
assert ( value == NULL || value == Py_None );
// The type is rather a value, so we are overriding it here.
value = exception_type;
exception_type = PyExceptionInstance_Class( exception_type );
throw PythonException(
INCREASE_REFCOUNT( exception_type ),
INCREASE_REFCOUNT( value ),
INCREASE_REFCOUNT_X( traceback )
);
}
else
{
assert( false );
PyErr_Format( PyExc_TypeError, WRONG_EXCEPTION_TYPE_ERROR_MESSAGE, Py_TYPE( exception_type )->tp_name );
throw PythonException();
}
}
NUITKA_NO_RETURN NUITKA_MAY_BE_UNUSED static inline void RAISE_EXCEPTION_WITH_TRACEBACK( PyObject *exception_type, PyObject *value, PyObject *traceback )
{
if ( traceback == Py_None )
{
traceback = NULL;
}
// Check traceback
if( traceback != NULL && !PyTraceBack_Check( traceback ) )
{
PyErr_Format( PyExc_TypeError, "raise: arg 3 must be a traceback or None" );
throw PythonException();
}
RAISE_EXCEPTION_WITH_VALUE( exception_type, value, traceback );
}
NUITKA_NO_RETURN NUITKA_MAY_BE_UNUSED static void RERAISE_EXCEPTION( void )
{
PyThreadState *tstate = PyThreadState_GET();
assert( tstate );
PyObject *type = tstate->exc_type != NULL ? tstate->exc_type : Py_None;
PyObject *value = tstate->exc_value;
PyObject *tb = tstate->exc_traceback;
assertObject( type );
#if PYTHON_VERSION >= 300
if ( type == Py_None )
{
PyErr_Format( PyExc_RuntimeError, "No active exception to reraise" );
throw PythonException();
}
#endif
RAISE_EXCEPTION_WITH_TRACEBACK( type, value, tb );
}
// Throw an exception from within an expression, this is without normalization. Note:
// There is also a form for use as a statement, and also doesn't do it, seeing this used
// normally means, the implicit exception was not propagated.
NUITKA_NO_RETURN NUITKA_MAY_BE_UNUSED static PyObject *THROW_EXCEPTION( PyObject *exception_type, PyObject *exception_value, PyObject *traceback )
{
RAISE_EXCEPTION_WITH_VALUE_NO_NORMALIZE(
exception_type,
exception_value,
traceback
);
}
NUITKA_MAY_BE_UNUSED static void THROW_IF_ERROR_OCCURED( void )
{
if ( ERROR_OCCURED() )
{
throw PythonException();
}
}
NUITKA_MAY_BE_UNUSED static void THROW_IF_ERROR_OCCURED_NOT( PyObject *ignored )
{
if ( ERROR_OCCURED() )
{
if ( PyErr_ExceptionMatches( ignored ))
{
PyErr_Clear();
}
else
{
throw PythonException();
}
}
}
#endif
<|endoftext|>
|
<commit_before>#ifndef K3_RUNTIME_BASESTRING_H
#define K3_RUNTIME_BASESTRING_H
#include <cstring>
#include <memory>
#include <vector>
#include "yaml-cpp/yaml.h"
#include "rapidjson/document.h"
#include "boost/serialization/array.hpp"
#include "boost/functional/hash.hpp"
#include "Common.hpp"
#include "dataspace/Dataspace.hpp"
char* dupstr(const char*) throw ();
namespace K3 {
class base_string {
public:
// Constructors/Destructors/Assignment.
base_string(): buffer(nullptr) {}
base_string(const base_string& other): buffer(dupstr(other.buffer)) {}
base_string(base_string&& other): base_string() {
swap(*this, other);
}
base_string(const char* b): buffer(dupstr(b)) {}
base_string(const std::string& s) : buffer(dupstr(s.c_str())) {}
base_string(const char* from, std::size_t count): base_string() {
if (from && count) {
buffer = new char[count + 1];
strncpy(buffer, from, count);
buffer[count] = 0;
}
}
~base_string() {
if (buffer) {
delete [] buffer;
}
buffer = 0;
}
base_string& operator += (const base_string& other) {
auto new_string = std::string(buffer) + std::string(other.buffer);
buffer = dupstr(new_string.c_str());
return *this;
}
base_string& operator += (const char* other) {
return *this += base_string(other);
}
base_string& operator =(const base_string& other) {
base_string temp(other);
swap(*this, temp);
return *this;
}
base_string& operator =(base_string&& other) {
swap(*this, other);
return *this;
}
friend void swap(base_string& first, base_string& second) {
using std::swap;
swap(first.buffer, second.buffer);
}
// Conversions
operator std::string() const {
return std::string(buffer ? buffer : "");
}
// Accessors
std::size_t length() const {
if (buffer) {
return strlen(buffer);
}
return 0;
}
const char* c_str() const {
return buffer;
}
// Comparisons
bool operator ==(const base_string& other) const {
return strcmp(buffer ? buffer : "", other.buffer ? other.buffer : "") == 0;
}
bool operator !=(const base_string& other) const {
return strcmp(buffer ? buffer : "", other.buffer ? other.buffer : "") != 0;
}
bool operator <=(const base_string& other) const {
return strcmp(buffer ? buffer : "", other.buffer ? other.buffer : "") <= 0;
}
bool operator <(const base_string& other) const {
return strcmp(buffer ? buffer : "", other.buffer ? other.buffer : "") < 0;
}
bool operator >=(const base_string& other) const {
return strcmp(buffer ? buffer : "", other.buffer ? other.buffer : "") >= 0;
}
bool operator >(const base_string& other) const {
return strcmp(buffer ? buffer : "", other.buffer ? other.buffer : "") > 0;
}
// Operations
base_string substr(std::size_t from, std::size_t to) const {
if (!buffer) {
return base_string();
}
auto n = length();
if (from > n) {
from = n;
}
if (to > n) {
to = n;
}
return base_string(buffer + from, to - from);
}
// Modifies this string.
Seq<R_elem<string_impl>> splitString(const string_impl& splitter) {
Seq<R_elem<string_impl>> results;
if (!buffer) {
return results;
}
R_elem<string_impl> rec;
char * pch;
pch = strtok (buffer, splitter.c_str());
while (pch != NULL)
{
rec.elem = string_impl(pch);
results.insert(rec);
pch = strtok (NULL, splitter.c_str());
}
return results;
}
// Stream Operators
friend std::ostream& operator <<(std::ostream& out, const K3::base_string& s) {
if (s.buffer) {
return out << s.c_str();
}
return out;
}
char* begin() const {
return buffer;
}
char* end() const {
return buffer + length();
}
template <class archive>
void serialize(archive& a, const unsigned int) {
std::size_t len;
if (archive::is_saving::value) {
len = length();
}
a & len;
if (archive::is_loading::value) {
// Possibly extraneous:
// Buffer might always be null when loading
// since this base_str was just constructed
if(buffer) {
delete [] buffer;
buffer = 0;
}
if (len) {
buffer = new char[len + 1];
buffer[len] = 0;
} else {
buffer = 0;
}
}
if (buffer) {
a & boost::serialization::make_array(buffer, len);
}
}
private:
char* buffer;
};
inline base_string operator + (base_string s, char const* t) {
return s += t;
}
inline base_string operator + (char const* t, base_string s) {
auto new_string = base_string(t);
return new_string += s;
}
} // namespace K3
namespace JSON {
template <> struct convert<K3::base_string> {
template <class Allocator>
static rapidjson::Value encode(const K3::base_string& from, Allocator& al) {
Value v;
if (from.c_str()) {
v.SetString(from.c_str(), al);
}
else {
v.SetString("", al);
}
return v;
}
};
}
namespace YAML {
template <>
struct convert<K3::base_string> {
static Node encode(const K3::base_string& s) {
Node node;
node = std::string(s.c_str());
return node;
}
static bool decode(const Node& node, K3::base_string& s) {
try {
auto t = node.as<std::string>();
s = K3::base_string(t);
return true;
} catch (YAML::TypedBadConversion<std::string> e) {
return false;
}
}
};
}
#endif
<commit_msg>Make +operator on base_strings slightly more efficient.<commit_after>#ifndef K3_RUNTIME_BASESTRING_H
#define K3_RUNTIME_BASESTRING_H
#include <cstring>
#include <memory>
#include <vector>
#include "yaml-cpp/yaml.h"
#include "rapidjson/document.h"
#include "boost/serialization/array.hpp"
#include "boost/functional/hash.hpp"
#include "Common.hpp"
#include "dataspace/Dataspace.hpp"
char* dupstr(const char*) throw ();
namespace K3 {
class base_string {
public:
// Constructors/Destructors/Assignment.
base_string(): buffer(nullptr) {}
base_string(const base_string& other): buffer(dupstr(other.buffer)) {}
base_string(base_string&& other): base_string() {
swap(*this, other);
}
base_string(const char* b): buffer(dupstr(b)) {}
base_string(const std::string& s) : buffer(dupstr(s.c_str())) {}
base_string(const char* from, std::size_t count): base_string() {
if (from && count) {
buffer = new char[count + 1];
strncpy(buffer, from, count);
buffer[count] = 0;
}
}
~base_string() {
if (buffer) {
delete [] buffer;
}
buffer = 0;
}
base_string& operator += (const base_string& other) {
auto new_string = std::string(buffer) + std::string(other.buffer);
buffer = dupstr(new_string.c_str());
return *this;
}
base_string& operator += (const char* other) {
return *this += base_string(other);
}
base_string& operator =(const base_string& other) {
base_string temp(other);
swap(*this, temp);
return *this;
}
base_string& operator =(base_string&& other) {
swap(*this, other);
return *this;
}
friend void swap(base_string& first, base_string& second) {
using std::swap;
swap(first.buffer, second.buffer);
}
// Conversions
operator std::string() const {
return std::string(buffer ? buffer : "");
}
// Accessors
std::size_t length() const {
if (buffer) {
return strlen(buffer);
}
return 0;
}
const char* c_str() const {
return buffer;
}
// Comparisons
bool operator ==(const base_string& other) const {
return strcmp(buffer ? buffer : "", other.buffer ? other.buffer : "") == 0;
}
bool operator !=(const base_string& other) const {
return strcmp(buffer ? buffer : "", other.buffer ? other.buffer : "") != 0;
}
bool operator <=(const base_string& other) const {
return strcmp(buffer ? buffer : "", other.buffer ? other.buffer : "") <= 0;
}
bool operator <(const base_string& other) const {
return strcmp(buffer ? buffer : "", other.buffer ? other.buffer : "") < 0;
}
bool operator >=(const base_string& other) const {
return strcmp(buffer ? buffer : "", other.buffer ? other.buffer : "") >= 0;
}
bool operator >(const base_string& other) const {
return strcmp(buffer ? buffer : "", other.buffer ? other.buffer : "") > 0;
}
// Operations
base_string substr(std::size_t from, std::size_t to) const {
if (!buffer) {
return base_string();
}
auto n = length();
if (from > n) {
from = n;
}
if (to > n) {
to = n;
}
return base_string(buffer + from, to - from);
}
// Modifies this string.
Seq<R_elem<string_impl>> splitString(const string_impl& splitter) {
Seq<R_elem<string_impl>> results;
if (!buffer) {
return results;
}
R_elem<string_impl> rec;
char * pch;
pch = strtok (buffer, splitter.c_str());
while (pch != NULL)
{
rec.elem = string_impl(pch);
results.insert(rec);
pch = strtok (NULL, splitter.c_str());
}
return results;
}
// Stream Operators
friend std::ostream& operator <<(std::ostream& out, const K3::base_string& s) {
if (s.buffer) {
return out << s.c_str();
}
return out;
}
char* begin() const {
return buffer;
}
char* end() const {
return buffer + length();
}
template <class archive>
void serialize(archive& a, const unsigned int) {
std::size_t len;
if (archive::is_saving::value) {
len = length();
}
a & len;
if (archive::is_loading::value) {
// Possibly extraneous:
// Buffer might always be null when loading
// since this base_str was just constructed
if(buffer) {
delete [] buffer;
buffer = 0;
}
if (len) {
buffer = new char[len + 1];
buffer[len] = 0;
} else {
buffer = 0;
}
}
if (buffer) {
a & boost::serialization::make_array(buffer, len);
}
}
private:
char* buffer;
};
inline base_string operator + (base_string s, base_string const& t) {
return s += t;
}
inline base_string operator + (base_string s, char const* t) {
return s += t;
}
inline base_string operator + (char const* t, base_string const& s) {
auto new_string = base_string(t);
return new_string += s;
}
} // namespace K3
namespace JSON {
template <> struct convert<K3::base_string> {
template <class Allocator>
static rapidjson::Value encode(const K3::base_string& from, Allocator& al) {
Value v;
if (from.c_str()) {
v.SetString(from.c_str(), al);
}
else {
v.SetString("", al);
}
return v;
}
};
}
namespace YAML {
template <>
struct convert<K3::base_string> {
static Node encode(const K3::base_string& s) {
Node node;
node = std::string(s.c_str());
return node;
}
static bool decode(const Node& node, K3::base_string& s) {
try {
auto t = node.as<std::string>();
s = K3::base_string(t);
return true;
} catch (YAML::TypedBadConversion<std::string> e) {
return false;
}
}
};
}
#endif
<|endoftext|>
|
<commit_before>//===--- RequirementEnvironment.cpp - Requirement Environments ------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements the RequirementEnvironment class, which is used to
// capture how a witness to a protocol requirement maps type parameters.
//
//===----------------------------------------------------------------------===//
#include "swift/AST/RequirementEnvironment.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/Decl.h"
#include "swift/AST/DeclContext.h"
#include "swift/AST/GenericSignature.h"
#include "swift/AST/GenericSignatureBuilder.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/Types.h"
#include "llvm/ADT/Statistic.h"
#define DEBUG_TYPE "Protocol conformance checking"
using namespace swift;
STATISTIC(NumRequirementEnvironments, "# of requirement environments");
RequirementEnvironment::RequirementEnvironment(
DeclContext *conformanceDC,
GenericSignature *reqSig,
ProtocolDecl *proto,
ClassDecl *covariantSelf,
ProtocolConformance *conformance)
: reqSig(reqSig) {
ASTContext &ctx = conformanceDC->getASTContext();
auto concreteType = conformanceDC->getSelfInterfaceType();
auto *conformanceSig = conformanceDC->getGenericSignatureOfContext();
// This is a substitution function from the generic parameters of the
// conforming type to the synthetic environment.
//
// For structs, enums and protocols, this is a 1:1 mapping; for classes,
// we increase the depth of each generic parameter by 1 so that we can
// introduce a class-bound 'Self' parameter.
//
// This is a raw function rather than a substitution map because we need to
// keep generic parameters as generic, even if the conformanceSig (the best
// way to create the substitution map) equates them to concrete types.
auto conformanceToSyntheticTypeFn = [&](SubstitutableType *type) {
auto *genericParam = cast<GenericTypeParamType>(type);
if (covariantSelf) {
return GenericTypeParamType::get(genericParam->getDepth() + 1,
genericParam->getIndex(), ctx);
}
return GenericTypeParamType::get(genericParam->getDepth(),
genericParam->getIndex(), ctx);
};
auto conformanceToSyntheticConformanceFn =
MakeAbstractConformanceForGenericType();
auto substConcreteType = concreteType.subst(
conformanceToSyntheticTypeFn, conformanceToSyntheticConformanceFn);
// Calculate the depth at which the requirement's generic parameters
// appear in the synthetic signature.
unsigned depth = 0;
if (covariantSelf) {
depth++;
}
if (conformanceSig) {
depth += conformanceSig->getGenericParams().back()->getDepth() + 1;
}
// Build a substitution map to replace the protocol's \c Self and the type
// parameters of the requirement into a combined context that provides the
// type parameters of the conformance context and the parameters of the
// requirement.
auto selfType = cast<GenericTypeParamType>(
proto->getSelfInterfaceType()->getCanonicalType());
reqToSyntheticEnvMap = SubstitutionMap::get(reqSig,
[selfType, substConcreteType, depth, covariantSelf, &ctx]
(SubstitutableType *type) -> Type {
// If the conforming type is a class, the protocol 'Self' maps to
// the class-constrained 'Self'. Otherwise, it maps to the concrete
// type.
if (type->isEqual(selfType)) {
if (covariantSelf)
return GenericTypeParamType::get(/*depth=*/0, /*index=*/0, ctx);
return substConcreteType;
}
// Other requirement generic parameters map 1:1 with their depth
// increased appropriately.
auto *genericParam = cast<GenericTypeParamType>(type);
// In a protocol requirement, the only generic parameter at depth 0
// should be 'Self', and all others at depth 1. Anything else is
// invalid code.
if (genericParam->getDepth() != 1)
return Type();
auto substGenericParam =
GenericTypeParamType::get(depth, genericParam->getIndex(), ctx);
return substGenericParam;
},
[selfType, substConcreteType, conformance, conformanceDC, &ctx](
CanType type, Type replacement, ProtocolDecl *proto)
-> Optional<ProtocolConformanceRef> {
// The protocol 'Self' conforms concretely to the conforming type.
if (type->isEqual(selfType)) {
ProtocolConformance *specialized = conformance;
if (conformance && conformance->getGenericSignature()) {
auto concreteSubs =
substConcreteType->getContextSubstitutionMap(
conformanceDC->getParentModule(), conformanceDC);
specialized =
ctx.getSpecializedConformance(substConcreteType, conformance,
concreteSubs);
}
if (specialized)
return ProtocolConformanceRef(specialized);
}
// All other generic parameters come from the requirement itself
// and conform abstractly.
return ProtocolConformanceRef(proto);
});
// If the requirement itself is non-generic, the synthetic signature
// is that of the conformance context.
if (!covariantSelf &&
reqSig->getGenericParams().size() == 1 &&
reqSig->getRequirements().size() == 1) {
syntheticSignature = conformanceDC->getGenericSignatureOfContext();
if (syntheticSignature) {
syntheticSignature = syntheticSignature->getCanonicalSignature();
syntheticEnvironment =
syntheticSignature->createGenericEnvironment();
}
return;
}
// Construct a generic signature builder by collecting the constraints
// from the requirement and the context of the conformance together,
// because both define the capabilities of the requirement.
GenericSignatureBuilder builder(ctx);
auto source =
GenericSignatureBuilder::FloatingRequirementSource::forAbstract();
// If the conforming type is a class, add a class-constrained 'Self'
// parameter.
if (covariantSelf) {
auto paramTy = GenericTypeParamType::get(/*depth=*/0, /*index=*/0, ctx);
builder.addGenericParameter(paramTy);
}
// Now, add all generic parameters from the conforming type.
if (conformanceSig) {
for (auto param : conformanceSig->getGenericParams()) {
auto substParam = Type(param).subst(conformanceToSyntheticTypeFn,
conformanceToSyntheticConformanceFn);
builder.addGenericParameter(substParam->castTo<GenericTypeParamType>());
}
}
// Next, add requirements.
if (covariantSelf) {
auto paramTy = GenericTypeParamType::get(/*depth=*/0, /*index=*/0, ctx);
Requirement reqt(RequirementKind::Superclass, paramTy, substConcreteType);
builder.addRequirement(reqt, source, nullptr);
}
if (conformanceSig) {
for (auto &rawReq : conformanceSig->getRequirements()) {
if (auto req = rawReq.subst(conformanceToSyntheticTypeFn,
conformanceToSyntheticConformanceFn))
builder.addRequirement(*req, source, nullptr);
}
}
// Finally, add the generic parameters from the requirement.
for (auto genericParam : reqSig->getGenericParams().slice(1)) {
// The only depth that makes sense is depth == 1, the generic parameters
// of the requirement itself. Anything else is from invalid code.
if (genericParam->getDepth() != 1) {
return;
}
// Create an equivalent generic parameter at the next depth.
auto substGenericParam =
GenericTypeParamType::get(depth, genericParam->getIndex(), ctx);
builder.addGenericParameter(substGenericParam);
}
++NumRequirementEnvironments;
// Next, add each of the requirements (mapped from the requirement's
// interface types into the abstract type parameters).
for (auto &rawReq : reqSig->getRequirements()) {
if (auto req = rawReq.subst(reqToSyntheticEnvMap))
builder.addRequirement(*req, source, conformanceDC->getParentModule());
}
// Produce the generic signature and environment.
// FIXME: Pass in a source location for the conformance, perhaps? It seems
// like this could fail.
syntheticSignature =
std::move(builder).computeGenericSignature(SourceLoc());
syntheticEnvironment = syntheticSignature->createGenericEnvironment();
}
<commit_msg>Switch requirement environment over to the abstract generic signature request<commit_after>//===--- RequirementEnvironment.cpp - Requirement Environments ------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements the RequirementEnvironment class, which is used to
// capture how a witness to a protocol requirement maps type parameters.
//
//===----------------------------------------------------------------------===//
#include "swift/AST/RequirementEnvironment.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/Decl.h"
#include "swift/AST/DeclContext.h"
#include "swift/AST/GenericSignature.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/AST/Types.h"
#include "llvm/ADT/Statistic.h"
#define DEBUG_TYPE "Protocol conformance checking"
using namespace swift;
STATISTIC(NumRequirementEnvironments, "# of requirement environments");
RequirementEnvironment::RequirementEnvironment(
DeclContext *conformanceDC,
GenericSignature *reqSig,
ProtocolDecl *proto,
ClassDecl *covariantSelf,
ProtocolConformance *conformance)
: reqSig(reqSig) {
ASTContext &ctx = conformanceDC->getASTContext();
auto concreteType = conformanceDC->getSelfInterfaceType();
auto *conformanceSig = conformanceDC->getGenericSignatureOfContext();
// This is a substitution function from the generic parameters of the
// conforming type to the synthetic environment.
//
// For structs, enums and protocols, this is a 1:1 mapping; for classes,
// we increase the depth of each generic parameter by 1 so that we can
// introduce a class-bound 'Self' parameter.
//
// This is a raw function rather than a substitution map because we need to
// keep generic parameters as generic, even if the conformanceSig (the best
// way to create the substitution map) equates them to concrete types.
auto conformanceToSyntheticTypeFn = [&](SubstitutableType *type) {
auto *genericParam = cast<GenericTypeParamType>(type);
if (covariantSelf) {
return GenericTypeParamType::get(genericParam->getDepth() + 1,
genericParam->getIndex(), ctx);
}
return GenericTypeParamType::get(genericParam->getDepth(),
genericParam->getIndex(), ctx);
};
auto conformanceToSyntheticConformanceFn =
MakeAbstractConformanceForGenericType();
auto substConcreteType = concreteType.subst(
conformanceToSyntheticTypeFn, conformanceToSyntheticConformanceFn);
// Calculate the depth at which the requirement's generic parameters
// appear in the synthetic signature.
unsigned depth = 0;
if (covariantSelf) {
depth++;
}
if (conformanceSig) {
depth += conformanceSig->getGenericParams().back()->getDepth() + 1;
}
// Build a substitution map to replace the protocol's \c Self and the type
// parameters of the requirement into a combined context that provides the
// type parameters of the conformance context and the parameters of the
// requirement.
auto selfType = cast<GenericTypeParamType>(
proto->getSelfInterfaceType()->getCanonicalType());
reqToSyntheticEnvMap = SubstitutionMap::get(reqSig,
[selfType, substConcreteType, depth, covariantSelf, &ctx]
(SubstitutableType *type) -> Type {
// If the conforming type is a class, the protocol 'Self' maps to
// the class-constrained 'Self'. Otherwise, it maps to the concrete
// type.
if (type->isEqual(selfType)) {
if (covariantSelf)
return GenericTypeParamType::get(/*depth=*/0, /*index=*/0, ctx);
return substConcreteType;
}
// Other requirement generic parameters map 1:1 with their depth
// increased appropriately.
auto *genericParam = cast<GenericTypeParamType>(type);
// In a protocol requirement, the only generic parameter at depth 0
// should be 'Self', and all others at depth 1. Anything else is
// invalid code.
if (genericParam->getDepth() != 1)
return Type();
auto substGenericParam =
GenericTypeParamType::get(depth, genericParam->getIndex(), ctx);
return substGenericParam;
},
[selfType, substConcreteType, conformance, conformanceDC, &ctx](
CanType type, Type replacement, ProtocolDecl *proto)
-> Optional<ProtocolConformanceRef> {
// The protocol 'Self' conforms concretely to the conforming type.
if (type->isEqual(selfType)) {
ProtocolConformance *specialized = conformance;
if (conformance && conformance->getGenericSignature()) {
auto concreteSubs =
substConcreteType->getContextSubstitutionMap(
conformanceDC->getParentModule(), conformanceDC);
specialized =
ctx.getSpecializedConformance(substConcreteType, conformance,
concreteSubs);
}
if (specialized)
return ProtocolConformanceRef(specialized);
}
// All other generic parameters come from the requirement itself
// and conform abstractly.
return ProtocolConformanceRef(proto);
});
// If the requirement itself is non-generic, the synthetic signature
// is that of the conformance context.
if (!covariantSelf &&
reqSig->getGenericParams().size() == 1 &&
reqSig->getRequirements().size() == 1) {
syntheticSignature = conformanceDC->getGenericSignatureOfContext();
if (syntheticSignature) {
syntheticSignature = syntheticSignature->getCanonicalSignature();
syntheticEnvironment =
syntheticSignature->createGenericEnvironment();
}
return;
}
// Construct a generic signature by collecting the constraints
// from the requirement and the context of the conformance together,
// because both define the capabilities of the requirement.
SmallVector<GenericTypeParamType *, 2> genericParamTypes;
// If the conforming type is a class, add a class-constrained 'Self'
// parameter.
if (covariantSelf) {
auto paramTy = GenericTypeParamType::get(/*depth=*/0, /*index=*/0, ctx);
genericParamTypes.push_back(paramTy);
}
// Now, add all generic parameters from the conforming type.
if (conformanceSig) {
for (auto param : conformanceSig->getGenericParams()) {
auto substParam = Type(param).subst(conformanceToSyntheticTypeFn,
conformanceToSyntheticConformanceFn);
genericParamTypes.push_back(substParam->castTo<GenericTypeParamType>());
}
}
// Next, add requirements.
SmallVector<Requirement, 2> requirements;
if (covariantSelf) {
auto paramTy = GenericTypeParamType::get(/*depth=*/0, /*index=*/0, ctx);
Requirement reqt(RequirementKind::Superclass, paramTy, substConcreteType);
requirements.push_back(reqt);
}
if (conformanceSig) {
for (auto &rawReq : conformanceSig->getRequirements()) {
if (auto req = rawReq.subst(conformanceToSyntheticTypeFn,
conformanceToSyntheticConformanceFn))
requirements.push_back(*req);
}
}
// Finally, add the generic parameters from the requirement.
for (auto genericParam : reqSig->getGenericParams().slice(1)) {
// The only depth that makes sense is depth == 1, the generic parameters
// of the requirement itself. Anything else is from invalid code.
if (genericParam->getDepth() != 1) {
return;
}
// Create an equivalent generic parameter at the next depth.
auto substGenericParam =
GenericTypeParamType::get(depth, genericParam->getIndex(), ctx);
genericParamTypes.push_back(substGenericParam);
}
++NumRequirementEnvironments;
// Next, add each of the requirements (mapped from the requirement's
// interface types into the abstract type parameters).
for (auto &rawReq : reqSig->getRequirements()) {
if (auto req = rawReq.subst(reqToSyntheticEnvMap))
requirements.push_back(*req);
}
// Produce the generic signature and environment.
// FIXME: Pass in a source location for the conformance, perhaps? It seems
// like this could fail.
syntheticSignature = evaluateOrDefault(
ctx.evaluator,
AbstractGenericSignatureRequest{
nullptr, std::move(genericParamTypes), std::move(requirements)},
nullptr);
syntheticEnvironment = syntheticSignature->createGenericEnvironment();
}
<|endoftext|>
|
<commit_before>#include <string>
#include <vector>
#include <boost/tokenizer.hpp>
#include <iostream>
#include <stdlib.h>
#include <cstdio>
#include <sys/wait.h>
using namespace boost;
using namespace std;
class rshell{
protected:
//Data Members
string commands;
string nextConnector;
vector<string> commandlist;
bool prevCommandPass;
bool allCount;
bool forceExit;
public:
//Constructor
rshell(){
commands = "";
nextConnector = ";";
prevCommandPass = true;
forceExit = false;
allCount = true;
}
// Parses the string (strings ending in ';' will keep the ';')
void parseAllCommands(){
char_separator<char> delims(" ");
tokenizer<char_separator<char> > tokenlist(commands, delims);
for (tokenizer<char_separator<char> >::iterator i = tokenlist.begin(); i != tokenlist.end(); i++){
string com(*i);
commandlist.push_back(com);
}
}
// Executes one command and sets prevCommandPass to true or false.
void executeCommand(vector<string> com){
char* argv[1024];
pid_t p = getpid();
pid_t pid = fork();
int status;
for(unsigned int i = 0; i < com.size(); i++){
argv[i] = (char*)com.at(i).c_str();
}
argv[com.size()] = NULL;
if (pid == 0){
if (execvp(argv[0], argv)){
prevCommandPass = true;
}
perror("execvp failed: ");
prevCommandPass = false;
_exit(1);
}
else if (pid > 0){
if ((p = wait(&status)) < 0){
perror("child failed: ");
prevCommandPass = false;
_exit(1);
}
}
else{
perror("fork failed: ");
_exit(1);
}
}
//Splits commandlist into commands with their arguments then calls executeCommand to run them.
void executeAllCommands(){
vector<string> commandsublist;
unsigned int i = 0;
unsigned int j = 0;
while (i < commandlist.size()){
j = 0;
if (checkCommandRun()){
while (!checkBreaker(i)){
//Exit check
if (commandlist.at(i) == "exit"){
cout << "Forced Exit." << endl;
forceExit = true;
_Exit(0);
}
// Comment check
if (commandlist.at(i) == "#" || checkComment(commandlist.at(i))){
executeCommand(commandsublist);
return;
}
//Adds command to the list
commandsublist.push_back(commandlist.at(i));
i++;
j++;
if (i == commandlist.size()){
executeCommand(commandsublist);
return;
}
}
if (checkBreaker(i)){
if (nextConnector == "||"){
if (allCount == true){
prevCommandPass = true;
}
else{
if (prevCommandPass == false){
allCount = false;
}
else{
allCount = true;
}
}
}
else if (nextConnector == "&&"){
if (allCount == true){
if (prevCommandPass == false){
allCount = false;
}
}
else{
allCount = false;
prevCommandPass = false;
}
}
else if (nextConnector == ";"){
allCount = true;
prevCommandPass = true;
}
nextConnector = commandlist.at(i);
}
i++;
}
executeCommand(commandsublist);
commandsublist.clear();
}
}
// Checks if there is a '#' at the front of the string
bool checkComment(string str){
if (str.at(0) == '#'){
return true;
}
return false
}
// Checks if the string is a breaker
bool checkBreaker(int i){
if (i < commandlist.size() + 1){
if (commandlist.at(i) == "|" && commandlist.at(i + 1) == "|"){
return true;
}
else if (commandlist.at(i) == "&" && commandlist.at(i + 1) == "&"){
return true;
}
else if (commandlist.at(i) == ";"){
return true;
else{
return false;
}
}
else
return false;
}
}
// Checks if the next command should be run
bool checkCommandRun(){
if (nextConnector == "||"){
if(allCount == true){
return false;
}
else{
return true;
}
}
else if (nextConnector == "&&"){
if(allCount == true){
return true;
}
else{
return false;
}
}
else if (nextConnector == ";"){
return true;
}
else{
return false;
}
}
//Starts the program.
void run(){
while (!forceExit && commands != "exit"){
cout << "$";
getline(cin, commands);
parseAllCommands();
executeAllCommands();
commandlist.clear();
nextConnector = ";";
prevCommandPass = true;
}
}
};
<commit_msg>tiny tiny change<commit_after>#include <string>
#include <vector>
#include <boost/tokenizer.hpp>
#include <iostream>
#include <stdlib.h>
#include <cstdio>
#include <sys/wait.h>
using namespace boost;
using namespace std;
class rshell{
protected:
//Data Members
string commands;
string nextConnector;
vector<string> commandlist;
bool prevCommandPass;
bool allCount;
bool forceExit;
public:
//Constructor
rshell(){
commands = "";
nextConnector = ";";
prevCommandPass = true;
forceExit = false;
allCount = true;
}
// Parses the string (strings ending in ';' will keep the ';')
void parseAllCommands(){
char_separator<char> delims(" ");
tokenizer<char_separator<char> > tokenlist(commands, delims);
for (tokenizer<char_separator<char> >::iterator i = tokenlist.begin(); i != tokenlist.end(); i++){
string com(*i);
commandlist.push_back(com);
}
}
// Executes one command and sets prevCommandPass to true or false.
void executeCommand(vector<string> com){
char* argv[1024];
pid_t p = getpid();
pid_t pid = fork();
int status;
for(unsigned int i = 0; i < com.size(); i++){
argv[i] = (char*)com.at(i).c_str();
}
argv[com.size()] = NULL;
if (pid == 0){
if (execvp(argv[0], argv)){
prevCommandPass = true;
}
perror("execvp failed: ");
prevCommandPass = false;
_exit(1);
}
else if (pid > 0){
if ((p = wait(&status)) < 0){
perror("child failed: ");
prevCommandPass = false;
_exit(1);
}
}
else{
perror("fork failed: ");
_exit(1);
}
}
//Splits commandlist into commands with their arguments then calls executeCommand to run them.
void executeAllCommands(){
vector<string> commandsublist;
unsigned int i = 0;
unsigned int j = 0;
while (i < commandlist.size()){
j = 0;
if (checkCommandRun()){
while (!checkBreaker(i)){
//Exit check
if (commandlist.at(i) == "exit"){
cout << "Forced Exit." << endl;
forceExit = true;
_Exit(0);
}
// Comment check
if (commandlist.at(i) == "#" || checkComment(commandlist.at(i))){
executeCommand(commandsublist);
return;
}
//Adds command to the list
commandsublist.push_back(commandlist.at(i));
i++;
j++;
if (i == commandlist.size()){
executeCommand(commandsublist);
return;
}
}
if (checkBreaker(i)){
if (nextConnector == "||"){
if (allCount == true){
prevCommandPass = true;
}
else{
if (prevCommandPass == false){
allCount = false;
}
else{
allCount = true;
}
}
}
else if (nextConnector == "&&"){
if (allCount == true){
if (prevCommandPass == false){
allCount = false;
}
}
else{
allCount = false;
prevCommandPass = false;
}
}
else if (nextConnector == ";"){
allCount = true;
prevCommandPass = true;
}
nextConnector = commandlist.at(i);
}
i++;
}
executeCommand(commandsublist);
commandsublist.clear();
}
}
// Checks if there is a '#' at the front of the string
bool checkComment(string str){
if (str.at(0) == '#'){
return true;
}
return false
}
// Checks if the string is a breaker
bool checkBreaker(int i){
if (i < commandlist.size() + 1){
if (commandlist.at(i) == "|" && commandlist.at(i + 1) == "|"){
return true;
}
else if (commandlist.at(i) == "&" && commandlist.at(i + 1) == "&"){
return true;
}
else if (commandlist.at(i) == ";"){
return true;
else{
return false;
}
}
else
return false;
}
}
// Checks if the next command should be run
bool checkCommandRun(){
if (nextConnector == "||"){
if(allCount == true){
return false;
}
else{
return true;
}
}
else if (nextConnector == "&&"){
if(allCount == true){
return true;
}
else{
return false;
}
}
else if (nextConnector == ";"){
return true;
}
else{
return false;
}
}
//Starts the program.
void run(){
while (!forceExit && commands != "exit"){
cout << "$";
getline(cin, commands);
parseAllCommands();
executeAllCommands();
commandlist.clear();
nextConnector = ";";
prevCommandPass = true;
}
}
};
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: TestMultiTexturing.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// .NAME Test of vtkGLSLShaderDeviceAdapter
// .SECTION Description
// this program tests the shader support in vtkRendering.
#include <vtkActor.h>
#include <vtkCellArray.h>
#include <vtkDoubleArray.h>
#include <vtkFloatArray.h>
#include <vtkImageData.h>
#include <vtkPlaneSource.h>
#include <vtkProperty.h>
#include <vtkPointData.h>
#include <vtkPoints.h>
#include <vtkPointSet.h>
#include <vtkPolyData.h>
#include <vtkPainterPolyDataMapper.h>
#include <vtkPNGReader.h>
#include <vtkRenderer.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkStripper.h>
#include <vtkTriangleFilter.h>
#include <vtkTexture.h>
#include <vtkTestUtilities.h>
#include <vtkRegressionTestImage.h>
int TestMultiTexturing(int argc, char *argv[])
{
char* fname1 =
vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/RedCircle.png");
char* fname2 =
vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/BlueCircle.png");
char* fname3 =
vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/GreenCircle.png");
vtkPNGReader * imageReaderRed = vtkPNGReader::New();
vtkPNGReader * imageReaderBlue = vtkPNGReader::New();
vtkPNGReader * imageReaderGreen = vtkPNGReader::New();
imageReaderRed->SetFileName(fname1);
imageReaderBlue->SetFileName(fname2);
imageReaderGreen->SetFileName(fname3);
imageReaderRed->Update();
imageReaderBlue->Update();
imageReaderGreen->Update();
/*vtkPolyData * polyData = vtkPolyData::New();
vtkPoints * points = vtkPoints::New();
points->Allocate(16);
points->InsertNextPoint(-1.0, -1.0, 0.0);
points->InsertNextPoint(1.0, -1.0, 0.0);
points->InsertNextPoint(1.0, 1.0, 0.0);
points->InsertNextPoint(-1.0, 1.0, 0.0);
polyData->SetPoints(points);
vtkCellArray * cells = vtkCellArray::New();
cells->Allocate(cells->EstimateSize(1, 4));
cells->InsertNextCell(4);
cells->InsertCellPoint(0);
cells->InsertCellPoint(1);
cells->InsertCellPoint(2);
cells->InsertCellPoint(3);
polyData->SetPolys(cells);*/
vtkPlaneSource *planeSource = vtkPlaneSource::New();
planeSource->Update();
vtkTriangleFilter *triangleFilter = vtkTriangleFilter::New();
triangleFilter->SetInputConnection(planeSource->GetOutputPort());
planeSource->Delete();
vtkStripper *stripper = vtkStripper::New();
stripper->SetInputConnection(triangleFilter->GetOutputPort());
triangleFilter->Delete();
stripper->Update();
vtkPolyData *polyData = stripper->GetOutput();
polyData->Register(NULL);
stripper->Delete();
polyData->GetPointData()->SetNormals(NULL);
vtkFloatArray *TCoords = vtkFloatArray::New();
TCoords->SetNumberOfComponents(2);
TCoords->Allocate(8);
TCoords->InsertNextTuple2(0.0, 0.0);
TCoords->InsertNextTuple2(0.0, 1.0);
TCoords->InsertNextTuple2(1.0, 0.0);
TCoords->InsertNextTuple2(1.0, 1.0);
TCoords->SetName("MultTCoords");
polyData->GetPointData()->AddArray(TCoords);
TCoords->Delete();
vtkTexture * textureRed = vtkTexture::New();
vtkTexture * textureBlue = vtkTexture::New();
vtkTexture * textureGreen = vtkTexture::New();
textureRed->SetInputConnection(imageReaderRed->GetOutputPort());
textureBlue->SetInputConnection(imageReaderBlue->GetOutputPort());
textureGreen->SetInputConnection(imageReaderGreen->GetOutputPort());
textureRed->SetTextureUnit(vtkTexture::VTK_TEXTURE_UNIT_0);
textureBlue->SetTextureUnit(vtkTexture::VTK_TEXTURE_UNIT_1);
textureGreen->SetTextureUnit(vtkTexture::VTK_TEXTURE_UNIT_2);
// replace the fargments color and then accumulate the textures
// RGBA values.
textureRed->SetBlendingMode(vtkTexture::VTK_TEXTURE_BLENDING_MODE_REPLACE);
textureBlue->SetBlendingMode(vtkTexture::VTK_TEXTURE_BLENDING_MODE_ADD);
textureGreen->SetBlendingMode(vtkTexture::VTK_TEXTURE_BLENDING_MODE_ADD);
vtkPolyDataMapper * mapper = vtkPolyDataMapper::New();
mapper->SetInput(polyData);
mapper->MapDataArrayToMultiTextureAttribute(
vtkTexture::VTK_TEXTURE_UNIT_0, "MultTCoords", vtkDataObject::FIELD_ASSOCIATION_POINTS);
mapper->MapDataArrayToMultiTextureAttribute(
vtkTexture::VTK_TEXTURE_UNIT_1, "MultTCoords", vtkDataObject::FIELD_ASSOCIATION_POINTS);
mapper->MapDataArrayToMultiTextureAttribute(
vtkTexture::VTK_TEXTURE_UNIT_2, "MultTCoords", vtkDataObject::FIELD_ASSOCIATION_POINTS);
vtkActor * actor = vtkActor::New();
actor->GetProperty()->SetTexture(vtkTexture::VTK_TEXTURE_UNIT_0,textureRed);
actor->GetProperty()->SetTexture(vtkTexture::VTK_TEXTURE_UNIT_1,textureBlue);
actor->GetProperty()->SetTexture(vtkTexture::VTK_TEXTURE_UNIT_2,textureGreen);
actor->SetMapper(mapper);
vtkRenderer * renderer = vtkRenderer::New();
vtkRenderWindow * renWin = vtkRenderWindow::New();
renWin->SetSize(300, 300);
renWin->AddRenderer(renderer);
renderer->SetBackground(1.0, 0.5, 1.0);
vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
iren->SetRenderWindow(renWin);
renderer->AddActor(actor);
renWin->Render();
int retVal = vtkRegressionTestImage( renWin );
if ( retVal == vtkRegressionTester::DO_INTERACTOR)
{
iren->Start();
}
//points->Delete();
//cells->Delete();
polyData->Delete();
mapper->Delete();
actor->Delete();
renWin->Delete();
renderer->Delete();
iren->Delete();
imageReaderRed->Delete();
imageReaderBlue->Delete();
imageReaderGreen->Delete();
textureRed->Delete();
textureBlue->Delete();
textureGreen->Delete();
return !retVal;
}
<commit_msg>BUG:Fixed memory leak.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: TestMultiTexturing.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// .NAME Test of vtkGLSLShaderDeviceAdapter
// .SECTION Description
// this program tests the shader support in vtkRendering.
#include <vtkActor.h>
#include <vtkCellArray.h>
#include <vtkDoubleArray.h>
#include <vtkFloatArray.h>
#include <vtkImageData.h>
#include <vtkPlaneSource.h>
#include <vtkProperty.h>
#include <vtkPointData.h>
#include <vtkPoints.h>
#include <vtkPointSet.h>
#include <vtkPolyData.h>
#include <vtkPainterPolyDataMapper.h>
#include <vtkPNGReader.h>
#include <vtkRenderer.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkStripper.h>
#include <vtkTriangleFilter.h>
#include <vtkTexture.h>
#include <vtkTestUtilities.h>
#include <vtkRegressionTestImage.h>
int TestMultiTexturing(int argc, char *argv[])
{
char* fname1 =
vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/RedCircle.png");
char* fname2 =
vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/BlueCircle.png");
char* fname3 =
vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/GreenCircle.png");
vtkPNGReader * imageReaderRed = vtkPNGReader::New();
vtkPNGReader * imageReaderBlue = vtkPNGReader::New();
vtkPNGReader * imageReaderGreen = vtkPNGReader::New();
imageReaderRed->SetFileName(fname1);
imageReaderBlue->SetFileName(fname2);
imageReaderGreen->SetFileName(fname3);
delete[] fname1;
delete[] fname2;
delete[] fname3;
imageReaderRed->Update();
imageReaderBlue->Update();
imageReaderGreen->Update();
/*vtkPolyData * polyData = vtkPolyData::New();
vtkPoints * points = vtkPoints::New();
points->Allocate(16);
points->InsertNextPoint(-1.0, -1.0, 0.0);
points->InsertNextPoint(1.0, -1.0, 0.0);
points->InsertNextPoint(1.0, 1.0, 0.0);
points->InsertNextPoint(-1.0, 1.0, 0.0);
polyData->SetPoints(points);
vtkCellArray * cells = vtkCellArray::New();
cells->Allocate(cells->EstimateSize(1, 4));
cells->InsertNextCell(4);
cells->InsertCellPoint(0);
cells->InsertCellPoint(1);
cells->InsertCellPoint(2);
cells->InsertCellPoint(3);
polyData->SetPolys(cells);*/
vtkPlaneSource *planeSource = vtkPlaneSource::New();
planeSource->Update();
vtkTriangleFilter *triangleFilter = vtkTriangleFilter::New();
triangleFilter->SetInputConnection(planeSource->GetOutputPort());
planeSource->Delete();
vtkStripper *stripper = vtkStripper::New();
stripper->SetInputConnection(triangleFilter->GetOutputPort());
triangleFilter->Delete();
stripper->Update();
vtkPolyData *polyData = stripper->GetOutput();
polyData->Register(NULL);
stripper->Delete();
polyData->GetPointData()->SetNormals(NULL);
vtkFloatArray *TCoords = vtkFloatArray::New();
TCoords->SetNumberOfComponents(2);
TCoords->Allocate(8);
TCoords->InsertNextTuple2(0.0, 0.0);
TCoords->InsertNextTuple2(0.0, 1.0);
TCoords->InsertNextTuple2(1.0, 0.0);
TCoords->InsertNextTuple2(1.0, 1.0);
TCoords->SetName("MultTCoords");
polyData->GetPointData()->AddArray(TCoords);
TCoords->Delete();
vtkTexture * textureRed = vtkTexture::New();
vtkTexture * textureBlue = vtkTexture::New();
vtkTexture * textureGreen = vtkTexture::New();
textureRed->SetInputConnection(imageReaderRed->GetOutputPort());
textureBlue->SetInputConnection(imageReaderBlue->GetOutputPort());
textureGreen->SetInputConnection(imageReaderGreen->GetOutputPort());
textureRed->SetTextureUnit(vtkTexture::VTK_TEXTURE_UNIT_0);
textureBlue->SetTextureUnit(vtkTexture::VTK_TEXTURE_UNIT_1);
textureGreen->SetTextureUnit(vtkTexture::VTK_TEXTURE_UNIT_2);
// replace the fargments color and then accumulate the textures
// RGBA values.
textureRed->SetBlendingMode(vtkTexture::VTK_TEXTURE_BLENDING_MODE_REPLACE);
textureBlue->SetBlendingMode(vtkTexture::VTK_TEXTURE_BLENDING_MODE_ADD);
textureGreen->SetBlendingMode(vtkTexture::VTK_TEXTURE_BLENDING_MODE_ADD);
vtkPolyDataMapper * mapper = vtkPolyDataMapper::New();
mapper->SetInput(polyData);
mapper->MapDataArrayToMultiTextureAttribute(
vtkTexture::VTK_TEXTURE_UNIT_0, "MultTCoords", vtkDataObject::FIELD_ASSOCIATION_POINTS);
mapper->MapDataArrayToMultiTextureAttribute(
vtkTexture::VTK_TEXTURE_UNIT_1, "MultTCoords", vtkDataObject::FIELD_ASSOCIATION_POINTS);
mapper->MapDataArrayToMultiTextureAttribute(
vtkTexture::VTK_TEXTURE_UNIT_2, "MultTCoords", vtkDataObject::FIELD_ASSOCIATION_POINTS);
vtkActor * actor = vtkActor::New();
actor->GetProperty()->SetTexture(vtkTexture::VTK_TEXTURE_UNIT_0,textureRed);
actor->GetProperty()->SetTexture(vtkTexture::VTK_TEXTURE_UNIT_1,textureBlue);
actor->GetProperty()->SetTexture(vtkTexture::VTK_TEXTURE_UNIT_2,textureGreen);
actor->SetMapper(mapper);
vtkRenderer * renderer = vtkRenderer::New();
vtkRenderWindow * renWin = vtkRenderWindow::New();
renWin->SetSize(300, 300);
renWin->AddRenderer(renderer);
renderer->SetBackground(1.0, 0.5, 1.0);
vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
iren->SetRenderWindow(renWin);
renderer->AddActor(actor);
renWin->Render();
int retVal = vtkRegressionTestImage( renWin );
if ( retVal == vtkRegressionTester::DO_INTERACTOR)
{
iren->Start();
}
//points->Delete();
//cells->Delete();
polyData->Delete();
mapper->Delete();
actor->Delete();
renWin->Delete();
renderer->Delete();
iren->Delete();
imageReaderRed->Delete();
imageReaderBlue->Delete();
imageReaderGreen->Delete();
textureRed->Delete();
textureBlue->Delete();
textureGreen->Delete();
return !retVal;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2018-present ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include <seastar/core/print.hh>
#include "db/query_context.hh"
#include "db/system_keyspace.hh"
#include "db/large_data_handler.hh"
#include "sstables/sstables.hh"
static logging::logger large_data_logger("large_data");
namespace db {
nop_large_data_handler::nop_large_data_handler()
: large_data_handler(std::numeric_limits<uint64_t>::max(), std::numeric_limits<uint64_t>::max(),
std::numeric_limits<uint64_t>::max(), std::numeric_limits<uint64_t>::max()) {
// Don't require start() to be called on nop large_data_handler.
start();
}
large_data_handler::large_data_handler(uint64_t partition_threshold_bytes, uint64_t row_threshold_bytes, uint64_t cell_threshold_bytes, uint64_t rows_count_threshold)
: _partition_threshold_bytes(partition_threshold_bytes)
, _row_threshold_bytes(row_threshold_bytes)
, _cell_threshold_bytes(cell_threshold_bytes)
, _rows_count_threshold(rows_count_threshold)
{
large_data_logger.debug("partition_threshold_bytes={} row_threshold_bytes={} cell_threshold_bytes={} rows_count_threshold={}",
partition_threshold_bytes, row_threshold_bytes, cell_threshold_bytes, rows_count_threshold);
}
future<bool> large_data_handler::maybe_record_large_partitions(const sstables::sstable& sst, const sstables::key& key, uint64_t partition_size) {
assert(running());
if (partition_size > _partition_threshold_bytes) {
++_stats.partitions_bigger_than_threshold;
return with_sem([&sst, &key, partition_size, this] {
return record_large_partitions(sst, key, partition_size);
}).then([] {
return true;
});
}
return make_ready_future<bool>(false);
}
void large_data_handler::start() {
_running = true;
}
future<> large_data_handler::stop() {
if (!running()) {
return make_ready_future<>();
}
_running = false;
return _sem.wait(max_concurrency);
}
template <typename T> static std::string key_to_str(const T& key, const schema& s) {
std::ostringstream oss;
oss << key.with_schema(s);
return oss.str();
}
future<> large_data_handler::maybe_delete_large_data_entries(sstables::shared_sstable sst) {
assert(running());
auto schema = sst->get_schema();
auto filename = sst->get_filename();
auto data_size = sst->data_size();
future<> large_partitions = make_ready_future<>();
auto entry = sst->get_large_data_stat(sstables::large_data_type::partition_size);
if (entry && entry->above_threshold) {
large_partitions = with_sem([schema, filename, this] () mutable {
return delete_large_data_entries(*schema, std::move(filename), db::system_keyspace::LARGE_PARTITIONS);
});
}
future<> large_rows = make_ready_future<>();
entry = sst->get_large_data_stat(sstables::large_data_type::row_size);
if (entry && entry->above_threshold) {
large_rows = with_sem([schema, filename, this] () mutable {
return delete_large_data_entries(*schema, std::move(filename), db::system_keyspace::LARGE_ROWS);
});
}
future<> large_cells = make_ready_future<>();
entry = sst->get_large_data_stat(sstables::large_data_type::cell_size);
if (entry && entry->above_threshold) {
large_cells = with_sem([schema, filename, this] () mutable {
return delete_large_data_entries(*schema, std::move(filename), db::system_keyspace::LARGE_CELLS);
});
}
return when_all(std::move(large_partitions), std::move(large_rows), std::move(large_cells)).discard_result();
}
template <typename... Args>
static future<> try_record(std::string_view large_table, const sstables::sstable& sst, const sstables::key& partition_key, int64_t size,
std::string_view desc, std::string_view extra_path, const std::vector<sstring> &extra_fields, Args&&... args) {
sstring extra_fields_str;
sstring extra_values;
for (std::string_view field : extra_fields) {
extra_fields_str += format(", {}", field);
extra_values += ", ?";
}
const sstring req = format("INSERT INTO system.large_{}s (keyspace_name, table_name, sstable_name, {}_size, partition_key, compaction_time{}) VALUES (?, ?, ?, ?, ?, ?{}) USING TTL 2592000",
large_table, large_table, extra_fields_str, extra_values);
const schema &s = *sst.get_schema();
auto ks_name = s.ks_name();
auto cf_name = s.cf_name();
const auto sstable_name = sst.get_filename();
std::string pk_str = key_to_str(partition_key.to_partition_key(s), s);
auto timestamp = db_clock::now();
large_data_logger.warn("Writing large {} {}/{}: {}{} ({} bytes)", desc, ks_name, cf_name, pk_str, extra_path, size);
return db::qctx->execute_cql(req, ks_name, cf_name, sstable_name, size, pk_str, timestamp, args...)
.discard_result()
.handle_exception([ks_name, cf_name, large_table, sstable_name] (std::exception_ptr ep) {
large_data_logger.warn("Failed to add a record to system.large_{}s: ks = {}, table = {}, sst = {} exception = {}",
large_table, ks_name, cf_name, sstable_name, ep);
});
}
future<> cql_table_large_data_handler::record_large_partitions(const sstables::sstable& sst, const sstables::key& key, uint64_t partition_size) const {
return try_record("partition", sst, key, int64_t(partition_size), "partition", "", {});
}
void cql_table_large_data_handler::log_too_many_rows(const sstables::sstable& sst, const sstables::key& partition_key,
uint64_t rows_count) const {
const schema& s = *sst.get_schema();
large_data_logger.warn("Writing a partition with too many rows [{}/{}:{}] ({} rows)",
s.ks_name(), s.cf_name(), partition_key.to_partition_key(s).with_schema(s),
rows_count);
}
future<> cql_table_large_data_handler::record_large_cells(const sstables::sstable& sst, const sstables::key& partition_key,
const clustering_key_prefix* clustering_key, const column_definition& cdef, uint64_t cell_size) const {
auto column_name = cdef.name_as_text();
std::string_view cell_type = cdef.is_atomic() ? "cell" : "collection";
static const std::vector<sstring> extra_fields{"clustering_key", "column_name"};
if (clustering_key) {
const schema &s = *sst.get_schema();
auto ck_str = key_to_str(*clustering_key, s);
return try_record("cell", sst, partition_key, int64_t(cell_size), cell_type, format("{} {}", ck_str, column_name), extra_fields, ck_str, column_name);
} else {
return try_record("cell", sst, partition_key, int64_t(cell_size), cell_type, column_name, extra_fields, data_value::make_null(utf8_type), column_name);
}
}
future<> cql_table_large_data_handler::record_large_rows(const sstables::sstable& sst, const sstables::key& partition_key,
const clustering_key_prefix* clustering_key, uint64_t row_size) const {
static const std::vector<sstring> extra_fields{"clustering_key"};
if (clustering_key) {
const schema &s = *sst.get_schema();
std::string ck_str = key_to_str(*clustering_key, s);
return try_record("row", sst, partition_key, int64_t(row_size), "row", ck_str, extra_fields, ck_str);
} else {
return try_record("row", sst, partition_key, int64_t(row_size), "static row", "", extra_fields, data_value::make_null(utf8_type));
}
}
future<> cql_table_large_data_handler::delete_large_data_entries(const schema& s, sstring sstable_name, std::string_view large_table_name) const {
const sstring req =
format("DELETE FROM system.{} WHERE keyspace_name = ? AND table_name = ? AND sstable_name = ?",
large_table_name);
return db::qctx->execute_cql(req, s.ks_name(), s.cf_name(), sstable_name)
.discard_result()
.handle_exception([&s, sstable_name, large_table_name] (std::exception_ptr ep) {
large_data_logger.warn("Failed to drop entries from {}: ks = {}, table = {}, sst = {} exception = {}",
large_table_name, s.ks_name(), s.cf_name(), sstable_name, ep);
});
}
}
<commit_msg>large_data_handler: Prepare for stopped qctx<commit_after>/*
* Copyright (C) 2018-present ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include <seastar/core/print.hh>
#include "db/query_context.hh"
#include "db/system_keyspace.hh"
#include "db/large_data_handler.hh"
#include "sstables/sstables.hh"
static logging::logger large_data_logger("large_data");
namespace db {
nop_large_data_handler::nop_large_data_handler()
: large_data_handler(std::numeric_limits<uint64_t>::max(), std::numeric_limits<uint64_t>::max(),
std::numeric_limits<uint64_t>::max(), std::numeric_limits<uint64_t>::max()) {
// Don't require start() to be called on nop large_data_handler.
start();
}
large_data_handler::large_data_handler(uint64_t partition_threshold_bytes, uint64_t row_threshold_bytes, uint64_t cell_threshold_bytes, uint64_t rows_count_threshold)
: _partition_threshold_bytes(partition_threshold_bytes)
, _row_threshold_bytes(row_threshold_bytes)
, _cell_threshold_bytes(cell_threshold_bytes)
, _rows_count_threshold(rows_count_threshold)
{
large_data_logger.debug("partition_threshold_bytes={} row_threshold_bytes={} cell_threshold_bytes={} rows_count_threshold={}",
partition_threshold_bytes, row_threshold_bytes, cell_threshold_bytes, rows_count_threshold);
}
future<bool> large_data_handler::maybe_record_large_partitions(const sstables::sstable& sst, const sstables::key& key, uint64_t partition_size) {
assert(running());
if (partition_size > _partition_threshold_bytes) {
++_stats.partitions_bigger_than_threshold;
return with_sem([&sst, &key, partition_size, this] {
return record_large_partitions(sst, key, partition_size);
}).then([] {
return true;
});
}
return make_ready_future<bool>(false);
}
void large_data_handler::start() {
_running = true;
}
future<> large_data_handler::stop() {
if (!running()) {
return make_ready_future<>();
}
_running = false;
return _sem.wait(max_concurrency);
}
template <typename T> static std::string key_to_str(const T& key, const schema& s) {
std::ostringstream oss;
oss << key.with_schema(s);
return oss.str();
}
future<> large_data_handler::maybe_delete_large_data_entries(sstables::shared_sstable sst) {
assert(running());
auto schema = sst->get_schema();
auto filename = sst->get_filename();
auto data_size = sst->data_size();
future<> large_partitions = make_ready_future<>();
auto entry = sst->get_large_data_stat(sstables::large_data_type::partition_size);
if (entry && entry->above_threshold) {
large_partitions = with_sem([schema, filename, this] () mutable {
return delete_large_data_entries(*schema, std::move(filename), db::system_keyspace::LARGE_PARTITIONS);
});
}
future<> large_rows = make_ready_future<>();
entry = sst->get_large_data_stat(sstables::large_data_type::row_size);
if (entry && entry->above_threshold) {
large_rows = with_sem([schema, filename, this] () mutable {
return delete_large_data_entries(*schema, std::move(filename), db::system_keyspace::LARGE_ROWS);
});
}
future<> large_cells = make_ready_future<>();
entry = sst->get_large_data_stat(sstables::large_data_type::cell_size);
if (entry && entry->above_threshold) {
large_cells = with_sem([schema, filename, this] () mutable {
return delete_large_data_entries(*schema, std::move(filename), db::system_keyspace::LARGE_CELLS);
});
}
return when_all(std::move(large_partitions), std::move(large_rows), std::move(large_cells)).discard_result();
}
template <typename... Args>
static future<> try_record(std::string_view large_table, const sstables::sstable& sst, const sstables::key& partition_key, int64_t size,
std::string_view desc, std::string_view extra_path, const std::vector<sstring> &extra_fields, Args&&... args) {
// FIXME This check is for test/cql-test-env that stop qctx (it does so because
// it stops query processor and doesn't want us to access its freed instantes)
if (!db::qctx) {
return make_ready_future<>();
}
sstring extra_fields_str;
sstring extra_values;
for (std::string_view field : extra_fields) {
extra_fields_str += format(", {}", field);
extra_values += ", ?";
}
const sstring req = format("INSERT INTO system.large_{}s (keyspace_name, table_name, sstable_name, {}_size, partition_key, compaction_time{}) VALUES (?, ?, ?, ?, ?, ?{}) USING TTL 2592000",
large_table, large_table, extra_fields_str, extra_values);
const schema &s = *sst.get_schema();
auto ks_name = s.ks_name();
auto cf_name = s.cf_name();
const auto sstable_name = sst.get_filename();
std::string pk_str = key_to_str(partition_key.to_partition_key(s), s);
auto timestamp = db_clock::now();
large_data_logger.warn("Writing large {} {}/{}: {}{} ({} bytes)", desc, ks_name, cf_name, pk_str, extra_path, size);
return db::qctx->execute_cql(req, ks_name, cf_name, sstable_name, size, pk_str, timestamp, args...)
.discard_result()
.handle_exception([ks_name, cf_name, large_table, sstable_name] (std::exception_ptr ep) {
large_data_logger.warn("Failed to add a record to system.large_{}s: ks = {}, table = {}, sst = {} exception = {}",
large_table, ks_name, cf_name, sstable_name, ep);
});
}
future<> cql_table_large_data_handler::record_large_partitions(const sstables::sstable& sst, const sstables::key& key, uint64_t partition_size) const {
return try_record("partition", sst, key, int64_t(partition_size), "partition", "", {});
}
void cql_table_large_data_handler::log_too_many_rows(const sstables::sstable& sst, const sstables::key& partition_key,
uint64_t rows_count) const {
const schema& s = *sst.get_schema();
large_data_logger.warn("Writing a partition with too many rows [{}/{}:{}] ({} rows)",
s.ks_name(), s.cf_name(), partition_key.to_partition_key(s).with_schema(s),
rows_count);
}
future<> cql_table_large_data_handler::record_large_cells(const sstables::sstable& sst, const sstables::key& partition_key,
const clustering_key_prefix* clustering_key, const column_definition& cdef, uint64_t cell_size) const {
auto column_name = cdef.name_as_text();
std::string_view cell_type = cdef.is_atomic() ? "cell" : "collection";
static const std::vector<sstring> extra_fields{"clustering_key", "column_name"};
if (clustering_key) {
const schema &s = *sst.get_schema();
auto ck_str = key_to_str(*clustering_key, s);
return try_record("cell", sst, partition_key, int64_t(cell_size), cell_type, format("{} {}", ck_str, column_name), extra_fields, ck_str, column_name);
} else {
return try_record("cell", sst, partition_key, int64_t(cell_size), cell_type, column_name, extra_fields, data_value::make_null(utf8_type), column_name);
}
}
future<> cql_table_large_data_handler::record_large_rows(const sstables::sstable& sst, const sstables::key& partition_key,
const clustering_key_prefix* clustering_key, uint64_t row_size) const {
static const std::vector<sstring> extra_fields{"clustering_key"};
if (clustering_key) {
const schema &s = *sst.get_schema();
std::string ck_str = key_to_str(*clustering_key, s);
return try_record("row", sst, partition_key, int64_t(row_size), "row", ck_str, extra_fields, ck_str);
} else {
return try_record("row", sst, partition_key, int64_t(row_size), "static row", "", extra_fields, data_value::make_null(utf8_type));
}
}
future<> cql_table_large_data_handler::delete_large_data_entries(const schema& s, sstring sstable_name, std::string_view large_table_name) const {
const sstring req =
format("DELETE FROM system.{} WHERE keyspace_name = ? AND table_name = ? AND sstable_name = ?",
large_table_name);
return db::qctx->execute_cql(req, s.ks_name(), s.cf_name(), sstable_name)
.discard_result()
.handle_exception([&s, sstable_name, large_table_name] (std::exception_ptr ep) {
large_data_logger.warn("Failed to drop entries from {}: ks = {}, table = {}, sst = {} exception = {}",
large_table_name, s.ks_name(), s.cf_name(), sstable_name, ep);
});
}
}
<|endoftext|>
|
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "EC_Sound.h"
#include "IModule.h"
#include "Framework.h"
#include "Entity.h"
#include "Audio.h"
#include "AssetAPI.h"
#include "EC_Placeable.h"
#include "EC_SoundListener.h"
#include "SceneManager.h"
#include "LoggingFunctions.h"
DEFINE_POCO_LOGGING_FUNCTIONS("EC_Sound")
#include "MemoryLeakCheck.h"
EC_Sound::EC_Sound(IModule *module):
IComponent(module->GetFramework()),
soundRef(this, "Sound ref"),
soundInnerRadius(this, "Sound radius inner", 0.0f),
soundOuterRadius(this, "Sound radius outer", 20.0f),
loopSound(this, "Loop sound", false),
soundGain(this, "Sound gain", 1.0f),
spatial(this, "Spatial", true)
{
static AttributeMetadata metaData("", "0", "1", "0.1");
soundGain.SetMetadata(&metaData);
connect(this, SIGNAL(ParentEntitySet()), SLOT(UpdateSignals()));
connect(this, SIGNAL(OnAttributeChanged(IAttribute*, AttributeChange::Type)), SLOT(AttributeUpdated(IAttribute*)));
}
EC_Sound::~EC_Sound()
{
StopSound();
}
void EC_Sound::AttributeUpdated(IAttribute *attribute)
{
if (attribute == &soundRef)
framework_->Asset()->RequestAsset(soundRef.Get().ref);
UpdateSoundSettings();
}
void EC_Sound::RegisterActions()
{
Scene::Entity *entity = GetParentEntity();
assert(entity);
if (entity)
{
entity->ConnectAction("PlaySound", this, SLOT(PlaySound()));
entity->ConnectAction("StopSound", this, SLOT(StopSound()));
}
}
void EC_Sound::PositionChange(const QVector3D &pos)
{
if (soundChannel)
soundChannel->SetPosition(Vector3df(pos.x(), pos.y(), pos.z()));
}
void EC_Sound::PlaySound()
{
ComponentChanged(AttributeChange::LocalOnly);
// If previous sound is still playing stop it before we apply a new sound.
if (soundChannel)
{
soundChannel->Stop();
soundChannel.reset();
}
AssetPtr audioAsset = GetFramework()->Asset()->GetAsset(soundRef.Get().ref);
if (!audioAsset)
{
///\todo Make a request.
return;
}
bool soundListenerExists = true;
EC_Placeable *placeable = dynamic_cast<EC_Placeable *>(FindPlaceable().get());
// If we are going to play back positional audio, check that there is a sound listener enabled that can listen to it.
// Otherwise, if no SoundListener exists, play back the audio as nonpositional.
if (placeable && spatial.Get())
soundListenerExists = (GetActiveSoundListener() != Scene::EntityPtr());
if (placeable && spatial.Get() && soundListenerExists)
{
soundChannel = GetFramework()->Audio()->PlaySound3D(placeable->GetPosition(), audioAsset, SoundChannel::Triggered);
if (soundChannel)
soundChannel->SetRange(soundInnerRadius.Get(), soundOuterRadius.Get(), 2.0f);
}
else // Play back sound as a nonpositional sound, if no EC_Placeable was found or if spatial was not set.
{
soundChannel = GetFramework()->Audio()->PlaySound(audioAsset, SoundChannel::Ambient);
}
if (soundChannel)
{
soundChannel->SetGain(soundGain.Get());
soundChannel->SetLooped(loopSound.Get());
}
}
void EC_Sound::StopSound()
{
if (soundChannel)
soundChannel->Stop();
soundChannel.reset();
}
void EC_Sound::UpdateSoundSettings()
{
if (soundChannel)
{
soundChannel->SetGain(soundGain.Get());
soundChannel->SetLooped(loopSound.Get());
soundChannel->SetRange(soundInnerRadius.Get(), soundOuterRadius.Get(), 2.0f);
}
}
Scene::EntityPtr EC_Sound::GetActiveSoundListener()
{
#ifdef _DEBUG
int numActiveListeners = 0; // For debugging, count how many listeners are active.
#endif
Scene::EntityList listeners = parent_entity_->GetScene()->GetEntitiesWithComponent("EC_SoundListener");
foreach(Scene::EntityPtr listener, listeners)
{
EC_SoundListener *ec = listener->GetComponent<EC_SoundListener>().get();
if (ec->active.Get())
{
#ifndef _DEBUG
assert(ec->GetParentEntity());
return ec->GetParentEntity()->shared_from_this;
#else
++numActiveListeners;
#endif
}
}
if (numActiveListeners != 1)
LogWarning("Warning: When playing back positional 3D audio, " + QString::number(numActiveListeners).toStdString() + " active sound listeners were found!");
return Scene::EntityPtr();
}
void EC_Sound::UpdateSignals()
{
if (!GetParentEntity())
{
LogError("Couldn't update singals cause component dont have parent entity set.");
return;
}
Scene::SceneManager *scene = GetParentEntity()->GetScene();
if(!scene)
{
LogError("Fail to update signals cause parent entity's scene is null.");
return;
}
RegisterActions();
}
ComponentPtr EC_Sound::FindPlaceable() const
{
assert(framework_);
ComponentPtr comp;
if(!GetParentEntity())
{
LogError("Fail to find a placeable component cause parent entity is null.");
return comp;
}
comp = GetParentEntity()->GetComponent<EC_Placeable>();
//We need to update sound source position when placeable component has changed it's transformation.
connect(comp.get(), SIGNAL(PositionChanged(const QVector3D &)),
SLOT(PositionChange(const QVector3D &)), Qt::UniqueConnection);
return comp;
}
<commit_msg>Fix EC_Sound to build in release mode.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "EC_Sound.h"
#include "IModule.h"
#include "Framework.h"
#include "Entity.h"
#include "Audio.h"
#include "AssetAPI.h"
#include "EC_Placeable.h"
#include "EC_SoundListener.h"
#include "SceneManager.h"
#include "LoggingFunctions.h"
DEFINE_POCO_LOGGING_FUNCTIONS("EC_Sound")
#include "MemoryLeakCheck.h"
EC_Sound::EC_Sound(IModule *module):
IComponent(module->GetFramework()),
soundRef(this, "Sound ref"),
soundInnerRadius(this, "Sound radius inner", 0.0f),
soundOuterRadius(this, "Sound radius outer", 20.0f),
loopSound(this, "Loop sound", false),
soundGain(this, "Sound gain", 1.0f),
spatial(this, "Spatial", true)
{
static AttributeMetadata metaData("", "0", "1", "0.1");
soundGain.SetMetadata(&metaData);
connect(this, SIGNAL(ParentEntitySet()), SLOT(UpdateSignals()));
connect(this, SIGNAL(OnAttributeChanged(IAttribute*, AttributeChange::Type)), SLOT(AttributeUpdated(IAttribute*)));
}
EC_Sound::~EC_Sound()
{
StopSound();
}
void EC_Sound::AttributeUpdated(IAttribute *attribute)
{
if (attribute == &soundRef)
framework_->Asset()->RequestAsset(soundRef.Get().ref);
UpdateSoundSettings();
}
void EC_Sound::RegisterActions()
{
Scene::Entity *entity = GetParentEntity();
assert(entity);
if (entity)
{
entity->ConnectAction("PlaySound", this, SLOT(PlaySound()));
entity->ConnectAction("StopSound", this, SLOT(StopSound()));
}
}
void EC_Sound::PositionChange(const QVector3D &pos)
{
if (soundChannel)
soundChannel->SetPosition(Vector3df(pos.x(), pos.y(), pos.z()));
}
void EC_Sound::PlaySound()
{
ComponentChanged(AttributeChange::LocalOnly);
// If previous sound is still playing stop it before we apply a new sound.
if (soundChannel)
{
soundChannel->Stop();
soundChannel.reset();
}
AssetPtr audioAsset = GetFramework()->Asset()->GetAsset(soundRef.Get().ref);
if (!audioAsset)
{
///\todo Make a request.
return;
}
bool soundListenerExists = true;
EC_Placeable *placeable = dynamic_cast<EC_Placeable *>(FindPlaceable().get());
// If we are going to play back positional audio, check that there is a sound listener enabled that can listen to it.
// Otherwise, if no SoundListener exists, play back the audio as nonpositional.
if (placeable && spatial.Get())
soundListenerExists = (GetActiveSoundListener() != Scene::EntityPtr());
if (placeable && spatial.Get() && soundListenerExists)
{
soundChannel = GetFramework()->Audio()->PlaySound3D(placeable->GetPosition(), audioAsset, SoundChannel::Triggered);
if (soundChannel)
soundChannel->SetRange(soundInnerRadius.Get(), soundOuterRadius.Get(), 2.0f);
}
else // Play back sound as a nonpositional sound, if no EC_Placeable was found or if spatial was not set.
{
soundChannel = GetFramework()->Audio()->PlaySound(audioAsset, SoundChannel::Ambient);
}
if (soundChannel)
{
soundChannel->SetGain(soundGain.Get());
soundChannel->SetLooped(loopSound.Get());
}
}
void EC_Sound::StopSound()
{
if (soundChannel)
soundChannel->Stop();
soundChannel.reset();
}
void EC_Sound::UpdateSoundSettings()
{
if (soundChannel)
{
soundChannel->SetGain(soundGain.Get());
soundChannel->SetLooped(loopSound.Get());
soundChannel->SetRange(soundInnerRadius.Get(), soundOuterRadius.Get(), 2.0f);
}
}
Scene::EntityPtr EC_Sound::GetActiveSoundListener()
{
#ifdef _DEBUG
int numActiveListeners = 0; // For debugging, count how many listeners are active.
#endif
Scene::EntityList listeners = parent_entity_->GetScene()->GetEntitiesWithComponent("EC_SoundListener");
foreach(Scene::EntityPtr listener, listeners)
{
EC_SoundListener *ec = listener->GetComponent<EC_SoundListener>().get();
if (ec->active.Get())
{
#ifndef _DEBUG
assert(ec->GetParentEntity());
return ec->GetParentEntity()->shared_from_this();
#else
++numActiveListeners;
#endif
}
}
#ifdef _DEBUG
if (numActiveListeners != 1)
LogWarning("Warning: When playing back positional 3D audio, " + QString::number(numActiveListeners).toStdString() + " active sound listeners were found!");
#endif
return Scene::EntityPtr();
}
void EC_Sound::UpdateSignals()
{
if (!GetParentEntity())
{
LogError("Couldn't update singals cause component dont have parent entity set.");
return;
}
Scene::SceneManager *scene = GetParentEntity()->GetScene();
if(!scene)
{
LogError("Fail to update signals cause parent entity's scene is null.");
return;
}
RegisterActions();
}
ComponentPtr EC_Sound::FindPlaceable() const
{
assert(framework_);
ComponentPtr comp;
if(!GetParentEntity())
{
LogError("Fail to find a placeable component cause parent entity is null.");
return comp;
}
comp = GetParentEntity()->GetComponent<EC_Placeable>();
//We need to update sound source position when placeable component has changed it's transformation.
connect(comp.get(), SIGNAL(PositionChanged(const QVector3D &)),
SLOT(PositionChange(const QVector3D &)), Qt::UniqueConnection);
return comp;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#if !defined(NOMINMAX)
#define NOMINMAX // fckng Windows
#endif
#include "vtrc-client/vtrc-client.h"
#include "vtrc-common/vtrc-thread-pool.h"
#include "vtrc-common/vtrc-stub-wrapper.h"
#include "vtrc-common/vtrc-random-device.h"
#include "protocol/hello.pb.h"
#include "boost/lexical_cast.hpp"
#include "openssl/err.h"
#include "openssl/rand.h"
#if defined(X509_NAME)
#undef X509_NAME
#endif
#include "openssl/ssl.h"
#include "../protocol/ssl-wrapper.h"
using namespace vtrc;
const std::string CERTF = "../server.crt";
namespace {
typedef howto::hello_ssl_service_Stub stub_type;
typedef common::stub_wrapper<stub_type> stub_wrap;
void on_connect( )
{
std::cout << "connect...";
}
void on_ready( )
{
std::cout << "ready...";
}
void on_disconnect( )
{
std::cout << "disconnect...";
}
void ssl_throw( const char *add )
{
std::string err(add);
err += ": ";
size_t final = err.size( );
err.resize( final + 1024 );
ERR_error_string_n(ERR_get_error( ), &err[final], err.size( ) - final );
throw std::runtime_error( err );
}
}
int verify_callback( X509_STORE_CTX *x509, void */*p*/ )
{
char subject[512];
int ver = X509_verify_cert(x509);
if( ver <= 0 ) {
int err = X509_STORE_CTX_get_error(x509);
char errorbuf[1024];
ERR_error_string_n(err, errorbuf, 1024);
std::cout << "Cert is not valid. " << errorbuf << "\n";
}
X509 *cc = X509_STORE_CTX_get_current_cert( x509 );
if( !cc ) {
ssl_throw("ds");
}
X509_NAME *sn = X509_get_subject_name( cc );
X509_NAME_oneline(sn, subject, 256);
std::cout << "Verify call: " << subject << "\n";
/// we don't care, cuz "Hello, world!"
return 1;
}
class my_ssl_wrapper: public ssl_wrapper_client {
public:
my_ssl_wrapper( )
:ssl_wrapper_client(TLSv1_2_client_method( ))
{ }
private:
void init_context( )
{
SSL_CTX_set_mode( get_context( ), SSL_MODE_AUTO_RETRY );
SSL_CTX_set_mode( get_context( ), SSL_MODE_ENABLE_PARTIAL_WRITE );
SSL_CTX_set_mode( get_context( ), SSL_MODE_RELEASE_BUFFERS );
SSL_CTX_set_cert_verify_callback( get_context( ), verify_callback, 0 );
int err = SSL_CTX_load_verify_locations( get_context( ),
CERTF.c_str( ), 0 );
if( err == 0 ) {
ssl_throw("SSL_CTX_load_verify_locations");
}
}
};
std::string send_data( stub_wrap &stub, my_ssl_wrapper &ssl,
const std::string &data, bool decode = true )
{
howto::request_message req;
howto::response_message res;
req.set_block( ssl.encrypt( data ) );
//std::cout << "packed: " << req.block( ).size( ) << "\n";
stub.call( &stub_type::send_block, &req, &res );
std::string result;
if( decode ) {
result = ssl.decrypt( res.block( ) );
} else {
ssl.get_in( ).write( res.block( ) );
}
// std::cout << "result: " << result.size( ) << " "
// << res.block( ).size( ) << "\n";
return result;
}
void connect_handshake( stub_wrap &stub )
{
my_ssl_wrapper ssl;
ssl.init( );
howto::request_message req;
howto::response_message res;
std::string data;
while (!ssl.init_finished( )) {
std::string res_data = ssl.do_handshake( );
if( !res_data.empty( ) ) {
req.set_block( res_data );
stub.call( &stub_type::send_block, &req, &res );
data = res.block( );
if( !data.empty( ) ) { //
ssl.get_in( ).write( data.c_str( ), data.size( ) );
}
}
}
std::cout << "Init success!\n";
int i = 0;
std::cout << i++ << ": " << send_data( stub, ssl, "Hello, World1" )
<< "\n";
std::cout << i++ << ": " << send_data( stub, ssl, "Hello, World2", false )
<< "\n";
std::cout << i++ << ": " << send_data( stub, ssl, "Hello, World3" )
<< "\n";
std::string test(41, '!');
std::cout << i++ << ": " << send_data( stub, ssl, test ) << "\n";
}
int main( int argc, const char **argv )
{
common::thread_pool tp( 1 );
const char *address = "127.0.0.1";
unsigned short port = 56560;
if( argc > 2 ) {
address = argv[1];
port = boost::lexical_cast<unsigned short>( argv[2] );
} else if( argc > 1 ) {
port = boost::lexical_cast<unsigned short>( argv[1] );
}
vtrc::common::random_device rd(true);
std::string seed = rd.generate_block( 1024 );
RAND_seed( seed.c_str( ), seed.size( ) );
SSL_load_error_strings( );
SSLeay_add_ssl_algorithms( );
try {
client::vtrc_client_sptr cl =
client::vtrc_client::create( tp.get_io_service( ) );
cl->on_connect_connect( on_connect );
cl->on_ready_connect( on_ready );
cl->on_disconnect_connect( on_disconnect );
std::cout << "Connecting..." << std::endl;
cl->connect( address, port );
std::cout << "Ok" << std::endl;
vtrc::unique_ptr<common::rpc_channel> channel(cl->create_channel( ));
stub_wrap hello(channel.get( ));
connect_handshake( hello );
} catch( const std::exception &ex ) {
std::cerr << "Hello, world failed: " << ex.what( ) << "\n";
}
tp.stop( );
tp.join_all( );
/// make valgrind happy.
google::protobuf::ShutdownProtobufLibrary( );
return 0;
}
<commit_msg>exmpl<commit_after>#include <iostream>
#if !defined(NOMINMAX)
#define NOMINMAX // fckng Windows
#endif
#include "vtrc-client/vtrc-client.h"
#include "vtrc-common/vtrc-thread-pool.h"
#include "vtrc-common/vtrc-stub-wrapper.h"
#include "vtrc-common/vtrc-random-device.h"
#include "protocol/hello.pb.h"
#include "boost/lexical_cast.hpp"
#include "openssl/err.h"
#include "openssl/rand.h"
#if defined(X509_NAME)
#undef X509_NAME // fckng MS
#endif
#include "openssl/ssl.h"
#include "../protocol/ssl-wrapper.h"
using namespace vtrc;
const std::string CERTF = "../server.crt";
namespace {
typedef howto::hello_ssl_service_Stub stub_type;
typedef common::stub_wrapper<stub_type> stub_wrap;
void on_connect( )
{
std::cout << "connect...";
}
void on_ready( )
{
std::cout << "ready...";
}
void on_disconnect( )
{
std::cout << "disconnect...";
}
void ssl_throw( const char *add )
{
std::string err(add);
err += ": ";
size_t final = err.size( );
err.resize( final + 1024 );
ERR_error_string_n(ERR_get_error( ), &err[final], err.size( ) - final );
throw std::runtime_error( err );
}
}
int verify_callback( X509_STORE_CTX *x509, void */*p*/ )
{
char subject[512];
int ver = X509_verify_cert(x509);
if( ver <= 0 ) {
int err = X509_STORE_CTX_get_error(x509);
char errorbuf[1024];
ERR_error_string_n(err, errorbuf, 1024);
std::cout << "Cert is not valid. " << errorbuf << "\n";
}
X509 *cc = X509_STORE_CTX_get_current_cert( x509 );
if( !cc ) {
ssl_throw("ds");
}
X509_NAME *sn = X509_get_subject_name( cc );
X509_NAME_oneline(sn, subject, 256);
std::cout << "Verify call: " << subject << "\n";
/// we don't care, cuz "Hello, world!"
return 1;
}
class my_ssl_wrapper: public ssl_wrapper_client {
public:
my_ssl_wrapper( )
:ssl_wrapper_client(TLSv1_2_client_method( ))
{ }
private:
void init_context( )
{
SSL_CTX_set_mode( get_context( ), SSL_MODE_AUTO_RETRY );
SSL_CTX_set_mode( get_context( ), SSL_MODE_ENABLE_PARTIAL_WRITE );
SSL_CTX_set_mode( get_context( ), SSL_MODE_RELEASE_BUFFERS );
SSL_CTX_set_cert_verify_callback( get_context( ), verify_callback, 0 );
int err = SSL_CTX_load_verify_locations( get_context( ),
CERTF.c_str( ), 0 );
if( err == 0 ) {
ssl_throw("SSL_CTX_load_verify_locations");
}
}
};
std::string send_data( stub_wrap &stub, my_ssl_wrapper &ssl,
const std::string &data, bool decode = true )
{
howto::request_message req;
howto::response_message res;
req.set_block( ssl.encrypt( data ) );
//std::cout << "packed: " << req.block( ).size( ) << "\n";
stub.call( &stub_type::send_block, &req, &res );
std::string result;
if( decode ) {
result = ssl.decrypt( res.block( ) );
} else {
ssl.get_in( ).write( res.block( ) );
}
// std::cout << "result: " << result.size( ) << " "
// << res.block( ).size( ) << "\n";
return result;
}
void connect_handshake( stub_wrap &stub )
{
my_ssl_wrapper ssl;
ssl.init( );
howto::request_message req;
howto::response_message res;
std::string data;
while (!ssl.init_finished( )) {
std::string res_data = ssl.do_handshake( );
if( !res_data.empty( ) ) {
req.set_block( res_data );
stub.call( &stub_type::send_block, &req, &res );
data = res.block( );
if( !data.empty( ) ) { //
ssl.get_in( ).write( data.c_str( ), data.size( ) );
}
}
}
std::cout << "Init success!\n";
int i = 0;
std::cout << i++ << ": " << send_data( stub, ssl, "Hello, World1" )
<< "\n";
std::cout << i++ << ": " << send_data( stub, ssl, "Hello, World2", false )
<< "\n";
std::cout << i++ << ": " << send_data( stub, ssl, "Hello, World3" )
<< "\n";
std::string test(41, '!');
std::cout << i++ << ": " << send_data( stub, ssl, test ) << "\n";
}
int main( int argc, const char **argv )
{
common::thread_pool tp( 1 );
const char *address = "127.0.0.1";
unsigned short port = 56560;
if( argc > 2 ) {
address = argv[1];
port = boost::lexical_cast<unsigned short>( argv[2] );
} else if( argc > 1 ) {
port = boost::lexical_cast<unsigned short>( argv[1] );
}
vtrc::common::random_device rd(true);
std::string seed = rd.generate_block( 1024 );
RAND_seed( seed.c_str( ), seed.size( ) );
SSL_load_error_strings( );
SSLeay_add_ssl_algorithms( );
try {
client::vtrc_client_sptr cl =
client::vtrc_client::create( tp.get_io_service( ) );
cl->on_connect_connect( on_connect );
cl->on_ready_connect( on_ready );
cl->on_disconnect_connect( on_disconnect );
std::cout << "Connecting..." << std::endl;
cl->connect( address, port );
std::cout << "Ok" << std::endl;
vtrc::unique_ptr<common::rpc_channel> channel(cl->create_channel( ));
stub_wrap hello(channel.get( ));
connect_handshake( hello );
} catch( const std::exception &ex ) {
std::cerr << "Hello, world failed: " << ex.what( ) << "\n";
}
tp.stop( );
tp.join_all( );
/// make valgrind happy.
google::protobuf::ShutdownProtobufLibrary( );
return 0;
}
<|endoftext|>
|
<commit_before>/*
* ALURE OpenAL utility library
* Copyright (c) 2009 by Chris Robinson.
*
* 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.
*/
/* Title: Streaming */
#include "config.h"
#include "main.h"
#include <string.h>
#include <memory>
static bool SizeIsUS = false;
static alureStream *InitStream(alureStream *instream, ALsizei chunkLength, ALsizei numBufs, ALuint *bufs)
{
std::auto_ptr<alureStream> stream(instream);
ALenum format;
ALuint freq, blockAlign;
if(!stream->GetFormat(&format, &freq, &blockAlign))
{
SetError("Could not get stream format");
return NULL;
}
if(format == AL_NONE)
{
SetError("No valid format");
return NULL;
}
if(blockAlign == 0)
{
SetError("Invalid block size");
return NULL;
}
if(freq == 0)
{
SetError("Invalid sample rate");
return NULL;
}
alureUInt64 len64 = chunkLength;
if(SizeIsUS)
{
ALuint framesPerBlock = DetectCompressionRate(format);
if(framesPerBlock == 0)
{
SetError("Unknown compression rate");
return NULL;
}
len64 = len64 * freq / 1000000 / framesPerBlock * blockAlign;
if(len64 > 0xFFFFFFFF)
{
SetError("Chunk length too large");
return NULL;
}
}
chunkLength = len64 - (len64%blockAlign);
if(chunkLength <= 0)
{
SetError("Chunk length too small");
return NULL;
}
stream->chunkLen = chunkLength;
stream->dataChunk = new ALubyte[stream->chunkLen];
alGenBuffers(numBufs, bufs);
if(alGetError() != AL_NO_ERROR)
{
SetError("Buffer creation failed");
return NULL;
}
ALsizei filled;
for(filled = 0;filled < numBufs;filled++)
{
ALuint got = stream->GetData(stream->dataChunk, stream->chunkLen);
got -= got%blockAlign;
if(got == 0) break;
alBufferData(bufs[filled], format, stream->dataChunk, got, freq);
}
while(filled < numBufs)
{
alBufferData(bufs[filled], format, stream->dataChunk, 0, freq);
filled++;
}
if(alGetError() != AL_NO_ERROR)
{
alDeleteBuffers(numBufs, bufs);
alGetError();
SetError("Buffering error");
return NULL;
}
return stream.release();
}
extern "C" {
/* Function: alureStreamSizeIsMicroSec
*
* Specifies if the chunk size value given to the alureCreateStream functions
* is in bytes (default) or microseconds. Specifying the size in microseconds
* can help manage the time needed in between needed updates (since the format
* and sample rate of the stream may not be known), while specifying the size
* in bytes can help control memory usage.
*
* Returns:
* Previously set value.
*
* *Version Added*: 1.1
*
* See Also:
* <alureCreateStreamFromFile>, <alureCreateStreamFromMemory>,
* <alureCreateStreamFromStaticMemory>, <alureCreateStreamFromCallback>
*/
ALURE_API ALboolean ALURE_APIENTRY alureStreamSizeIsMicroSec(ALboolean useUS)
{
ALboolean old = (SizeIsUS ? AL_TRUE : AL_FALSE);
SizeIsUS = !!useUS;
return old;
}
/* Function: alureCreateStreamFromFile
*
* Opens a file and sets it up for streaming. The given chunkLength is the
* number of bytes, or microseconds worth of bytes if
* <alureStreamSizeIsMicroSec> was last called with AL_TRUE, each buffer will
* fill with. ALURE will optionally generate the specified number of buffer
* objects, fill them with the beginning of the data, then place the new IDs
* into the provided storage, before returning. Requires an active context.
*
* Returns:
* An opaque handle used to control the opened stream, or NULL on error.
*
* See Also:
* <alureStreamSizeIsMicroSec>, <alureCreateStreamFromMemory>,
* <alureCreateStreamFromStaticMemory>, <alureCreateStreamFromCallback>
*/
ALURE_API alureStream* ALURE_APIENTRY alureCreateStreamFromFile(const ALchar *fname, ALsizei chunkLength, ALsizei numBufs, ALuint *bufs)
{
if(alGetError() != AL_NO_ERROR)
{
SetError("Existing OpenAL error");
return NULL;
}
if(chunkLength < 0)
{
SetError("Invalid chunk length");
return NULL;
}
if(numBufs < 0)
{
SetError("Invalid buffer count");
return NULL;
}
alureStream *stream = create_stream(fname);
if(!stream->IsValid())
{
delete stream;
return NULL;
}
return InitStream(stream, chunkLength, numBufs, bufs);
}
/* Function: alureCreateStreamFromMemory
*
* Opens a file image from memory and sets it up for streaming, similar to
* <alureCreateStreamFromFile>. The given data buffer can be safely deleted
* after calling this function. Requires an active context.
*
* Returns:
* An opaque handle used to control the opened stream, or NULL on error.
*
* See Also:
* <alureStreamSizeIsMicroSec>, <alureCreateStreamFromFile>,
* <alureCreateStreamFromStaticMemory>, <alureCreateStreamFromCallback>
*/
ALURE_API alureStream* ALURE_APIENTRY alureCreateStreamFromMemory(const ALubyte *fdata, ALuint length, ALsizei chunkLength, ALsizei numBufs, ALuint *bufs)
{
if(alGetError() != AL_NO_ERROR)
{
SetError("Existing OpenAL error");
return NULL;
}
if(chunkLength < 0)
{
SetError("Invalid chunk length");
return NULL;
}
if(numBufs < 0)
{
SetError("Invalid buffer count");
return NULL;
}
if(length <= 0)
{
SetError("Invalid data length");
return NULL;
}
ALubyte *streamData = new ALubyte[length];
memcpy(streamData, fdata, length);
MemDataInfo memData;
memData.Data = streamData;
memData.Length = length;
memData.Pos = 0;
alureStream *stream = create_stream(memData);
stream->data = streamData;
if(!stream->IsValid())
{
delete stream;
return NULL;
}
return InitStream(stream, chunkLength, numBufs, bufs);
}
/* Function: alureCreateStreamFromStaticMemory
*
* Identical to <alureCreateStreamFromMemory>, except the given memory is used
* directly and not duplicated. As a consequence, the data buffer must remain
* valid while the stream is alive. Requires an active context.
*
* Returns:
* An opaque handle used to control the opened stream, or NULL on error.
*
* See Also:
* <alureStreamSizeIsMicroSec>, <alureCreateStreamFromFile>,
* <alureCreateStreamFromMemory>, <alureCreateStreamFromCallback>
*/
ALURE_API alureStream* ALURE_APIENTRY alureCreateStreamFromStaticMemory(const ALubyte *fdata, ALuint length, ALsizei chunkLength, ALsizei numBufs, ALuint *bufs)
{
if(alGetError() != AL_NO_ERROR)
{
SetError("Existing OpenAL error");
return NULL;
}
if(chunkLength < 0)
{
SetError("Invalid chunk length");
return NULL;
}
if(numBufs < 0)
{
SetError("Invalid buffer count");
return NULL;
}
if(length <= 0)
{
SetError("Invalid data length");
return NULL;
}
MemDataInfo memData;
memData.Data = fdata;
memData.Length = length;
memData.Pos = 0;
alureStream *stream = create_stream(memData);
if(!stream->IsValid())
{
delete stream;
return NULL;
}
return InitStream(stream, chunkLength, numBufs, bufs);
}
/* Function: alureCreateStreamFromCallback
*
* Creates a stream using the specified callback to retrieve data. Requires an
* active context.
*
* Parameters:
* callback - This is called when more data is needed from the stream. Up to
* the specified number of bytes should be written to the data
* pointer, and the number of bytes actually written should be
* returned. The number of bytes written must be block aligned for
* the format (eg. a multiple of 4 for AL_FORMAT_STEREO16), or an
* OpenAL error may occur during buffering.
* userdata - A handle passed through to the callback.
* format - The format of the data the callback will be giving. The format must
* be valid for the context.
* samplerate - The sample rate (frequency) of the stream
*
* Returns:
* An opaque handle used to control the opened stream, or NULL on error.
*
* See Also:
* <alureStreamSizeIsMicroSec>, <alureCreateStreamFromFile>,
* <alureCreateStreamFromMemory>, <alureCreateStreamFromStaticMemory>
*/
ALURE_API alureStream* ALURE_APIENTRY alureCreateStreamFromCallback(
ALuint (*callback)(void *userdata, ALubyte *data, ALuint bytes),
void *userdata, ALenum format, ALuint samplerate,
ALsizei chunkLength, ALsizei numBufs, ALuint *bufs)
{
if(alGetError() != AL_NO_ERROR)
{
SetError("Existing OpenAL error");
return NULL;
}
if(callback == NULL)
{
SetError("Invalid callback");
return NULL;
}
if(chunkLength < 0)
{
SetError("Invalid chunk length");
return NULL;
}
if(numBufs < 0)
{
SetError("Invalid buffer count");
return NULL;
}
UserCallbacks newcb;
newcb.open_file = NULL;
newcb.open_mem = NULL;
newcb.get_fmt = NULL;
newcb.decode = callback;
newcb.rewind = NULL;
newcb.close = NULL;
alureStream *stream = create_stream(userdata, format, samplerate, newcb);
return InitStream(stream, chunkLength, numBufs, bufs);
}
/* Function: alureGetStreamFrequency
*
* Retrieves the frequency used for the given stream.
*
* Returns:
* 0 on error.
*
* *Version Added*: 1.1
*/
ALURE_API ALsizei ALURE_APIENTRY alureGetStreamFrequency(alureStream *stream)
{
ALenum format;
ALuint rate, balign;
if(!alureStream::Verify(stream))
{
SetError("Invalid stream pointer");
return 0;
}
if(!stream->GetFormat(&format, &rate, &balign))
{
SetError("Could not get stream format");
return 0;
}
return rate;
}
/* Function: alureBufferDataFromStream
*
* Buffers the given buffer objects with the next chunks of data from the
* stream. The given buffer objects do not need to be ones given by the
* alureCreateStreamFrom* functions. Requires an active context.
*
* Returns:
* The number of buffers filled with new data, or -1 on error. If the value
* returned is less than the number requested, the end of the stream has been
* reached.
*/
ALURE_API ALsizei ALURE_APIENTRY alureBufferDataFromStream(alureStream *stream, ALsizei numBufs, ALuint *bufs)
{
if(alGetError() != AL_NO_ERROR)
{
SetError("Existing OpenAL error");
return -1;
}
if(!alureStream::Verify(stream))
{
SetError("Invalid stream pointer");
return -1;
}
if(numBufs < 0)
{
SetError("Invalid buffer count");
return -1;
}
ALenum format;
ALuint freq, blockAlign;
if(!stream->GetFormat(&format, &freq, &blockAlign))
{
SetError("Could not get stream format");
return -1;
}
ALsizei filled;
for(filled = 0;filled < numBufs;filled++)
{
ALuint got = stream->GetData(stream->dataChunk, stream->chunkLen);
got -= got%blockAlign;
if(got == 0) break;
alBufferData(bufs[filled], format, stream->dataChunk, got, freq);
if(alGetError() != AL_NO_ERROR)
{
SetError("Buffer load failed");
return -1;
}
}
return filled;
}
/* Function: alureRewindStream
*
* Rewinds the stream so that the next alureBufferDataFromStream call will
* restart from the beginning of the audio file.
*
* Returns:
* AL_FALSE on error.
*
* See Also:
* <alureSetStreamOrder>
*/
ALURE_API ALboolean ALURE_APIENTRY alureRewindStream(alureStream *stream)
{
if(!alureStream::Verify(stream))
{
SetError("Invalid stream pointer");
return AL_FALSE;
}
return stream->Rewind();
}
/* Function: alureSetStreamOrder
*
* Skips the module decoder to the specified order, so following buffering
* calls will decode from the specified order. For non-module formats, setting
* order 0 is identical to rewinding the stream (other orders will fail).
*
* Returns:
* AL_FALSE on error.
*
* *Version Added*: 1.1
*
* See Also:
* <alureRewindStream>
*/
ALURE_API ALboolean ALURE_APIENTRY alureSetStreamOrder(alureStream *stream, ALuint order)
{
if(!alureStream::Verify(stream))
{
SetError("Invalid stream pointer");
return AL_FALSE;
}
return stream->SetOrder(order);
}
/* Function: alureDestroyStream
*
* Closes an opened stream. For convenience, it will also delete the given
* buffer objects. The given buffer objects do not need to be ones given by the
* alureCreateStreamFrom* functions. Requires an active context.
*
* Returns:
* AL_FALSE on error.
*/
ALURE_API ALboolean ALURE_APIENTRY alureDestroyStream(alureStream *stream, ALsizei numBufs, ALuint *bufs)
{
if(alGetError() != AL_NO_ERROR)
{
SetError("Existing OpenAL error");
return AL_FALSE;
}
if(numBufs < 0)
{
SetError("Invalid buffer count");
return AL_FALSE;
}
if(stream && !alureStream::Verify(stream))
{
SetError("Invalid stream pointer");
return AL_FALSE;
}
alDeleteBuffers(numBufs, bufs);
if(alGetError() != AL_NO_ERROR)
{
SetError("Buffer deletion failed");
return AL_FALSE;
}
if(stream)
{
StopStream(stream);
std::istream *f = stream->fstream;
delete stream;
delete f;
}
return AL_TRUE;
}
}
<commit_msg>Make sure the stream's std::istream is handled properly when initializing<commit_after>/*
* ALURE OpenAL utility library
* Copyright (c) 2009 by Chris Robinson.
*
* 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.
*/
/* Title: Streaming */
#include "config.h"
#include "main.h"
#include <string.h>
#include <memory>
static bool SizeIsUS = false;
static alureStream *InitStream(alureStream *instream, ALsizei chunkLength, ALsizei numBufs, ALuint *bufs)
{
std::auto_ptr<std::istream> fstream(instream->fstream);
std::auto_ptr<alureStream> stream(instream);
ALenum format;
ALuint freq, blockAlign;
if(!stream->GetFormat(&format, &freq, &blockAlign))
{
SetError("Could not get stream format");
return NULL;
}
if(format == AL_NONE)
{
SetError("No valid format");
return NULL;
}
if(blockAlign == 0)
{
SetError("Invalid block size");
return NULL;
}
if(freq == 0)
{
SetError("Invalid sample rate");
return NULL;
}
alureUInt64 len64 = chunkLength;
if(SizeIsUS)
{
ALuint framesPerBlock = DetectCompressionRate(format);
if(framesPerBlock == 0)
{
SetError("Unknown compression rate");
return NULL;
}
len64 = len64 * freq / 1000000 / framesPerBlock * blockAlign;
if(len64 > 0xFFFFFFFF)
{
SetError("Chunk length too large");
return NULL;
}
}
chunkLength = len64 - (len64%blockAlign);
if(chunkLength <= 0)
{
SetError("Chunk length too small");
return NULL;
}
stream->chunkLen = chunkLength;
stream->dataChunk = new ALubyte[stream->chunkLen];
alGenBuffers(numBufs, bufs);
if(alGetError() != AL_NO_ERROR)
{
SetError("Buffer creation failed");
return NULL;
}
ALsizei filled;
for(filled = 0;filled < numBufs;filled++)
{
ALuint got = stream->GetData(stream->dataChunk, stream->chunkLen);
got -= got%blockAlign;
if(got == 0) break;
alBufferData(bufs[filled], format, stream->dataChunk, got, freq);
}
while(filled < numBufs)
{
alBufferData(bufs[filled], format, stream->dataChunk, 0, freq);
filled++;
}
if(alGetError() != AL_NO_ERROR)
{
alDeleteBuffers(numBufs, bufs);
alGetError();
SetError("Buffering error");
return NULL;
}
fstream.release();
return stream.release();
}
extern "C" {
/* Function: alureStreamSizeIsMicroSec
*
* Specifies if the chunk size value given to the alureCreateStream functions
* is in bytes (default) or microseconds. Specifying the size in microseconds
* can help manage the time needed in between needed updates (since the format
* and sample rate of the stream may not be known), while specifying the size
* in bytes can help control memory usage.
*
* Returns:
* Previously set value.
*
* *Version Added*: 1.1
*
* See Also:
* <alureCreateStreamFromFile>, <alureCreateStreamFromMemory>,
* <alureCreateStreamFromStaticMemory>, <alureCreateStreamFromCallback>
*/
ALURE_API ALboolean ALURE_APIENTRY alureStreamSizeIsMicroSec(ALboolean useUS)
{
ALboolean old = (SizeIsUS ? AL_TRUE : AL_FALSE);
SizeIsUS = !!useUS;
return old;
}
/* Function: alureCreateStreamFromFile
*
* Opens a file and sets it up for streaming. The given chunkLength is the
* number of bytes, or microseconds worth of bytes if
* <alureStreamSizeIsMicroSec> was last called with AL_TRUE, each buffer will
* fill with. ALURE will optionally generate the specified number of buffer
* objects, fill them with the beginning of the data, then place the new IDs
* into the provided storage, before returning. Requires an active context.
*
* Returns:
* An opaque handle used to control the opened stream, or NULL on error.
*
* See Also:
* <alureStreamSizeIsMicroSec>, <alureCreateStreamFromMemory>,
* <alureCreateStreamFromStaticMemory>, <alureCreateStreamFromCallback>
*/
ALURE_API alureStream* ALURE_APIENTRY alureCreateStreamFromFile(const ALchar *fname, ALsizei chunkLength, ALsizei numBufs, ALuint *bufs)
{
if(alGetError() != AL_NO_ERROR)
{
SetError("Existing OpenAL error");
return NULL;
}
if(chunkLength < 0)
{
SetError("Invalid chunk length");
return NULL;
}
if(numBufs < 0)
{
SetError("Invalid buffer count");
return NULL;
}
alureStream *stream = create_stream(fname);
if(!stream->IsValid())
{
delete stream;
return NULL;
}
return InitStream(stream, chunkLength, numBufs, bufs);
}
/* Function: alureCreateStreamFromMemory
*
* Opens a file image from memory and sets it up for streaming, similar to
* <alureCreateStreamFromFile>. The given data buffer can be safely deleted
* after calling this function. Requires an active context.
*
* Returns:
* An opaque handle used to control the opened stream, or NULL on error.
*
* See Also:
* <alureStreamSizeIsMicroSec>, <alureCreateStreamFromFile>,
* <alureCreateStreamFromStaticMemory>, <alureCreateStreamFromCallback>
*/
ALURE_API alureStream* ALURE_APIENTRY alureCreateStreamFromMemory(const ALubyte *fdata, ALuint length, ALsizei chunkLength, ALsizei numBufs, ALuint *bufs)
{
if(alGetError() != AL_NO_ERROR)
{
SetError("Existing OpenAL error");
return NULL;
}
if(chunkLength < 0)
{
SetError("Invalid chunk length");
return NULL;
}
if(numBufs < 0)
{
SetError("Invalid buffer count");
return NULL;
}
if(length <= 0)
{
SetError("Invalid data length");
return NULL;
}
ALubyte *streamData = new ALubyte[length];
memcpy(streamData, fdata, length);
MemDataInfo memData;
memData.Data = streamData;
memData.Length = length;
memData.Pos = 0;
alureStream *stream = create_stream(memData);
stream->data = streamData;
if(!stream->IsValid())
{
delete stream;
return NULL;
}
return InitStream(stream, chunkLength, numBufs, bufs);
}
/* Function: alureCreateStreamFromStaticMemory
*
* Identical to <alureCreateStreamFromMemory>, except the given memory is used
* directly and not duplicated. As a consequence, the data buffer must remain
* valid while the stream is alive. Requires an active context.
*
* Returns:
* An opaque handle used to control the opened stream, or NULL on error.
*
* See Also:
* <alureStreamSizeIsMicroSec>, <alureCreateStreamFromFile>,
* <alureCreateStreamFromMemory>, <alureCreateStreamFromCallback>
*/
ALURE_API alureStream* ALURE_APIENTRY alureCreateStreamFromStaticMemory(const ALubyte *fdata, ALuint length, ALsizei chunkLength, ALsizei numBufs, ALuint *bufs)
{
if(alGetError() != AL_NO_ERROR)
{
SetError("Existing OpenAL error");
return NULL;
}
if(chunkLength < 0)
{
SetError("Invalid chunk length");
return NULL;
}
if(numBufs < 0)
{
SetError("Invalid buffer count");
return NULL;
}
if(length <= 0)
{
SetError("Invalid data length");
return NULL;
}
MemDataInfo memData;
memData.Data = fdata;
memData.Length = length;
memData.Pos = 0;
alureStream *stream = create_stream(memData);
if(!stream->IsValid())
{
delete stream;
return NULL;
}
return InitStream(stream, chunkLength, numBufs, bufs);
}
/* Function: alureCreateStreamFromCallback
*
* Creates a stream using the specified callback to retrieve data. Requires an
* active context.
*
* Parameters:
* callback - This is called when more data is needed from the stream. Up to
* the specified number of bytes should be written to the data
* pointer, and the number of bytes actually written should be
* returned. The number of bytes written must be block aligned for
* the format (eg. a multiple of 4 for AL_FORMAT_STEREO16), or an
* OpenAL error may occur during buffering.
* userdata - A handle passed through to the callback.
* format - The format of the data the callback will be giving. The format must
* be valid for the context.
* samplerate - The sample rate (frequency) of the stream
*
* Returns:
* An opaque handle used to control the opened stream, or NULL on error.
*
* See Also:
* <alureStreamSizeIsMicroSec>, <alureCreateStreamFromFile>,
* <alureCreateStreamFromMemory>, <alureCreateStreamFromStaticMemory>
*/
ALURE_API alureStream* ALURE_APIENTRY alureCreateStreamFromCallback(
ALuint (*callback)(void *userdata, ALubyte *data, ALuint bytes),
void *userdata, ALenum format, ALuint samplerate,
ALsizei chunkLength, ALsizei numBufs, ALuint *bufs)
{
if(alGetError() != AL_NO_ERROR)
{
SetError("Existing OpenAL error");
return NULL;
}
if(callback == NULL)
{
SetError("Invalid callback");
return NULL;
}
if(chunkLength < 0)
{
SetError("Invalid chunk length");
return NULL;
}
if(numBufs < 0)
{
SetError("Invalid buffer count");
return NULL;
}
UserCallbacks newcb;
newcb.open_file = NULL;
newcb.open_mem = NULL;
newcb.get_fmt = NULL;
newcb.decode = callback;
newcb.rewind = NULL;
newcb.close = NULL;
alureStream *stream = create_stream(userdata, format, samplerate, newcb);
return InitStream(stream, chunkLength, numBufs, bufs);
}
/* Function: alureGetStreamFrequency
*
* Retrieves the frequency used for the given stream.
*
* Returns:
* 0 on error.
*
* *Version Added*: 1.1
*/
ALURE_API ALsizei ALURE_APIENTRY alureGetStreamFrequency(alureStream *stream)
{
ALenum format;
ALuint rate, balign;
if(!alureStream::Verify(stream))
{
SetError("Invalid stream pointer");
return 0;
}
if(!stream->GetFormat(&format, &rate, &balign))
{
SetError("Could not get stream format");
return 0;
}
return rate;
}
/* Function: alureBufferDataFromStream
*
* Buffers the given buffer objects with the next chunks of data from the
* stream. The given buffer objects do not need to be ones given by the
* alureCreateStreamFrom* functions. Requires an active context.
*
* Returns:
* The number of buffers filled with new data, or -1 on error. If the value
* returned is less than the number requested, the end of the stream has been
* reached.
*/
ALURE_API ALsizei ALURE_APIENTRY alureBufferDataFromStream(alureStream *stream, ALsizei numBufs, ALuint *bufs)
{
if(alGetError() != AL_NO_ERROR)
{
SetError("Existing OpenAL error");
return -1;
}
if(!alureStream::Verify(stream))
{
SetError("Invalid stream pointer");
return -1;
}
if(numBufs < 0)
{
SetError("Invalid buffer count");
return -1;
}
ALenum format;
ALuint freq, blockAlign;
if(!stream->GetFormat(&format, &freq, &blockAlign))
{
SetError("Could not get stream format");
return -1;
}
ALsizei filled;
for(filled = 0;filled < numBufs;filled++)
{
ALuint got = stream->GetData(stream->dataChunk, stream->chunkLen);
got -= got%blockAlign;
if(got == 0) break;
alBufferData(bufs[filled], format, stream->dataChunk, got, freq);
if(alGetError() != AL_NO_ERROR)
{
SetError("Buffer load failed");
return -1;
}
}
return filled;
}
/* Function: alureRewindStream
*
* Rewinds the stream so that the next alureBufferDataFromStream call will
* restart from the beginning of the audio file.
*
* Returns:
* AL_FALSE on error.
*
* See Also:
* <alureSetStreamOrder>
*/
ALURE_API ALboolean ALURE_APIENTRY alureRewindStream(alureStream *stream)
{
if(!alureStream::Verify(stream))
{
SetError("Invalid stream pointer");
return AL_FALSE;
}
return stream->Rewind();
}
/* Function: alureSetStreamOrder
*
* Skips the module decoder to the specified order, so following buffering
* calls will decode from the specified order. For non-module formats, setting
* order 0 is identical to rewinding the stream (other orders will fail).
*
* Returns:
* AL_FALSE on error.
*
* *Version Added*: 1.1
*
* See Also:
* <alureRewindStream>
*/
ALURE_API ALboolean ALURE_APIENTRY alureSetStreamOrder(alureStream *stream, ALuint order)
{
if(!alureStream::Verify(stream))
{
SetError("Invalid stream pointer");
return AL_FALSE;
}
return stream->SetOrder(order);
}
/* Function: alureDestroyStream
*
* Closes an opened stream. For convenience, it will also delete the given
* buffer objects. The given buffer objects do not need to be ones given by the
* alureCreateStreamFrom* functions. Requires an active context.
*
* Returns:
* AL_FALSE on error.
*/
ALURE_API ALboolean ALURE_APIENTRY alureDestroyStream(alureStream *stream, ALsizei numBufs, ALuint *bufs)
{
if(alGetError() != AL_NO_ERROR)
{
SetError("Existing OpenAL error");
return AL_FALSE;
}
if(numBufs < 0)
{
SetError("Invalid buffer count");
return AL_FALSE;
}
if(stream && !alureStream::Verify(stream))
{
SetError("Invalid stream pointer");
return AL_FALSE;
}
alDeleteBuffers(numBufs, bufs);
if(alGetError() != AL_NO_ERROR)
{
SetError("Buffer deletion failed");
return AL_FALSE;
}
if(stream)
{
StopStream(stream);
std::istream *f = stream->fstream;
delete stream;
delete f;
}
return AL_TRUE;
}
}
<|endoftext|>
|
<commit_before>#include<iostream>
#include<string.h>
#include<string>
#include<vector>
#include<sys/types.h>
#include<sys/wait.h>
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<cstring>
#include<boost/tokenizer.hpp>
#include<algorithm>
#include<iterator>
#include<sstream>
using namespace std;
using namespace boost;
void parse_line(char c_line[], char *command_line[]);
void run_line(char *command_line[]);
int main()
{
string str;
string arg = "";
while(1)
{
str = "";
char userName[100] = "";
if(getlogin_r(userName, sizeof(userName)-1) != 0) //Getting username, and returns null if cant be found
{
perror("Error getting username");
}
cout << '[' << userName << '@';
char hostName[100] = "";
if(gethostname(hostName, sizeof(hostName)-1) != 0) // Getting host name, returns numm if it cannot be found
{
perror("Error getting hostname");
}
cout << hostName << ']';
cout << "$";
getline(cin,str); //Gets a command
if(str == "exit") //If the command is exit the program stops
{
break;
}
if(str.size() != 0 && str.at(0) == '#')
{
str = "";
}
if(str != "")
{
for(unsigned i = 0; i < str.size(); i++)
{
if(str.at(i) == ';') //Looks for semicolons and adds a space in order to make parsing easier
{
str.insert(i, " ");
i++;
}
if(str.at(i) == '#') //Removes all part of the command after the comment
{
str = str.substr(0,i);
}
}
while(str.find(" ") != string::npos)
{
str.erase(str.find(" "));
}
if(str.at(str.size() - 1 ) == ' ')
{
str = str.substr(0,str.size()-1);
}
char c_line[64];
char *command_line[64];
strcpy(c_line,str.c_str());
c_line[str.size()] = '\0';
parse_line(c_line, command_line);
run_line(command_line);
}
}
return 0;
}
int k = 0;
void parse_line(char c_line[], char *command_line[])
{
while(*c_line != '\0')
{
while(*c_line == ' ' || *c_line == '\n' || *c_line == '\t')
{
*c_line++ = '\0';
}
if(*c_line == ';')
{
run_line(command_line);
//for(int i = 0; i < 64; i++)
//{
// command_line[i] = new char[16];
//}
//command_line = new char*[64];
//for(int i = 0; i < 64; i++)
//{
// delete [] command_line[i];
//}
//delete [] command_line;
c_line++;
}
*command_line++ = c_line;
while(*c_line != '\0' && *c_line != ' ' && *c_line != '\n' && *c_line != '\t')
{
c_line++;
}
*command_line = '\0';
}
return;
}
void run_line(char *command_line[])
{
pid_t pid;
int status;
if((pid = fork()) < 0)
{
perror("forking failed");
}
else if(pid == 0)
{
if(execvp(*command_line,command_line) < 0)
{
perror("execvp failed");
exit(1);
}
}
else
{
while(wait(&status) != pid)
;
}
return;
}
<commit_msg>tried to fix rshell.cpp<commit_after>#include<iostream>
#include<string.h>
#include<string>
#include<vector>
#include<sys/types.h>
#include<sys/wait.h>
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<cstring>
#include<boost/tokenizer.hpp>
#include<algorithm>
#include<iterator>
#include<sstream>
using namespace std;
using namespace boost;
void parse_line(char c_line[], char *command_line[]);
void run_line(char *command_line[]);
int main()
{
string str;
string arg = "";
while(1)
{
str = "";
char userName[100] = "";
if(getlogin_r(userName, sizeof(userName)-1) != 0) //Getting username, and returns null if cant be found
{
perror("Error getting username");
}
cout << '[' << userName << '@';
char hostName[100] = "";
if(gethostname(hostName, sizeof(hostName)-1) != 0) // Getting host name, returns numm if it cannot be found
{
perror("Error getting hostname");
}
cout << hostName << ']';
cout << "$";
getline(cin,str); //Gets a command
if(str == "exit") //If the command is exit the program stops
{
break;
}
if(str.size() != 0 && str.at(0) == '#')
{
str = "";
}
if(str != "")
{
for(unsigned i = 0; i < str.size(); i++)
{
if(str.at(i) == ';') //Looks for semicolons and adds a space in order to make parsing easier
{
str.insert(i, " ");
i++;
}
if(str.at(i) == '#') //Removes all part of the command after the comment
{
str = str.substr(0,i);
}
}
while(str.find(' ') != string::npos)
{
str.erase(str.find(" ") + 1);
}
if(str.at(str.size() - 1 ) == ' ')
{
str = str.substr(0,str.size()-1);
}
char c_line[100];
char *command_line[64];
strcpy(c_line,str.c_str());
c_line[str.size()] = '\0';
parse_line(c_line, command_line);
run_line(command_line);
}
}
return 0;
}
void parse_line(char c_line[], char *command_line[])
{
while(*c_line != '\0')
{
while(*c_line == ' ' || *c_line == '\n' || *c_line == '\t')
{
*c_line++ = '\0';
}
if(*c_line == ';')
{
run_line(command_line);
//for(int i = 0; i < 64; i++)
//{
// command_line[i] = new char[16];
//}
//command_line = new char*[64];
//for(int i = 0; i < 64; i++)
//{
// delete [] command_line[i];
//}
//delete [] command_line;
c_line++;
}
*command_line++ = c_line;
while(*c_line != '\0' && *c_line != ' ' && *c_line != '\n' && *c_line != '\t')
{
c_line++;
}
*command_line = '\0';
}
return;
}
void run_line(char *command_line[])
{
pid_t pid;
int status;
if((pid = fork()) < 0)
{
perror("forking failed");
}
else if(pid == 0)
{
if(execvp(*command_line,command_line) < 0)
{
perror("execvp failed");
exit(1);
}
}
else
{
while(wait(&status) != pid)
;
}
return;
}
<|endoftext|>
|
<commit_before>/*
***********************************************************************************************************************
*
* Copyright (c) 2016-2021 Advanced Micro Devices, Inc. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
**********************************************************************************************************************/
/*
***********************************************************************************************************************
*
* Copyright (c) 2021 Google LLC. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
**********************************************************************************************************************/
/**
***********************************************************************************************************************
* @file llpcCompilationUtils.cpp
* @brief LLPC source file: contains the implementation LLPC pipeline compilation logic for standalone LLPC compilers.
***********************************************************************************************************************
*/
#ifdef WIN_OS
// NOTE: Disable Windows-defined min()/max() because we use STL-defined std::min()/std::max() in LLPC.
#define NOMINMAX
#endif
#include "llpcPipelineBuilder.h"
#include "llpcAutoLayout.h"
#include "llpcDebug.h"
#include "llpcInputUtils.h"
#include "vkgcUtil.h"
#include "llvm/ADT/ScopeExit.h"
#include "llvm/ADT/StringExtras.h"
using namespace llvm;
using namespace Vkgc;
namespace Llpc {
namespace StandaloneCompiler {
// =====================================================================================================================
// Returns true iff the compiled pipeline is a graphics pipeline.
//
// @returns : True if the compiled pipeline is a graphics pipeline, false if compute.
bool PipelineBuilder::isGraphicsPipeline() const {
return (m_compileInfo.stageMask & (shaderStageToMask(ShaderStageCompute) - 1)) != 0;
}
// =====================================================================================================================
// Builds pipeline using the provided build info and performs linking.
//
// @returns : Result::Success on success, other status on failure.
Result PipelineBuilder::build() {
llvm::SmallVector<BinaryData, 1> pipelines;
pipelines.push_back(BinaryData());
pipelines[0] = {};
const bool isGraphics = isGraphicsPipeline();
if (isGraphics) {
Result result = buildGraphicsPipeline(pipelines[0]);
if (result != Result::Success)
return result;
} else {
Result result = buildComputePipeline(pipelines[0]);
if (result != Result::Success)
return result;
}
for (const auto &pipeline : pipelines) {
decodePipelineBinary(&pipeline, &m_compileInfo, isGraphics);
}
return Result::Success;
}
// =====================================================================================================================
// Build the graphics pipeline.
//
// @param [in/out] outBinaryData : The compiled pipeline. The caller must value-initialize this parameter.
// @returns : Result::Success on success, other status on failure.
Result PipelineBuilder::buildGraphicsPipeline(BinaryData &outBinaryData) {
GraphicsPipelineBuildInfo *pipelineInfo = &m_compileInfo.gfxPipelineInfo;
GraphicsPipelineBuildOut *pipelineOut = &m_compileInfo.gfxPipelineOut;
// Fill pipeline shader info.
PipelineShaderInfo *shaderInfos[ShaderStageGfxCount] = {
&pipelineInfo->vs, &pipelineInfo->tcs, &pipelineInfo->tes, &pipelineInfo->gs, &pipelineInfo->fs,
};
ResourceMappingNodeMap nodeSets;
unsigned pushConstSize = 0;
for (StandaloneCompiler::ShaderModuleData &moduleData : m_compileInfo.shaderModuleDatas) {
const ShaderStage stage = moduleData.shaderStage;
PipelineShaderInfo *shaderInfo = shaderInfos[stage];
const ShaderModuleBuildOut *shaderOut = &moduleData.shaderOut;
// If entry target is not specified, use the one from command line option.
if (!shaderInfo->pEntryTarget)
shaderInfo->pEntryTarget = m_compileInfo.entryTarget.c_str();
shaderInfo->pModuleData = shaderOut->pModuleData;
shaderInfo->entryStage = stage;
// If not compiling from pipeline, lay out user data now.
if (m_compileInfo.doAutoLayout)
doAutoLayoutDesc(stage, moduleData.spirvBin, pipelineInfo, shaderInfo, nodeSets, pushConstSize,
/*autoLayoutDesc = */ m_compileInfo.autoLayoutDesc);
}
if (m_compileInfo.doAutoLayout)
buildTopLevelMapping(m_compileInfo.stageMask, nodeSets, pushConstSize, &pipelineInfo->resourceMapping,
m_compileInfo.autoLayoutDesc);
pipelineInfo->pInstance = nullptr; // Placeholder, unused.
pipelineInfo->pUserData = &m_compileInfo.pipelineBuf;
pipelineInfo->pfnOutputAlloc = allocateBuffer;
pipelineInfo->unlinked = m_compileInfo.unlinked;
// NOTE: If number of patch control points is not specified, we set it to 3.
if (pipelineInfo->iaState.patchControlPoints == 0)
pipelineInfo->iaState.patchControlPoints = 3;
pipelineInfo->options.robustBufferAccess = m_compileInfo.robustBufferAccess;
pipelineInfo->options.enableRelocatableShaderElf = m_compileInfo.relocatableShaderElf;
pipelineInfo->options.scalarBlockLayout = m_compileInfo.scalarBlockLayout;
pipelineInfo->options.enableScratchAccessBoundsChecks = m_compileInfo.scratchAccessBoundsChecks;
PipelineBuildInfo localPipelineInfo = {};
localPipelineInfo.pGraphicsInfo = pipelineInfo;
void *pipelineDumpHandle = runPreBuildActions(localPipelineInfo);
auto onExit = make_scope_exit([&] { runPostBuildActions(pipelineDumpHandle, outBinaryData); });
Result result = m_compiler.BuildGraphicsPipeline(pipelineInfo, pipelineOut, pipelineDumpHandle);
if (result != Result::Success)
return result;
outBinaryData = pipelineOut->pipelineBin;
return Result::Success;
}
// =====================================================================================================================
// Build the compute pipeline.
//
// @param [in/out] outBinaryData : The compiled pipeline. The caller must value-initialize this parameter.
// @returns : Result::Success on success, other status on failure.
Result PipelineBuilder::buildComputePipeline(BinaryData &outBinaryData) {
assert(m_compileInfo.shaderModuleDatas.size() == 1);
assert(m_compileInfo.shaderModuleDatas[0].shaderStage == ShaderStageCompute);
ComputePipelineBuildInfo *pipelineInfo = &m_compileInfo.compPipelineInfo;
ComputePipelineBuildOut *pipelineOut = &m_compileInfo.compPipelineOut;
PipelineShaderInfo *shaderInfo = &pipelineInfo->cs;
const ShaderModuleBuildOut *shaderOut = &m_compileInfo.shaderModuleDatas[0].shaderOut;
// If entry target is not specified, use the one from command line option.
if (!shaderInfo->pEntryTarget)
shaderInfo->pEntryTarget = m_compileInfo.entryTarget.c_str();
shaderInfo->entryStage = ShaderStageCompute;
shaderInfo->pModuleData = shaderOut->pModuleData;
// If not compiling from pipeline, lay out user data now.
if (m_compileInfo.doAutoLayout) {
ResourceMappingNodeMap nodeSets;
unsigned pushConstSize = 0;
doAutoLayoutDesc(ShaderStageCompute, m_compileInfo.shaderModuleDatas[0].spirvBin, nullptr, shaderInfo, nodeSets,
pushConstSize, /*autoLayoutDesc =*/m_compileInfo.autoLayoutDesc);
buildTopLevelMapping(ShaderStageComputeBit, nodeSets, pushConstSize, &pipelineInfo->resourceMapping,
m_compileInfo.autoLayoutDesc);
}
pipelineInfo->pInstance = nullptr; // Placeholder, unused.
pipelineInfo->pUserData = &m_compileInfo.pipelineBuf;
pipelineInfo->pfnOutputAlloc = allocateBuffer;
pipelineInfo->unlinked = m_compileInfo.unlinked;
pipelineInfo->options.robustBufferAccess = m_compileInfo.robustBufferAccess;
pipelineInfo->options.enableRelocatableShaderElf = m_compileInfo.relocatableShaderElf;
pipelineInfo->options.scalarBlockLayout = m_compileInfo.scalarBlockLayout;
pipelineInfo->options.enableScratchAccessBoundsChecks = m_compileInfo.scratchAccessBoundsChecks;
PipelineBuildInfo localPipelineInfo = {};
localPipelineInfo.pComputeInfo = pipelineInfo;
void *pipelineDumpHandle = runPreBuildActions(localPipelineInfo);
auto onExit = make_scope_exit([&] { runPostBuildActions(pipelineDumpHandle, outBinaryData); });
Result result = m_compiler.BuildComputePipeline(pipelineInfo, pipelineOut, pipelineDumpHandle);
if (result != Result::Success)
return result;
outBinaryData = pipelineOut->pipelineBin;
return Result::Success;
}
// =====================================================================================================================
// Runs pre-compilation actions: starts a pipeline dump (if requested) and prints pipeline info (if requested).
// The caller must call `runPostBuildActions` after calling this function to perform the necessary cleanup.
//
// @param buildInfo : Build info of the pipeline.
// @returns : Handle to the started pipeline dump, nullptr if pipeline dump was not started.
void *PipelineBuilder::runPreBuildActions(PipelineBuildInfo buildInfo) {
void *pipelineDumpHandle = nullptr;
if (shouldDumpPipelines())
pipelineDumpHandle = IPipelineDumper::BeginPipelineDump(m_dumpOptions.getPointer(), buildInfo);
if (m_printPipelineInfo)
printPipelineInfo(buildInfo);
return pipelineDumpHandle;
}
// =====================================================================================================================
// Runs post-compilation actions: finalizes the pipeline dump, if started. Must be called after `runPreBuildActions`.
//
// @param pipelineDumpHandle : Handle to the started pipeline dump.
// @param pipeline : The compiled pipeline.
void PipelineBuilder::runPostBuildActions(void *pipelineDumpHandle, BinaryData pipeline) {
if (!pipelineDumpHandle)
return;
if (pipeline.pCode)
IPipelineDumper::DumpPipelineBinary(pipelineDumpHandle, m_compileInfo.gfxIp, &pipeline);
IPipelineDumper::EndPipelineDump(pipelineDumpHandle);
}
// =====================================================================================================================
// Prints pipeline dump hash code and filenames. Can be called before pipeline compilation.
//
// @param buildInfo : Build info of the pipeline.
void PipelineBuilder::printPipelineInfo(PipelineBuildInfo buildInfo) {
uint64_t hash = 0;
if (isGraphicsPipeline())
hash = IPipelineDumper::GetPipelineHash(buildInfo.pGraphicsInfo);
else
hash = IPipelineDumper::GetPipelineHash(buildInfo.pComputeInfo);
LLPC_OUTS("LLPC PipelineHash: " << format("0x%016" PRIX64, hash) << " Files: " << join(m_compileInfo.fileNames, " ")
<< "\n");
}
} // namespace StandaloneCompiler
} // namespace Llpc
<commit_msg>Address review points<commit_after>/*
***********************************************************************************************************************
*
* Copyright (c) 2016-2021 Advanced Micro Devices, Inc. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
**********************************************************************************************************************/
/*
***********************************************************************************************************************
*
* Copyright (c) 2021 Google LLC. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
**********************************************************************************************************************/
/**
***********************************************************************************************************************
* @file llpcCompilationUtils.cpp
* @brief LLPC source file: contains the implementation LLPC pipeline compilation logic for standalone LLPC compilers.
***********************************************************************************************************************
*/
#ifdef WIN_OS
// NOTE: Disable Windows-defined min()/max() because we use STL-defined std::min()/std::max() in LLPC.
#define NOMINMAX
#endif
#include "llpcPipelineBuilder.h"
#include "llpcAutoLayout.h"
#include "llpcDebug.h"
#include "llpcInputUtils.h"
#include "vkgcUtil.h"
#include "llvm/ADT/ScopeExit.h"
#include "llvm/ADT/StringExtras.h"
using namespace llvm;
using namespace Vkgc;
namespace Llpc {
namespace StandaloneCompiler {
// =====================================================================================================================
// Returns true iff the compiled pipeline is a graphics pipeline.
//
// @returns : True if the compiled pipeline is a graphics pipeline, false if compute.
bool PipelineBuilder::isGraphicsPipeline() const {
return (m_compileInfo.stageMask & (shaderStageToMask(ShaderStageCompute) - 1)) != 0;
}
// =====================================================================================================================
// Builds pipeline using the provided build info and performs linking.
//
// @returns : Result::Success on success, other status on failure.
Result PipelineBuilder::build() {
// Use vector of BinaryData for future pipeline type
SmallVector<BinaryData, 1> pipelines;
pipelines.push_back({});
const bool isGraphics = isGraphicsPipeline();
if (isGraphics) {
Result result = buildGraphicsPipeline(pipelines[0]);
if (result != Result::Success)
return result;
} else {
Result result = buildComputePipeline(pipelines[0]);
if (result != Result::Success)
return result;
}
for (const auto &pipeline : pipelines) {
auto result = decodePipelineBinary(&pipeline, &m_compileInfo, isGraphics);
if (result != Result::Success)
return result;
}
return Result::Success;
}
// =====================================================================================================================
// Build the graphics pipeline.
//
// @param [in/out] outBinaryData : The compiled pipeline. The caller must value-initialize this parameter.
// @returns : Result::Success on success, other status on failure.
Result PipelineBuilder::buildGraphicsPipeline(BinaryData &outBinaryData) {
GraphicsPipelineBuildInfo *pipelineInfo = &m_compileInfo.gfxPipelineInfo;
GraphicsPipelineBuildOut *pipelineOut = &m_compileInfo.gfxPipelineOut;
// Fill pipeline shader info.
PipelineShaderInfo *shaderInfos[ShaderStageGfxCount] = {
&pipelineInfo->vs, &pipelineInfo->tcs, &pipelineInfo->tes, &pipelineInfo->gs, &pipelineInfo->fs,
};
ResourceMappingNodeMap nodeSets;
unsigned pushConstSize = 0;
for (StandaloneCompiler::ShaderModuleData &moduleData : m_compileInfo.shaderModuleDatas) {
const ShaderStage stage = moduleData.shaderStage;
PipelineShaderInfo *shaderInfo = shaderInfos[stage];
const ShaderModuleBuildOut *shaderOut = &moduleData.shaderOut;
// If entry target is not specified, use the one from command line option.
if (!shaderInfo->pEntryTarget)
shaderInfo->pEntryTarget = m_compileInfo.entryTarget.c_str();
shaderInfo->pModuleData = shaderOut->pModuleData;
shaderInfo->entryStage = stage;
// If not compiling from pipeline, lay out user data now.
if (m_compileInfo.doAutoLayout)
doAutoLayoutDesc(stage, moduleData.spirvBin, pipelineInfo, shaderInfo, nodeSets, pushConstSize,
/*autoLayoutDesc = */ m_compileInfo.autoLayoutDesc);
}
if (m_compileInfo.doAutoLayout)
buildTopLevelMapping(m_compileInfo.stageMask, nodeSets, pushConstSize, &pipelineInfo->resourceMapping,
m_compileInfo.autoLayoutDesc);
pipelineInfo->pInstance = nullptr; // Placeholder, unused.
pipelineInfo->pUserData = &m_compileInfo.pipelineBuf;
pipelineInfo->pfnOutputAlloc = allocateBuffer;
pipelineInfo->unlinked = m_compileInfo.unlinked;
// NOTE: If number of patch control points is not specified, we set it to 3.
if (pipelineInfo->iaState.patchControlPoints == 0)
pipelineInfo->iaState.patchControlPoints = 3;
pipelineInfo->options.robustBufferAccess = m_compileInfo.robustBufferAccess;
pipelineInfo->options.enableRelocatableShaderElf = m_compileInfo.relocatableShaderElf;
pipelineInfo->options.scalarBlockLayout = m_compileInfo.scalarBlockLayout;
pipelineInfo->options.enableScratchAccessBoundsChecks = m_compileInfo.scratchAccessBoundsChecks;
PipelineBuildInfo localPipelineInfo = {};
localPipelineInfo.pGraphicsInfo = pipelineInfo;
void *pipelineDumpHandle = runPreBuildActions(localPipelineInfo);
auto onExit = make_scope_exit([&] { runPostBuildActions(pipelineDumpHandle, outBinaryData); });
Result result = m_compiler.BuildGraphicsPipeline(pipelineInfo, pipelineOut, pipelineDumpHandle);
if (result != Result::Success)
return result;
outBinaryData = pipelineOut->pipelineBin;
return Result::Success;
}
// =====================================================================================================================
// Build the compute pipeline.
//
// @param [in/out] outBinaryData : The compiled pipeline. The caller must value-initialize this parameter.
// @returns : Result::Success on success, other status on failure.
Result PipelineBuilder::buildComputePipeline(BinaryData &outBinaryData) {
assert(m_compileInfo.shaderModuleDatas.size() == 1);
assert(m_compileInfo.shaderModuleDatas[0].shaderStage == ShaderStageCompute);
ComputePipelineBuildInfo *pipelineInfo = &m_compileInfo.compPipelineInfo;
ComputePipelineBuildOut *pipelineOut = &m_compileInfo.compPipelineOut;
PipelineShaderInfo *shaderInfo = &pipelineInfo->cs;
const ShaderModuleBuildOut *shaderOut = &m_compileInfo.shaderModuleDatas[0].shaderOut;
// If entry target is not specified, use the one from command line option.
if (!shaderInfo->pEntryTarget)
shaderInfo->pEntryTarget = m_compileInfo.entryTarget.c_str();
shaderInfo->entryStage = ShaderStageCompute;
shaderInfo->pModuleData = shaderOut->pModuleData;
// If not compiling from pipeline, lay out user data now.
if (m_compileInfo.doAutoLayout) {
ResourceMappingNodeMap nodeSets;
unsigned pushConstSize = 0;
doAutoLayoutDesc(ShaderStageCompute, m_compileInfo.shaderModuleDatas[0].spirvBin, nullptr, shaderInfo, nodeSets,
pushConstSize, /*autoLayoutDesc =*/m_compileInfo.autoLayoutDesc);
buildTopLevelMapping(ShaderStageComputeBit, nodeSets, pushConstSize, &pipelineInfo->resourceMapping,
m_compileInfo.autoLayoutDesc);
}
pipelineInfo->pInstance = nullptr; // Placeholder, unused.
pipelineInfo->pUserData = &m_compileInfo.pipelineBuf;
pipelineInfo->pfnOutputAlloc = allocateBuffer;
pipelineInfo->unlinked = m_compileInfo.unlinked;
pipelineInfo->options.robustBufferAccess = m_compileInfo.robustBufferAccess;
pipelineInfo->options.enableRelocatableShaderElf = m_compileInfo.relocatableShaderElf;
pipelineInfo->options.scalarBlockLayout = m_compileInfo.scalarBlockLayout;
pipelineInfo->options.enableScratchAccessBoundsChecks = m_compileInfo.scratchAccessBoundsChecks;
PipelineBuildInfo localPipelineInfo = {};
localPipelineInfo.pComputeInfo = pipelineInfo;
void *pipelineDumpHandle = runPreBuildActions(localPipelineInfo);
auto onExit = make_scope_exit([&] { runPostBuildActions(pipelineDumpHandle, outBinaryData); });
Result result = m_compiler.BuildComputePipeline(pipelineInfo, pipelineOut, pipelineDumpHandle);
if (result != Result::Success)
return result;
outBinaryData = pipelineOut->pipelineBin;
return Result::Success;
}
// =====================================================================================================================
// Runs pre-compilation actions: starts a pipeline dump (if requested) and prints pipeline info (if requested).
// The caller must call `runPostBuildActions` after calling this function to perform the necessary cleanup.
//
// @param buildInfo : Build info of the pipeline.
// @returns : Handle to the started pipeline dump, nullptr if pipeline dump was not started.
void *PipelineBuilder::runPreBuildActions(PipelineBuildInfo buildInfo) {
void *pipelineDumpHandle = nullptr;
if (shouldDumpPipelines())
pipelineDumpHandle = IPipelineDumper::BeginPipelineDump(m_dumpOptions.getPointer(), buildInfo);
if (m_printPipelineInfo)
printPipelineInfo(buildInfo);
return pipelineDumpHandle;
}
// =====================================================================================================================
// Runs post-compilation actions: finalizes the pipeline dump, if started. Must be called after `runPreBuildActions`.
//
// @param pipelineDumpHandle : Handle to the started pipeline dump.
// @param pipeline : The compiled pipeline.
void PipelineBuilder::runPostBuildActions(void *pipelineDumpHandle, BinaryData pipeline) {
if (!pipelineDumpHandle)
return;
if (pipeline.pCode)
IPipelineDumper::DumpPipelineBinary(pipelineDumpHandle, m_compileInfo.gfxIp, &pipeline);
IPipelineDumper::EndPipelineDump(pipelineDumpHandle);
}
// =====================================================================================================================
// Prints pipeline dump hash code and filenames. Can be called before pipeline compilation.
//
// @param buildInfo : Build info of the pipeline.
void PipelineBuilder::printPipelineInfo(PipelineBuildInfo buildInfo) {
uint64_t hash = 0;
if (isGraphicsPipeline())
hash = IPipelineDumper::GetPipelineHash(buildInfo.pGraphicsInfo);
else
hash = IPipelineDumper::GetPipelineHash(buildInfo.pComputeInfo);
LLPC_OUTS("LLPC PipelineHash: " << format("0x%016" PRIX64, hash) << " Files: " << join(m_compileInfo.fileNames, " ")
<< "\n");
}
} // namespace StandaloneCompiler
} // namespace Llpc
<|endoftext|>
|
<commit_before>// largest_palindrome_product.cpp : algorithm to find the largest palindrome product
//
// Copyright (C) 2017-2020 Stillwater Supercomputing, Inc.
//
// This file is part of the universal numbers project, which is released under an MIT Open Source license.
#include <iostream>
#include <universal/integer/integer.hpp>
/*
* A palinddrome number reads the same both ways. The largest palindrome made from the product
* of two 2-digit numbers is 9009 = 91 x 99.
*
* Find the largest palindrome made from the product of two n-digit numbers.
*/
template<size_t nbits>
bool Largest2DigitPalindromeProduct() {
using namespace std;
using namespace sw::unum;
using Integer = integer<nbits>;
using Real = long double;
int nrOfSteps = 0;
// construct palindromes starting from the largest descending to the smallest
for (Integer i = 9; i >= 0; --i) {
for (Integer j = 9; j >= 0; --j) {
// construct the palindrome
Integer palindrome = (i * 1000) + (j * 100) + (j * 10) + i;
// cout << palindrome << endl;
// generate guidance on the scale of the product terms
Real squareRoot = std::sqrt((long double)palindrome);
// cout << "sqrt guidance is " << squareRoot << endl;
Integer a, b, c;
a = squareRoot;
while (a < 100) {
b = palindrome / a;
if ((palindrome % a) == 0 && b < 100) {
cout << "In step " << nrOfSteps << " found largest 2-digit palindrome product: " << a << " * " << b << " = " << palindrome << " check product: " << a * b << endl;
return true;
}
else {
++a;
++nrOfSteps;
}
}
}
}
return false; // didn't find a solution
}
template<size_t nbits>
bool Largest3DigitPalindromeProduct() {
using namespace std;
using namespace sw::unum;
using Integer = integer<nbits>;
using Real = long double;
int nrOfSteps = 0;
// construct palindromes starting from the largest descending to the smallest
for (Integer i = 9; i >= 0; --i) {
for (Integer j = 9; j >= 0; --j) {
for (Integer k = 9; k >= 0; --k) {
// construct the palindrome
Integer palindrome = (i * 100000) + (j * 10000) + (k * 1000) + (k * 100) + (j * 10) + i;
// cout << palindrome << endl;
// generate guidance on the scale of the product terms
Real squareRoot = std::sqrt((long double)palindrome);
// cout << "sqrt guidance is " << squareRoot << endl;
Integer a, b, c;
a = squareRoot;
while (a < 1000) {
b = palindrome / a;
if ((palindrome % a) == 0 && b < 1000) {
cout << "In step " << nrOfSteps << " found largest 3-digit palindrome product: " << a << " * " << b << " = " << palindrome << " check product: " << a * b << endl;
return true;
}
else {
++a;
++nrOfSteps;
}
}
}
}
}
return false; // didn't find a solution
}
template<size_t nbits>
bool Largest4DigitPalindromeProduct() {
using namespace std;
using namespace sw::unum;
using Integer = integer<nbits>;
using Real = long double;
int nrOfSteps = 0;
// construct palindromes starting from the largest descending to the smallest
for (Integer i = 9; i >= 0; --i) {
for (Integer j = 9; j >= 0; --j) {
for (Integer k = 9; k >= 0; --k) {
for (Integer m = 9; m >= 0; --m) {
// construct the palindrome
Integer palindrome = (i * 10000000) + (j * 1000000) + (k * 100000) + (m * 10000) + (m * 1000) + (k * 100) + (j * 10) + i;
// cout << palindrome << endl;
// generate guidance on the scale of the product terms
Real squareRoot = std::sqrt((long double)palindrome);
// cout << "sqrt guidance is " << squareRoot << endl;
Integer a, b;
a = squareRoot;
while (a < 10000) {
b = palindrome / a;
if ((palindrome % a) == 0 && b < 10000) {
cout << "In step " << nrOfSteps << " found largest 4-digit palindrome product: " << a << " * " << b << " = " << palindrome << " check product: " << a * b << endl;
return true;
}
else {
++a;
++nrOfSteps;
}
}
}
}
}
}
return false; // didn't find a solution
}
template<size_t nbits>
bool Largest5DigitPalindromeProduct() {
using namespace std;
using namespace sw::unum;
using Integer = integer<nbits>;
using Real = long double;
int nrOfSteps = 0;
// construct palindromes starting from the largest descending to the smallest
for (Integer i = 9; i >= 0; --i) {
for (Integer j = 9; j >= 0; --j) {
for (Integer k = 9; k >= 0; --k) {
for (Integer m = 9; m >= 0; --m) {
for (Integer n = 9; n >= 0; --n) {
// construct the palindrome
Integer palindrome = (i * 1000000000) + (j * 100000000) + (k * 10000000) + (m * 1000000) + (n * 100000) + (n * 10000) + (m * 1000) + (k * 100) + (j * 10) + i;
// cout << palindrome << endl;
// generate guidance on the scale of the product terms
Real squareRoot = std::sqrt((long double)palindrome);
// cout << "sqrt guidance is " << squareRoot << endl;
Integer a, b;
a = squareRoot;
while (a < 10000) {
b = palindrome / a;
if ((palindrome % a) == 0 && b < 10000) {
cout << "In step " << nrOfSteps << " found largest 5-digit palindrome product: " << a << " * " << b << " = " << palindrome << " check product: " << a * b << endl;
return true;
}
else {
++a;
++nrOfSteps;
}
}
}
}
}
}
}
return false; // didn't find a solution
}
int main()
try {
using namespace std;
using namespace sw::unum;
constexpr size_t nbits = 32;
using Integer = integer<nbits>;
using Real = long double;
Largest2DigitPalindromeProduct<nbits>();
Largest3DigitPalindromeProduct<nbits>();
Largest4DigitPalindromeProduct<nbits>();
Largest5DigitPalindromeProduct<nbits>();
return EXIT_SUCCESS;
}
catch (char const* msg) {
std::cerr << msg << std::endl;
return EXIT_FAILURE;
}
catch (const std::runtime_error& err) {
std::cerr << "Uncaught runtime exception: " << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (...) {
std::cerr << "Caught unknown exception" << std::endl;
return EXIT_FAILURE;
}
<commit_msg>compilation fix for g++<commit_after>// largest_palindrome_product.cpp : algorithm to find the largest palindrome product
//
// Copyright (C) 2017-2020 Stillwater Supercomputing, Inc.
//
// This file is part of the universal numbers project, which is released under an MIT Open Source license.
#include <iostream>
#include <cmath>
#include <universal/integer/integer.hpp>
/*
* A palinddrome number reads the same both ways. The largest palindrome made from the product
* of two 2-digit numbers is 9009 = 91 x 99.
*
* Find the largest palindrome made from the product of two n-digit numbers.
*/
template<size_t nbits>
bool Largest2DigitPalindromeProduct() {
using namespace std;
using namespace sw::unum;
using Integer = integer<nbits>;
using Real = long double;
int nrOfSteps = 0;
// construct palindromes starting from the largest descending to the smallest
for (Integer i = 9; i >= 0; --i) {
for (Integer j = 9; j >= 0; --j) {
// construct the palindrome
Integer palindrome = (i * 1000) + (j * 100) + (j * 10) + i;
// cout << palindrome << endl;
// generate guidance on the scale of the product terms
Real squareRoot = std::sqrt((long double)palindrome);
// cout << "sqrt guidance is " << squareRoot << endl;
Integer a, b, c;
a = squareRoot;
while (a < 100) {
b = palindrome / a;
if ((palindrome % a) == 0 && b < 100) {
cout << "In step " << nrOfSteps << " found largest 2-digit palindrome product: " << a << " * " << b << " = " << palindrome << " check product: " << a * b << endl;
return true;
}
else {
++a;
++nrOfSteps;
}
}
}
}
return false; // didn't find a solution
}
template<size_t nbits>
bool Largest3DigitPalindromeProduct() {
using namespace std;
using namespace sw::unum;
using Integer = integer<nbits>;
using Real = long double;
int nrOfSteps = 0;
// construct palindromes starting from the largest descending to the smallest
for (Integer i = 9; i >= 0; --i) {
for (Integer j = 9; j >= 0; --j) {
for (Integer k = 9; k >= 0; --k) {
// construct the palindrome
Integer palindrome = (i * 100000) + (j * 10000) + (k * 1000) + (k * 100) + (j * 10) + i;
// cout << palindrome << endl;
// generate guidance on the scale of the product terms
Real squareRoot = std::sqrt((long double)palindrome);
// cout << "sqrt guidance is " << squareRoot << endl;
Integer a, b, c;
a = squareRoot;
while (a < 1000) {
b = palindrome / a;
if ((palindrome % a) == 0 && b < 1000) {
cout << "In step " << nrOfSteps << " found largest 3-digit palindrome product: " << a << " * " << b << " = " << palindrome << " check product: " << a * b << endl;
return true;
}
else {
++a;
++nrOfSteps;
}
}
}
}
}
return false; // didn't find a solution
}
template<size_t nbits>
bool Largest4DigitPalindromeProduct() {
using namespace std;
using namespace sw::unum;
using Integer = integer<nbits>;
using Real = long double;
int nrOfSteps = 0;
// construct palindromes starting from the largest descending to the smallest
for (Integer i = 9; i >= 0; --i) {
for (Integer j = 9; j >= 0; --j) {
for (Integer k = 9; k >= 0; --k) {
for (Integer m = 9; m >= 0; --m) {
// construct the palindrome
Integer palindrome = (i * 10000000) + (j * 1000000) + (k * 100000) + (m * 10000) + (m * 1000) + (k * 100) + (j * 10) + i;
// cout << palindrome << endl;
// generate guidance on the scale of the product terms
Real squareRoot = std::sqrt((long double)palindrome);
// cout << "sqrt guidance is " << squareRoot << endl;
Integer a, b;
a = squareRoot;
while (a < 10000) {
b = palindrome / a;
if ((palindrome % a) == 0 && b < 10000) {
cout << "In step " << nrOfSteps << " found largest 4-digit palindrome product: " << a << " * " << b << " = " << palindrome << " check product: " << a * b << endl;
return true;
}
else {
++a;
++nrOfSteps;
}
}
}
}
}
}
return false; // didn't find a solution
}
template<size_t nbits>
bool Largest5DigitPalindromeProduct() {
using namespace std;
using namespace sw::unum;
using Integer = integer<nbits>;
using Real = long double;
int nrOfSteps = 0;
// construct palindromes starting from the largest descending to the smallest
for (Integer i = 9; i >= 0; --i) {
for (Integer j = 9; j >= 0; --j) {
for (Integer k = 9; k >= 0; --k) {
for (Integer m = 9; m >= 0; --m) {
for (Integer n = 9; n >= 0; --n) {
// construct the palindrome
Integer palindrome = (i * 1000000000) + (j * 100000000) + (k * 10000000) + (m * 1000000) + (n * 100000) + (n * 10000) + (m * 1000) + (k * 100) + (j * 10) + i;
// cout << palindrome << endl;
// generate guidance on the scale of the product terms
Real squareRoot = std::sqrt((long double)palindrome);
// cout << "sqrt guidance is " << squareRoot << endl;
Integer a, b;
a = squareRoot;
while (a < 10000) {
b = palindrome / a;
if ((palindrome % a) == 0 && b < 10000) {
cout << "In step " << nrOfSteps << " found largest 5-digit palindrome product: " << a << " * " << b << " = " << palindrome << " check product: " << a * b << endl;
return true;
}
else {
++a;
++nrOfSteps;
}
}
}
}
}
}
}
return false; // didn't find a solution
}
int main()
try {
using namespace std;
using namespace sw::unum;
constexpr size_t nbits = 32;
using Integer = integer<nbits>;
using Real = long double;
Largest2DigitPalindromeProduct<nbits>();
Largest3DigitPalindromeProduct<nbits>();
Largest4DigitPalindromeProduct<nbits>();
Largest5DigitPalindromeProduct<nbits>();
return EXIT_SUCCESS;
}
catch (char const* msg) {
std::cerr << msg << std::endl;
return EXIT_FAILURE;
}
catch (const std::runtime_error& err) {
std::cerr << "Uncaught runtime exception: " << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (...) {
std::cerr << "Caught unknown exception" << std::endl;
return EXIT_FAILURE;
}
<|endoftext|>
|
<commit_before>#include<iostream>
#include<string.h>
#include<string>
#include<vector>
#include<sys/types.h>
#include<sys/wait.h>
#include<sys/stat.h>
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<cstring>
#include<algorithm>
#include<iterator>
#include<sstream>
using namespace std;
bool run_test(char command[]);
bool run_word_test(char command[]);
bool test_word(const char command[]);
bool test_check_brackets(const char command[], bool &brackets);
void parse_line(char c_line[], char *command_line[]);
void run_line(char *command_line[]);
int main()
{
string str;
string arg = "";
while(1)
{
str = "";
char userName[100] = "";
if(getlogin_r(userName, sizeof(userName)-1) != 0) //Getting username, and returns null if cant be found
{
perror("Error getting username");
}
cout << '[' << userName << '@';
char hostName[100] = "";
if(gethostname(hostName, sizeof(hostName)-1) != 0) // Getting host name, returns numm if it cannot be found
{
perror("Error getting hostname");
}
cout << hostName << ']';
cout << "$";
getline(cin,str); //Gets a command
if(str == "exit") //If the command is exit the program stops
{
break;
}
if(str.size() != 0 && str.at(0) == '#')
{
str = "";
}
if(str != "")
{
for(unsigned i = 0; i < str.size(); i++)
{
if(str.at(i) == '#') //Removes all part of the command after the comment
{
str = str.substr(0,i);
}
}
while(str.at(0) == ' ')
{
str = str.substr(1,str.size()-1);
}
if(str.at(str.size() - 1 ) == ' ')
{
str = str.substr(0,str.size()- 1);
}
bool extra_brac = false;
bool testBool_brac = false;
bool testBool = false;
char c_line[100];
char *command_line[64];
strcpy(c_line,str.c_str());
c_line[str.size()] = '\0';
testBool_brac = test_check_brackets(c_line, extra_brac);
if(testBool_brac && extra_brac)
{
run_test(c_line);
}
else if(!testBool_brac && !extra_brac)
{
testBool = test_word(c_line);
if(testBool)
{
run_word_test(c_line);
}
else
{
parse_line(c_line, command_line);
run_line(command_line);
}
}
}
}
return 0;
}
void parse_line(char c_line[], char *command_line[])
{
while(*c_line != '\0')
{
while(*c_line == ' ' || *c_line == '\n' || *c_line == '\t')
{
*c_line++ = '\0';
}
*command_line++ = c_line;
while(*c_line != '\0' && *c_line != ' ' && *c_line != '\n' && *c_line != '\t')
{
c_line++;
}
*command_line = NULL;
}
return;
}
bool test_word(const char command[])
{
int i = 0;
if(command[i] == 't' && command[i + 1] == 'e')
{
if(command[i + 3] == 't')
{
return true;
}
}
return false;
}
bool run_word_test(char command[])
{
bool file = false;
bool dir = false;
bool exist = false;
int i = 3;
char fix_command[100];
i++;
for(; command[i] == ' '; ++i){} // to skip all the spaces between test and the flag
if(command[i] == '-' && command[i + 1] == 'f')
{
file = true;
i++;
i++;
}
else if(command[i] == '-' && command[i + 1] == 'd')
{
dir = true;
i++;
i++;
}
else if(command[i] == '-' && (command[i + 1] != 'e' && command[i + 1] != ' '))
{
cout << "Invalid Flag\n";
return false;
}
else if(command[i] == '-' && (command[i + 1] == 'e' || command[i + 1] == ' '))
{
exist = true;
i++;
i++;
}
else
{
cout << "Error missing Flag\n";
return false;
}
for(; command[i] == ' '; ++i){} // skip all spaces between flag and argument
if(command[i] != '\0')
{
int j = 0;
for(; command[i] != '\0' && command[i] != ' '; ++i)
{
fix_command[j] = command[i];
j++;
}
fix_command[j] = '\0';
}
if(exist)
{
struct stat exist;
if(stat(fix_command, &exist) == 0)
{
cout << "(True)\n";
return true;
}
else
{
cout << "(False)\n";
return false;
}
}
else if(file)
{
struct stat file;
stat(fix_command, &file);
if(S_ISREG(file.st_mode) != 0)
{
cout << "(True)\n";
return true;
}
else
{
cout << "(False)\n";
return false;
}
}
else if(dir)
{
struct stat dir;
stat(fix_command, &dir);
if(S_ISDIR(dir.st_mode) != 0)
{
cout << "(True)\n";
return true;
}
else
{
cout << "(False)\n";
return false;
}
}
return false;
}
bool test_check_brackets(const char command[], bool &brackets)
{
bool endBracket = true;
int i = 0;
if(command[i] == '[')
{
i++;
if(command[i] == ' ')
{
for(; command[i] != '\0'; i++)
{
if(command[i] == ']')
{
endBracket = false;
if(command[i - 1] == ' ')
{
brackets = true;
return true;
}
else
{
brackets = true;
cout << "Need a space before ]\n";
return false;
}
}
}
if(endBracket)
{
cout << "Missing ]\n";
brackets = true;
return false;
}
}
else
{
brackets = true;
cout << "Need a space after [\n";
return false;
}
}
return false;
}
bool run_test(char command[])
{
bool file = false;
bool dir = false;
bool exist = false;
int i = 1;
for(; command[i] == ' '; i++){} // gets rid of spaces between [ and flag
if(command[i] == '-')
{
i++;
if(command[i] == 'f')
{
file = true;
i++;
}
else if(command[i] == 'd')
{
dir = true;
i++;
}
else if(command[i] == 'e' || command[i] == ' ')
{
exist = true;
i++;
}
else
{
cout << "Error, invalid flag\n";
return false;
}
}
else if(command[i] != '-')
{
cout << "Error, missing flag\n";
return false;
}
char fix_command[100];
for(; command[i] == ' '; i++){} // to skip all the spaces between the flag and the argument
if(command[i] != '\0')
{
int j = 0;
for(; command[i] != '\0' && command[i] != ' '; i++)
{
fix_command[j] = command[i];
j++;
}
fix_command[j] = '\0';
}
else
{
cout << "Invalid argument with flag\n";
return false;
}
if(exist)
{
struct stat exist;
if(stat(fix_command, &exist) == 0)
{
cout << "(True)\n";
return true;
}
else
{
cout << "(False)\n";
return false;
}
}
else if(file)
{
struct stat file;
stat(fix_command, &file);
if(S_ISREG(file.st_mode) != 0)
{
cout << "(True)\n";
return true;
}
else
{
cout << "(False)\n";
return false;
}
}
else if(dir)
{
struct stat dir;
stat(fix_command, &dir);
if(S_ISDIR(dir.st_mode) != 0)
{
cout << "(True)\n";
return true;
}
else
{
cout << "(False)\n";
return false;
}
}
return false;
}
void run_line(char *command_line[])
{
pid_t pid;
int status;
if((pid = fork()) < 0)
{
perror("forking failed");
}
else if(pid == 0)
{
if(execvp(*command_line,command_line) < 0)
{
perror("execvp failed");
exit(1);
}
}
else
{
while(wait(&status) != pid)
;
}
return;
}
<commit_msg>Updated the comments for rshell.cpp<commit_after>#include<iostream>
#include<string.h>
#include<string>
#include<vector>
#include<sys/types.h>
#include<sys/wait.h>
#include<sys/stat.h>
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<cstring>
#include<algorithm>
#include<iterator>
#include<sstream>
using namespace std;
bool run_test(char command[]);
bool run_word_test(char command[]);
bool test_word(const char command[]);
bool test_check_brackets(const char command[], bool &brackets);
void parse_line(char c_line[], char *command_line[]);
void run_line(char *command_line[]);
int main()
{
string str;
string arg = "";
while(1)
{
str = "";
char userName[100] = "";
if(getlogin_r(userName, sizeof(userName)-1) != 0) //Getting username, and returns null if cant be found
{
perror("Error getting username");
}
cout << '[' << userName << '@';
char hostName[100] = "";
if(gethostname(hostName, sizeof(hostName)-1) != 0) // Getting host name, returns numm if it cannot be found
{
perror("Error getting hostname");
}
cout << hostName << ']';
cout << "$";
getline(cin,str); //Gets a command
if(str == "exit") //If the command is exit the program stops
{
break;
}
if(str.size() != 0 && str.at(0) == '#')
{
str = "";
}
if(str != "")
{
for(unsigned i = 0; i < str.size(); i++)
{
if(str.at(i) == '#') //Removes all part of the command after the comment
{
str = str.substr(0,i);
}
}
while(str.at(0) == ' ')
{
str = str.substr(1,str.size()-1);
}
if(str.at(str.size() - 1 ) == ' ')
{
str = str.substr(0,str.size()- 1);
}
bool extra_brac = false;
bool testBool_brac = false;
bool testBool = false;
char c_line[100];
char *command_line[64];
strcpy(c_line,str.c_str());
c_line[str.size()] = '\0';
testBool_brac = test_check_brackets(c_line, extra_brac);
if(testBool_brac && extra_brac) // This is to check if there were brackets and it passed with both
{
run_test(c_line);
}
else if(!testBool_brac && !extra_brac) // If there werent brackets then it checks for test
{
testBool = test_word(c_line);
if(testBool)
{
run_word_test(c_line);
}
else // if there were neither test or brackets then it runs the command by execvp
{
parse_line(c_line, command_line);
run_line(command_line);
}
}
}
}
return 0;
}
void parse_line(char c_line[], char *command_line[])
{
while(*c_line != '\0')
{
while(*c_line == ' ' || *c_line == '\n' || *c_line == '\t')
{
*c_line++ = '\0';
}
*command_line++ = c_line;
while(*c_line != '\0' && *c_line != ' ' && *c_line != '\n' && *c_line != '\t')
{
c_line++;
}
*command_line = NULL;
}
return;
}
bool test_word(const char command[])
{
int i = 0;
if(command[i] == 't' && command[i + 1] == 'e')
{
if(command[i + 3] == 't')
{
return true;
}
}
return false;
}
bool run_word_test(char command[])
{
bool file = false;
bool dir = false;
bool exist = false;
int i = 3;
char fix_command[100];
i++;
for(; command[i] == ' '; ++i){} // to skip all the spaces between test and the flag
if(command[i] == '-' && command[i + 1] == 'f')
{
file = true;
i++;
i++;
}
else if(command[i] == '-' && command[i + 1] == 'd')
{
dir = true;
i++;
i++;
}
else if(command[i] == '-' && (command[i + 1] != 'e' && command[i + 1] != ' '))
{
cout << "Invalid Flag\n";
return false;
}
else if(command[i] == '-' && (command[i + 1] == 'e' || command[i + 1] == ' '))
{
exist = true;
i++;
i++;
}
else
{
cout << "Error missing Flag\n";
return false;
}
for(; command[i] == ' '; ++i){} // skip all spaces between flag and argument
if(command[i] != '\0')
{
int j = 0; // This transfers the argument to a new c_str
for(; command[i] != '\0' && command[i] != ' '; ++i)
{
fix_command[j] = command[i];
j++;
}
fix_command[j] = '\0';
}
if(exist) // This works on each different flag, and returns True or False depending on the flag
{
struct stat exist;
if(stat(fix_command, &exist) == 0)
{
cout << "(True)\n";
return true;
}
else
{
cout << "(False)\n";
return false;
}
}
else if(file)
{
struct stat file;
stat(fix_command, &file);
if(S_ISREG(file.st_mode) != 0)
{
cout << "(True)\n";
return true;
}
else
{
cout << "(False)\n";
return false;
}
}
else if(dir)
{
struct stat dir;
stat(fix_command, &dir);
if(S_ISDIR(dir.st_mode) != 0)
{
cout << "(True)\n";
return true;
}
else
{
cout << "(False)\n";
return false;
}
}
return false;
}
bool test_check_brackets(const char command[], bool &brackets)
{
bool endBracket = true;
int i = 0;
if(command[i] == '[')
{
i++;
if(command[i] == ' ')
{
for(; command[i] != '\0'; i++)
{
if(command[i] == ']')
{
endBracket = false; // this bool is to remind that the first bracket was found and end
if(command[i - 1] == ' ')
{
brackets = true;
return true;
}
else
{
brackets = true;
cout << "Need a space before ]\n";
return false;
}
}
}
if(endBracket)
{ // Since open bracket was found, but not the end one. It is an error
cout << "Missing ]\n";
brackets = true;
return false;
}
}
else
{
brackets = true;
cout << "Need a space after [\n";
return false;
}
}
return false;
}
bool run_test(char command[])
{
bool file = false;
bool dir = false;
bool exist = false;
int i = 1;
for(; command[i] == ' '; i++){} // gets rid of spaces between [ and flag
if(command[i] == '-')
{
i++;
if(command[i] == 'f')
{
file = true;
i++;
}
else if(command[i] == 'd')
{
dir = true;
i++;
}
else if(command[i] == 'e' || command[i] == ' ')
{
exist = true;
i++;
}
else
{
cout << "Error, invalid flag\n";
return false;
}
}
else if(command[i] != '-')
{
cout << "Error, missing flag\n";
return false;
}
char fix_command[100];
for(; command[i] == ' '; i++){} // to skip all the spaces between the flag and the argument
if(command[i] != '\0')
{
int j = 0; // Transfers the argument to new c_str
for(; command[i] != '\0' && command[i] != ' '; i++)
{
fix_command[j] = command[i];
j++;
}
fix_command[j] = '\0';
}
else
{
cout << "Invalid argument with flag\n";
return false;
}
if(exist)
{
struct stat exist;
if(stat(fix_command, &exist) == 0)
{
cout << "(True)\n";
return true;
}
else
{
cout << "(False)\n";
return false;
}
}
else if(file)
{
struct stat file;
stat(fix_command, &file);
if(S_ISREG(file.st_mode) != 0)
{
cout << "(True)\n";
return true;
}
else
{
cout << "(False)\n";
return false;
}
}
else if(dir)
{
struct stat dir;
stat(fix_command, &dir);
if(S_ISDIR(dir.st_mode) != 0)
{
cout << "(True)\n";
return true;
}
else
{
cout << "(False)\n";
return false;
}
}
return false;
}
void run_line(char *command_line[])
{
pid_t pid;
int status;
if((pid = fork()) < 0) //forks process
{
perror("forking failed"); //error if forking failed
}
else if(pid == 0)
{
if(execvp(*command_line,command_line) < 0) //executes command
{
perror("execvp failed"); //error if execution failes
exit(1);
}
}
else
{
while(wait(&status) != pid) //waits to return to parent process
;
}
return;
}
<|endoftext|>
|
<commit_before>// Time: O(1), per operation.
// Space: O(k), k is the capacity of cache.
class LFUCache {
public:
LFUCache(int capacity) : capa_(capacity), size_(0) {
}
int get(int key) {
if (!key_to_val_freq_.count(key)) {
return -1;
}
freq_to_keys_[key_to_val_freq_[key].second].erase(key_to_it_[key]);
if (freq_to_keys_[key_to_val_freq_[key].second].empty()) {
freq_to_keys_.erase(key_to_val_freq_[key].second);
if (min_freq_ == key_to_val_freq_[key].second) {
++min_freq_;
}
}
++key_to_val_freq_[key].second;
freq_to_keys_[key_to_val_freq_[key].second].emplace_back(key);
key_to_it_[key] = prev(freq_to_keys_[key_to_val_freq_[key].second].end());
return key_to_val_freq_[key].first;
}
void put(int key, int value) {
if (capa_ <= 0) {
return;
}
if (get(key) != -1) {
key_to_val_freq_[key].first = value;
return;
}
if (size_ == capa_) {
key_to_val_freq_.erase(freq_to_keys_[min_freq_].front());
key_to_it_.erase(freq_to_keys_[min_freq_].front());
freq_to_keys_[min_freq_].pop_front();
if (freq_to_keys_[min_freq_].empty()) {
freq_to_keys_.erase(min_freq_);
}
--size_;
}
min_freq_ = 1;
key_to_val_freq_[key] = {value, min_freq_};
freq_to_keys_[min_freq_].emplace_back(key);
key_to_it_[key] = prev(freq_to_keys_[min_freq_].end());
++size_;
}
private:
int capa_;
int size_;
int min_freq_;
unordered_map<int, list<int>> freq_to_keys_; // freq to list of keys
unordered_map<int, list<int>::iterator> key_to_it_; // key to list iterator
unordered_map<int, pair<int, int>> key_to_val_freq_; // key to {value, freq}
};
/**
* Your LFUCache object will be instantiated and called as such:
* LFUCache obj = new LFUCache(capacity);
* int param_1 = obj.get(key);
* obj.put(key,value);
*/
<commit_msg>Update lfu-cache.cpp<commit_after>// Time: O(1), per operation.
// Space: O(k), k is the capacity of cache.
class LFUCache {
public:
LFUCache(int capacity) : capa_(capacity), size_(0) {
}
int get(int key) {
if (!key_to_nodeit_.count(key)) {
return -1;
}
auto new_node = *key_to_nodeit_[key];
auto& freq = std::get<2>(new_node);
freq_to_nodes_[freq].erase(key_to_nodeit_[key]);
if (freq_to_nodes_[freq].empty()) {
freq_to_nodes_.erase(freq);
if (min_freq_ == freq) {
++min_freq_;
}
}
++freq;
freq_to_nodes_[freq].emplace_back(new_node);
key_to_nodeit_[key] = prev(freq_to_nodes_[freq].end());
return std::get<1>(*key_to_nodeit_[key]);
}
void put(int key, int value) {
if (capa_ <= 0) {
return;
}
if (get(key) != -1) {
std::get<1>(*key_to_nodeit_[key]) = value;
return;
}
if (size_ == capa_) {
key_to_nodeit_.erase(std::get<0>(freq_to_nodes_[min_freq_].front()));
freq_to_nodes_[min_freq_].pop_front();
if (freq_to_nodes_[min_freq_].empty()) {
freq_to_nodes_.erase(min_freq_);
}
--size_;
}
min_freq_ = 1;
freq_to_nodes_[min_freq_].emplace_back(make_tuple(key, value, min_freq_));
key_to_nodeit_[key] = prev(freq_to_nodes_[min_freq_].end());
++size_;
}
private:
int capa_;
int size_;
int min_freq_;
unordered_map<int, list<tuple<int, int, int>>> freq_to_nodes_; // freq to list of {key, val, freq}
unordered_map<int, list<tuple<int, int, int>>::iterator> key_to_nodeit_; // key to list iterator
};
/**
* Your LFUCache object will be instantiated and called as such:
* LFUCache obj = new LFUCache(capacity);
* int param_1 = obj.get(key);
* obj.put(key,value);
*/
<|endoftext|>
|
<commit_before>#include "MpptUnit.h"
MpptUnit::MpptUnit()
: mpptStatus_(0)
, arrayVoltage_(0)
, arrayCurrent_(0)
, batteryVoltage_(0)
, temperature_(0)
{
// Initialize to 0
}
MpptUnit::~MpptUnit()
{
}
/* MpptUnit Gets */
unsigned char MpptUnit::getMpptStatus() const
{
return mpptStatus_;
}
unsigned short MpptUnit::getArrayVoltage() const
{
return arrayVoltage_;
}
unsigned short MpptUnit::getArrayCurrent() const
{
return arrayCurrent_;
}
unsigned short MpptUnit::getBatteryVoltage() const
{
return batteryVoltage_;
}
unsigned short MpptUnit::getTemperature() const
{
return temperature_;
}
/* MpptUnit Sets */
void MpptUnit::setMpptStatus(const unsigned char& mpptStatus)
{
mpptStatus_ = mpptStatus;
emit mpptStatusReceived(mpptStatus_);
}
void MpptUnit::setArrayVoltage(const unsigned short& arrayVoltage)
{
arrayVoltage_ = (arrayVoltage * 100);
emit arrayVoltageReceived(arrayVoltage_);
}
void MpptUnit::setArrayCurrent(const unsigned short& arrayCurrent)
{
arrayCurrent_ = arrayCurrent;
emit arrayCurrentReceived(arrayCurrent_);
}
void MpptUnit::setBatteryVoltage(const unsigned short& batteryVoltage)
{
batteryVoltage_ = batteryVoltage;
emit batteryVoltageReceived(batteryVoltage_);
}
void MpptUnit::setTemperature(const unsigned short& temperature)
{
temperature_ = temperature;
emit temperatureReceived(temperature_);
}
<commit_msg>added MPPT conversions<commit_after>#include "MpptUnit.h"
MpptUnit::MpptUnit()
: mpptStatus_(0)
, arrayVoltage_(0)
, arrayCurrent_(0)
, batteryVoltage_(0)
, temperature_(0)
{
// Initialize to 0
}
MpptUnit::~MpptUnit()
{
}
/* MpptUnit Gets */
unsigned char MpptUnit::getMpptStatus() const
{
return mpptStatus_;
}
unsigned short MpptUnit::getArrayVoltage() const
{
return arrayVoltage_;
}
unsigned short MpptUnit::getArrayCurrent() const
{
return arrayCurrent_;
}
unsigned short MpptUnit::getBatteryVoltage() const
{
return batteryVoltage_;
}
unsigned short MpptUnit::getTemperature() const
{
return temperature_;
}
/* MpptUnit Sets */
void MpptUnit::setMpptStatus(const unsigned char& mpptStatus)
{
mpptStatus_ = mpptStatus;
emit mpptStatusReceived(mpptStatus_);
}
void MpptUnit::setArrayVoltage(const unsigned short& arrayVoltage)
{
arrayVoltage_ = (arrayVoltage * 100);
emit arrayVoltageReceived(arrayVoltage_);
}
void MpptUnit::setArrayCurrent(const unsigned short& arrayCurrent)
{
arrayCurrent_ = (arrayCurrent * 1000);
emit arrayCurrentReceived(arrayCurrent_);
}
void MpptUnit::setBatteryVoltage(const unsigned short& batteryVoltage)
{
batteryVoltage_ = (batteryVoltage * 100);
emit batteryVoltageReceived(batteryVoltage_);
}
void MpptUnit::setTemperature(const unsigned short& temperature)
{
temperature_ = (temperature * 100);
emit temperatureReceived(temperature_);
}
<|endoftext|>
|
<commit_before>#include <string>
#include <vector>
#include <boost/tokenizer.hpp>
#include <iostream>
#include <stdlib.h>
#include <cstdio>
#include <sys/wait.h>
using namespace boost;
using namespace std;
class rshell{
protected:
//Variables
string commands;
string nextConnector;
vector<string> commandlist;
bool prevCommandPass;
bool forceExit;
public:
//Constructor
rshell(){
commands = "";
nextConnector = ";";
prevCommandPass = true;
forceExit = false;
}
//Separates string into tokens and puts them into commandlist, if the token ends with a ;, it stays with the string
void parseAllCommands(){
char_separator<char> delims(" ");
tokenizer<char_separator<char> > tokenlist(commands, delims);
for (tokenizer<char_separator<char> >::iterator i = tokenlist.begin(); i != tokenlist.end(); i++){
string com(*i);
commandlist.push_back(com);
}
}
//Executes one command and sets prevCommandPass to true or false.
void executeCommand(vector<string> com){
char* argv[1024];
int pid_child;
int status_child;
for(unsigned int i = 0; i < com.size(); i++){
argv[i] = (char*)com.at(i).c_str();
}
argv[com.size()] = NULL;
pid_child = fork();
if (pid_child == 0){
if(execvp(argv[0], argv) == -1){
perror("execvp failed: ");
prevCommandPass = false;
return;
}
}
else{
if (waitpid(pid_child, &status_child, 0) == -1){
perror("pid incorrect: ");
}
}
prevCommandPass = true;
}
//Splits commandlist into commands with their arguments then calls executeCommand to run them.
void executeAllCommands(){
vector<string> commandsublist;
unsigned int i = 0;
unsigned int j = 0;
while (i < commandlist.size()){
j = 0;
if (checkCommandRun()){
while (!checkBreaker(commandlist.at(i))){
//Exit check
if (commandlist.at(i) == "exit"){
forceExit = true;
return;
}
//Comment check
if (commandlist.at(i) == "#" || checkComment(commandlist.at(i))){
executeCommand(commandsublist);
return;
}
//Adds command to the list
commandsublist.push_back(commandlist.at(i));
if (commandsublist.at(j).at(commandsublist.at(j).length() - 1) == ';'){
commandsublist.at(j).erase(commandsublist.at(j).length() - 1);
nextConnector = ';';
break;
}
i++;
j++;
if (i == commandlist.size()){
executeCommand(commandsublist);
return;
}
}
if (checkBreaker(commandlist.at(i))){
nextConnector = commandlist.at(i);
}
i++;
}
executeCommand(commandsublist);
commandsublist.clear();
}
}
//Checks if there is a comment sign in the first letter returns true
bool checkComment(string str){
if (str.at(0) == '#'){
return true;
}
return false;
}
//Checks if the string is a breaker
bool checkBreaker(string str){
if (str == "||" || str == "&&" || str == ";"){
return true;
}
return false;
}
//Checks if the next command should be ran.
bool checkCommandRun(){
if (nextConnector == "||"){
if(prevCommandPass){
return false;
}
return true;
}
if (nextConnector == "&&"){
if(prevCommandPass){
return true;
}
return false;
}
if (nextConnector == ";"){
return true;
}
return true;
}
//Starts the program.
void run(){
while (!forceExit){
cout << "$";
getline(cin, commands);
if (commands != "" && commands != "exit"){
parseAllCommands();
executeAllCommands();
}
if (commands == "exit"){
cout << "Forced Exit." << endl;
forceExit = true;
return;
}
commandlist.clear();
}
}
};
<commit_msg>improved readability<commit_after>#include <string>
#include <vector>
#include <boost/tokenizer.hpp>
#include <iostream>
#include <stdlib.h>
#include <cstdio>
#include <sys/wait.h>
using namespace boost;
using namespace std;
class rshell{
protected:
//Data Members
string commands;
string nextConnector;
vector<string> commandlist;
bool prevCommandPass;
bool forceExit;
public:
//Constructor
rshell(){
commands = "";
nextConnector = ";";
prevCommandPass = true;
forceExit = false;
}
// Parses the string (strings ending in ';' will keep the ';')
void parseAllCommands(){
char_separator<char> delims(" ");
tokenizer<char_separator<char> > tokenlist(commands, delims);
for (tokenizer<char_separator<char> >::iterator i = tokenlist.begin(); i != tokenlist.end(); i++){
string com(*i);
commandlist.push_back(com);
}
}
// Executes one command and sets prevCommandPass to true or false.
void executeCommand(vector<string> com){
char* argv[1024];
int pid_child;
int status_child;
for(unsigned int i = 0; i < com.size(); i++){
argv[i] = (char*)com.at(i).c_str();
}
argv[com.size()] = NULL;
pid_child = fork();
if (pid_child == 0){
if(execvp(argv[0], argv) == -1){
perror("execvp failed: ");
prevCommandPass = false;
return;
}
}
else{
if (waitpid(pid_child, &status_child, 0) == -1){
perror("pid incorrect: ");
}
}
prevCommandPass = true;
}
//Splits commandlist into commands with their arguments then calls executeCommand to run them.
void executeAllCommands(){
vector<string> commandsublist;
unsigned int i = 0;
unsigned int j = 0;
while (i < commandlist.size()){
j = 0;
if (checkCommandRun()){
while (!checkBreaker(commandlist.at(i))){
//Exit check
if (commandlist.at(i) == "exit"){
forceExit = true;
return;
}
// Comment check
if (commandlist.at(i) == "#" || checkComment(commandlist.at(i))){
executeCommand(commandsublist);
return;
}
//Adds command to the list
commandsublist.push_back(commandlist.at(i));
if (commandsublist.at(j).at(commandsublist.at(j).length() - 1) == ';'){
commandsublist.at(j).erase(commandsublist.at(j).length() - 1);
nextConnector = ';';
break;
}
i++;
j++;
if (i == commandlist.size()){
executeCommand(commandsublist);
return;
}
}
if (checkBreaker(commandlist.at(i))){
nextConnector = commandlist.at(i);
}
i++;
}
executeCommand(commandsublist);
commandsublist.clear();
}
}
// Checks if there is a '#' at the front of the string
bool checkComment(string str){
if (str.at(0) == '#'){
return true;
}
return false;
}
// Checks if the string is a breaker
bool checkBreaker(string str){
if (str == "||" || str == "&&" || str == ";"){
return true;
}
return false;
}
// Checks if the next command should be run
bool checkCommandRun(){
if (nextConnector == "||"){
if(prevCommandPass){
return false;
}
return true;
}
if (nextConnector == "&&"){
if(prevCommandPass){
return true;
}
return false;
}
if (nextConnector == ";"){
return true;
}
return true;
}
//Starts the program.
void run(){
while (!forceExit){
cout << "$";
getline(cin, commands);
parseAllCommands();
executeAllCommands();
if (commands == "exit"){
cout << "Forced Exit." << endl;
forceExit = true;
return;
}
commandlist.clear();
}
}
};
<|endoftext|>
|
<commit_before>#include "WebSystemController.h"
#include "Overlay.h"
#include "Crawl.h"
#pragma mark – Life Cycle
void WebSystemController::init() {
// Connect the websystem
connection.setHost("projectvictory.hostfile", 80);
// Set up listeners
connection.addHashTagCountListener(this, &WebSystemController::onHashTagCount);
connection.addShoutoutListener(this, &WebSystemController::onShoutout);
connection.addCommandListener(this, &WebSystemController::onCommand);
// Set up the voting GUI
initVotingGUI();
initWebSystemGUI();
}
void WebSystemController::update() {
float currentTime = ofGetElapsedTimef();
static float lastHashTagUpdate = 0.f;
if ( lastHashTagUpdate + (float(UPDATE_VOTES_EVERY_MS) / 1000) < currentTime && overlay && webSystemIsEnabled ) {
connection.requestHashTagCount( overlay->voteDisplay.topic1 );
connection.requestHashTagCount( overlay->voteDisplay.topic2 );
lastHashTagUpdate = currentTime;
}
// only decay effects 10/sec
static float lastEffectsDecaySecs = 0.0f;
if ( shouldDecaysEffects && currentTime - lastEffectsDecaySecs > DECAY_EFFECT_EVERY_SEC) {
decayVideoFXToDefault();
lastEffectsDecaySecs = currentTime;
}
}
#pragma mark - VoteSystem
void WebSystemController::initWebSystemGUI() {
websystemGUI = new ofxUISuperCanvas( "WEB SYSTEM", 20, 20, 200, 200 );
websystemGUI->setColorBack( ofColor(ofColor::green, 125) );
websystemGUI->addLabelToggle( "ENABLED", &webSystemIsEnabled );
websystemGUI->addLabelToggle( "SHOUTOUTS", &shoutoutsAreEnabled );
websystemGUI->addLabelToggle( "COMMANDS", &commandsAreEnabled );
websystemGUI->addLabelToggle( "DECAYS", &shouldDecaysEffects );
websystemGUI->autoSizeToFitWidgets();
}
#pragma mark – Web System Connection
void WebSystemController::onHashTagCount(Json::Value body) {
if (!webSystemIsEnabled) { return; }
// Do something with the incoming count
string hashTag = body["tag"].asString();
// This will return the straight out number.
// You can dig into "result" to get an array with number of votes cast per minute for 120 minutes
float numberOfShoutouts = WebSystem::Utils::countHashTagsInResult( body["result"] );
overlay->voteDisplay.setVote(hashTag, numberOfShoutouts);
}
void WebSystemController::onShoutout(Json::Value body) {
// Get the info on the shoutout (you might want to store these in a vector if they are used later)
string screenname = body["tweet"]["userScreenName"].asString();
string tweetText = body["tweet"]["text"].asString();
if (!webSystemIsEnabled || !shoutoutsAreEnabled) { return; }
cout << "@" << screenname << ": " << tweetText << endl;
overlay->crawl.addCrawlItem( screenname, tweetText );
}
void WebSystemController::onCommand(Json::Value body) {
if (!webSystemIsEnabled || !commandsAreEnabled) { return; }
// p.s. if you want to know what is the body, you can send it to cout:
// cout << body;
// Get the screen name of the user who tweeted
string screenname = body["tweet"]["userScreenName"].asString();
// DO NOT USE THE TWEET TEXT. It is unmoderated!
string doNotUse = body["tweet"]["text"].asString();
// Get the text command which trigger the action
string command = body["payload"]["command"].asString();
cout << "@" << screenname << " triggered " << command << endl;
// Store a trigger to save the image
// This is dirty. Want tweet id as string.
stringstream s;
s << body["tweet"]["id"];
string tweetid = s.str();
tweetid.erase(tweetid.size() - 1);
screenShotTriggers[ ofGetElapsedTimef() ] = tweetid;
// Apply the payload to the videofx. They need to be a decayer somewhere, so this may not be how it works.
if (videoFX) {
WebSystem::Utils::applyPayload( videoFX, body["payload"] );
cout << "should have applied payload" << endl;
}
}
#pragma mark – Decay
void WebSystemController::decayVideoFXToDefault() {
// store the last time on first run (this won't work if using multiple effects)
static float lastUpdate = ofGetElapsedTimef();
// I think, the 0.3 means that each effect will decay by 30% every second
WebSystem::Utils::decayEffects( videoFX, lastUpdate, 0.3f );
lastUpdate = ofGetElapsedTimef();
}
#pragma mark - VoteSystem
void WebSystemController::initVotingGUI() {
voteGUI = new ofxUISuperCanvas( "VOTEING SYSTEM", 20, 340, 200, 200 );
voteGUI->setColorBack(ofColor(ofColor::thistle, 125));
voteGUI->addLabel("TOPIC 1");
vote1TextInput = voteGUI->addTextInput("TOPIC 1", "");
voteGUI->addLabel("TOPIC 2");
vote2TextInput = voteGUI->addTextInput("TOPIC 2", "");
voteGUI->addButton("UPDATE TOPICS", false);
voteGUI->autoSizeToFitWidgets();
ofAddListener( voteGUI->newGUIEvent, this, &WebSystemController::voteingGUIEvent );
voteGUI->loadSettings("settings.voting.gui.xml");
}
void WebSystemController::voteingGUIEvent(ofxUIEventArgs &e) {
if ( e.widget->getName() == "UPDATE TOPICS") {
ofxUIButton *button = (ofxUIButton *)e.widget;
if (button->getValue()) {
overlay->voteDisplay.topic1 = vote1TextInput->getTextString();
overlay->voteDisplay.topic2 = vote2TextInput->getTextString();
overlay->voteDisplay.resetVotes();
} else {
voteGUI->saveSettings("settings.voting.gui.xml");
}
}
}
// Image saving
string WebSystemController::getNextScreenShotFilename() {
float currentTime = ofGetElapsedTimef();
string filename = "";
// find the first trigger needing to be saved
ScreenShotTriggersIt it = screenShotTriggers.begin();
bool found = false;
while ( !found && it != screenShotTriggers.end()) {
if ( it->first < currentTime + 1.0f) {
found = true;
filename = it->second;
screenShotTriggers.erase(it);
}
}
return filename;
}
<commit_msg>GUI Positioning<commit_after>#include "WebSystemController.h"
#include "Overlay.h"
#include "Crawl.h"
#pragma mark – Life Cycle
void WebSystemController::init() {
// Connect the websystem
connection.setHost("projectvictory.hostfile", 80);
// Set up listeners
connection.addHashTagCountListener(this, &WebSystemController::onHashTagCount);
connection.addShoutoutListener(this, &WebSystemController::onShoutout);
connection.addCommandListener(this, &WebSystemController::onCommand);
// Set up the voting GUI
initVotingGUI();
initWebSystemGUI();
}
void WebSystemController::update() {
float currentTime = ofGetElapsedTimef();
static float lastHashTagUpdate = 0.f;
if ( lastHashTagUpdate + (float(UPDATE_VOTES_EVERY_MS) / 1000) < currentTime && overlay && webSystemIsEnabled ) {
connection.requestHashTagCount( overlay->voteDisplay.topic1 );
connection.requestHashTagCount( overlay->voteDisplay.topic2 );
lastHashTagUpdate = currentTime;
}
// only decay effects 10/sec
static float lastEffectsDecaySecs = 0.0f;
if ( shouldDecaysEffects && currentTime - lastEffectsDecaySecs > DECAY_EFFECT_EVERY_SEC) {
decayVideoFXToDefault();
lastEffectsDecaySecs = currentTime;
}
}
#pragma mark - VoteSystem
void WebSystemController::initWebSystemGUI() {
websystemGUI = new ofxUISuperCanvas( "WEB SYSTEM", 20, 20, 200, 200 );
websystemGUI->setColorBack( ofColor(ofColor::green, 125) );
websystemGUI->addLabelToggle( "ENABLED", &webSystemIsEnabled );
websystemGUI->addLabelToggle( "SHOUTOUTS", &shoutoutsAreEnabled );
websystemGUI->addLabelToggle( "COMMANDS", &commandsAreEnabled );
websystemGUI->addLabelToggle( "DECAYS", &shouldDecaysEffects );
websystemGUI->autoSizeToFitWidgets();
}
#pragma mark – Web System Connection
void WebSystemController::onHashTagCount(Json::Value body) {
if (!webSystemIsEnabled) { return; }
// Do something with the incoming count
string hashTag = body["tag"].asString();
// This will return the straight out number.
// You can dig into "result" to get an array with number of votes cast per minute for 120 minutes
float numberOfShoutouts = WebSystem::Utils::countHashTagsInResult( body["result"] );
overlay->voteDisplay.setVote(hashTag, numberOfShoutouts);
}
void WebSystemController::onShoutout(Json::Value body) {
// Get the info on the shoutout (you might want to store these in a vector if they are used later)
string screenname = body["tweet"]["userScreenName"].asString();
string tweetText = body["tweet"]["text"].asString();
if (!webSystemIsEnabled || !shoutoutsAreEnabled) { return; }
cout << "@" << screenname << ": " << tweetText << endl;
overlay->crawl.addCrawlItem( screenname, tweetText );
}
void WebSystemController::onCommand(Json::Value body) {
if (!webSystemIsEnabled || !commandsAreEnabled) { return; }
// p.s. if you want to know what is the body, you can send it to cout:
// cout << body;
// Get the screen name of the user who tweeted
string screenname = body["tweet"]["userScreenName"].asString();
// DO NOT USE THE TWEET TEXT. It is unmoderated!
string doNotUse = body["tweet"]["text"].asString();
// Get the text command which trigger the action
string command = body["payload"]["command"].asString();
cout << "@" << screenname << " triggered " << command << endl;
// Store a trigger to save the image
// This is dirty. Want tweet id as string.
stringstream s;
s << body["tweet"]["id"];
string tweetid = s.str();
tweetid.erase(tweetid.size() - 1);
screenShotTriggers[ ofGetElapsedTimef() ] = tweetid;
// Apply the payload to the videofx. They need to be a decayer somewhere, so this may not be how it works.
if (videoFX) {
WebSystem::Utils::applyPayload( videoFX, body["payload"] );
cout << "should have applied payload" << endl;
}
}
#pragma mark – Decay
void WebSystemController::decayVideoFXToDefault() {
// store the last time on first run (this won't work if using multiple effects)
static float lastUpdate = ofGetElapsedTimef();
// I think, the 0.3 means that each effect will decay by 30% every second
WebSystem::Utils::decayEffects( videoFX, lastUpdate, 0.3f );
lastUpdate = ofGetElapsedTimef();
}
#pragma mark - VoteSystem
void WebSystemController::initVotingGUI() {
voteGUI = new ofxUISuperCanvas( "VOTEING SYSTEM", 20, 180, 200, 200 );
voteGUI->setColorBack(ofColor(ofColor::thistle, 125));
voteGUI->addLabel("TOPIC 1");
vote1TextInput = voteGUI->addTextInput("TOPIC 1", "");
voteGUI->addLabel("TOPIC 2");
vote2TextInput = voteGUI->addTextInput("TOPIC 2", "");
voteGUI->addButton("UPDATE TOPICS", false);
voteGUI->autoSizeToFitWidgets();
ofAddListener( voteGUI->newGUIEvent, this, &WebSystemController::voteingGUIEvent );
voteGUI->loadSettings("settings.voting.gui.xml");
}
void WebSystemController::voteingGUIEvent(ofxUIEventArgs &e) {
if ( e.widget->getName() == "UPDATE TOPICS") {
ofxUIButton *button = (ofxUIButton *)e.widget;
if (button->getValue()) {
overlay->voteDisplay.topic1 = vote1TextInput->getTextString();
overlay->voteDisplay.topic2 = vote2TextInput->getTextString();
overlay->voteDisplay.resetVotes();
} else {
voteGUI->saveSettings("settings.voting.gui.xml");
}
}
}
// Image saving
string WebSystemController::getNextScreenShotFilename() {
float currentTime = ofGetElapsedTimef();
string filename = "";
// find the first trigger needing to be saved
ScreenShotTriggersIt it = screenShotTriggers.begin();
bool found = false;
while ( !found && it != screenShotTriggers.end()) {
if ( it->first < currentTime + 1.0f) {
found = true;
filename = it->second;
screenShotTriggers.erase(it);
}
}
return filename;
}
<|endoftext|>
|
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id: ValuePrinter.cpp 46307 2012-10-04 06:53:23Z axel $
// author: Axel Naumann <axel@cern.ch>
//------------------------------------------------------------------------------
#include "cling/Interpreter/StoredValueRef.h"
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/ValuePrinter.h"
#include "cling/Utils/AST.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/ExecutionEngine/GenericValue.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclCXX.h"
#include "clang/Frontend/CompilerInstance.h"
using namespace cling;
using namespace clang;
using namespace llvm;
StoredValueRef::StoredValue::StoredValue(Interpreter& interp,
QualType clangTy,
const llvm::Type* llvm_Ty)
: Value(GenericValue(), clangTy, llvm_Ty), m_Interp(interp), m_Mem(0){
if (clangTy->isIntegralOrEnumerationType() ||
clangTy->isRealFloatingType() ||
clangTy->hasPointerRepresentation()) {
return;
};
if (const MemberPointerType* MPT = clangTy->getAs<MemberPointerType>()) {
if (MPT->isMemberDataPointer()) {
return;
}
}
m_Mem = m_Buf;
const uint64_t size = (uint64_t) getAllocSizeInBytes();
if (size > sizeof(m_Buf)) {
m_Mem = new char[size];
}
setGV(llvm::PTOGV(m_Mem));
}
StoredValueRef::StoredValue::~StoredValue() {
// Destruct the object, then delete the memory if needed.
Destruct();
if (m_Mem != m_Buf)
delete [] m_Mem;
}
void* StoredValueRef::StoredValue::GetDtorWrapperPtr(CXXRecordDecl* CXXRD) {
std::string funcname;
{
llvm::raw_string_ostream namestr(funcname);
namestr << "__cling_StoredValue_Destruct_" << CXXRD;
}
void* dtorWrapperPtr = m_Interp.getAddressOfGlobal(funcname.c_str());
if (dtorWrapperPtr)
return dtorWrapperPtr;
std::string code("extern \"C\" void ");
std::string typeName
= utils::TypeName::GetFullyQualifiedName(getClangType(),
CXXRD->getASTContext());
code += funcname + "(void* obj){((" + typeName + "*)obj)->~"
+ typeName +"();}";
m_Interp.declare(code);
return m_Interp.getAddressOfGlobal(funcname.c_str());
}
void StoredValueRef::StoredValue::Destruct() {
// If applicable, call addr->~Type() to destruct the object.
// template <typename T> void destr(T* obj = 0) { (T)obj->~T(); }
// |-FunctionDecl destr 'void (struct XB *)'
// |-TemplateArgument type 'struct XB'
// |-ParmVarDecl obj 'struct XB *'
// `-CompoundStmt
// `-CXXMemberCallExpr 'void'
// `-MemberExpr '<bound member function type>' ->~XB
// `-ImplicitCastExpr 'struct XB *' <LValueToRValue>
// `-DeclRefExpr 'struct XB *' lvalue ParmVar 'obj' 'struct XB *'
if (getClangType.isConst())
return;
const RecordType* RT = dyn_cast<RecordType>(getClangType());
if (!RT)
return;
CXXRecordDecl* CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl());
if (!CXXRD || CXXRD->hasTrivialDestructor())
return;
CXXRD = CXXRD->getCanonicalDecl();
void* funcPtr = GetDtorWrapperPtr(CXXRD);
if (!funcPtr)
return;
typedef void (*DtorWrapperFunc_t)(void* obj);
DtorWrapperFunc_t wrapperFuncPtr = (DtorWrapperFunc_t) funcPtr;
(*wrapperFuncPtr)(getAs<void*>());
}
long long StoredValueRef::StoredValue::getAllocSizeInBytes() const {
const ASTContext& ctx = m_Interp.getCI()->getASTContext();
return (long long) ctx.getTypeSizeInChars(getClangType()).getQuantity();
}
void StoredValueRef::dump() const {
ASTContext& ctx = m_Value->m_Interp.getCI()->getASTContext();
valuePrinterInternal::StreamStoredValueRef(llvm::errs(), this, ctx);
}
StoredValueRef StoredValueRef::allocate(Interpreter& interp, QualType t,
const llvm::Type* llvmTy) {
return new StoredValue(interp, t, llvmTy);
}
StoredValueRef StoredValueRef::bitwiseCopy(Interpreter& interp,
const Value& value) {
StoredValue* SValue
= new StoredValue(interp, value.getClangType(), value.getLLVMType());
if (SValue->m_Mem) {
const char* src = (const char*)value.getGV().PointerVal;
// It's not a pointer. LLVM stores a char[5] (i.e. 5 x i8) as an i40,
// so use that instead. We don't keep it as an int; instead, we "allocate"
// it as a "proper" char[5] in the m_Mem. "Allocate" because it uses the
// m_Buf, so no actual allocation happens.
uint64_t IntVal = value.getGV().IntVal.getSExtValue();
if (!src) src = (const char*)&IntVal;
memcpy(SValue->m_Mem, src,
SValue->getAllocSizeInBytes());
} else {
SValue->setGV(value.getGV());
}
return SValue;
}
<commit_msg>The destructor is called N::A<B>::~A<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id: ValuePrinter.cpp 46307 2012-10-04 06:53:23Z axel $
// author: Axel Naumann <axel@cern.ch>
//------------------------------------------------------------------------------
#include "cling/Interpreter/StoredValueRef.h"
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/ValuePrinter.h"
#include "cling/Utils/AST.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/ExecutionEngine/GenericValue.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclCXX.h"
#include "clang/Frontend/CompilerInstance.h"
using namespace cling;
using namespace clang;
using namespace llvm;
StoredValueRef::StoredValue::StoredValue(Interpreter& interp,
QualType clangTy,
const llvm::Type* llvm_Ty)
: Value(GenericValue(), clangTy, llvm_Ty), m_Interp(interp), m_Mem(0){
if (clangTy->isIntegralOrEnumerationType() ||
clangTy->isRealFloatingType() ||
clangTy->hasPointerRepresentation()) {
return;
};
if (const MemberPointerType* MPT = clangTy->getAs<MemberPointerType>()) {
if (MPT->isMemberDataPointer()) {
return;
}
}
m_Mem = m_Buf;
const uint64_t size = (uint64_t) getAllocSizeInBytes();
if (size > sizeof(m_Buf)) {
m_Mem = new char[size];
}
setGV(llvm::PTOGV(m_Mem));
}
StoredValueRef::StoredValue::~StoredValue() {
// Destruct the object, then delete the memory if needed.
Destruct();
if (m_Mem != m_Buf)
delete [] m_Mem;
}
void* StoredValueRef::StoredValue::GetDtorWrapperPtr(CXXRecordDecl* CXXRD) {
std::string funcname;
{
llvm::raw_string_ostream namestr(funcname);
namestr << "__cling_StoredValue_Destruct_" << CXXRD;
}
void* dtorWrapperPtr = m_Interp.getAddressOfGlobal(funcname.c_str());
if (dtorWrapperPtr)
return dtorWrapperPtr;
std::string code("extern \"C\" void ");
std::string typeName
= utils::TypeName::GetFullyQualifiedName(getClangType(),
CXXRD->getASTContext());
code += funcname + "(void* obj){((" + typeName + "*)obj)->~"
+ getClangType().toString() +"();}";
m_Interp.declare(code);
return m_Interp.getAddressOfGlobal(funcname.c_str());
}
void StoredValueRef::StoredValue::Destruct() {
// If applicable, call addr->~Type() to destruct the object.
// template <typename T> void destr(T* obj = 0) { (T)obj->~T(); }
// |-FunctionDecl destr 'void (struct XB *)'
// |-TemplateArgument type 'struct XB'
// |-ParmVarDecl obj 'struct XB *'
// `-CompoundStmt
// `-CXXMemberCallExpr 'void'
// `-MemberExpr '<bound member function type>' ->~XB
// `-ImplicitCastExpr 'struct XB *' <LValueToRValue>
// `-DeclRefExpr 'struct XB *' lvalue ParmVar 'obj' 'struct XB *'
if (getClangType.isConst())
return;
const RecordType* RT = dyn_cast<RecordType>(getClangType());
if (!RT)
return;
CXXRecordDecl* CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl());
if (!CXXRD || CXXRD->hasTrivialDestructor())
return;
CXXRD = CXXRD->getCanonicalDecl();
void* funcPtr = GetDtorWrapperPtr(CXXRD);
if (!funcPtr)
return;
typedef void (*DtorWrapperFunc_t)(void* obj);
DtorWrapperFunc_t wrapperFuncPtr = (DtorWrapperFunc_t) funcPtr;
(*wrapperFuncPtr)(getAs<void*>());
}
long long StoredValueRef::StoredValue::getAllocSizeInBytes() const {
const ASTContext& ctx = m_Interp.getCI()->getASTContext();
return (long long) ctx.getTypeSizeInChars(getClangType()).getQuantity();
}
void StoredValueRef::dump() const {
ASTContext& ctx = m_Value->m_Interp.getCI()->getASTContext();
valuePrinterInternal::StreamStoredValueRef(llvm::errs(), this, ctx);
}
StoredValueRef StoredValueRef::allocate(Interpreter& interp, QualType t,
const llvm::Type* llvmTy) {
return new StoredValue(interp, t, llvmTy);
}
StoredValueRef StoredValueRef::bitwiseCopy(Interpreter& interp,
const Value& value) {
StoredValue* SValue
= new StoredValue(interp, value.getClangType(), value.getLLVMType());
if (SValue->m_Mem) {
const char* src = (const char*)value.getGV().PointerVal;
// It's not a pointer. LLVM stores a char[5] (i.e. 5 x i8) as an i40,
// so use that instead. We don't keep it as an int; instead, we "allocate"
// it as a "proper" char[5] in the m_Mem. "Allocate" because it uses the
// m_Buf, so no actual allocation happens.
uint64_t IntVal = value.getGV().IntVal.getSExtValue();
if (!src) src = (const char*)&IntVal;
memcpy(SValue->m_Mem, src,
SValue->getAllocSizeInBytes());
} else {
SValue->setGV(value.getGV());
}
return SValue;
}
<|endoftext|>
|
<commit_before>#include <memory>
#include <algorithm>
#include <iterator>
#include <unordered_set>
#include <unordered_map>
#include "s_rules.hh"
#include "s_closure.hh"
#include "cons_util.hh"
#include "env.hh"
#include "zs_error.hh"
#include "builtin_equal.hh"
#include "builtin_extra.hh"
#include "builtin_util.hh"
#include "printer.hh"
#include "hasher.hh"
// #include <iostream>
using namespace std;
namespace Procedure{
namespace {
Lisp_ptr pick_first(Lisp_ptr p){
if(p.tag() == Ptr_tag::cons){
auto c = p.get<Cons*>();
if(!c) throw zs_error("syntax-rules: the pattern is empty list\n");
return c->car();
}else if(p.tag() == Ptr_tag::vector){
auto v = p.get<Vector*>();
assert(v);
if(v->empty()) throw zs_error("syntax-rules: the pattern is empty vector\n");
return (*v)[0];
}else{
throw zs_error("syntax-rules: informal pattern passed! (%s)\n", stringify(p.tag()));
}
}
void check_pattern(const SyntaxRules& sr, Lisp_ptr p,
unordered_set<Lisp_ptr> tab){
if(identifierp(p)){
if(find(begin(sr.literals()), end(sr.literals()), p) != end(sr.literals())){
// literal identifier
return;
}
// pattern variable
if(tab.find(p) != tab.end()){
throw zs_error("syntax-rules error: duplicated pattern variable! (%s)\n",
identifier_symbol(p)->name().c_str());
}
tab.insert(p);
return;
}else if(p.tag() == Ptr_tag::cons){
if(nullp(p)) return;
auto i = begin(p);
for(; i; ++i){
check_pattern(sr, *i, tab);
}
check_pattern(sr, i.base(), tab);
}else if(p.tag() == Ptr_tag::vector){
auto v = p.get<Vector*>();
for(auto i : *v){
check_pattern(sr, i, tab);
}
}else{
return;
}
}
void check_pattern(const SyntaxRules& sr, Lisp_ptr p){
pick_first(p);
check_pattern(sr, p, {});
}
} // namespace
constexpr ProcInfo SyntaxRules::sr_procinfo;
SyntaxRules::SyntaxRules(Env* e, Lisp_ptr lits, Lisp_ptr rls)
: env_(e), literals_(lits), rules_(rls){
for(auto i : lits){
if(!identifierp(i))
throw builtin_identifier_check_failed("syntax-rules", i);
}
for(auto i : rls){
bind_cons_list_strict
(i,
[&](Lisp_ptr pat, Lisp_ptr tmpl){
(void)tmpl;
check_pattern(*this, pat);
});
}
}
SyntaxRules::~SyntaxRules() = default;
static
bool try_match_1(std::unordered_map<Lisp_ptr, Lisp_ptr>& match_obj,
const SyntaxRules& sr, Lisp_ptr ignore_ident, Lisp_ptr pattern,
Env* form_env, Lisp_ptr form){
// cout << __func__ << "\tpattern = " << pattern << "\n\t\tform = " << form << endl;
// for(auto ii : match_obj){
// cout << '\t' << ii.first << " = " << ii.second << '\n';
// }
if(form.tag() == Ptr_tag::syntactic_closure){
// destruct syntactic closure
auto sc = form.get<SyntacticClosure*>();
return try_match_1(match_obj, sr, ignore_ident, pattern, sc->env(), sc->expr());
}
const auto ellipsis_sym = intern(vm.symtable(), "...");
if(identifierp(pattern)){
if(find(begin(sr.literals()), end(sr.literals()), pattern) != end(sr.literals())){
// literal identifier
// if(!identifierp(form))
// cout << __func__ << "\tcheck failed @ " << __LINE__ << endl;
if(!identifierp(form)) return false;
// if(!identifier_eq(sr.env(), pattern, form_env, form))
// cout << __func__ << "\tcheck failed @ " << __LINE__ << endl;
return identifier_eq(sr.env(), pattern, form_env, form);
}else{
// non-literal identifier
if(pattern != ignore_ident){
match_obj.insert({pattern, new SyntacticClosure(form_env, nullptr, form)});
}
return true;
}
}else if(pattern.tag() == Ptr_tag::cons){
if(form.tag() != Ptr_tag::cons){
// cout << __func__ << "\tcheck failed @ " << __LINE__ << endl;
return false;
}
if(nullp(pattern) && nullp(form)){
return true;
}
auto p_i = begin(pattern);
auto f_i = begin(form);
for(; p_i; ++p_i, (f_i ? ++f_i : f_i)){
// checks ellipsis
auto p_n = next(p_i);
if((p_n) && identifierp(*p_n) && identifier_symbol(*p_n) == ellipsis_sym){
if(identifierp(*p_i)){
// like: (A B C ...)
if(*p_i == ignore_ident){
throw zs_error("syntax-rules error: '...' is appeared following the first identifier.\n");
}
auto p_e = p_i;
while(p_e) ++p_e;
if(!nullp(p_e.base())){
throw zs_error("syntax-rules error: '...' is appeared in a inproper list pattern!\n");
}
auto f_e = f_i;
while(f_e) ++f_e;
if(!nullp(f_e.base())){
throw zs_error("syntax-rules error: '...' is used for a inproper list form!\n");
}
match_obj.insert({*p_i, f_i.base()});
return true;
}else{
// like: ((A B C) ...)
throw zs_error("syntax-rules error: ellipsis pattern is under implementing...\n");
}
}
if(!f_i) break; // this check is delayed to here, for checking the ellipsis.
if(!try_match_1(match_obj, sr, ignore_ident, *p_i, form_env, *f_i)){
// cout << __func__ << "\tcheck failed @ " << __LINE__ << endl;
return false;
}
}
// checks length
if((p_i.base().tag() == Ptr_tag::cons) && (f_i.base().tag() == Ptr_tag::cons)){
// cout << "\treached @ " << __LINE__ << endl;
// cout << "\t\t pat = " << p_i.base() << ", form = " << f_i.base() << endl;
return (nullp(p_i.base()) && nullp(f_i.base()));
}else{
// dotted list case
// cout << __func__ << "\treached @ " << __LINE__ << endl;
return try_match_1(match_obj, sr, ignore_ident, p_i.base(), form_env, f_i.base());
}
}else if(pattern.tag() == Ptr_tag::vector){
if(form.tag() != Ptr_tag::vector){
// cout << __func__ << "\tcheck failed @ " << __LINE__ << endl;
return false;
}
auto p_v = pattern.get<Vector*>();
auto f_v = form.get<Vector*>();
auto p_i = begin(*p_v), p_e = end(*p_v);
auto f_i = begin(*f_v), f_e = end(*f_v);
for(; p_i != p_e; ++p_i, ++f_i){
// checks ellipsis
auto p_n = next(p_i);
if((p_n != p_e) && identifierp(*p_n) && identifier_symbol(*p_n) == ellipsis_sym){
if(identifierp(*p_i)){
// like: (A B C ...)
if(*p_i == ignore_ident){
throw zs_error("syntax-rules error: '...' is appeared following the first identifier.\n");
}
match_obj.insert({*p_i, new Vector(f_i, f_e)});
return true;
}else{
// like: ((A B C) ...)
throw zs_error("syntax-rules error: ellipsis pattern is under implementing...\n");
}
}
if(f_i == f_e) break; // this check is delayed to here, for checking the ellipsis.
if(!try_match_1(match_obj, sr, ignore_ident, *p_i, form_env, *f_i)){
// cout << __func__ << "\tcheck failed @ " << __LINE__ << endl;
return false;
}
}
// checks length
if((p_i == p_e) && (f_i == f_e)){
return true;
}else{
// cout << __func__ << "\tcheck failed @ " << __LINE__ << endl;
return false;
}
}else{
// cout << __func__ << "\tcheck failed @ " << __LINE__ << endl;
return equal_internal(pattern, form);
}
}
static
Lisp_ptr expand(const std::unordered_map<Lisp_ptr, Lisp_ptr>& match_obj,
Lisp_ptr tmpl){
// cout << __func__ << " arg = " << tmpl << endl;
const auto ellipsis_sym = intern(vm.symtable(), "...");
if(identifierp(tmpl)){
auto m_ret = match_obj.find(tmpl);
if(m_ret != match_obj.end()){
return m_ret->second;
}else{
return tmpl;
}
}else if(tmpl.tag() == Ptr_tag::cons){
if(nullp(tmpl)) return tmpl;
GrowList gl;
auto t_i = begin(tmpl);
for(; t_i; ++t_i){
auto t_n = next(t_i);
// check ellipsis
if(identifierp(*t_i)
&& (t_n) && identifierp(*t_n)
&& identifier_symbol(*t_n) == ellipsis_sym){
auto m_ret = match_obj.find(*t_i);
if(m_ret == match_obj.end()){
throw zs_error("syntax-rules error: invalid template: followed by '...', but not bound by pattern\n");
}
if(m_ret->second.tag() == Ptr_tag::cons){
// this can be replaced directly?
for(auto i : m_ret->second){
gl.push(i);
}
}else if(m_ret->second.tag() == Ptr_tag::vector){
auto m_ret_vec = m_ret->second.get<Vector*>();
for(auto i : *m_ret_vec){
gl.push(i);
}
}else{
throw zs_error("syntax-rules error: invalid template: not sequence type\n");
}
++t_i;
}else{
gl.push(expand(match_obj, *t_i));
}
}
return gl.extract_with_tail(expand(match_obj, t_i.base()));
}else if(tmpl.tag() == Ptr_tag::vector){
auto t_vec = tmpl.get<Vector*>();
Vector vec;
for(auto t_i = begin(*t_vec), t_e = end(*t_vec); t_i != t_e; ++t_i){
auto t_n = next(t_i);
// check ellipsis
if(identifierp(*t_i)
&& (t_n != t_e) && identifierp(*t_n)
&& identifier_symbol(*t_n) == ellipsis_sym){
auto m_ret = match_obj.find(*t_i);
if(m_ret == match_obj.end()){
throw zs_error("syntax-rules error: invalid template: followed by '...', but not bound by pattern\n");
}
if(m_ret->second.tag() == Ptr_tag::cons){
vec.insert(vec.end(), begin(m_ret->second), end(m_ret->second));
}else if(m_ret->second.tag() == Ptr_tag::vector){
auto m_ret_vec = m_ret->second.get<Vector*>();
vec.insert(vec.end(), begin(*m_ret_vec), end(*m_ret_vec));
}else{
throw zs_error("syntax-rules error: invalid template: not sequence type\n");
}
++t_i;
}else{
vec.push_back(expand(match_obj, *t_i));
}
}
return new Vector(move(vec));
}else{
return tmpl;
}
}
Lisp_ptr SyntaxRules::apply(Lisp_ptr form, Env* form_env) const{
std::unordered_map<Lisp_ptr, Lisp_ptr> match_obj;
// cout << "## " << __func__ << ": form = " << form << endl;
for(auto i : this->rules()){
auto pat = i.get<Cons*>()->car();
auto tmpl = i.get<Cons*>()->cdr().get<Cons*>()->car();
// cout << "## trying: pattern = " << pat << endl;
auto ignore_ident = pick_first(pat);
if(try_match_1(match_obj, *this, ignore_ident, pat, form_env, form)){
// cout << "## matched!: pattern = " << pat << '\n';
// for(auto ii : match_obj){
// cout << '\t' << ii.first << " = " << ii.second << '\n' << endl;;
// }
return expand(match_obj, tmpl);
}else{
// cleaning map
for(auto e : match_obj){
if(auto sc = e.second.get<SyntacticClosure*>()){
delete sc;
}
}
match_obj.clear();
}
}
// cout << "## no match: form = " << form << endl;
throw zs_error("syntax-rules error: no matching pattern found!\n");
}
} // Procedure
<commit_msg>fixed syntax-rules ellipsis treating (not completed)<commit_after>#include <memory>
#include <algorithm>
#include <iterator>
#include <unordered_set>
#include <unordered_map>
#include "s_rules.hh"
#include "s_closure.hh"
#include "cons_util.hh"
#include "env.hh"
#include "zs_error.hh"
#include "builtin_equal.hh"
#include "builtin_extra.hh"
#include "builtin_util.hh"
#include "printer.hh"
#include "hasher.hh"
// #include <iostream>
using namespace std;
namespace Procedure{
namespace {
Lisp_ptr pick_first(Lisp_ptr p){
if(p.tag() == Ptr_tag::cons){
auto c = p.get<Cons*>();
if(!c) throw zs_error("syntax-rules: the pattern is empty list\n");
return c->car();
}else if(p.tag() == Ptr_tag::vector){
auto v = p.get<Vector*>();
assert(v);
if(v->empty()) throw zs_error("syntax-rules: the pattern is empty vector\n");
return (*v)[0];
}else{
throw zs_error("syntax-rules: informal pattern passed! (%s)\n", stringify(p.tag()));
}
}
void check_pattern(const SyntaxRules& sr, Lisp_ptr p,
unordered_set<Lisp_ptr> tab){
if(identifierp(p)){
if(find(begin(sr.literals()), end(sr.literals()), p) != end(sr.literals())){
// literal identifier
return;
}
// pattern variable
if(tab.find(p) != tab.end()){
throw zs_error("syntax-rules error: duplicated pattern variable! (%s)\n",
identifier_symbol(p)->name().c_str());
}
tab.insert(p);
return;
}else if(p.tag() == Ptr_tag::cons){
if(nullp(p)) return;
auto i = begin(p);
for(; i; ++i){
check_pattern(sr, *i, tab);
}
check_pattern(sr, i.base(), tab);
}else if(p.tag() == Ptr_tag::vector){
auto v = p.get<Vector*>();
for(auto i : *v){
check_pattern(sr, i, tab);
}
}else{
return;
}
}
void check_pattern(const SyntaxRules& sr, Lisp_ptr p){
pick_first(p);
check_pattern(sr, p, {});
}
} // namespace
constexpr ProcInfo SyntaxRules::sr_procinfo;
SyntaxRules::SyntaxRules(Env* e, Lisp_ptr lits, Lisp_ptr rls)
: env_(e), literals_(lits), rules_(rls){
for(auto i : lits){
if(!identifierp(i))
throw builtin_identifier_check_failed("syntax-rules", i);
}
for(auto i : rls){
bind_cons_list_strict
(i,
[&](Lisp_ptr pat, Lisp_ptr tmpl){
(void)tmpl;
check_pattern(*this, pat);
});
}
}
SyntaxRules::~SyntaxRules() = default;
static
void ensure_binding(std::unordered_map<Lisp_ptr, Lisp_ptr>& match_obj,
const SyntaxRules& sr, Lisp_ptr ignore_ident, Lisp_ptr pattern){
if(identifierp(pattern)){
if(find(begin(sr.literals()), end(sr.literals()), pattern) != end(sr.literals())){
return;
}else{
// non-literal identifier
if(pattern != ignore_ident){
match_obj.insert({pattern, new Vector()});
}
return;
}
}else if(pattern.tag() == Ptr_tag::cons){
if(nullp(pattern)){
return;
}
auto p_i = begin(pattern);
for(; p_i; ++p_i){
ensure_binding(match_obj, sr, ignore_ident, *p_i);
}
// checks length
if((p_i.base().tag() == Ptr_tag::cons)){
return;
}else{
// dotted list case
ensure_binding(match_obj, sr, ignore_ident, p_i.base());
return;
}
}else if(pattern.tag() == Ptr_tag::vector){
auto p_v = pattern.get<Vector*>();
auto p_i = begin(*p_v), p_e = end(*p_v);
for(; p_i != p_e; ++p_i){
ensure_binding(match_obj, sr, ignore_ident, *p_i);
}
}else{
return;
}
}
static
bool try_match_1(std::unordered_map<Lisp_ptr, Lisp_ptr>& match_obj,
const SyntaxRules& sr, Lisp_ptr ignore_ident, Lisp_ptr pattern,
Env* form_env, Lisp_ptr form,
bool insert_by_push){
// cout << __func__ << "\tpattern = " << pattern << "\n\t\tform = " << form << endl;
// for(auto ii : match_obj){
// cout << '\t' << ii.first << " = " << ii.second << '\n';
// }
if(form.tag() == Ptr_tag::syntactic_closure){
// destruct syntactic closure
auto sc = form.get<SyntacticClosure*>();
return try_match_1(match_obj, sr, ignore_ident, pattern, sc->env(), sc->expr(), insert_by_push);
}
const auto ellipsis_sym = intern(vm.symtable(), "...");
if(identifierp(pattern)){
if(find(begin(sr.literals()), end(sr.literals()), pattern) != end(sr.literals())){
// literal identifier
// if(!identifierp(form))
// cout << __func__ << "\tcheck failed @ " << __LINE__ << endl;
if(!identifierp(form)) return false;
// if(!identifier_eq(sr.env(), pattern, form_env, form))
// cout << __func__ << "\tcheck failed @ " << __LINE__ << endl;
return identifier_eq(sr.env(), pattern, form_env, form);
}else{
// non-literal identifier
if(pattern != ignore_ident){
auto val = new SyntacticClosure(form_env, nullptr, form);
if(insert_by_push){
auto place = match_obj.find(pattern);
assert(place->second.tag() == Ptr_tag::vector);
place->second.get<Vector*>()->push_back(val);
}else{
match_obj.insert({pattern, val});
}
}
return true;
}
}else if(pattern.tag() == Ptr_tag::cons){
if(form.tag() != Ptr_tag::cons){
// cout << __func__ << "\tcheck failed @ " << __LINE__ << endl;
return false;
}
if(nullp(pattern) && nullp(form)){
return true;
}
auto p_i = begin(pattern);
auto f_i = begin(form);
for(; p_i; ++p_i, (f_i ? ++f_i : f_i)){
// checks ellipsis
auto p_n = next(p_i);
if((p_n) && identifierp(*p_n) && identifier_symbol(*p_n) == ellipsis_sym){
if(*p_i == ignore_ident){
throw zs_error("syntax-rules error: '...' is appeared following the first identifier.\n");
}
auto p_e = p_i;
while(p_e) ++p_e;
if(!nullp(p_e.base())){
throw zs_error("syntax-rules error: '...' is appeared in a inproper list pattern!\n");
}
// accumulating...
ensure_binding(match_obj, sr, ignore_ident, *p_i);
for(; f_i; ++f_i){
if(!try_match_1(match_obj, sr, ignore_ident, *p_i, form_env, *f_i, true)){
// cout << __func__ << "\tcheck failed @ " << __LINE__ << endl;
return false;
}
}
if(!nullp(f_i.base())){
throw zs_error("syntax-rules error: '...' is used for a inproper list form!\n");
}
return true;
}
if(!f_i) break; // this check is delayed to here, for checking the ellipsis.
if(!try_match_1(match_obj, sr, ignore_ident, *p_i, form_env, *f_i, insert_by_push)){
// cout << __func__ << "\tcheck failed @ " << __LINE__ << endl;
return false;
}
}
// checks length
if((p_i.base().tag() == Ptr_tag::cons) && (f_i.base().tag() == Ptr_tag::cons)){
// cout << "\treached @ " << __LINE__ << endl;
// cout << "\t\t pat = " << p_i.base() << ", form = " << f_i.base() << endl;
return (nullp(p_i.base()) && nullp(f_i.base()));
}else{
// dotted list case
// cout << __func__ << "\treached @ " << __LINE__ << endl;
return try_match_1(match_obj, sr, ignore_ident, p_i.base(), form_env, f_i.base(), insert_by_push);
}
}else if(pattern.tag() == Ptr_tag::vector){
if(form.tag() != Ptr_tag::vector){
// cout << __func__ << "\tcheck failed @ " << __LINE__ << endl;
return false;
}
auto p_v = pattern.get<Vector*>();
auto f_v = form.get<Vector*>();
auto p_i = begin(*p_v), p_e = end(*p_v);
auto f_i = begin(*f_v), f_e = end(*f_v);
for(; p_i != p_e; ++p_i, ++f_i){
// checks ellipsis
auto p_n = next(p_i);
if((p_n != p_e) && identifierp(*p_n) && identifier_symbol(*p_n) == ellipsis_sym){
if(identifierp(*p_i)){
// like: (A B C ...)
if(*p_i == ignore_ident){
throw zs_error("syntax-rules error: '...' is appeared following the first identifier.\n");
}
match_obj.insert({*p_i, new Vector(f_i, f_e)});
return true;
}else{
// like: ((A B C) ...)
throw zs_error("syntax-rules error: ellipsis pattern is under implementing...\n");
}
}
if(f_i == f_e) break; // this check is delayed to here, for checking the ellipsis.
if(!try_match_1(match_obj, sr, ignore_ident, *p_i, form_env, *f_i, insert_by_push)){
// cout << __func__ << "\tcheck failed @ " << __LINE__ << endl;
return false;
}
}
// checks length
if((p_i == p_e) && (f_i == f_e)){
return true;
}else{
// cout << __func__ << "\tcheck failed @ " << __LINE__ << endl;
return false;
}
}else{
// cout << __func__ << "\tcheck failed @ " << __LINE__ << endl;
return equal_internal(pattern, form);
}
}
static
Lisp_ptr expand(const std::unordered_map<Lisp_ptr, Lisp_ptr>& match_obj,
Lisp_ptr tmpl){
// cout << __func__ << " arg = " << tmpl << endl;
// for(auto ii : match_obj){
// cout << '\t' << ii.first << " = " << ii.second << '\n';
// }
const auto ellipsis_sym = intern(vm.symtable(), "...");
if(identifierp(tmpl)){
auto m_ret = match_obj.find(tmpl);
if(m_ret != match_obj.end()){
return m_ret->second;
}else{
return tmpl;
}
}else if(tmpl.tag() == Ptr_tag::cons){
if(nullp(tmpl)) return tmpl;
GrowList gl;
auto t_i = begin(tmpl);
for(; t_i; ++t_i){
auto t_n = next(t_i);
// check ellipsis
if(identifierp(*t_i)
&& (t_n) && identifierp(*t_n)
&& identifier_symbol(*t_n) == ellipsis_sym){
auto m_ret = match_obj.find(*t_i);
if(m_ret == match_obj.end()){
// cout << __func__ << " key = " << *t_i << endl;
throw zs_error("syntax-rules error: invalid template: followed by '...', but not bound by pattern\n");
}
if(m_ret->second.tag() == Ptr_tag::cons){
// this can be replaced directly?
for(auto i : m_ret->second){
gl.push(i);
}
}else if(m_ret->second.tag() == Ptr_tag::vector){
auto m_ret_vec = m_ret->second.get<Vector*>();
for(auto i : *m_ret_vec){
gl.push(i);
}
}else{
throw zs_error("syntax-rules error: invalid template: not sequence type\n");
}
++t_i;
}else{
gl.push(expand(match_obj, *t_i));
}
}
return gl.extract_with_tail(expand(match_obj, t_i.base()));
}else if(tmpl.tag() == Ptr_tag::vector){
auto t_vec = tmpl.get<Vector*>();
Vector vec;
for(auto t_i = begin(*t_vec), t_e = end(*t_vec); t_i != t_e; ++t_i){
auto t_n = next(t_i);
// check ellipsis
if(identifierp(*t_i)
&& (t_n != t_e) && identifierp(*t_n)
&& identifier_symbol(*t_n) == ellipsis_sym){
auto m_ret = match_obj.find(*t_i);
if(m_ret == match_obj.end()){
throw zs_error("syntax-rules error: invalid template: followed by '...', but not bound by pattern\n");
}
if(m_ret->second.tag() == Ptr_tag::cons){
vec.insert(vec.end(), begin(m_ret->second), end(m_ret->second));
}else if(m_ret->second.tag() == Ptr_tag::vector){
auto m_ret_vec = m_ret->second.get<Vector*>();
vec.insert(vec.end(), begin(*m_ret_vec), end(*m_ret_vec));
}else{
throw zs_error("syntax-rules error: invalid template: not sequence type\n");
}
++t_i;
}else{
vec.push_back(expand(match_obj, *t_i));
}
}
return new Vector(move(vec));
}else{
return tmpl;
}
}
Lisp_ptr SyntaxRules::apply(Lisp_ptr form, Env* form_env) const{
std::unordered_map<Lisp_ptr, Lisp_ptr> match_obj;
// cout << "## " << __func__ << ": form = " << form << endl;
for(auto i : this->rules()){
auto pat = i.get<Cons*>()->car();
auto tmpl = i.get<Cons*>()->cdr().get<Cons*>()->car();
// cout << "## trying: pattern = " << pat << endl;
auto ignore_ident = pick_first(pat);
if(try_match_1(match_obj, *this, ignore_ident, pat, form_env, form, false)){
// cout << "## matched!:\tpattern = " << pat << '\n';
// cout << "## \t\tform = " << form << '\n';
// for(auto ii : match_obj){
// cout << '\t' << ii.first << " = " << ii.second << '\n';
// }
auto ex = expand(match_obj, tmpl);
// cout << "## expand = " << ex << '\n';
// cout << endl;
return ex;
}else{
// cleaning map
for(auto e : match_obj){
if(auto sc = e.second.get<SyntacticClosure*>()){
delete sc;
}
}
match_obj.clear();
}
}
// cout << "## no match: form = " << form << endl;
throw zs_error("syntax-rules error: no matching pattern found!\n");
}
} // Procedure
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2257
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1333184 by johtaylo@johtaylo-jtincrementor-increment on 2016/10/28 03:00:05<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2258
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2571
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1503341 by johtaylo@johtaylo-jtincrementor2-increment on 2018/01/13 03:00:06<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2572
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2897
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1781819 by chui@ocl-promo-incrementor on 2019/05/13 03:00:04<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2898
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2368
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1376751 by johtaylo@johtaylo-jtincrementor-increment on 2017/02/23 03:00:05<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2369
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2544
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1487469 by johtaylo@johtaylo-jtincrementor2-increment on 2017/11/28 03:00:04<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2545
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2778
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1709971 by chui@ocl-promo-incrementor on 2018/11/21 03:00:10<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2779
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2029
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1235185 by johtaylo@johtaylo-JTBUILDER03-increment on 2016/02/08 03:00:10<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2030
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3034
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 2027775 by chui@ocl-promo-incrementor on 2019/11/09 03:00:06<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3035
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|>
|
<commit_before>// Copyright 2018 Ulf Adams
//
// The contents of this file may be used under the terms of the Apache License,
// Version 2.0.
//
// (See accompanying file LICENSE-Apache or copy at
// http://www.apache.org/licenses/LICENSE-2.0)
//
// Alternatively, the contents of this file may be used under the terms of
// the Boost Software License, Version 1.0.
// (See accompanying file LICENSE-Boost or copy at
// https://www.boost.org/LICENSE_1_0.txt)
//
// Unless required by applicable law or agreed to in writing, this software
// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.
#include <math.h>
#include <inttypes.h>
#include <iostream>
#include <string.h>
#include <chrono>
#include <random>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#if defined(__linux__)
#include <sys/types.h>
#include <unistd.h>
#endif
#include "ryu/ryu.h"
#include "third_party/double-conversion/double-conversion/utils.h"
#include "third_party/double-conversion/double-conversion/double-conversion.h"
using double_conversion::StringBuilder;
using double_conversion::DoubleToStringConverter;
using namespace std::chrono;
constexpr int BUFFER_SIZE = 40;
static char buffer[BUFFER_SIZE];
static DoubleToStringConverter converter(
DoubleToStringConverter::Flags::EMIT_TRAILING_DECIMAL_POINT
| DoubleToStringConverter::Flags::EMIT_TRAILING_ZERO_AFTER_POINT,
"Infinity",
"NaN",
'E',
7,
7,
0,
0);
static StringBuilder builder(buffer, BUFFER_SIZE);
void fcv(float value) {
builder.Reset();
converter.ToShortestSingle(value, &builder);
builder.Finalize();
}
void dcv(double value) {
builder.Reset();
converter.ToShortest(value, &builder);
builder.Finalize();
}
static float int32Bits2Float(uint32_t bits) {
float f;
memcpy(&f, &bits, sizeof(float));
return f;
}
static double int64Bits2Double(uint64_t bits) {
double f;
memcpy(&f, &bits, sizeof(double));
return f;
}
struct mean_and_variance {
int64_t n = 0;
double mean = 0;
double m2 = 0;
void update(double x) {
++n;
double d = x - mean;
mean += d / n;
double d2 = x - mean;
m2 += d * d2;
}
double variance() const {
return m2 / (n - 1);
}
double stddev() const {
return sqrt(variance());
}
};
float generate_float(std::mt19937& mt32) {
uint32_t r = mt32();
float f = int32Bits2Float(r);
return f;
}
static int bench32(int samples, int iterations, bool verbose, bool ryu_only, bool classic) {
char bufferown[BUFFER_SIZE];
std::mt19937 mt32(12345);
mean_and_variance mv1;
mean_and_variance mv2;
int throwaway = 0;
if (classic) {
for (int i = 0; i < samples; ++i) {
const float f = generate_float(mt32);
auto t1 = steady_clock::now();
for (int j = 0; j < iterations; ++j) {
f2s_buffered(f, bufferown);
throwaway += bufferown[2];
}
auto t2 = steady_clock::now();
double delta1 = duration_cast<nanoseconds>(t2 - t1).count() / static_cast<double>(iterations);
mv1.update(delta1);
double delta2 = 0.0;
if (!ryu_only) {
t1 = steady_clock::now();
for (int j = 0; j < iterations; ++j) {
fcv(f);
throwaway += buffer[2];
}
t2 = steady_clock::now();
delta2 = duration_cast<nanoseconds>(t2 - t1).count() / static_cast<double>(iterations);
mv2.update(delta2);
}
if (verbose) {
if (ryu_only) {
printf("%.6a,%f\n", f, delta1);
} else {
printf("%.6a,%f,%f\n", f, delta1, delta2);
}
}
if (!ryu_only && strcmp(bufferown, buffer) != 0) {
printf("For %.6a %20s %20s\n", f, bufferown, buffer);
}
}
} else {
std::vector<float> vec(samples);
for (int i = 0; i < samples; ++i) {
vec[i] = generate_float(mt32);
}
for (int j = 0; j < iterations; ++j) {
auto t1 = steady_clock::now();
for (int i = 0; i < samples; ++i) {
f2s_buffered(vec[i], bufferown);
throwaway += bufferown[2];
}
auto t2 = steady_clock::now();
double delta1 = duration_cast<nanoseconds>(t2 - t1).count() / static_cast<double>(samples);
mv1.update(delta1);
double delta2 = 0.0;
if (!ryu_only) {
t1 = steady_clock::now();
for (int i = 0; i < samples; ++i) {
fcv(vec[i]);
throwaway += buffer[2];
}
t2 = steady_clock::now();
delta2 = duration_cast<nanoseconds>(t2 - t1).count() / static_cast<double>(samples);
mv2.update(delta2);
}
if (verbose) {
if (ryu_only) {
printf("%f\n", delta1);
} else {
printf("%f,%f\n", delta1, delta2);
}
}
}
}
if (!verbose) {
printf("32: %8.3f %8.3f", mv1.mean, mv1.stddev());
if (!ryu_only) {
printf(" %8.3f %8.3f", mv2.mean, mv2.stddev());
}
printf("\n");
}
return throwaway;
}
double generate_double(std::mt19937& mt32) {
uint64_t r = mt32();
r <<= 32;
r |= mt32(); // calling mt32() in separate statements guarantees order of evaluation
double f = int64Bits2Double(r);
return f;
}
static int bench64(int samples, int iterations, bool verbose, bool ryu_only, bool classic) {
char bufferown[BUFFER_SIZE];
std::mt19937 mt32(12345);
mean_and_variance mv1;
mean_and_variance mv2;
int throwaway = 0;
if (classic) {
for (int i = 0; i < samples; ++i) {
const double f = generate_double(mt32);
auto t1 = steady_clock::now();
for (int j = 0; j < iterations; ++j) {
d2s_buffered(f, bufferown);
throwaway += bufferown[2];
}
auto t2 = steady_clock::now();
double delta1 = duration_cast<nanoseconds>(t2 - t1).count() / static_cast<double>(iterations);
mv1.update(delta1);
double delta2 = 0.0;
if (!ryu_only) {
t1 = steady_clock::now();
for (int j = 0; j < iterations; ++j) {
dcv(f);
throwaway += buffer[2];
}
t2 = steady_clock::now();
delta2 = duration_cast<nanoseconds>(t2 - t1).count() / static_cast<double>(iterations);
mv2.update(delta2);
}
if (verbose) {
if (ryu_only) {
printf("%.13a,%f\n", f, delta1);
} else {
printf("%.13a,%f,%f\n", f, delta1, delta2);
}
}
if (!ryu_only && strcmp(bufferown, buffer) != 0) {
printf("For %.13a %28s %28s\n", f, bufferown, buffer);
}
}
} else {
std::vector<double> vec(samples);
for (int i = 0; i < samples; ++i) {
vec[i] = generate_double(mt32);
}
for (int j = 0; j < iterations; ++j) {
auto t1 = steady_clock::now();
for (int i = 0; i < samples; ++i) {
d2s_buffered(vec[i], bufferown);
throwaway += bufferown[2];
}
auto t2 = steady_clock::now();
double delta1 = duration_cast<nanoseconds>(t2 - t1).count() / static_cast<double>(samples);
mv1.update(delta1);
double delta2 = 0.0;
if (!ryu_only) {
t1 = steady_clock::now();
for (int i = 0; i < samples; ++i) {
dcv(vec[i]);
throwaway += buffer[2];
}
t2 = steady_clock::now();
delta2 = duration_cast<nanoseconds>(t2 - t1).count() / static_cast<double>(samples);
mv2.update(delta2);
}
if (verbose) {
if (ryu_only) {
printf("%f\n", delta1);
} else {
printf("%f,%f\n", delta1, delta2);
}
}
}
}
if (!verbose) {
printf("64: %8.3f %8.3f", mv1.mean, mv1.stddev());
if (!ryu_only) {
printf(" %8.3f %8.3f", mv2.mean, mv2.stddev());
}
printf("\n");
}
return throwaway;
}
int main(int argc, char** argv) {
#if defined(__linux__)
// Also disable hyperthreading with something like this:
// cat /sys/devices/system/cpu/cpu*/topology/core_id
// sudo /bin/bash -c "echo 0 > /sys/devices/system/cpu/cpu6/online"
cpu_set_t my_set;
CPU_ZERO(&my_set);
CPU_SET(2, &my_set);
sched_setaffinity(getpid(), sizeof(cpu_set_t), &my_set);
#endif
// By default, run both 32 and 64-bit benchmarks with 10000 samples and 1000 iterations each.
bool run32 = true;
bool run64 = true;
int samples = 10000;
int iterations = 1000;
bool verbose = false;
bool ryu_only = false;
bool classic = false;
for (int i = 1; i < argc; ++i) {
if (strcmp(argv[i], "-32") == 0) {
run32 = true;
run64 = false;
} else if (strcmp(argv[i], "-64") == 0) {
run32 = false;
run64 = true;
} else if (strcmp(argv[i], "-v") == 0) {
verbose = true;
} else if (strcmp(argv[i], "-ryu") == 0) {
ryu_only = true;
} else if (strcmp(argv[i], "-classic") == 0) {
classic = true;
} else if (strncmp(argv[i], "-samples=", 9) == 0) {
sscanf(argv[i], "-samples=%i", &samples);
} else if (strncmp(argv[i], "-iterations=", 12) == 0) {
sscanf(argv[i], "-iterations=%i", &iterations);
} else {
printf("Unrecognized option '%s'.\n", argv[i]);
return EXIT_FAILURE;
}
}
if (!verbose) {
// No need to buffer the output if we're just going to print three lines.
setbuf(stdout, NULL);
}
if (verbose) {
printf("%sryu_time_in_ns%s\n", classic ? "hexfloat," : "", ryu_only ? "" : ",grisu3_time_in_ns");
} else {
printf(" Average & Stddev Ryu%s\n", ryu_only ? "" : " Average & Stddev Grisu3");
}
int throwaway = 0;
if (run32) {
throwaway += bench32(samples, iterations, verbose, ryu_only, classic);
}
if (run64) {
throwaway += bench64(samples, iterations, verbose, ryu_only, classic);
}
if (argc == 1000) {
// Prevent the compiler from optimizing the code away.
printf("%d\n", throwaway);
}
return 0;
}
<commit_msg>benchmark.cc: Extract benchmark_options.<commit_after>// Copyright 2018 Ulf Adams
//
// The contents of this file may be used under the terms of the Apache License,
// Version 2.0.
//
// (See accompanying file LICENSE-Apache or copy at
// http://www.apache.org/licenses/LICENSE-2.0)
//
// Alternatively, the contents of this file may be used under the terms of
// the Boost Software License, Version 1.0.
// (See accompanying file LICENSE-Boost or copy at
// https://www.boost.org/LICENSE_1_0.txt)
//
// Unless required by applicable law or agreed to in writing, this software
// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.
#include <math.h>
#include <inttypes.h>
#include <iostream>
#include <string.h>
#include <chrono>
#include <random>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#if defined(__linux__)
#include <sys/types.h>
#include <unistd.h>
#endif
#include "ryu/ryu.h"
#include "third_party/double-conversion/double-conversion/utils.h"
#include "third_party/double-conversion/double-conversion/double-conversion.h"
using double_conversion::StringBuilder;
using double_conversion::DoubleToStringConverter;
using namespace std::chrono;
constexpr int BUFFER_SIZE = 40;
static char buffer[BUFFER_SIZE];
static DoubleToStringConverter converter(
DoubleToStringConverter::Flags::EMIT_TRAILING_DECIMAL_POINT
| DoubleToStringConverter::Flags::EMIT_TRAILING_ZERO_AFTER_POINT,
"Infinity",
"NaN",
'E',
7,
7,
0,
0);
static StringBuilder builder(buffer, BUFFER_SIZE);
void fcv(float value) {
builder.Reset();
converter.ToShortestSingle(value, &builder);
builder.Finalize();
}
void dcv(double value) {
builder.Reset();
converter.ToShortest(value, &builder);
builder.Finalize();
}
static float int32Bits2Float(uint32_t bits) {
float f;
memcpy(&f, &bits, sizeof(float));
return f;
}
static double int64Bits2Double(uint64_t bits) {
double f;
memcpy(&f, &bits, sizeof(double));
return f;
}
struct mean_and_variance {
int64_t n = 0;
double mean = 0;
double m2 = 0;
void update(double x) {
++n;
double d = x - mean;
mean += d / n;
double d2 = x - mean;
m2 += d * d2;
}
double variance() const {
return m2 / (n - 1);
}
double stddev() const {
return sqrt(variance());
}
};
class benchmark_options {
public:
benchmark_options() = default;
benchmark_options(const benchmark_options&) = delete;
benchmark_options& operator=(const benchmark_options&) = delete;
bool run32() const { return m_run32; }
bool run64() const { return m_run64; }
int samples() const { return m_samples; }
int iterations() const { return m_iterations; }
bool verbose() const { return m_verbose; }
bool ryu_only() const { return m_ryu_only; }
bool classic() const { return m_classic; }
void parse(const char * const arg) {
if (strcmp(arg, "-32") == 0) {
m_run32 = true;
m_run64 = false;
} else if (strcmp(arg, "-64") == 0) {
m_run32 = false;
m_run64 = true;
} else if (strcmp(arg, "-v") == 0) {
m_verbose = true;
} else if (strcmp(arg, "-ryu") == 0) {
m_ryu_only = true;
} else if (strcmp(arg, "-classic") == 0) {
m_classic = true;
} else if (strncmp(arg, "-samples=", 9) == 0) {
sscanf(arg, "-samples=%i", &m_samples);
} else if (strncmp(arg, "-iterations=", 12) == 0) {
sscanf(arg, "-iterations=%i", &m_iterations);
} else {
printf("Unrecognized option '%s'.\n", arg);
exit(EXIT_FAILURE);
}
}
private:
// By default, run both 32 and 64-bit benchmarks with 10000 samples and 1000 iterations each.
bool m_run32 = true;
bool m_run64 = true;
int m_samples = 10000;
int m_iterations = 1000;
bool m_verbose = false;
bool m_ryu_only = false;
bool m_classic = false;
};
float generate_float(std::mt19937& mt32) {
uint32_t r = mt32();
float f = int32Bits2Float(r);
return f;
}
static int bench32(const benchmark_options& options) {
char bufferown[BUFFER_SIZE];
std::mt19937 mt32(12345);
mean_and_variance mv1;
mean_and_variance mv2;
int throwaway = 0;
if (options.classic()) {
for (int i = 0; i < options.samples(); ++i) {
const float f = generate_float(mt32);
auto t1 = steady_clock::now();
for (int j = 0; j < options.iterations(); ++j) {
f2s_buffered(f, bufferown);
throwaway += bufferown[2];
}
auto t2 = steady_clock::now();
double delta1 = duration_cast<nanoseconds>(t2 - t1).count() / static_cast<double>(options.iterations());
mv1.update(delta1);
double delta2 = 0.0;
if (!options.ryu_only()) {
t1 = steady_clock::now();
for (int j = 0; j < options.iterations(); ++j) {
fcv(f);
throwaway += buffer[2];
}
t2 = steady_clock::now();
delta2 = duration_cast<nanoseconds>(t2 - t1).count() / static_cast<double>(options.iterations());
mv2.update(delta2);
}
if (options.verbose()) {
if (options.ryu_only()) {
printf("%.6a,%f\n", f, delta1);
} else {
printf("%.6a,%f,%f\n", f, delta1, delta2);
}
}
if (!options.ryu_only() && strcmp(bufferown, buffer) != 0) {
printf("For %.6a %20s %20s\n", f, bufferown, buffer);
}
}
} else {
std::vector<float> vec(options.samples());
for (int i = 0; i < options.samples(); ++i) {
vec[i] = generate_float(mt32);
}
for (int j = 0; j < options.iterations(); ++j) {
auto t1 = steady_clock::now();
for (int i = 0; i < options.samples(); ++i) {
f2s_buffered(vec[i], bufferown);
throwaway += bufferown[2];
}
auto t2 = steady_clock::now();
double delta1 = duration_cast<nanoseconds>(t2 - t1).count() / static_cast<double>(options.samples());
mv1.update(delta1);
double delta2 = 0.0;
if (!options.ryu_only()) {
t1 = steady_clock::now();
for (int i = 0; i < options.samples(); ++i) {
fcv(vec[i]);
throwaway += buffer[2];
}
t2 = steady_clock::now();
delta2 = duration_cast<nanoseconds>(t2 - t1).count() / static_cast<double>(options.samples());
mv2.update(delta2);
}
if (options.verbose()) {
if (options.ryu_only()) {
printf("%f\n", delta1);
} else {
printf("%f,%f\n", delta1, delta2);
}
}
}
}
if (!options.verbose()) {
printf("32: %8.3f %8.3f", mv1.mean, mv1.stddev());
if (!options.ryu_only()) {
printf(" %8.3f %8.3f", mv2.mean, mv2.stddev());
}
printf("\n");
}
return throwaway;
}
double generate_double(std::mt19937& mt32) {
uint64_t r = mt32();
r <<= 32;
r |= mt32(); // calling mt32() in separate statements guarantees order of evaluation
double f = int64Bits2Double(r);
return f;
}
static int bench64(const benchmark_options& options) {
char bufferown[BUFFER_SIZE];
std::mt19937 mt32(12345);
mean_and_variance mv1;
mean_and_variance mv2;
int throwaway = 0;
if (options.classic()) {
for (int i = 0; i < options.samples(); ++i) {
const double f = generate_double(mt32);
auto t1 = steady_clock::now();
for (int j = 0; j < options.iterations(); ++j) {
d2s_buffered(f, bufferown);
throwaway += bufferown[2];
}
auto t2 = steady_clock::now();
double delta1 = duration_cast<nanoseconds>(t2 - t1).count() / static_cast<double>(options.iterations());
mv1.update(delta1);
double delta2 = 0.0;
if (!options.ryu_only()) {
t1 = steady_clock::now();
for (int j = 0; j < options.iterations(); ++j) {
dcv(f);
throwaway += buffer[2];
}
t2 = steady_clock::now();
delta2 = duration_cast<nanoseconds>(t2 - t1).count() / static_cast<double>(options.iterations());
mv2.update(delta2);
}
if (options.verbose()) {
if (options.ryu_only()) {
printf("%.13a,%f\n", f, delta1);
} else {
printf("%.13a,%f,%f\n", f, delta1, delta2);
}
}
if (!options.ryu_only() && strcmp(bufferown, buffer) != 0) {
printf("For %.13a %28s %28s\n", f, bufferown, buffer);
}
}
} else {
std::vector<double> vec(options.samples());
for (int i = 0; i < options.samples(); ++i) {
vec[i] = generate_double(mt32);
}
for (int j = 0; j < options.iterations(); ++j) {
auto t1 = steady_clock::now();
for (int i = 0; i < options.samples(); ++i) {
d2s_buffered(vec[i], bufferown);
throwaway += bufferown[2];
}
auto t2 = steady_clock::now();
double delta1 = duration_cast<nanoseconds>(t2 - t1).count() / static_cast<double>(options.samples());
mv1.update(delta1);
double delta2 = 0.0;
if (!options.ryu_only()) {
t1 = steady_clock::now();
for (int i = 0; i < options.samples(); ++i) {
dcv(vec[i]);
throwaway += buffer[2];
}
t2 = steady_clock::now();
delta2 = duration_cast<nanoseconds>(t2 - t1).count() / static_cast<double>(options.samples());
mv2.update(delta2);
}
if (options.verbose()) {
if (options.ryu_only()) {
printf("%f\n", delta1);
} else {
printf("%f,%f\n", delta1, delta2);
}
}
}
}
if (!options.verbose()) {
printf("64: %8.3f %8.3f", mv1.mean, mv1.stddev());
if (!options.ryu_only()) {
printf(" %8.3f %8.3f", mv2.mean, mv2.stddev());
}
printf("\n");
}
return throwaway;
}
int main(int argc, char** argv) {
#if defined(__linux__)
// Also disable hyperthreading with something like this:
// cat /sys/devices/system/cpu/cpu*/topology/core_id
// sudo /bin/bash -c "echo 0 > /sys/devices/system/cpu/cpu6/online"
cpu_set_t my_set;
CPU_ZERO(&my_set);
CPU_SET(2, &my_set);
sched_setaffinity(getpid(), sizeof(cpu_set_t), &my_set);
#endif
benchmark_options options;
for (int i = 1; i < argc; ++i) {
options.parse(argv[i]);
}
if (!options.verbose()) {
// No need to buffer the output if we're just going to print three lines.
setbuf(stdout, NULL);
}
if (options.verbose()) {
printf("%sryu_time_in_ns%s\n", options.classic() ? "hexfloat," : "", options.ryu_only() ? "" : ",grisu3_time_in_ns");
} else {
printf(" Average & Stddev Ryu%s\n", options.ryu_only() ? "" : " Average & Stddev Grisu3");
}
int throwaway = 0;
if (options.run32()) {
throwaway += bench32(options);
}
if (options.run64()) {
throwaway += bench64(options);
}
if (argc == 1000) {
// Prevent the compiler from optimizing the code away.
printf("%d\n", throwaway);
}
return 0;
}
<|endoftext|>
|
<commit_before>#include "isect2d.h"
#include "vec2.h"
#include <iostream>
#include <cmath>
#include <vector>
#include <memory>
#include <random>
#include <stack>
#include <GLFW/glfw3.h>
#include "../../tangram-es/core/include/glm/glm/glm.hpp"
//#include "../../tangram-es/core/include/glm/glm/gtx/norm.hpp"
#include "glm_vec.h"
//#define CIRCLES
#define N_CIRCLES 500
#define AREA
#define N_BOX 1000
GLFWwindow* window;
float width = 800;
float height = 600;
float dpiRatio = 1;
bool pause = false;
using Vec2 = glm::vec2;
//using Vec2 = isect2d::Vec2;
using OBB = isect2d::OBB<Vec2>;
using AABB = isect2d::AABB<Vec2>;
std::vector<OBB> obbs;
float rand_0_1(float scale) {
return ((float)rand() / (float)(RAND_MAX)) * scale;
}
void update() {
double time = glfwGetTime();
if(!pause) {
int i = 0;
for (auto& obb : obbs) {
float r1 = rand_0_1(10);
float r2 = rand_0_1(20);
float r3 = rand_0_1(M_PI);
auto centroid = obb.getCentroid();
if (++i % 2 == 0) {
obb.move(centroid.x, centroid.y + .02 * cos(time * 0.25) * r2);
obb.rotate(cos(r3) * 0.1 + obb.getAngle());
} else {
obb.move(centroid.x + 0.1 * cos(time) * r1, centroid.y);
obb.rotate(cos(r2) * 0.1 + obb.getAngle());
}
}
}
}
void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods) {
if(key == 'P' && action == GLFW_PRESS) {
pause = !pause;
}
}
void initBBoxes() {
#if defined CIRCLES
int n = N_BOX;
float o = (2 * M_PI) / n;
float size = 200;
float boxSize = n / (0.4 * n);
for (int i = 0; i < n; ++i) {
float r = rand_0_1(20);
obbs.push_back(OBB(cos(o * i) * size + width / 2,
sin(o * i) * size + height / 2, r,
r + boxSize * 8, r * boxSize / 3 + boxSize));
}
#elif defined AREA
int n = N_BOX;
float boxSize = 5;
std::default_random_engine generator;
std::uniform_real_distribution<double> xDistribution(-350.0,350.0);
std::uniform_real_distribution<double> yDistribution(-250.0,250.0);
std::uniform_real_distribution<double> boxScaleDist(-2.0f,2.0f);
for(int i = 0; i < n; i++) {
float boxSizeFactorW = boxScaleDist(generator);
float boxSizeFactorH = boxScaleDist(generator);
float xVal = xDistribution(generator) + width/2.0f;
float yVal = yDistribution(generator) + height/2.0f;
float angle = yVal/(xVal+1.0f);
obbs.push_back(OBB(xVal, yVal, angle+M_PI*i/4,
boxSize-boxSizeFactorW,
boxSize-boxSizeFactorH));
}
#else
int n = 4;
float o = (2 * M_PI) / n;
float size = 50;
float boxSize = 15;
for (int i = 0; i < n; ++i) {
float r = rand_0_1(20);
obbs.push_back(OBB(cos(o * i) * size + width / 2,
sin(o * i) * size + height / 2, r,
r + boxSize * 8, r * boxSize / 3 + boxSize));
}
#endif
}
void init() {
glfwInit();
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
glfwWindowHint(GLFW_SAMPLES, 4);
window = glfwCreateWindow(width, height, "isect2d", NULL, NULL);
if (!window) {
glfwTerminate();
}
int fbWidth, fbHeight;
glfwGetFramebufferSize(window, &fbWidth, &fbHeight);
glfwSetKeyCallback(window, keyCallback);
dpiRatio = fbWidth / width;
glfwMakeContextCurrent(window);
initBBoxes();
}
void line(float sx, float sy, float ex, float ey) {
glBegin(GL_LINES);
glVertex2f(sx, sy);
glVertex2f(ex, ey);
glEnd();
}
void cross(float x, float y, float size = 3) {
line(x - size, y, x + size, y);
line(x, y - size, x, y + size);
}
void drawAABB(const AABB& _aabb) {
line(_aabb.getMin().x, _aabb.getMin().y, _aabb.getMin().x, _aabb.getMax().y);
line(_aabb.getMin().x, _aabb.getMin().y, _aabb.getMax().x, _aabb.getMin().y);
line(_aabb.getMax().x, _aabb.getMin().y, _aabb.getMax().x, _aabb.getMax().y);
line(_aabb.getMin().x, _aabb.getMax().y, _aabb.getMax().x, _aabb.getMax().y);
}
void drawOBB(const OBB& obb, bool isect) {
const auto* quad = obb.getQuad();
for(int i = 0; i < 4; ++i) {
if(isect) {
glColor4f(0.5, 1.0, 0.5, 1.0);
} else {
glColor4f(1.0, 0.5, 0.5, 1.0);
}
auto start = quad[i];
auto end = quad[(i + 1) % 4];
line(start.x, start.y, end.x, end.y);
glColor4f(1.0, 1.0, 1.0, 0.1);
cross(obb.getCentroid().x, obb.getCentroid().y, 2);
}
}
void render() {
const int n1 = 4;
const int n2 = 16;
ISect2D<Vec2> context({n2, n2}, {800, 600});
while (!glfwWindowShouldClose(window)) {
update();
if (pause) {
glfwPollEvents();
continue;
}
glViewport(0, 0, width * dpiRatio, height * dpiRatio);
glClearColor(0.18f, 0.18f, 0.22f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, width, 0, height, -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
for (auto& obb : obbs) {
drawOBB(obb, false);
}
float sum1 = 0, sum2 = 0;
// grid broad phase
std::vector<AABB> aabbs;
std::set<std::pair<int, int>> pairs;
{
for (auto& obb : obbs) {
auto aabb = obb.getExtent();
aabb.m_userData = (void*)&obb;
aabbs.push_back(aabb);
}
const clock_t beginBroadPhaseTime = clock();
pairs = intersect(aabbs, {n1, n1}, {800, 600});
float broadTime = (float(clock() - beginBroadPhaseTime) / CLOCKS_PER_SEC) * 1000;
// narrow phase
clock_t beginNarrowTime = clock();
for (auto pair : pairs) {
auto obb1 = obbs[pair.first];
auto obb2 = obbs[pair.second];
intersect(obb1, obb2);
}
float narrowTime = (float(clock() - beginNarrowTime) / CLOCKS_PER_SEC) * 1000;
std::cout << "grid1: " << broadTime << "\t" << narrowTime <<"ms " << "pairs: " << pairs.size() << std::endl;
sum1 = broadTime + narrowTime;
}
// grid broad phase
{
std::vector<AABB> aabbs;
for (auto& obb : obbs) {
auto aabb = obb.getExtent();
aabb.m_userData = (void*)&obb;
aabbs.push_back(aabb);
}
const clock_t beginBroadPhaseTime = clock();
context.clear();
context.intersect(aabbs);
float broadTime = (float(clock() - beginBroadPhaseTime) / CLOCKS_PER_SEC) * 1000;
// narrow phase
clock_t beginNarrowTime = clock();
for (auto pair : context.pairs) {
auto obb1 = obbs[pair.first];
auto obb2 = obbs[pair.second];
intersect(obb1, obb2);
}
float narrowTime = (float(clock() - beginNarrowTime) / CLOCKS_PER_SEC) * 1000;
std::cout << "grid2: " << broadTime << "\t" << narrowTime <<"ms " << "pairs: " << context.pairs.size() << std::endl;
sum2 = broadTime + narrowTime;
}
std::cout << "sum: " << sum1 <<" | " << sum2 << " diff: " << (sum1 - sum2) << "ms"<< std::endl;
// narrow phase
{
clock_t narrowTime = 0;
for (auto pair : context.pairs) {
clock_t beginNarrowTime;
auto obb1 = obbs[pair.first];
auto obb2 = obbs[pair.second];
// narrow phase
beginNarrowTime = clock();
bool isect = intersect(obb1, obb2);
narrowTime += (clock() - beginNarrowTime);
if (isect) {
drawOBB(obb1, true);
drawOBB(obb2, true);
line(obb1.getCentroid().x, obb1.getCentroid().y, obb2.getCentroid().x, obb2.getCentroid().y);
}
}
//std::cout << " / narrowphase: " << (float(narrowTime) / CLOCKS_PER_SEC) * 1000 << "ms" << std::endl;
}
glfwSwapBuffers(window);
glfwPollEvents();
}
}
int main() {
init();
render();
return 0;
}
<commit_msg>cleanups<commit_after>#include "isect2d.h"
#include "vec2.h"
#include <iostream>
#include <cmath>
#include <vector>
#include <memory>
#include <random>
#include <stack>
#include <GLFW/glfw3.h>
#include "../../tangram-es/core/include/glm/glm/glm.hpp"
#include "glm_vec.h"
//#define CIRCLES
#define N_CIRCLES 500
#define AREA
#define N_BOX 1000
GLFWwindow* window;
float width = 800;
float height = 600;
float dpiRatio = 1;
bool pause = false;
using Vec2 = glm::vec2;
//using Vec2 = isect2d::Vec2;
using OBB = isect2d::OBB<Vec2>;
using AABB = isect2d::AABB<Vec2>;
std::vector<OBB> obbs;
float rand_0_1(float scale) {
return ((float)rand() / (float)(RAND_MAX)) * scale;
}
void update() {
double time = glfwGetTime();
if(!pause) {
int i = 0;
for (auto& obb : obbs) {
float r1 = rand_0_1(10);
float r2 = rand_0_1(20);
float r3 = rand_0_1(M_PI);
auto centroid = obb.getCentroid();
if (++i % 2 == 0) {
obb.move(centroid.x, centroid.y + .02 * cos(time * 0.25) * r2);
obb.rotate(cos(r3) * 0.1 + obb.getAngle());
} else {
obb.move(centroid.x + 0.1 * cos(time) * r1, centroid.y);
obb.rotate(cos(r2) * 0.1 + obb.getAngle());
}
}
}
}
void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods) {
if(key == 'P' && action == GLFW_PRESS) {
pause = !pause;
}
}
void initBBoxes() {
#if defined CIRCLES
int n = N_BOX;
float o = (2 * M_PI) / n;
float size = 200;
float boxSize = n / (0.4 * n);
for (int i = 0; i < n; ++i) {
float r = rand_0_1(20);
obbs.push_back(OBB(cos(o * i) * size + width / 2,
sin(o * i) * size + height / 2, r,
r + boxSize * 8, r * boxSize / 3 + boxSize));
}
#elif defined AREA
int n = N_BOX;
float boxWidth = 30;
float boxHeight = 5;
std::default_random_engine generator;
std::uniform_real_distribution<double> xDistribution(-350.0,350.0);
std::uniform_real_distribution<double> yDistribution(-250.0,250.0);
std::uniform_real_distribution<double> boxScaleDist(-2.0f,2.0f);
for(int i = 0; i < n; i++) {
float boxSizeFactorW = boxScaleDist(generator);
float boxSizeFactorH = boxScaleDist(generator);
float xVal = xDistribution(generator) + width/2.0f;
float yVal = yDistribution(generator) + height/2.0f;
float angle = yVal/(xVal+1.0f);
obbs.push_back(OBB(xVal, yVal, angle+M_PI*i/4,
boxWidth-boxSizeFactorW,
boxHeight-boxSizeFactorH));
}
#else
int n = 10;
float o = (2 * M_PI) / n;
float size = 50;
float boxSize = 15;
for (int i = 0; i < n; ++i) {
float r = rand_0_1(20);
obbs.push_back(OBB(cos(o * i) * size + width / 2,
sin(o * i) * size + height / 2, r,
r + boxSize * 8, r * boxSize / 3 + boxSize));
}
#endif
}
void init() {
glfwInit();
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
glfwWindowHint(GLFW_SAMPLES, 4);
window = glfwCreateWindow(width, height, "isect2d", NULL, NULL);
if (!window) {
glfwTerminate();
}
int fbWidth, fbHeight;
glfwGetFramebufferSize(window, &fbWidth, &fbHeight);
glfwSetKeyCallback(window, keyCallback);
dpiRatio = fbWidth / width;
glfwMakeContextCurrent(window);
initBBoxes();
}
void line(float sx, float sy, float ex, float ey) {
glBegin(GL_LINES);
glVertex2f(sx, sy);
glVertex2f(ex, ey);
glEnd();
}
void cross(float x, float y, float size = 3) {
line(x - size, y, x + size, y);
line(x, y - size, x, y + size);
}
void drawAABB(const AABB& _aabb) {
line(_aabb.getMin().x, _aabb.getMin().y, _aabb.getMin().x, _aabb.getMax().y);
line(_aabb.getMin().x, _aabb.getMin().y, _aabb.getMax().x, _aabb.getMin().y);
line(_aabb.getMax().x, _aabb.getMin().y, _aabb.getMax().x, _aabb.getMax().y);
line(_aabb.getMin().x, _aabb.getMax().y, _aabb.getMax().x, _aabb.getMax().y);
}
void drawOBB(const OBB& obb, bool isect) {
const auto* quad = obb.getQuad();
for(int i = 0; i < 4; ++i) {
if(isect) {
glColor4f(0.5, 1.0, 0.5, 1.0);
} else {
glColor4f(1.0, 0.5, 0.5, 1.0);
}
auto start = quad[i];
auto end = quad[(i + 1) % 4];
line(start.x, start.y, end.x, end.y);
glColor4f(1.0, 1.0, 1.0, 0.1);
cross(obb.getCentroid().x, obb.getCentroid().y, 2);
}
}
void render() {
const int n1 = 4;
const int n2 = 16;
ISect2D<Vec2> context({n2, n2}, {800, 600});
while (!glfwWindowShouldClose(window)) {
update();
if (pause) {
glfwPollEvents();
continue;
}
glViewport(0, 0, width * dpiRatio, height * dpiRatio);
glClearColor(0.18f, 0.18f, 0.22f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, width, 0, height, -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
for (auto& obb : obbs) {
drawOBB(obb, false);
}
float sum1 = 0, sum2 = 0;
// grid broad phase
std::vector<AABB> aabbs;
std::set<std::pair<int, int>> pairs;
{
for (auto& obb : obbs) {
auto aabb = obb.getExtent();
aabb.m_userData = (void*)&obb;
aabbs.push_back(aabb);
}
const clock_t beginBroadPhaseTime = clock();
pairs = intersect(aabbs, {n1, n1}, {800, 600});
float broadTime = (float(clock() - beginBroadPhaseTime) / CLOCKS_PER_SEC) * 1000;
// narrow phase
clock_t beginNarrowTime = clock();
for (auto& pair : pairs) {
intersect(obbs[pair.first], obbs[pair.first]);
}
float narrowTime = (float(clock() - beginNarrowTime) / CLOCKS_PER_SEC) * 1000;
std::cout << "grid1: " << broadTime << "\t" << narrowTime <<"ms "
<< "pairs: " << pairs.size() << std::endl;
sum1 = broadTime + narrowTime;
}
// grid broad phase
{
std::vector<AABB> aabbs;
for (auto& obb : obbs) {
auto aabb = obb.getExtent();
aabb.m_userData = (void*)&obb;
aabbs.push_back(aabb);
}
const clock_t beginBroadPhaseTime = clock();
context.clear();
context.intersect(aabbs);
float broadTime = (float(clock() - beginBroadPhaseTime) / CLOCKS_PER_SEC) * 1000;
// narrow phase
clock_t beginNarrowTime = clock();
for (auto& pair : context.pairs) {
intersect(obbs[pair.first], obbs[pair.first]);
}
float narrowTime = (float(clock() - beginNarrowTime) / CLOCKS_PER_SEC) * 1000;
std::cout << "grid2: " << broadTime << "\t" << narrowTime <<"ms "
<< "pairs: " << context.pairs.size() << std::endl;
sum2 = broadTime + narrowTime;
}
std::cout << "sum: " << sum1 <<" | " << sum2 << " diff: " << (sum1 - sum2) << "ms"<< std::endl;
// narrow phase
{
for (auto& pair : context.pairs) {
auto obb1 = obbs[pair.first];
auto obb2 = obbs[pair.second];
bool isect = intersect(obb1, obb2);
if (isect) {
drawOBB(obb1, true);
drawOBB(obb2, true);
line(obb1.getCentroid().x, obb1.getCentroid().y,
obb2.getCentroid().x, obb2.getCentroid().y);
}
}
}
glfwSwapBuffers(window);
glfwPollEvents();
}
}
int main() {
init();
render();
return 0;
}
<|endoftext|>
|
<commit_before>#include "../uuidxx.h"
#include <string>
#include <iostream>
#include <set>
#include <array>
#include <string.h>
using namespace uuidxx;
using namespace std;
template<class T, class... Tail>
auto make_array(T head, Tail... tail) -> std::array<T, 1 + sizeof...(Tail)>
{
std::array<T, 1 + sizeof...(Tail)> a = { head, tail ... };
return a;
}
bool TestEquality()
{
bool result = true;
uuid test1, test2;
auto passTest = [&](bool reverse = false) {
if ((test1.ToString() != test2.ToString()) ^ reverse)
{
cout << "FAIL!" << endl;
cout << "\tFailed on: " << test1.ToString() << " vs " << test2.ToString() << endl;
result = false;
}
else
{
cout << "pass" << endl;
}
};
cout << "Testing equality of normal GUIDs... ";
test1 = uuid("2C121B80-14B1-4B5A-AD48-9043DC251FDF");
test2 = uuid("2C121B80-14B1-4B5A-AD48-9043DC251FDF");
passTest();
cout << "Testing equality of lower- vs upper-cased GUIDs... ";
test1 = uuid("2C121B80-14B1-4B5A-AD48-9043DC251FDF");
test2 = uuid("2c121b80-14b1-4b5a-ad48-9043dc251fdf");
passTest();
cout << "Testing equality of braced vs non-braced GUIDs... ";
test1 = uuid("2C121B80-14B1-4B5A-AD48-9043DC251FDF");
test2 = uuid("{2C121B80-14B1-4B5A-AD48-9043DC251FDF}");
passTest();
cout << "Testing inequality of random GUIDs... ";
test1 = uuid::Generate();
test2 = uuid::Generate();
passTest(true);
return result;
}
bool InnerTestParsing(string test, string testCase, bool &result)
{
cout << "Testing " << test << " parsing: " << testCase << "... ";
uuid test1(testCase);
string strValue = test1.ToString();
if (strcasecmp(strValue.c_str(), "{A04CB1DE-25F7-4BC0-A1CE-1D0246FF362B}") != 0)
{
cout << "FAIL!" << endl;
cout << "\tFailed on: " << strValue.c_str() << " vs " << "A04CB1DE-25F7-4BC0-A1CE-1D0246FF362B" << endl;
result = false;
return false;
}
cout << "pass" << endl;
return true;
}
bool TestParsing()
{
bool result = true;
InnerTestParsing("basic", "A04CB1DE-25F7-4BC0-A1CE-1D0246FF362B", result);
InnerTestParsing("braces", "{A04CB1DE-25F7-4BC0-A1CE-1D0246FF362B}", result);
InnerTestParsing("lower-case", "a04cb1de-25f7-4bc0-a1ce-1d0246ff362b", result);
InnerTestParsing("mixed-case", "A04cb1de-25f7-4bc0-a1ce-1d0246ff362b", result);
InnerTestParsing("left-brace", "{A04CB1DE-25F7-4BC0-A1CE-1D0246FF362B", result);
InnerTestParsing("right-brace", "A04CB1DE-25F7-4BC0-A1CE-1D0246FF362B}", result);
return result;
}
bool TestStringGeneration()
{
bool result = true;
uuid test("BAA55AAB-F3FC-461C-9789-8CC6E2E2CE8C");
cout << "Testing generation of string without braces... ";
if (test.ToString(false) == "BAA55AAB-F3FC-461C-9789-8CC6E2E2CE8C")
{
cout << "pass" << endl;
}
else
{
cout << "FAIL!" << endl;
result = false;
}
cout << "Testing generation of string without braces... ";
if (test.ToString(true) == "{BAA55AAB-F3FC-461C-9789-8CC6E2E2CE8C}")
{
cout << "pass" << endl;
}
else
{
cout << "FAIL!" << endl;
result = false;
}
return true;
}
bool TestUniqueness()
{
int rounds = 4096;
cout << "Generating and testing uniqueness of " << rounds << " uuids... ";
int collisions = 0;
std::set<uuid> uuidMap;
for (int i = 0; i < rounds; ++i)
{
auto test = uuid::Generate();
if (uuidMap.insert(test).second == false)
{
++collisions;
}
}
if (collisions == 0)
{
cout << "pass" << endl;
return true;
}
else
{
cout << collisions << " collisions. FAIL!" << endl;
return false;
}
}
int main (int argc, char *argv[])
{
auto tests = make_array(TestStringGeneration, TestEquality, TestParsing, TestUniqueness);
int fails = 0;
for (auto test : tests)
{
if (!test())
{
++fails;
}
}
return fails;
}
<commit_msg>Expanded test cases<commit_after>#include "../uuidxx.h"
#include <string>
#include <iostream>
#include <set>
#include <array>
#include <string.h>
using namespace uuidxx;
using namespace std;
template<class T, class... Tail>
auto make_array(T head, Tail... tail) -> std::array<T, 1 + sizeof...(Tail)>
{
std::array<T, 1 + sizeof...(Tail)> a = { head, tail ... };
return a;
}
bool TestEquality()
{
bool result = true;
uuid test1, test2;
auto passTest = [&](bool reverse = false) {
if ((test1 != test2) ^ reverse)
{
cout << "FAIL!" << endl;
cout << "\tFailed on: " << test1.ToString() << " vs " << test2.ToString() << endl;
result = false;
}
else
{
cout << "pass" << endl;
}
};
cout << "Testing assignment... ";
test1 = uuid::Generate();
test2 = test1;
passTest();
cout << "Testing move operator... ";
test1 = uuid::Generate();
test2 = std::move(test1);
passTest(false);
cout << "Testing equality of normal GUIDs... ";
test1 = uuid("2C121B80-14B1-4B5A-AD48-9043DC251FDF");
test2 = uuid("2C121B80-14B1-4B5A-AD48-9043DC251FDF");
passTest();
cout << "Testing equality of lower- vs upper-cased GUIDs... ";
test1 = uuid("2C121B80-14B1-4B5A-AD48-9043DC251FDF");
test2 = uuid("2c121b80-14b1-4b5a-ad48-9043dc251fdf");
passTest();
cout << "Testing equality of braced vs non-braced GUIDs... ";
test1 = uuid("2C121B80-14B1-4B5A-AD48-9043DC251FDF");
test2 = uuid("{2C121B80-14B1-4B5A-AD48-9043DC251FDF}");
passTest();
cout << "Testing inequality of random GUIDs... ";
test1 = uuid::Generate();
test2 = uuid::Generate();
passTest(true);
return result;
}
bool InnerTestParsing(string test, string testCase, bool &result)
{
cout << "Testing " << test << " parsing: " << testCase << "... ";
uuid test1(testCase);
string strValue = test1.ToString();
if (strcasecmp(strValue.c_str(), "{A04CB1DE-25F7-4BC0-A1CE-1D0246FF362B}") != 0)
{
cout << "FAIL!" << endl;
cout << "\tFailed on: " << strValue.c_str() << " vs " << "A04CB1DE-25F7-4BC0-A1CE-1D0246FF362B" << endl;
result = false;
return false;
}
cout << "pass" << endl;
return true;
}
bool TestParsing()
{
bool result = true;
InnerTestParsing("basic", "A04CB1DE-25F7-4BC0-A1CE-1D0246FF362B", result);
InnerTestParsing("braces", "{A04CB1DE-25F7-4BC0-A1CE-1D0246FF362B}", result);
InnerTestParsing("lower-case", "a04cb1de-25f7-4bc0-a1ce-1d0246ff362b", result);
InnerTestParsing("mixed-case", "A04cb1de-25f7-4bc0-a1ce-1d0246ff362b", result);
InnerTestParsing("left-brace", "{A04CB1DE-25F7-4BC0-A1CE-1D0246FF362B", result);
InnerTestParsing("right-brace", "A04CB1DE-25F7-4BC0-A1CE-1D0246FF362B}", result);
return result;
}
bool TestStringGeneration()
{
bool result = true;
uuid test("BAA55AAB-F3FC-461C-9789-8CC6E2E2CE8C");
cout << "Testing generation of string without braces... ";
if (test.ToString(false) == "BAA55AAB-F3FC-461C-9789-8CC6E2E2CE8C")
{
cout << "pass" << endl;
}
else
{
cout << "FAIL!" << endl;
result = false;
}
cout << "Testing generation of string without braces... ";
if (test.ToString(true) == "{BAA55AAB-F3FC-461C-9789-8CC6E2E2CE8C}")
{
cout << "pass" << endl;
}
else
{
cout << "FAIL!" << endl;
result = false;
}
return true;
}
bool TestUniqueness()
{
int rounds = 4096;
cout << "Generating and testing uniqueness of " << rounds << " uuids... ";
int collisions = 0;
std::set<uuid> uuidMap;
for (int i = 0; i < rounds; ++i)
{
auto test = uuid::Generate();
if (uuidMap.insert(test).second == false)
{
++collisions;
}
}
if (collisions == 0)
{
cout << "pass" << endl;
return true;
}
else
{
cout << collisions << " collisions. FAIL!" << endl;
return false;
}
}
int main (int argc, char *argv[])
{
auto tests = make_array(TestStringGeneration, TestEquality, TestParsing, TestUniqueness);
int fails = 0;
for (auto test : tests)
{
if (!test())
{
++fails;
}
}
return fails;
}
<|endoftext|>
|
<commit_before>/**
* Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include "schemas.h"
using namespace cm;
using namespace fnord;
namespace cm {
msg::MessageSchema joinedSessionsSchema() {
Vector<msg::MessageSchemaField> fields;
msg::MessageSchemaField queries(
16,
"queries",
msg::FieldType::OBJECT,
0,
true,
false);
queries.fields.emplace_back(
18,
"time",
msg::FieldType::UINT32,
0xffffffff,
false,
false);
queries.fields.emplace_back(
1,
"page",
msg::FieldType::UINT32,
100,
false,
true,
msg::EncodingHint::BITPACK);
queries.fields.emplace_back(
2,
"language",
msg::FieldType::UINT32,
kMaxLanguage,
false,
false,
msg::EncodingHint::BITPACK);
queries.fields.emplace_back(
3,
"query_string",
msg::FieldType::STRING,
8192,
false,
true);
queries.fields.emplace_back(
4,
"query_string_normalized",
msg::FieldType::STRING,
8192,
false,
true);
queries.fields.emplace_back(
5,
"num_items",
msg::FieldType::UINT32,
250,
false,
false,
msg::EncodingHint::BITPACK);
queries.fields.emplace_back(
6,
"num_items_clicked",
msg::FieldType::UINT32,
250,
false,
false,
msg::EncodingHint::BITPACK);
queries.fields.emplace_back(
7,
"num_ad_impressions",
msg::FieldType::UINT32,
250,
false,
false,
msg::EncodingHint::BITPACK);
queries.fields.emplace_back(
8,
"num_ad_clicks",
msg::FieldType::UINT32,
250,
false,
false,
msg::EncodingHint::BITPACK);
queries.fields.emplace_back(
9,
"ab_test_group",
msg::FieldType::UINT32,
100,
false,
true,
msg::EncodingHint::BITPACK);
queries.fields.emplace_back(
10,
"device_type",
msg::FieldType::UINT32,
kMaxDeviceType,
false,
false,
msg::EncodingHint::BITPACK);
queries.fields.emplace_back(
11,
"page_type",
msg::FieldType::UINT32,
kMaxPageType,
false,
false,
msg::EncodingHint::BITPACK);
queries.fields.emplace_back(
12,
"category1",
msg::FieldType::UINT32,
0xffff,
false,
true,
msg::EncodingHint::BITPACK);
queries.fields.emplace_back(
13,
"category2",
msg::FieldType::UINT32,
0xffff,
false,
true,
msg::EncodingHint::BITPACK);
queries.fields.emplace_back(
14,
"category3",
msg::FieldType::UINT32,
0xffff,
false,
true,
msg::EncodingHint::BITPACK);
msg::MessageSchemaField query_items(
17,
"items",
msg::FieldType::OBJECT,
0,
true,
false);
query_items.fields.emplace_back(
19,
"position",
msg::FieldType::UINT32,
64,
false,
false,
msg::EncodingHint::BITPACK);
query_items.fields.emplace_back(
15,
"clicked",
msg::FieldType::BOOLEAN,
0,
false,
false);
query_items.fields.emplace_back(
20,
"item_id",
msg::FieldType::STRING,
1024,
false,
false);
query_items.fields.emplace_back(
21,
"shop_id",
msg::FieldType::STRING,
250,
false,
true);
query_items.fields.emplace_back(
21,
"shop_name",
msg::FieldType::STRING,
250,
false,
true);
query_items.fields.emplace_back(
22,
"category1",
msg::FieldType::UINT32,
0xffff,
false,
true,
msg::EncodingHint::BITPACK);
query_items.fields.emplace_back(
23,
"category2",
msg::FieldType::UINT32,
0xffff,
false,
true,
msg::EncodingHint::BITPACK);
query_items.fields.emplace_back(
24,
"category3",
msg::FieldType::UINT32,
0xffff,
false,
true,
msg::EncodingHint::BITPACK);
queries.fields.emplace_back(query_items);
fields.emplace_back(queries);
return msg::MessageSchema("joined_session", fields);
}
}
<commit_msg>add fields to session schema<commit_after>/**
* Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include "schemas.h"
using namespace cm;
using namespace fnord;
namespace cm {
msg::MessageSchema joinedSessionsSchema() {
Vector<msg::MessageSchemaField> fields;
fields.emplace_back(
25,
"num_items",
msg::FieldType::UINT32,
250,
false,
false,
msg::EncodingHint::BITPACK);
fields.emplace_back(
26,
"num_items_clicked",
msg::FieldType::UINT32,
250,
false,
false,
msg::EncodingHint::BITPACK);
fields.emplace_back(
27,
"num_ad_impressions",
msg::FieldType::UINT32,
250,
false,
false,
msg::EncodingHint::BITPACK);
fields.emplace_back(
28,
"num_ad_clicks",
msg::FieldType::UINT32,
250,
false,
false,
msg::EncodingHint::BITPACK);
fields.emplace_back(
29,
"num_queries",
msg::FieldType::UINT32,
250,
false,
false,
msg::EncodingHint::BITPACK);
fields.emplace_back(
30,
"num_queries_clicked",
msg::FieldType::UINT32,
250,
false,
false,
msg::EncodingHint::BITPACK);
msg::MessageSchemaField queries(
16,
"queries",
msg::FieldType::OBJECT,
0,
true,
false);
queries.fields.emplace_back(
18,
"time",
msg::FieldType::UINT32,
0xffffffff,
false,
false);
queries.fields.emplace_back(
1,
"page",
msg::FieldType::UINT32,
100,
false,
true,
msg::EncodingHint::BITPACK);
queries.fields.emplace_back(
2,
"language",
msg::FieldType::UINT32,
kMaxLanguage,
false,
false,
msg::EncodingHint::BITPACK);
queries.fields.emplace_back(
3,
"query_string",
msg::FieldType::STRING,
8192,
false,
true);
queries.fields.emplace_back(
4,
"query_string_normalized",
msg::FieldType::STRING,
8192,
false,
true);
queries.fields.emplace_back(
5,
"num_items",
msg::FieldType::UINT32,
250,
false,
false,
msg::EncodingHint::BITPACK);
queries.fields.emplace_back(
6,
"num_items_clicked",
msg::FieldType::UINT32,
250,
false,
false,
msg::EncodingHint::BITPACK);
queries.fields.emplace_back(
7,
"num_ad_impressions",
msg::FieldType::UINT32,
250,
false,
false,
msg::EncodingHint::BITPACK);
queries.fields.emplace_back(
8,
"num_ad_clicks",
msg::FieldType::UINT32,
250,
false,
false,
msg::EncodingHint::BITPACK);
queries.fields.emplace_back(
9,
"ab_test_group",
msg::FieldType::UINT32,
100,
false,
true,
msg::EncodingHint::BITPACK);
queries.fields.emplace_back(
10,
"device_type",
msg::FieldType::UINT32,
kMaxDeviceType,
false,
false,
msg::EncodingHint::BITPACK);
queries.fields.emplace_back(
11,
"page_type",
msg::FieldType::UINT32,
kMaxPageType,
false,
false,
msg::EncodingHint::BITPACK);
queries.fields.emplace_back(
12,
"category1",
msg::FieldType::UINT32,
0xffff,
false,
true,
msg::EncodingHint::BITPACK);
queries.fields.emplace_back(
13,
"category2",
msg::FieldType::UINT32,
0xffff,
false,
true,
msg::EncodingHint::BITPACK);
queries.fields.emplace_back(
14,
"category3",
msg::FieldType::UINT32,
0xffff,
false,
true,
msg::EncodingHint::BITPACK);
msg::MessageSchemaField query_items(
17,
"items",
msg::FieldType::OBJECT,
0,
true,
false);
query_items.fields.emplace_back(
19,
"position",
msg::FieldType::UINT32,
64,
false,
false,
msg::EncodingHint::BITPACK);
query_items.fields.emplace_back(
15,
"clicked",
msg::FieldType::BOOLEAN,
0,
false,
false);
query_items.fields.emplace_back(
20,
"item_id",
msg::FieldType::STRING,
1024,
false,
false);
query_items.fields.emplace_back(
21,
"shop_id",
msg::FieldType::STRING,
250,
false,
true);
query_items.fields.emplace_back(
21,
"shop_name",
msg::FieldType::STRING,
250,
false,
true);
query_items.fields.emplace_back(
22,
"category1",
msg::FieldType::UINT32,
0xffff,
false,
true,
msg::EncodingHint::BITPACK);
query_items.fields.emplace_back(
23,
"category2",
msg::FieldType::UINT32,
0xffff,
false,
true,
msg::EncodingHint::BITPACK);
query_items.fields.emplace_back(
24,
"category3",
msg::FieldType::UINT32,
0xffff,
false,
true,
msg::EncodingHint::BITPACK);
queries.fields.emplace_back(query_items);
fields.emplace_back(queries);
return msg::MessageSchema("joined_session", fields);
}
}
<|endoftext|>
|
<commit_before>/*
C++ interface test
*/
#include "libmemcached/memcached.hh"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
#include "server.h"
#include "test.h"
#include <string>
using namespace std;
extern "C" {
test_return basic_test(memcached_st *memc);
test_return increment_test(memcached_st *memc);
test_return basic_master_key_test(memcached_st *memc);
test_return mget_result_function(memcached_st *memc);
test_return mget_test(memcached_st *memc);
void *world_create(void);
void world_destroy(void *p);
}
test_return basic_test(memcached_st *memc)
{
Memcached foo(memc);
const string value_set("This is some data");
string value;
size_t value_length;
foo.set("mine", value_set, 0, 0);
value= foo.get("mine", &value_length);
assert((memcmp(value.c_str(), value_set.c_str(), value_length) == 0));
return TEST_SUCCESS;
}
test_return increment_test(memcached_st *memc)
{
Memcached mcach(memc);
bool rc;
const string key("inctest");
const string inc_value("1");
string ret_value;
uint64_t int_inc_value;
uint64_t int_ret_value;
size_t value_length;
mcach.set(key, inc_value, 0, 0);
ret_value= mcach.get(key, &value_length);
printf("\nretvalue %s\n",ret_value.c_str());
int_inc_value= uint64_t(atol(inc_value.c_str()));
int_ret_value= uint64_t(atol(ret_value.c_str()));
assert(int_ret_value == int_inc_value);
rc= mcach.increment(key, 1, &int_ret_value);
assert(rc == true);
assert(int_ret_value == 2);
rc= mcach.increment(key, 1, &int_ret_value);
assert(rc == true);
assert(int_ret_value == 3);
rc= mcach.increment(key, 5, &int_ret_value);
assert(rc == true);
assert(int_ret_value == 8);
return TEST_SUCCESS;
}
test_return basic_master_key_test(memcached_st *memc)
{
Memcached foo(memc);
const string value_set("Data for server A");
const string master_key_a("server-a");
const string master_key_b("server-b");
const string key("xyz");
string value;
size_t value_length;
foo.set_by_key(master_key_a, key, value_set, 0, 0);
value= foo.get_by_key(master_key_a, key, &value_length);
assert((memcmp(value.c_str(), value_set.c_str(), value_length) == 0));
value= foo.get_by_key(master_key_b, key, &value_length);
assert((memcmp(value.c_str(), value_set.c_str(), value_length) == 0));
return TEST_SUCCESS;
}
/* Count the results */
static memcached_return callback_counter(memcached_st *ptr __attribute__((unused)),
memcached_result_st *result __attribute__((unused)),
void *context)
{
unsigned int *counter= static_cast<unsigned int *>(context);
*counter= *counter + 1;
return MEMCACHED_SUCCESS;
}
test_return mget_result_function(memcached_st *memc)
{
Memcached mc(memc);
bool rc;
string key1("fudge");
string key2("son");
string key3("food");
vector<string> keys;
keys.reserve(3);
keys.push_back(key1);
keys.push_back(key2);
keys.push_back(key3);
unsigned int counter;
memcached_execute_function callbacks[1];
/* We need to empty the server before we continue the test */
rc= mc.flush(0);
rc= mc.set_all(keys, keys, 50, 9);
assert(rc == true);
rc= mc.mget(keys);
assert(rc == true);
callbacks[0]= &callback_counter;
counter= 0;
rc= mc.fetch_execute(callbacks, static_cast<void *>(&counter), 1);
assert(counter == 3);
return TEST_SUCCESS;
}
test_return mget_test(memcached_st *memc)
{
Memcached mc(memc);
bool rc;
memcached_return mc_rc;
vector<string> keys;
keys.reserve(3);
keys.push_back("fudge");
keys.push_back("son");
keys.push_back("food");
uint32_t flags;
string return_key;
size_t return_key_length;
string return_value;
size_t return_value_length;
/* We need to empty the server before we continue the test */
rc= mc.flush(0);
assert(rc == true);
rc= mc.mget(keys);
assert(rc == true);
while (mc.fetch(return_key, return_value, &return_key_length,
&return_value_length, &flags, &mc_rc))
{
assert(return_value.length() != 0);
}
assert(return_value_length == 0);
assert(mc_rc == MEMCACHED_END);
rc= mc.set_all(keys, keys, 50, 9);
assert(rc == true);
rc= mc.mget(keys);
assert(rc == true);
while ((mc.fetch(return_key, return_value, &return_key_length,
&return_value_length, &flags, &mc_rc)))
{
assert(return_value.length() != 0);
assert(mc_rc == MEMCACHED_SUCCESS);
assert(return_key_length == return_value_length);
assert(!memcmp(return_value.c_str(), return_key.c_str(), return_value_length));
}
return TEST_SUCCESS;
}
test_st tests[] ={
{ "basic", 0, basic_test },
{ "basic_master_key", 0, basic_master_key_test },
{ "increment_test", 0, increment_test },
{ "mget", 1, mget_test },
{ "mget_result_function", 1, mget_result_function },
{0, 0, 0}
};
collection_st collection[] ={
{"block", 0, 0, tests},
{0, 0, 0, 0}
};
#define SERVERS_TO_CREATE 1
extern "C" void *world_create(void)
{
server_startup_st *construct;
construct= (server_startup_st *)malloc(sizeof(server_startup_st));
memset(construct, 0, sizeof(server_startup_st));
construct->count= SERVERS_TO_CREATE;
server_startup(construct);
return construct;
}
void world_destroy(void *p)
{
server_startup_st *construct= static_cast<server_startup_st *>(p);
memcached_server_st *servers=
static_cast<memcached_server_st *>(construct->servers);
memcached_server_list_free(servers);
server_shutdown(construct);
free(construct);
}
void get_world(world_st *world)
{
world->collections= collection;
world->create= world_create;
world->destroy= world_destroy;
}
<commit_msg>Some more updates to the C++ test file to remove solaris warnings.<commit_after>/*
C++ interface test
*/
#include "libmemcached/memcached.hh"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
#include "server.h"
#include "test.h"
#include <string>
using namespace std;
extern "C" {
test_return basic_test(memcached_st *memc);
test_return increment_test(memcached_st *memc);
test_return basic_master_key_test(memcached_st *memc);
test_return mget_result_function(memcached_st *memc);
test_return mget_test(memcached_st *memc);
memcached_return callback_counter(memcached_st *ptr __attribute__((unused)),
memcached_result_st *result __attribute__((unused)),
void *context);
void *world_create(void);
void world_destroy(void *p);
}
test_return basic_test(memcached_st *memc)
{
Memcached foo(memc);
const string value_set("This is some data");
string value;
size_t value_length;
foo.set("mine", value_set, 0, 0);
value= foo.get("mine", &value_length);
assert((memcmp(value.c_str(), value_set.c_str(), value_length) == 0));
return TEST_SUCCESS;
}
test_return increment_test(memcached_st *memc)
{
Memcached mcach(memc);
bool rc;
const string key("inctest");
const string inc_value("1");
string ret_value;
uint64_t int_inc_value;
uint64_t int_ret_value;
size_t value_length;
mcach.set(key, inc_value, 0, 0);
ret_value= mcach.get(key, &value_length);
printf("\nretvalue %s\n",ret_value.c_str());
int_inc_value= uint64_t(atol(inc_value.c_str()));
int_ret_value= uint64_t(atol(ret_value.c_str()));
assert(int_ret_value == int_inc_value);
rc= mcach.increment(key, 1, &int_ret_value);
assert(rc == true);
assert(int_ret_value == 2);
rc= mcach.increment(key, 1, &int_ret_value);
assert(rc == true);
assert(int_ret_value == 3);
rc= mcach.increment(key, 5, &int_ret_value);
assert(rc == true);
assert(int_ret_value == 8);
return TEST_SUCCESS;
}
test_return basic_master_key_test(memcached_st *memc)
{
Memcached foo(memc);
const string value_set("Data for server A");
const string master_key_a("server-a");
const string master_key_b("server-b");
const string key("xyz");
string value;
size_t value_length;
foo.set_by_key(master_key_a, key, value_set, 0, 0);
value= foo.get_by_key(master_key_a, key, &value_length);
assert((memcmp(value.c_str(), value_set.c_str(), value_length) == 0));
value= foo.get_by_key(master_key_b, key, &value_length);
assert((memcmp(value.c_str(), value_set.c_str(), value_length) == 0));
return TEST_SUCCESS;
}
/* Count the results */
memcached_return callback_counter(memcached_st *ptr __attribute__((unused)),
memcached_result_st *result __attribute__((unused)),
void *context)
{
unsigned int *counter= static_cast<unsigned int *>(context);
*counter= *counter + 1;
return MEMCACHED_SUCCESS;
}
test_return mget_result_function(memcached_st *memc)
{
Memcached mc(memc);
bool rc;
string key1("fudge");
string key2("son");
string key3("food");
vector<string> keys;
keys.reserve(3);
keys.push_back(key1);
keys.push_back(key2);
keys.push_back(key3);
unsigned int counter;
memcached_execute_function callbacks[1];
/* We need to empty the server before we continue the test */
rc= mc.flush(0);
rc= mc.set_all(keys, keys, 50, 9);
assert(rc == true);
rc= mc.mget(keys);
assert(rc == true);
callbacks[0]= &callback_counter;
counter= 0;
rc= mc.fetch_execute(callbacks, static_cast<void *>(&counter), 1);
assert(counter == 3);
return TEST_SUCCESS;
}
test_return mget_test(memcached_st *memc)
{
Memcached mc(memc);
bool rc;
memcached_return mc_rc;
vector<string> keys;
keys.reserve(3);
keys.push_back("fudge");
keys.push_back("son");
keys.push_back("food");
uint32_t flags;
string return_key;
size_t return_key_length;
string return_value;
size_t return_value_length;
/* We need to empty the server before we continue the test */
rc= mc.flush(0);
assert(rc == true);
rc= mc.mget(keys);
assert(rc == true);
while (mc.fetch(return_key, return_value, &return_key_length,
&return_value_length, &flags, &mc_rc))
{
assert(return_value.length() != 0);
}
assert(return_value_length == 0);
assert(mc_rc == MEMCACHED_END);
rc= mc.set_all(keys, keys, 50, 9);
assert(rc == true);
rc= mc.mget(keys);
assert(rc == true);
while ((mc.fetch(return_key, return_value, &return_key_length,
&return_value_length, &flags, &mc_rc)))
{
assert(return_value.length() != 0);
assert(mc_rc == MEMCACHED_SUCCESS);
assert(return_key_length == return_value_length);
assert(!memcmp(return_value.c_str(), return_key.c_str(), return_value_length));
}
return TEST_SUCCESS;
}
test_st tests[] ={
{ "basic", 0, basic_test },
{ "basic_master_key", 0, basic_master_key_test },
{ "increment_test", 0, increment_test },
{ "mget", 1, mget_test },
{ "mget_result_function", 1, mget_result_function },
{0, 0, 0}
};
collection_st collection[] ={
{"block", 0, 0, tests},
{0, 0, 0, 0}
};
#define SERVERS_TO_CREATE 1
extern "C" void *world_create(void)
{
server_startup_st *construct;
construct= (server_startup_st *)malloc(sizeof(server_startup_st));
memset(construct, 0, sizeof(server_startup_st));
construct->count= SERVERS_TO_CREATE;
server_startup(construct);
return construct;
}
void world_destroy(void *p)
{
server_startup_st *construct= static_cast<server_startup_st *>(p);
memcached_server_st *servers=
static_cast<memcached_server_st *>(construct->servers);
memcached_server_list_free(servers);
server_shutdown(construct);
free(construct);
}
void get_world(world_st *world)
{
world->collections= collection;
world->create= world_create;
world->destroy= world_destroy;
}
<|endoftext|>
|
<commit_before>#include <cstdio>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include "filefinder.h"
#include "options.h"
#include "query_string.h"
#include "terminal.h"
std::vector<node> files;
std::vector<node> search(query_string qstr){
std::vector<node> result;
std::string str(qstr.get_str());
if( str != ""){
int count = 1;
for(std::size_t i=0; i < files.size() && count <=options.number_of_result_lines; ++i){
if(files[i].filename.find(qstr.get_str()) != std::string::npos){
result.push_back(files[i]);
count++;
}
}
}
return result;
}
int main(int argc, char* argv[]){
if(!get_options(argc, argv)){
return 1;
}
if(options.show_help){
print_help();
return 0;
}
if(options.show_version){
print_version();
return 0;
}
find_files(files);
query_string qstr;
terminal term;
int c;
unsigned selected = 0;
std::vector<node> results;
term.print_search_line(qstr.get_str(),qstr.get_pos());
while(1){
c = getchar();
if(c == 27){ // esc
c=getchar();
if(c == '['){
c=getchar();
if(c == 'A'){ // up
if(selected > 0){
selected--;
}
term.print_result(term, results, selected);
term.restore_cursor_pos();
term.cursor_right(qstr.get_pos()+1);
}else if(c == 'B'){ // down
selected++;
if(selected > results.size()-1){
selected = results.size()-1;
}
term.print_result(term, results, selected);
term.restore_cursor_pos();
term.cursor_right(qstr.get_pos()+1);
}else if(c == 'C'){ // right
if(qstr.cursor_right()){
term.cursor_right();
}
}else if(c == 'D'){ // left
if(qstr.cursor_left()){
term.cursor_left();
}
}
}
}else if(c == 9){
// tab
}else if(c == 10){ // enter
fprintf(stderr,"\n");
return 0;
}else if(c == 127){ //backspace
qstr.remove();
term.print_search_line(qstr.get_str(),qstr.get_pos());
results = search(qstr);
term.print_result(term, results, selected);
term.restore_cursor_pos();
term.cursor_right(qstr.get_pos()+1);
}else{
qstr.add(c);
term.print_search_line(qstr.get_str(),qstr.get_pos());
results = search(qstr);
term.print_result(term, results, selected);
term.restore_cursor_pos();
term.cursor_right(qstr.get_pos()+1);
}
}
}
<commit_msg>Move selection if selected is out of range.<commit_after>#include <cstdio>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include "filefinder.h"
#include "options.h"
#include "query_string.h"
#include "terminal.h"
std::vector<node> files;
std::vector<node> search(query_string qstr){
std::vector<node> result;
std::string str(qstr.get_str());
if( str != ""){
int count = 1;
for(std::size_t i=0; i < files.size() && count <=options.number_of_result_lines; ++i){
if(files[i].filename.find(qstr.get_str()) != std::string::npos){
result.push_back(files[i]);
count++;
}
}
}
return result;
}
int main(int argc, char* argv[]){
if(!get_options(argc, argv)){
return 1;
}
if(options.show_help){
print_help();
return 0;
}
if(options.show_version){
print_version();
return 0;
}
find_files(files);
query_string qstr;
terminal term;
int c;
unsigned selected = 0;
std::vector<node> results;
term.print_search_line(qstr.get_str(),qstr.get_pos());
while(1){
c = getchar();
if(c == 27){ // esc
c=getchar();
if(c == '['){
c=getchar();
if(c == 'A'){ // up
if(selected > 0){
selected--;
}
term.print_result(term, results, selected);
term.restore_cursor_pos();
term.cursor_right(qstr.get_pos()+1);
}else if(c == 'B'){ // down
selected++;
if(selected > results.size()-1){
selected = results.size()-1;
}
term.print_result(term, results, selected);
term.restore_cursor_pos();
term.cursor_right(qstr.get_pos()+1);
}else if(c == 'C'){ // right
if(qstr.cursor_right()){
term.cursor_right();
}
}else if(c == 'D'){ // left
if(qstr.cursor_left()){
term.cursor_left();
}
}
}
}else if(c == 9){
// tab
}else if(c == 10){ // enter
if(results.size()!=0){
}
fprintf(stderr,"\n");
return 0;
}else if(c == 127){ //backspace
qstr.remove();
term.print_search_line(qstr.get_str(),qstr.get_pos());
results = search(qstr);
if(selected >= results.size()){
selected = results.size()-1;
}
if(results.size()==0){
selected = 0;
}
term.print_result(term, results, selected);
term.restore_cursor_pos();
term.cursor_right(qstr.get_pos()+1);
}else{
qstr.add(c);
term.print_search_line(qstr.get_str(),qstr.get_pos());
results = search(qstr);
if(selected >= results.size()){
selected = results.size()-1;
}
if(results.size()==0){
selected = 0;
}
term.print_result(term, results, selected);
term.restore_cursor_pos();
term.cursor_right(qstr.get_pos()+1);
}
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ldapaccess.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: ihi $ $Date: 2008-01-14 14:40:59 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_extensions.hxx"
#include "ldapaccess.hxx"
#include "ldapuserprof.hxx"
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif // _RTL_USTRBUF_HXX_
#ifndef _RTL_STRBUF_HXX_
#include <rtl/strbuf.hxx>
#endif // _RTL_STRBUF_HXX_
namespace extensions { namespace config { namespace ldap {
//------------------------------------------------------------------------------
typedef int LdapErrCode;
//------------------------------------------------------------------------------
struct LdapMessageHolder
{
LdapMessageHolder() : msg(0) {}
~LdapMessageHolder() { if (msg) ldap_msgfree(msg); }
LDAPMessage * msg;
private:
LdapMessageHolder(LdapMessageHolder const&);
void operator=(LdapMessageHolder const&);
};
//------------------------------------------------------------------------------
LdapConnection::~LdapConnection()
{
if (isValid()) disconnect();
}
//------------------------------------------------------------------------------
void LdapConnection::disconnect()
{
if (mConnection != NULL)
{
ldap_unbind_s(mConnection) ;
mConnection = NULL;
}
}
//------------------------------------------------------------------------------
static void checkLdapReturnCode(const sal_Char *aOperation,
LdapErrCode aRetCode,
LDAP * /*aConnection*/)
{
if (aRetCode == LDAP_SUCCESS) { return ; }
static const sal_Char *kNoSpecificMessage = "No additional information" ;
rtl::OUStringBuffer message ;
if (aOperation != NULL)
{
message.appendAscii(aOperation).appendAscii(": ") ;
}
message.appendAscii(ldap_err2string(aRetCode)).appendAscii(" (") ;
sal_Char *stub = NULL ;
#ifndef LDAP_OPT_SIZELIMIT // for use with OpenLDAP
ldap_get_lderrno(aConnection, NULL, &stub) ;
#endif
if (stub != NULL)
{
message.appendAscii(stub) ;
// It would seem the message returned is actually
// not a copy of a string but rather some static
// string itself. At any rate freeing it seems to
// cause some undue problems at least on Windows.
// This call is thus disabled for the moment.
//ldap_memfree(stub) ;
}
else { message.appendAscii(kNoSpecificMessage) ; }
message.appendAscii(")") ;
throw ldap::LdapGenericException(message.makeStringAndClear(),
NULL, aRetCode) ;
}
//------------------------------------------------------------------------------
void LdapConnection::connectSimple(const LdapDefinition& aDefinition)
throw (ldap::LdapConnectionException, ldap::LdapGenericException)
{
OSL_ENSURE(!isValid(), "Recoonecting an LDAP connection that is already established");
if (isValid()) disconnect();
mLdapDefinition = aDefinition;
connectSimple();
}
//------------------------------------------------------------------------------
void LdapConnection::connectSimple()
throw (ldap::LdapConnectionException, ldap::LdapGenericException)
{
if (!isValid())
{
// Connect to the server
initConnection() ;
// Set Protocol V3
int version = LDAP_VERSION3;
ldap_set_option(mConnection,
LDAP_OPT_PROTOCOL_VERSION,
&version);
#ifdef LDAP_X_OPT_CONNECT_TIMEOUT // OpenLDAP doesn't support this and the func
/* timeout is specified in milliseconds -> 4 seconds*/
int timeout = 4000;
ldap_set_option( mConnection,
LDAP_X_OPT_CONNECT_TIMEOUT,
&timeout );
#endif
// Do the bind
LdapErrCode retCode = ldap_simple_bind_s(mConnection,
mLdapDefinition.mAnonUser ,
mLdapDefinition.mAnonCredentials) ;
checkLdapReturnCode("SimpleBind", retCode, mConnection) ;
}
}
//------------------------------------------------------------------------------
void LdapConnection::initConnection()
throw (ldap::LdapConnectionException)
{
if (mLdapDefinition.mServer.getLength() == 0)
{
rtl::OUStringBuffer message ;
message.appendAscii("Cannot initialise connection to LDAP: No server specified.") ;
throw ldap::LdapConnectionException(message.makeStringAndClear(), NULL) ;
}
if (mLdapDefinition.mPort == 0) mLdapDefinition.mPort = LDAP_PORT;
mConnection = ldap_init(mLdapDefinition.mServer,
mLdapDefinition.mPort) ;
if (mConnection == NULL)
{
rtl::OUStringBuffer message ;
message.appendAscii("Cannot initialise connection to LDAP server ") ;
message.appendAscii(mLdapDefinition.mServer) ;
message.appendAscii(":") ;
message.append(mLdapDefinition.mPort) ;
throw ldap::LdapConnectionException(message.makeStringAndClear(),
NULL) ;
}
}
//------------------------------------------------------------------------------
void LdapConnection::getUserProfile(const rtl::OUString& aUser,
const LdapUserProfileMap& aUserProfileMap,
LdapUserProfile& aUserProfile)
throw (lang::IllegalArgumentException,
ldap::LdapConnectionException, ldap::LdapGenericException)
{
if (!isValid()) { connectSimple(); }
rtl::OString aUserDn =findUserDn( rtl::OUStringToOString(aUser, RTL_TEXTENCODING_ASCII_US));
LdapMessageHolder result;
LdapErrCode retCode = ldap_search_s(mConnection,
aUserDn,
LDAP_SCOPE_BASE,
"(objectclass=*)",
const_cast<sal_Char **>(aUserProfileMap.getLdapAttributes()),
0, // Attributes + values
&result.msg) ;
checkLdapReturnCode("getUserProfile", retCode,mConnection) ;
aUserProfileMap.ldapToUserProfile(mConnection,
result.msg,
aUserProfile) ;
}
//------------------------------------------------------------------------------
rtl::OString LdapConnection::findUserDn(const rtl::OString& aUser)
throw (lang::IllegalArgumentException,
ldap::LdapConnectionException, ldap::LdapGenericException)
{
if (!isValid()) { connectSimple(); }
if (aUser.getLength() == 0)
{
throw lang::IllegalArgumentException(
rtl::OUString(RTL_CONSTASCII_USTRINGPARAM
("LdapConnection::findUserDn -User id is empty")),
NULL, 0) ;
}
rtl::OStringBuffer filter( "(&(objectclass=" );
filter.append( mLdapDefinition.mUserObjectClass ).append(")(") ;
filter.append( mLdapDefinition.mUserUniqueAttr ).append("=").append(aUser).append("))") ;
LdapMessageHolder result;
sal_Char * attributes [2];
attributes[0]= const_cast<sal_Char *>(LDAP_NO_ATTRS);
attributes[1]= NULL;
LdapErrCode retCode = ldap_search_s(mConnection,
mLdapDefinition.mBaseDN,
LDAP_SCOPE_SUBTREE,
filter.makeStringAndClear(), attributes, 0, &result.msg) ;
checkLdapReturnCode("FindUserDn", retCode,mConnection) ;
rtl::OString userDn ;
LDAPMessage *entry = ldap_first_entry(mConnection, result.msg) ;
if (entry != NULL)
{
sal_Char *charsDn = ldap_get_dn(mConnection, entry) ;
userDn = charsDn ;
ldap_memfree(charsDn) ;
}
else
{
OSL_ENSURE( false, "LdapConnection::findUserDn-could not get DN for User ");
}
return userDn ;
}
//------------------------------------------------------------------------------
rtl::OString LdapConnection::getSingleAttribute(
const rtl::OString& aDn,
const rtl::OString& aAttribute)
throw (ldap::LdapConnectionException, ldap::LdapGenericException)
{
if (!isValid()) { connectSimple(); }
const sal_Char *attributes [2] ;
rtl::OString value ;
attributes [0] = aAttribute ;
attributes [1] = 0 ;
LdapMessageHolder result ;
LdapErrCode retCode = ldap_search_s(mConnection,
aDn,
LDAP_SCOPE_BASE,
"(objectclass=*)",
const_cast<sal_Char **>(attributes),
0, // Attributes + values
&result.msg) ;
if (retCode == LDAP_NO_SUCH_OBJECT)
{
return value ;
}
checkLdapReturnCode("GetSingleAttribute", retCode, mConnection) ;
LDAPMessage *entry = ldap_first_entry(mConnection, result.msg) ;
if (entry != NULL)
{
sal_Char **values = ldap_get_values(mConnection, entry,
aAttribute) ;
if (values != NULL)
{
if (*values != NULL) { value = *values ; }
ldap_value_free(values) ;
}
}
return value ;
}
//------------------------------------------------------------------------------
} } } // extensions.config.ldap
<commit_msg>INTEGRATION: CWS changefileheader (1.8.48); FILE MERGED 2008/04/01 15:15:04 thb 1.8.48.2: #i85898# Stripping all external header guards 2008/03/31 12:31:25 rt 1.8.48.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: ldapaccess.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_extensions.hxx"
#include "ldapaccess.hxx"
#include "ldapuserprof.hxx"
#include <rtl/ustrbuf.hxx>
#include <rtl/strbuf.hxx>
namespace extensions { namespace config { namespace ldap {
//------------------------------------------------------------------------------
typedef int LdapErrCode;
//------------------------------------------------------------------------------
struct LdapMessageHolder
{
LdapMessageHolder() : msg(0) {}
~LdapMessageHolder() { if (msg) ldap_msgfree(msg); }
LDAPMessage * msg;
private:
LdapMessageHolder(LdapMessageHolder const&);
void operator=(LdapMessageHolder const&);
};
//------------------------------------------------------------------------------
LdapConnection::~LdapConnection()
{
if (isValid()) disconnect();
}
//------------------------------------------------------------------------------
void LdapConnection::disconnect()
{
if (mConnection != NULL)
{
ldap_unbind_s(mConnection) ;
mConnection = NULL;
}
}
//------------------------------------------------------------------------------
static void checkLdapReturnCode(const sal_Char *aOperation,
LdapErrCode aRetCode,
LDAP * /*aConnection*/)
{
if (aRetCode == LDAP_SUCCESS) { return ; }
static const sal_Char *kNoSpecificMessage = "No additional information" ;
rtl::OUStringBuffer message ;
if (aOperation != NULL)
{
message.appendAscii(aOperation).appendAscii(": ") ;
}
message.appendAscii(ldap_err2string(aRetCode)).appendAscii(" (") ;
sal_Char *stub = NULL ;
#ifndef LDAP_OPT_SIZELIMIT // for use with OpenLDAP
ldap_get_lderrno(aConnection, NULL, &stub) ;
#endif
if (stub != NULL)
{
message.appendAscii(stub) ;
// It would seem the message returned is actually
// not a copy of a string but rather some static
// string itself. At any rate freeing it seems to
// cause some undue problems at least on Windows.
// This call is thus disabled for the moment.
//ldap_memfree(stub) ;
}
else { message.appendAscii(kNoSpecificMessage) ; }
message.appendAscii(")") ;
throw ldap::LdapGenericException(message.makeStringAndClear(),
NULL, aRetCode) ;
}
//------------------------------------------------------------------------------
void LdapConnection::connectSimple(const LdapDefinition& aDefinition)
throw (ldap::LdapConnectionException, ldap::LdapGenericException)
{
OSL_ENSURE(!isValid(), "Recoonecting an LDAP connection that is already established");
if (isValid()) disconnect();
mLdapDefinition = aDefinition;
connectSimple();
}
//------------------------------------------------------------------------------
void LdapConnection::connectSimple()
throw (ldap::LdapConnectionException, ldap::LdapGenericException)
{
if (!isValid())
{
// Connect to the server
initConnection() ;
// Set Protocol V3
int version = LDAP_VERSION3;
ldap_set_option(mConnection,
LDAP_OPT_PROTOCOL_VERSION,
&version);
#ifdef LDAP_X_OPT_CONNECT_TIMEOUT // OpenLDAP doesn't support this and the func
/* timeout is specified in milliseconds -> 4 seconds*/
int timeout = 4000;
ldap_set_option( mConnection,
LDAP_X_OPT_CONNECT_TIMEOUT,
&timeout );
#endif
// Do the bind
LdapErrCode retCode = ldap_simple_bind_s(mConnection,
mLdapDefinition.mAnonUser ,
mLdapDefinition.mAnonCredentials) ;
checkLdapReturnCode("SimpleBind", retCode, mConnection) ;
}
}
//------------------------------------------------------------------------------
void LdapConnection::initConnection()
throw (ldap::LdapConnectionException)
{
if (mLdapDefinition.mServer.getLength() == 0)
{
rtl::OUStringBuffer message ;
message.appendAscii("Cannot initialise connection to LDAP: No server specified.") ;
throw ldap::LdapConnectionException(message.makeStringAndClear(), NULL) ;
}
if (mLdapDefinition.mPort == 0) mLdapDefinition.mPort = LDAP_PORT;
mConnection = ldap_init(mLdapDefinition.mServer,
mLdapDefinition.mPort) ;
if (mConnection == NULL)
{
rtl::OUStringBuffer message ;
message.appendAscii("Cannot initialise connection to LDAP server ") ;
message.appendAscii(mLdapDefinition.mServer) ;
message.appendAscii(":") ;
message.append(mLdapDefinition.mPort) ;
throw ldap::LdapConnectionException(message.makeStringAndClear(),
NULL) ;
}
}
//------------------------------------------------------------------------------
void LdapConnection::getUserProfile(const rtl::OUString& aUser,
const LdapUserProfileMap& aUserProfileMap,
LdapUserProfile& aUserProfile)
throw (lang::IllegalArgumentException,
ldap::LdapConnectionException, ldap::LdapGenericException)
{
if (!isValid()) { connectSimple(); }
rtl::OString aUserDn =findUserDn( rtl::OUStringToOString(aUser, RTL_TEXTENCODING_ASCII_US));
LdapMessageHolder result;
LdapErrCode retCode = ldap_search_s(mConnection,
aUserDn,
LDAP_SCOPE_BASE,
"(objectclass=*)",
const_cast<sal_Char **>(aUserProfileMap.getLdapAttributes()),
0, // Attributes + values
&result.msg) ;
checkLdapReturnCode("getUserProfile", retCode,mConnection) ;
aUserProfileMap.ldapToUserProfile(mConnection,
result.msg,
aUserProfile) ;
}
//------------------------------------------------------------------------------
rtl::OString LdapConnection::findUserDn(const rtl::OString& aUser)
throw (lang::IllegalArgumentException,
ldap::LdapConnectionException, ldap::LdapGenericException)
{
if (!isValid()) { connectSimple(); }
if (aUser.getLength() == 0)
{
throw lang::IllegalArgumentException(
rtl::OUString(RTL_CONSTASCII_USTRINGPARAM
("LdapConnection::findUserDn -User id is empty")),
NULL, 0) ;
}
rtl::OStringBuffer filter( "(&(objectclass=" );
filter.append( mLdapDefinition.mUserObjectClass ).append(")(") ;
filter.append( mLdapDefinition.mUserUniqueAttr ).append("=").append(aUser).append("))") ;
LdapMessageHolder result;
sal_Char * attributes [2];
attributes[0]= const_cast<sal_Char *>(LDAP_NO_ATTRS);
attributes[1]= NULL;
LdapErrCode retCode = ldap_search_s(mConnection,
mLdapDefinition.mBaseDN,
LDAP_SCOPE_SUBTREE,
filter.makeStringAndClear(), attributes, 0, &result.msg) ;
checkLdapReturnCode("FindUserDn", retCode,mConnection) ;
rtl::OString userDn ;
LDAPMessage *entry = ldap_first_entry(mConnection, result.msg) ;
if (entry != NULL)
{
sal_Char *charsDn = ldap_get_dn(mConnection, entry) ;
userDn = charsDn ;
ldap_memfree(charsDn) ;
}
else
{
OSL_ENSURE( false, "LdapConnection::findUserDn-could not get DN for User ");
}
return userDn ;
}
//------------------------------------------------------------------------------
rtl::OString LdapConnection::getSingleAttribute(
const rtl::OString& aDn,
const rtl::OString& aAttribute)
throw (ldap::LdapConnectionException, ldap::LdapGenericException)
{
if (!isValid()) { connectSimple(); }
const sal_Char *attributes [2] ;
rtl::OString value ;
attributes [0] = aAttribute ;
attributes [1] = 0 ;
LdapMessageHolder result ;
LdapErrCode retCode = ldap_search_s(mConnection,
aDn,
LDAP_SCOPE_BASE,
"(objectclass=*)",
const_cast<sal_Char **>(attributes),
0, // Attributes + values
&result.msg) ;
if (retCode == LDAP_NO_SUCH_OBJECT)
{
return value ;
}
checkLdapReturnCode("GetSingleAttribute", retCode, mConnection) ;
LDAPMessage *entry = ldap_first_entry(mConnection, result.msg) ;
if (entry != NULL)
{
sal_Char **values = ldap_get_values(mConnection, entry,
aAttribute) ;
if (values != NULL)
{
if (*values != NULL) { value = *values ; }
ldap_value_free(values) ;
}
}
return value ;
}
//------------------------------------------------------------------------------
} } } // extensions.config.ldap
<|endoftext|>
|
<commit_before>/******************************************************************************
* IMU_Functions.cpp
*
* Runs initialization and reads files on the BNO055 IMU
******************************************************************************/
#include "Mapper.h"
/******************************************************************************
* void start_read_imu
*
* Starts read_imu.py code
******************************************************************************/
void start_read_imu(void)
{
char cmd[50];
strcpy(cmd,"python read_imu.py & exit");
system(cmd);
/*
// clear fifo file //
//std::FILE* fifo = fopen("imu.fifo","w");
std::FILE* fifo = fopen("imu.txt","w");
fclose(fifo);
printf("Cleared fifo file\n");
// Start up the Python
std::FILE* fd = fopen("read_imu.py", "r");
printf("Started up Python\n");
PyRun_SimpleFile(fd,"read_imu.py");
printf("Ran PyRun_SimpleFile\n");
// Wait 2 seconds to let the python script start up
usleep(2000000);
// Check whether the python script wrote anything
//fd = fopen("imu.fifo","r");
fd = fopen("imu.txt","r");
printf("Python \n");
// Insert check here //
fseek(fd, 0, SEEK_END); // goto end of file
if (ftell(fd) == 0)
{
printf("file is empty\n");
}
else
{
printf("file is not empty\n");
}
fseek(fd, 0, SEEK_SET); // goto begin of file
// if it isn't printing values, restart initialization
fclose(fd);
//*/
return;
}
/******************************************************************************
* imu_t read_imu_fifo
*
* Reads IMU values from imu.fifo and write to the imu struct
******************************************************************************/
imu_t read_imu_fifo(void)
{
imu_t imu;
char buf[1000];
FILE *fd = fopen( "imu.fifo", "r");
fgets(buf,1000,fd);
fclose(fd);
sscanf(buf,"%f %f %f %f %f %f %i %i %i %i %f %f %f",
&imu.yaw,&imu.roll,&imu.pitch,
&imu.q, &imu.p, &imu.r,
&imu.sys,&imu.gyro,&imu.accel,
&imu.mag,imu.x_acc,&imu.y_acc,&imu.z_acc);
return imu;
}
<commit_msg>added print statement to imu_functions<commit_after>/******************************************************************************
* IMU_Functions.cpp
*
* Runs initialization and reads files on the BNO055 IMU
******************************************************************************/
#include "Mapper.h"
/******************************************************************************
* void start_read_imu
*
* Starts read_imu.py code
******************************************************************************/
void start_read_imu(void)
{
char cmd[50];
strcpy(cmd,"python read_imu.py & exit");
printf("%s\n", "ran strcpy command");
system(cmd);
/*
// clear fifo file //
//std::FILE* fifo = fopen("imu.fifo","w");
std::FILE* fifo = fopen("imu.txt","w");
fclose(fifo);
printf("Cleared fifo file\n");
// Start up the Python
std::FILE* fd = fopen("read_imu.py", "r");
printf("Started up Python\n");
PyRun_SimpleFile(fd,"read_imu.py");
printf("Ran PyRun_SimpleFile\n");
// Wait 2 seconds to let the python script start up
usleep(2000000);
// Check whether the python script wrote anything
//fd = fopen("imu.fifo","r");
fd = fopen("imu.txt","r");
printf("Python \n");
// Insert check here //
fseek(fd, 0, SEEK_END); // goto end of file
if (ftell(fd) == 0)
{
printf("file is empty\n");
}
else
{
printf("file is not empty\n");
}
fseek(fd, 0, SEEK_SET); // goto begin of file
// if it isn't printing values, restart initialization
fclose(fd);
//*/
return;
}
/******************************************************************************
* imu_t read_imu_fifo
*
* Reads IMU values from imu.fifo and write to the imu struct
******************************************************************************/
imu_t read_imu_fifo(void)
{
imu_t imu;
char buf[1000];
FILE *fd = fopen( "imu.fifo", "r");
fgets(buf,1000,fd);
fclose(fd);
sscanf(buf,"%f %f %f %f %f %f %i %i %i %i %f %f %f",
&imu.yaw,&imu.roll,&imu.pitch,
&imu.q, &imu.p, &imu.r,
&imu.sys,&imu.gyro,&imu.accel,
&imu.mag,imu.x_acc,&imu.y_acc,&imu.z_acc);
return imu;
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date: 2010-12-02 14:54:03 +0100 (Do, 2 Dec 2010) $
Version: $Revision: 21147 $
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkExtractDirectedPlaneImageFilterNew.h"
#include "mitkImageCast.h"
#include "mitkImageTimeSelector.h"
#include "itkImageRegionIterator.h"
mitk::ExtractDirectedPlaneImageFilterNew::ExtractDirectedPlaneImageFilterNew()
:m_CurrentWorldGeometry2D(NULL)
{
}
mitk::ExtractDirectedPlaneImageFilterNew::~ExtractDirectedPlaneImageFilterNew()
{
}
void mitk::ExtractDirectedPlaneImageFilterNew::GenerateData(){
mitk::Image::ConstPointer inputImage = ImageToImageFilter::GetInput(0);
if ( !inputImage )
{
MITK_ERROR << "mitk::ExtractDirectedPlaneImageFilterNew: No input available. Please set the input!" << std::endl;
itkExceptionMacro("mitk::ExtractDirectedPlaneImageFilterNew: No input available. Please set the input!");
return;
}
m_ImageGeometry = inputImage->GetGeometry();
//If no timestep is set, the lowest given will be selected
const mitk::TimeSlicedGeometry* inputTimeGeometry = this->GetInput()->GetTimeSlicedGeometry();
if ( !m_ActualInputTimestep )
{
ScalarType time = m_CurrentWorldGeometry2D->GetTimeBounds()[0];
if ( time > ScalarTypeNumericTraits::NonpositiveMin() )
{
m_ActualInputTimestep = inputTimeGeometry->MSToTimeStep( time );
}
}
if ( inputImage->GetDimension() > 4 || inputImage->GetDimension() < 2)
{
MITK_ERROR << "mitk::ExtractDirectedPlaneImageFilterNew:GenerateData works only with 3D and 3D+t images, sorry." << std::endl;
itkExceptionMacro("mitk::ExtractDirectedPlaneImageFilterNew works only with 3D and 3D+t images, sorry.");
return;
}
else if ( inputImage->GetDimension() == 4 )
{
mitk::ImageTimeSelector::Pointer timeselector = mitk::ImageTimeSelector::New();
timeselector->SetInput( inputImage );
timeselector->SetTimeNr( m_ActualInputTimestep );
timeselector->UpdateLargestPossibleRegion();
inputImage = timeselector->GetOutput();
}
else if ( inputImage->GetDimension() == 2)
{
mitk::Image::Pointer resultImage = ImageToImageFilter::GetOutput();
resultImage = const_cast<mitk::Image*>( inputImage.GetPointer() );
ImageToImageFilter::SetNthOutput( 0, resultImage);
return;
}
if ( !m_CurrentWorldGeometry2D )
{
MITK_ERROR<< "mitk::ExtractDirectedPlaneImageFilterNew::GenerateData has no CurrentWorldGeometry2D set" << std::endl;
return;
}
AccessFixedDimensionByItk( inputImage, ItkSliceExtraction, 3 );
}//Generate Data
void mitk::ExtractDirectedPlaneImageFilterNew::GenerateOutputInformation ()
{
Superclass::GenerateOutputInformation();
}
/*
* The desired slice is extracted by filling the image`s corresponding pixel values in an empty 2 dimensional itk::Image
* Therefor the itk image`s extent in pixel (in each direction) is doubled and its spacing (also in each direction) is divided by two
* (similar to the shannon theorem).
*/
template<typename TPixel, unsigned int VImageDimension>
void mitk::ExtractDirectedPlaneImageFilterNew::ItkSliceExtraction (itk::Image<TPixel, VImageDimension>* inputImage)
{
typedef itk::Image<TPixel, VImageDimension> InputImageType;
typedef itk::Image<TPixel, VImageDimension-1> SliceImageType;
typedef itk::ImageRegionConstIterator< SliceImageType > SliceIterator;
//Creating an itk::Image that represents the sampled slice
typename SliceImageType::Pointer resultSlice = SliceImageType::New();
typename SliceImageType::IndexType start;
start[0] = 0;
start[1] = 0;
Point3D origin = m_CurrentWorldGeometry2D->GetOrigin();
Vector3D right = m_CurrentWorldGeometry2D->GetAxisVector(0);
Vector3D bottom = m_CurrentWorldGeometry2D->GetAxisVector(1);
//Calculation the sample-spacing, i.e the half of the smallest spacing existing in the original image
Vector3D newPixelSpacing = m_ImageGeometry->GetSpacing();
float minSpacing = newPixelSpacing[0];
for (unsigned int i = 1; i < newPixelSpacing.Size(); i++)
{
if (newPixelSpacing[i] < minSpacing )
{
minSpacing = newPixelSpacing[i];
}
}
newPixelSpacing[0] = 0.5*minSpacing;
newPixelSpacing[1] = 0.5*minSpacing;
newPixelSpacing[2] = 0.5*minSpacing;
float pixelSpacing[2];
pixelSpacing[0] = newPixelSpacing[0];
pixelSpacing[1] = newPixelSpacing[1];
//Calculating the size of the sampled slice
typename SliceImageType::SizeType size;
Vector2D extentInMM;
extentInMM[0] = m_CurrentWorldGeometry2D->GetExtentInMM(0);
extentInMM[1] = m_CurrentWorldGeometry2D->GetExtentInMM(1);
//The maximum extent is the lenght of the diagonal of the considered plane
double maxExtent = sqrt(extentInMM[0]*extentInMM[0]+extentInMM[1]*extentInMM[1]);
unsigned int xTranlation = (maxExtent-extentInMM[0]);
unsigned int yTranlation = (maxExtent-extentInMM[1]);
size[0] = (maxExtent+xTranlation)/newPixelSpacing[0];
size[1] = (maxExtent+yTranlation)/newPixelSpacing[1];
//Creating an ImageRegion Object
typename SliceImageType::RegionType region;
region.SetSize( size );
region.SetIndex( start );
//Defining the image`s extent and origin by passing the region to it and allocating memory for it
resultSlice->SetRegions( region );
resultSlice->SetSpacing( pixelSpacing );
resultSlice->Allocate();
/*
* Here we create an new geometry so that the transformations are calculated correctly (our resulting slice has a different bounding box and spacing)
* The original current worldgeometry must be cloned because we have to keep the directions of the axis vector which represents the rotation
*/
right.Normalize();
bottom.Normalize();
//Here we translate the origin to adapt the new geometry to the previous calculated extent
origin[0] -= xTranlation*right[0]+yTranlation*bottom[0];
origin[1] -= xTranlation*right[1]+yTranlation*bottom[1];
origin[2] -= xTranlation*right[2]+yTranlation*bottom[2];
//Putting it together for the new geometry
mitk::Geometry3D::Pointer newSliceGeometryTest = dynamic_cast<Geometry3D*>(m_CurrentWorldGeometry2D->Clone().GetPointer());
newSliceGeometryTest->ChangeImageGeometryConsideringOriginOffset(true);
//Workaround because of BUG (#6505)
newSliceGeometryTest->GetIndexToWorldTransform()->SetMatrix(m_CurrentWorldGeometry2D->GetIndexToWorldTransform()->GetMatrix());
//Workaround end
newSliceGeometryTest->SetOrigin(origin);
ScalarType bounds[6]={0, size[0], 0, size[1], 0, 1};
newSliceGeometryTest->SetBounds(bounds);
newSliceGeometryTest->SetSpacing(newPixelSpacing);
newSliceGeometryTest->Modified();
//Workaround because of BUG (#6505)
itk::MatrixOffsetTransformBase<mitk::ScalarType,3,3>::MatrixType tempTransform = newSliceGeometryTest->GetIndexToWorldTransform()->GetMatrix();
//Workaround end
/*
* Now we iterate over the recently created slice.
* For each slice - pixel we check whether there is an according
* pixel in the input - image which can be set in the slice.
* In this way a slice is sampled out of the input - image regrading to the given PlaneGeometry
*/
Point3D currentSliceIndexPointIn2D;
Point3D currentImageWorldPointIn3D;
typename InputImageType::IndexType inputIndex;
SliceIterator sliceIterator ( resultSlice, resultSlice->GetLargestPossibleRegion() );
sliceIterator.GoToBegin();
while ( !sliceIterator.IsAtEnd() )
{
/*
* Here we add 0.5 to to assure that the indices are correctly transformed.
* (Because of the 0.5er Bug)
*/
currentSliceIndexPointIn2D[0] = sliceIterator.GetIndex()[0]+0.5;
currentSliceIndexPointIn2D[1] = sliceIterator.GetIndex()[1]+0.5;
currentSliceIndexPointIn2D[2] = 0;
newSliceGeometryTest->IndexToWorld( currentSliceIndexPointIn2D, currentImageWorldPointIn3D );
m_ImageGeometry->WorldToIndex( currentImageWorldPointIn3D, inputIndex);
if ( m_ImageGeometry->IsIndexInside( inputIndex ))
{
resultSlice->SetPixel( sliceIterator.GetIndex(), inputImage->GetPixel(inputIndex) );
}
++sliceIterator;
}
Image::Pointer resultImage = ImageToImageFilter::GetOutput();
GrabItkImageMemory(resultSlice, resultImage, NULL, false);
resultImage->SetClonedGeometry(newSliceGeometryTest);
//Workaround because of BUG (#6505)
resultImage->GetGeometry()->GetIndexToWorldTransform()->SetMatrix(tempTransform);
//Workaround end
}
///**TEST** May ba a little bit more efficient but doesn`t already work/
//right.Normalize();
//bottom.Normalize();
//Point3D currentImagePointIn3D = origin /*+ bottom*newPixelSpacing*/;
//unsigned int columns ( 0 );
/**ENDE**/
/****TEST***/
//SliceImageType::IndexType index = sliceIterator.GetIndex();
//if ( columns == (extentInPixel[0]) )
//{
//If we are at the end of a row, then we have to go to the beginning of the next row
//currentImagePointIn3D = origin;
//currentImagePointIn3D += newPixelSpacing[1]*bottom*index[1];
//columns = 0;
//m_ImageGeometry->WorldToIndex(currentImagePointIn3D, inputIndex);
//}
//else
//{
////
//if ( columns != 0 )
//{
//currentImagePointIn3D += newPixelSpacing[0]*right;
//}
//m_ImageGeometry->WorldToIndex(currentImagePointIn3D, inputIndex);
//}
//if ( m_ImageGeometry->IsIndexInside( inputIndex ))
//{
//resultSlice->SetPixel( sliceIterator.GetIndex(), inputImage->GetPixel(inputIndex) );
//}
//else if (currentImagePointIn3D == origin)
//{
//Point3D temp;
//temp[0] = bottom[0]*newPixelSpacing[0]*0.5;
//temp[1] = bottom[1]*newPixelSpacing[1]*0.5;
//temp[2] = bottom[2]*newPixelSpacing[2]*0.5;
//origin[0] += temp[0];
//origin[1] += temp[1];
//origin[2] += temp[2];
//currentImagePointIn3D = origin;
//m_ImageGeometry->WorldToIndex(currentImagePointIn3D, inputIndex);
//if ( m_ImageGeometry->IsIndexInside( inputIndex ))
//{
//resultSlice->SetPixel( sliceIterator.GetIndex(), inputImage->GetPixel(inputIndex) );
//}
//}
/****TEST ENDE****/
<commit_msg>CHG (#6417): Changed the initialization of an extracted slice. Now every pixel outside of the underlying 3D image is set black. Before those pixel were not at all and therefore appeared white<commit_after>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date: 2010-12-02 14:54:03 +0100 (Do, 2 Dec 2010) $
Version: $Revision: 21147 $
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkExtractDirectedPlaneImageFilterNew.h"
#include "mitkImageCast.h"
#include "mitkImageTimeSelector.h"
#include "itkImageRegionIterator.h"
mitk::ExtractDirectedPlaneImageFilterNew::ExtractDirectedPlaneImageFilterNew()
:m_CurrentWorldGeometry2D(NULL)
{
}
mitk::ExtractDirectedPlaneImageFilterNew::~ExtractDirectedPlaneImageFilterNew()
{
}
void mitk::ExtractDirectedPlaneImageFilterNew::GenerateData(){
mitk::Image::ConstPointer inputImage = ImageToImageFilter::GetInput(0);
if ( !inputImage )
{
MITK_ERROR << "mitk::ExtractDirectedPlaneImageFilterNew: No input available. Please set the input!" << std::endl;
itkExceptionMacro("mitk::ExtractDirectedPlaneImageFilterNew: No input available. Please set the input!");
return;
}
m_ImageGeometry = inputImage->GetGeometry();
//If no timestep is set, the lowest given will be selected
const mitk::TimeSlicedGeometry* inputTimeGeometry = this->GetInput()->GetTimeSlicedGeometry();
if ( !m_ActualInputTimestep )
{
ScalarType time = m_CurrentWorldGeometry2D->GetTimeBounds()[0];
if ( time > ScalarTypeNumericTraits::NonpositiveMin() )
{
m_ActualInputTimestep = inputTimeGeometry->MSToTimeStep( time );
}
}
if ( inputImage->GetDimension() > 4 || inputImage->GetDimension() < 2)
{
MITK_ERROR << "mitk::ExtractDirectedPlaneImageFilterNew:GenerateData works only with 3D and 3D+t images, sorry." << std::endl;
itkExceptionMacro("mitk::ExtractDirectedPlaneImageFilterNew works only with 3D and 3D+t images, sorry.");
return;
}
else if ( inputImage->GetDimension() == 4 )
{
mitk::ImageTimeSelector::Pointer timeselector = mitk::ImageTimeSelector::New();
timeselector->SetInput( inputImage );
timeselector->SetTimeNr( m_ActualInputTimestep );
timeselector->UpdateLargestPossibleRegion();
inputImage = timeselector->GetOutput();
}
else if ( inputImage->GetDimension() == 2)
{
mitk::Image::Pointer resultImage = ImageToImageFilter::GetOutput();
resultImage = const_cast<mitk::Image*>( inputImage.GetPointer() );
ImageToImageFilter::SetNthOutput( 0, resultImage);
return;
}
if ( !m_CurrentWorldGeometry2D )
{
MITK_ERROR<< "mitk::ExtractDirectedPlaneImageFilterNew::GenerateData has no CurrentWorldGeometry2D set" << std::endl;
return;
}
AccessFixedDimensionByItk( inputImage, ItkSliceExtraction, 3 );
}//Generate Data
void mitk::ExtractDirectedPlaneImageFilterNew::GenerateOutputInformation ()
{
Superclass::GenerateOutputInformation();
}
/*
* The desired slice is extracted by filling the image`s corresponding pixel values in an empty 2 dimensional itk::Image
* Therefor the itk image`s extent in pixel (in each direction) is doubled and its spacing (also in each direction) is divided by two
* (similar to the shannon theorem).
*/
template<typename TPixel, unsigned int VImageDimension>
void mitk::ExtractDirectedPlaneImageFilterNew::ItkSliceExtraction (itk::Image<TPixel, VImageDimension>* inputImage)
{
typedef itk::Image<TPixel, VImageDimension> InputImageType;
typedef itk::Image<TPixel, VImageDimension-1> SliceImageType;
typedef itk::ImageRegionConstIterator< SliceImageType > SliceIterator;
//Creating an itk::Image that represents the sampled slice
typename SliceImageType::Pointer resultSlice = SliceImageType::New();
typename SliceImageType::IndexType start;
start[0] = 0;
start[1] = 0;
Point3D origin = m_CurrentWorldGeometry2D->GetOrigin();
Vector3D right = m_CurrentWorldGeometry2D->GetAxisVector(0);
Vector3D bottom = m_CurrentWorldGeometry2D->GetAxisVector(1);
//Calculation the sample-spacing, i.e the half of the smallest spacing existing in the original image
Vector3D newPixelSpacing = m_ImageGeometry->GetSpacing();
float minSpacing = newPixelSpacing[0];
for (unsigned int i = 1; i < newPixelSpacing.Size(); i++)
{
if (newPixelSpacing[i] < minSpacing )
{
minSpacing = newPixelSpacing[i];
}
}
newPixelSpacing[0] = 0.5*minSpacing;
newPixelSpacing[1] = 0.5*minSpacing;
newPixelSpacing[2] = 0.5*minSpacing;
float pixelSpacing[2];
pixelSpacing[0] = newPixelSpacing[0];
pixelSpacing[1] = newPixelSpacing[1];
//Calculating the size of the sampled slice
typename SliceImageType::SizeType size;
Vector2D extentInMM;
extentInMM[0] = m_CurrentWorldGeometry2D->GetExtentInMM(0);
extentInMM[1] = m_CurrentWorldGeometry2D->GetExtentInMM(1);
//The maximum extent is the lenght of the diagonal of the considered plane
double maxExtent = sqrt(extentInMM[0]*extentInMM[0]+extentInMM[1]*extentInMM[1]);
unsigned int xTranlation = (maxExtent-extentInMM[0]);
unsigned int yTranlation = (maxExtent-extentInMM[1]);
size[0] = (maxExtent+xTranlation)/newPixelSpacing[0];
size[1] = (maxExtent+yTranlation)/newPixelSpacing[1];
//Creating an ImageRegion Object
typename SliceImageType::RegionType region;
region.SetSize( size );
region.SetIndex( start );
//Defining the image`s extent and origin by passing the region to it and allocating memory for it
resultSlice->SetRegions( region );
resultSlice->SetSpacing( pixelSpacing );
resultSlice->Allocate();
/*
* Here we create an new geometry so that the transformations are calculated correctly (our resulting slice has a different bounding box and spacing)
* The original current worldgeometry must be cloned because we have to keep the directions of the axis vector which represents the rotation
*/
right.Normalize();
bottom.Normalize();
//Here we translate the origin to adapt the new geometry to the previous calculated extent
origin[0] -= xTranlation*right[0]+yTranlation*bottom[0];
origin[1] -= xTranlation*right[1]+yTranlation*bottom[1];
origin[2] -= xTranlation*right[2]+yTranlation*bottom[2];
//Putting it together for the new geometry
mitk::Geometry3D::Pointer newSliceGeometryTest = dynamic_cast<Geometry3D*>(m_CurrentWorldGeometry2D->Clone().GetPointer());
newSliceGeometryTest->ChangeImageGeometryConsideringOriginOffset(true);
//Workaround because of BUG (#6505)
newSliceGeometryTest->GetIndexToWorldTransform()->SetMatrix(m_CurrentWorldGeometry2D->GetIndexToWorldTransform()->GetMatrix());
//Workaround end
newSliceGeometryTest->SetOrigin(origin);
ScalarType bounds[6]={0, size[0], 0, size[1], 0, 1};
newSliceGeometryTest->SetBounds(bounds);
newSliceGeometryTest->SetSpacing(newPixelSpacing);
newSliceGeometryTest->Modified();
//Workaround because of BUG (#6505)
itk::MatrixOffsetTransformBase<mitk::ScalarType,3,3>::MatrixType tempTransform = newSliceGeometryTest->GetIndexToWorldTransform()->GetMatrix();
//Workaround end
/*
* Now we iterate over the recently created slice.
* For each slice - pixel we check whether there is an according
* pixel in the input - image which can be set in the slice.
* In this way a slice is sampled out of the input - image regrading to the given PlaneGeometry
*/
Point3D currentSliceIndexPointIn2D;
Point3D currentImageWorldPointIn3D;
typename InputImageType::IndexType inputIndex;
SliceIterator sliceIterator ( resultSlice, resultSlice->GetLargestPossibleRegion() );
sliceIterator.GoToBegin();
while ( !sliceIterator.IsAtEnd() )
{
/*
* Here we add 0.5 to to assure that the indices are correctly transformed.
* (Because of the 0.5er Bug)
*/
currentSliceIndexPointIn2D[0] = sliceIterator.GetIndex()[0]+0.5;
currentSliceIndexPointIn2D[1] = sliceIterator.GetIndex()[1]+0.5;
currentSliceIndexPointIn2D[2] = 0;
newSliceGeometryTest->IndexToWorld( currentSliceIndexPointIn2D, currentImageWorldPointIn3D );
m_ImageGeometry->WorldToIndex( currentImageWorldPointIn3D, inputIndex);
if ( m_ImageGeometry->IsIndexInside( inputIndex ))
{
resultSlice->SetPixel( sliceIterator.GetIndex(), inputImage->GetPixel(inputIndex) );
}
else
{
resultSlice->SetPixel( sliceIterator.GetIndex(), 0);
}
++sliceIterator;
}
Image::Pointer resultImage = ImageToImageFilter::GetOutput();
GrabItkImageMemory(resultSlice, resultImage, NULL, false);
resultImage->SetClonedGeometry(newSliceGeometryTest);
//Workaround because of BUG (#6505)
resultImage->GetGeometry()->GetIndexToWorldTransform()->SetMatrix(tempTransform);
//Workaround end
}
///**TEST** May ba a little bit more efficient but doesn`t already work/
//right.Normalize();
//bottom.Normalize();
//Point3D currentImagePointIn3D = origin /*+ bottom*newPixelSpacing*/;
//unsigned int columns ( 0 );
/**ENDE**/
/****TEST***/
//SliceImageType::IndexType index = sliceIterator.GetIndex();
//if ( columns == (extentInPixel[0]) )
//{
//If we are at the end of a row, then we have to go to the beginning of the next row
//currentImagePointIn3D = origin;
//currentImagePointIn3D += newPixelSpacing[1]*bottom*index[1];
//columns = 0;
//m_ImageGeometry->WorldToIndex(currentImagePointIn3D, inputIndex);
//}
//else
//{
////
//if ( columns != 0 )
//{
//currentImagePointIn3D += newPixelSpacing[0]*right;
//}
//m_ImageGeometry->WorldToIndex(currentImagePointIn3D, inputIndex);
//}
//if ( m_ImageGeometry->IsIndexInside( inputIndex ))
//{
//resultSlice->SetPixel( sliceIterator.GetIndex(), inputImage->GetPixel(inputIndex) );
//}
//else if (currentImagePointIn3D == origin)
//{
//Point3D temp;
//temp[0] = bottom[0]*newPixelSpacing[0]*0.5;
//temp[1] = bottom[1]*newPixelSpacing[1]*0.5;
//temp[2] = bottom[2]*newPixelSpacing[2]*0.5;
//origin[0] += temp[0];
//origin[1] += temp[1];
//origin[2] += temp[2];
//currentImagePointIn3D = origin;
//m_ImageGeometry->WorldToIndex(currentImagePointIn3D, inputIndex);
//if ( m_ImageGeometry->IsIndexInside( inputIndex ))
//{
//resultSlice->SetPixel( sliceIterator.GetIndex(), inputImage->GetPixel(inputIndex) );
//}
//}
/****TEST ENDE****/
<|endoftext|>
|
<commit_before>//===-- ARMTargetMachine.cpp - Define TargetMachine for ARM ---------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//
//===----------------------------------------------------------------------===//
#include "ARMTargetMachine.h"
#include "ARMTargetAsmInfo.h"
#include "ARMFrameInfo.h"
#include "ARM.h"
#include "llvm/PassManager.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Target/TargetRegistry.h"
using namespace llvm;
static cl::opt<bool> DisableLdStOpti("disable-arm-loadstore-opti", cl::Hidden,
cl::desc("Disable load store optimization pass"));
static cl::opt<bool> DisableIfConversion("disable-arm-if-conversion",cl::Hidden,
cl::desc("Disable if-conversion pass"));
extern "C" void LLVMInitializeARMTarget() {
// Register the target.
RegisterTargetMachine<ARMTargetMachine> X(TheARMTarget);
RegisterTargetMachine<ThumbTargetMachine> Y(TheThumbTarget);
}
/// TargetMachine ctor - Create an ARM architecture model.
///
ARMBaseTargetMachine::ARMBaseTargetMachine(const Target &T,
const std::string &TT,
const std::string &FS,
bool isThumb)
: LLVMTargetMachine(T),
Subtarget(TT, FS, isThumb),
FrameInfo(Subtarget),
JITInfo(),
InstrItins(Subtarget.getInstrItineraryData()) {
DefRelocModel = getRelocationModel();
}
ARMTargetMachine::ARMTargetMachine(const Target &T, const std::string &TT,
const std::string &FS)
: ARMBaseTargetMachine(T, TT, FS, false), InstrInfo(Subtarget),
DataLayout(Subtarget.isAPCS_ABI() ?
std::string("e-p:32:32-f64:32:32-i64:32:32") :
std::string("e-p:32:32-f64:64:64-i64:64:64")),
TLInfo(*this) {
}
ThumbTargetMachine::ThumbTargetMachine(const Target &T, const std::string &TT,
const std::string &FS)
: ARMBaseTargetMachine(T, TT, FS, true),
DataLayout(Subtarget.isAPCS_ABI() ?
std::string("e-p:32:32-f64:32:32-i64:32:32-"
"i16:16:32-i8:8:32-i1:8:32-a:0:32") :
std::string("e-p:32:32-f64:64:64-i64:64:64-"
"i16:16:32-i8:8:32-i1:8:32-a:0:32")),
TLInfo(*this) {
// Create the approriate type of Thumb InstrInfo
if (Subtarget.hasThumb2())
InstrInfo = new Thumb2InstrInfo(Subtarget);
else
InstrInfo = new Thumb1InstrInfo(Subtarget);
}
const TargetAsmInfo *ARMBaseTargetMachine::createTargetAsmInfo() const {
switch (Subtarget.TargetType) {
default: llvm_unreachable("Unknown ARM subtarget kind");
case ARMSubtarget::isDarwin:
return new ARMDarwinTargetAsmInfo();
case ARMSubtarget::isELF:
return new ARMELFTargetAsmInfo();
}
}
// Pass Pipeline Configuration
bool ARMBaseTargetMachine::addInstSelector(PassManagerBase &PM,
CodeGenOpt::Level OptLevel) {
PM.add(createARMISelDag(*this));
return false;
}
bool ARMBaseTargetMachine::addPreRegAlloc(PassManagerBase &PM,
CodeGenOpt::Level OptLevel) {
if (Subtarget.hasNEON())
PM.add(createNEONPreAllocPass());
// FIXME: temporarily disabling load / store optimization pass for Thumb mode.
if (OptLevel != CodeGenOpt::None && !DisableLdStOpti && !Subtarget.isThumb())
PM.add(createARMLoadStoreOptimizationPass(true));
return true;
}
bool ARMBaseTargetMachine::addPreEmitPass(PassManagerBase &PM,
CodeGenOpt::Level OptLevel) {
// FIXME: temporarily disabling load / store optimization pass for Thumb1 mode.
if (OptLevel != CodeGenOpt::None && !DisableLdStOpti &&
!Subtarget.isThumb1Only())
PM.add(createARMLoadStoreOptimizationPass());
if (OptLevel != CodeGenOpt::None &&
!DisableIfConversion && !Subtarget.isThumb())
PM.add(createIfConverterPass());
if (Subtarget.isThumb2()) {
PM.add(createThumb2ITBlockPass());
PM.add(createThumb2SizeReductionPass());
}
PM.add(createARMConstantIslandPass());
return true;
}
bool ARMBaseTargetMachine::addCodeEmitter(PassManagerBase &PM,
CodeGenOpt::Level OptLevel,
MachineCodeEmitter &MCE) {
// FIXME: Move this to TargetJITInfo!
if (DefRelocModel == Reloc::Default)
setRelocationModel(Reloc::Static);
// Machine code emitter pass for ARM.
PM.add(createARMCodeEmitterPass(*this, MCE));
return false;
}
bool ARMBaseTargetMachine::addCodeEmitter(PassManagerBase &PM,
CodeGenOpt::Level OptLevel,
JITCodeEmitter &JCE) {
// FIXME: Move this to TargetJITInfo!
if (DefRelocModel == Reloc::Default)
setRelocationModel(Reloc::Static);
// Machine code emitter pass for ARM.
PM.add(createARMJITCodeEmitterPass(*this, JCE));
return false;
}
bool ARMBaseTargetMachine::addCodeEmitter(PassManagerBase &PM,
CodeGenOpt::Level OptLevel,
ObjectCodeEmitter &OCE) {
// FIXME: Move this to TargetJITInfo!
if (DefRelocModel == Reloc::Default)
setRelocationModel(Reloc::Static);
// Machine code emitter pass for ARM.
PM.add(createARMObjectCodeEmitterPass(*this, OCE));
return false;
}
bool ARMBaseTargetMachine::addSimpleCodeEmitter(PassManagerBase &PM,
CodeGenOpt::Level OptLevel,
MachineCodeEmitter &MCE) {
// Machine code emitter pass for ARM.
PM.add(createARMCodeEmitterPass(*this, MCE));
return false;
}
bool ARMBaseTargetMachine::addSimpleCodeEmitter(PassManagerBase &PM,
CodeGenOpt::Level OptLevel,
JITCodeEmitter &JCE) {
// Machine code emitter pass for ARM.
PM.add(createARMJITCodeEmitterPass(*this, JCE));
return false;
}
bool ARMBaseTargetMachine::addSimpleCodeEmitter(PassManagerBase &PM,
CodeGenOpt::Level OptLevel,
ObjectCodeEmitter &OCE) {
// Machine code emitter pass for ARM.
PM.add(createARMObjectCodeEmitterPass(*this, OCE));
return false;
}
<commit_msg>Adding a blank line back.<commit_after>//===-- ARMTargetMachine.cpp - Define TargetMachine for ARM ---------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//
//===----------------------------------------------------------------------===//
#include "ARMTargetMachine.h"
#include "ARMTargetAsmInfo.h"
#include "ARMFrameInfo.h"
#include "ARM.h"
#include "llvm/PassManager.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Target/TargetRegistry.h"
using namespace llvm;
static cl::opt<bool> DisableLdStOpti("disable-arm-loadstore-opti", cl::Hidden,
cl::desc("Disable load store optimization pass"));
static cl::opt<bool> DisableIfConversion("disable-arm-if-conversion",cl::Hidden,
cl::desc("Disable if-conversion pass"));
extern "C" void LLVMInitializeARMTarget() {
// Register the target.
RegisterTargetMachine<ARMTargetMachine> X(TheARMTarget);
RegisterTargetMachine<ThumbTargetMachine> Y(TheThumbTarget);
}
/// TargetMachine ctor - Create an ARM architecture model.
///
ARMBaseTargetMachine::ARMBaseTargetMachine(const Target &T,
const std::string &TT,
const std::string &FS,
bool isThumb)
: LLVMTargetMachine(T),
Subtarget(TT, FS, isThumb),
FrameInfo(Subtarget),
JITInfo(),
InstrItins(Subtarget.getInstrItineraryData()) {
DefRelocModel = getRelocationModel();
}
ARMTargetMachine::ARMTargetMachine(const Target &T, const std::string &TT,
const std::string &FS)
: ARMBaseTargetMachine(T, TT, FS, false), InstrInfo(Subtarget),
DataLayout(Subtarget.isAPCS_ABI() ?
std::string("e-p:32:32-f64:32:32-i64:32:32") :
std::string("e-p:32:32-f64:64:64-i64:64:64")),
TLInfo(*this) {
}
ThumbTargetMachine::ThumbTargetMachine(const Target &T, const std::string &TT,
const std::string &FS)
: ARMBaseTargetMachine(T, TT, FS, true),
DataLayout(Subtarget.isAPCS_ABI() ?
std::string("e-p:32:32-f64:32:32-i64:32:32-"
"i16:16:32-i8:8:32-i1:8:32-a:0:32") :
std::string("e-p:32:32-f64:64:64-i64:64:64-"
"i16:16:32-i8:8:32-i1:8:32-a:0:32")),
TLInfo(*this) {
// Create the approriate type of Thumb InstrInfo
if (Subtarget.hasThumb2())
InstrInfo = new Thumb2InstrInfo(Subtarget);
else
InstrInfo = new Thumb1InstrInfo(Subtarget);
}
const TargetAsmInfo *ARMBaseTargetMachine::createTargetAsmInfo() const {
switch (Subtarget.TargetType) {
default: llvm_unreachable("Unknown ARM subtarget kind");
case ARMSubtarget::isDarwin:
return new ARMDarwinTargetAsmInfo();
case ARMSubtarget::isELF:
return new ARMELFTargetAsmInfo();
}
}
// Pass Pipeline Configuration
bool ARMBaseTargetMachine::addInstSelector(PassManagerBase &PM,
CodeGenOpt::Level OptLevel) {
PM.add(createARMISelDag(*this));
return false;
}
bool ARMBaseTargetMachine::addPreRegAlloc(PassManagerBase &PM,
CodeGenOpt::Level OptLevel) {
if (Subtarget.hasNEON())
PM.add(createNEONPreAllocPass());
// FIXME: temporarily disabling load / store optimization pass for Thumb mode.
if (OptLevel != CodeGenOpt::None && !DisableLdStOpti && !Subtarget.isThumb())
PM.add(createARMLoadStoreOptimizationPass(true));
return true;
}
bool ARMBaseTargetMachine::addPreEmitPass(PassManagerBase &PM,
CodeGenOpt::Level OptLevel) {
// FIXME: temporarily disabling load / store optimization pass for Thumb1 mode.
if (OptLevel != CodeGenOpt::None && !DisableLdStOpti &&
!Subtarget.isThumb1Only())
PM.add(createARMLoadStoreOptimizationPass());
if (OptLevel != CodeGenOpt::None &&
!DisableIfConversion && !Subtarget.isThumb())
PM.add(createIfConverterPass());
if (Subtarget.isThumb2()) {
PM.add(createThumb2ITBlockPass());
PM.add(createThumb2SizeReductionPass());
}
PM.add(createARMConstantIslandPass());
return true;
}
bool ARMBaseTargetMachine::addCodeEmitter(PassManagerBase &PM,
CodeGenOpt::Level OptLevel,
MachineCodeEmitter &MCE) {
// FIXME: Move this to TargetJITInfo!
if (DefRelocModel == Reloc::Default)
setRelocationModel(Reloc::Static);
// Machine code emitter pass for ARM.
PM.add(createARMCodeEmitterPass(*this, MCE));
return false;
}
bool ARMBaseTargetMachine::addCodeEmitter(PassManagerBase &PM,
CodeGenOpt::Level OptLevel,
JITCodeEmitter &JCE) {
// FIXME: Move this to TargetJITInfo!
if (DefRelocModel == Reloc::Default)
setRelocationModel(Reloc::Static);
// Machine code emitter pass for ARM.
PM.add(createARMJITCodeEmitterPass(*this, JCE));
return false;
}
bool ARMBaseTargetMachine::addCodeEmitter(PassManagerBase &PM,
CodeGenOpt::Level OptLevel,
ObjectCodeEmitter &OCE) {
// FIXME: Move this to TargetJITInfo!
if (DefRelocModel == Reloc::Default)
setRelocationModel(Reloc::Static);
// Machine code emitter pass for ARM.
PM.add(createARMObjectCodeEmitterPass(*this, OCE));
return false;
}
bool ARMBaseTargetMachine::addSimpleCodeEmitter(PassManagerBase &PM,
CodeGenOpt::Level OptLevel,
MachineCodeEmitter &MCE) {
// Machine code emitter pass for ARM.
PM.add(createARMCodeEmitterPass(*this, MCE));
return false;
}
bool ARMBaseTargetMachine::addSimpleCodeEmitter(PassManagerBase &PM,
CodeGenOpt::Level OptLevel,
JITCodeEmitter &JCE) {
// Machine code emitter pass for ARM.
PM.add(createARMJITCodeEmitterPass(*this, JCE));
return false;
}
bool ARMBaseTargetMachine::addSimpleCodeEmitter(PassManagerBase &PM,
CodeGenOpt::Level OptLevel,
ObjectCodeEmitter &OCE) {
// Machine code emitter pass for ARM.
PM.add(createARMObjectCodeEmitterPass(*this, OCE));
return false;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2013-2014 ARM Limited
* All rights reserved.
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Ron Dreslinski
* Mitch Hayenga
*/
/**
* @file
* Hardware Prefetcher Definition.
*/
#include <list>
#include "mem/cache/prefetch/base.hh"
#include "mem/cache/base.hh"
#include "sim/system.hh"
BasePrefetcher::BasePrefetcher(const BasePrefetcherParams *p)
: ClockedObject(p), cache(nullptr), blkSize(0), system(p->sys),
onMiss(p->on_miss), onRead(p->on_read),
onWrite(p->on_write), onData(p->on_data), onInst(p->on_inst),
masterId(system->getMasterId(name())),
pageBytes(system->getPageBytes())
{
}
void
BasePrefetcher::setCache(BaseCache *_cache)
{
assert(!cache);
cache = _cache;
blkSize = cache->getBlockSize();
}
void
BasePrefetcher::regStats()
{
pfIssued
.name(name() + ".num_hwpf_issued")
.desc("number of hwpf issued")
;
}
bool
BasePrefetcher::observeAccess(const PacketPtr &pkt) const
{
Addr addr = pkt->getAddr();
bool fetch = pkt->req->isInstFetch();
bool read= pkt->isRead();
bool is_secure = pkt->isSecure();
if (pkt->req->isUncacheable()) return false;
if (fetch && !onInst) return false;
if (!fetch && !onData) return false;
if (!fetch && read && !onRead) return false;
if (!fetch && !read && !onWrite) return false;
if (onMiss) {
return !inCache(addr, is_secure) &&
!inMissQueue(addr, is_secure);
}
return true;
}
bool
BasePrefetcher::inCache(Addr addr, bool is_secure) const
{
if (cache->inCache(addr, is_secure)) {
return true;
}
return false;
}
bool
BasePrefetcher::inMissQueue(Addr addr, bool is_secure) const
{
if (cache->inMissQueue(addr, is_secure)) {
return true;
}
return false;
}
bool
BasePrefetcher::samePage(Addr a, Addr b) const
{
return roundDown(a, pageBytes) == roundDown(b, pageBytes);
}
<commit_msg>mem: Hide WriteInvalidate requests from prefetchers<commit_after>/*
* Copyright (c) 2013-2014 ARM Limited
* All rights reserved.
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Ron Dreslinski
* Mitch Hayenga
*/
/**
* @file
* Hardware Prefetcher Definition.
*/
#include <list>
#include "mem/cache/prefetch/base.hh"
#include "mem/cache/base.hh"
#include "sim/system.hh"
BasePrefetcher::BasePrefetcher(const BasePrefetcherParams *p)
: ClockedObject(p), cache(nullptr), blkSize(0), system(p->sys),
onMiss(p->on_miss), onRead(p->on_read),
onWrite(p->on_write), onData(p->on_data), onInst(p->on_inst),
masterId(system->getMasterId(name())),
pageBytes(system->getPageBytes())
{
}
void
BasePrefetcher::setCache(BaseCache *_cache)
{
assert(!cache);
cache = _cache;
blkSize = cache->getBlockSize();
}
void
BasePrefetcher::regStats()
{
pfIssued
.name(name() + ".num_hwpf_issued")
.desc("number of hwpf issued")
;
}
bool
BasePrefetcher::observeAccess(const PacketPtr &pkt) const
{
Addr addr = pkt->getAddr();
bool fetch = pkt->req->isInstFetch();
bool read = pkt->isRead();
bool inv = pkt->isInvalidate();
bool is_secure = pkt->isSecure();
if (pkt->req->isUncacheable()) return false;
if (fetch && !onInst) return false;
if (!fetch && !onData) return false;
if (!fetch && read && !onRead) return false;
if (!fetch && !read && !onWrite) return false;
if (!fetch && !read && inv) return false;
if (onMiss) {
return !inCache(addr, is_secure) &&
!inMissQueue(addr, is_secure);
}
return true;
}
bool
BasePrefetcher::inCache(Addr addr, bool is_secure) const
{
if (cache->inCache(addr, is_secure)) {
return true;
}
return false;
}
bool
BasePrefetcher::inMissQueue(Addr addr, bool is_secure) const
{
if (cache->inMissQueue(addr, is_secure)) {
return true;
}
return false;
}
bool
BasePrefetcher::samePage(Addr a, Addr b) const
{
return roundDown(a, pageBytes) == roundDown(b, pageBytes);
}
<|endoftext|>
|
<commit_before>// ============================================================
// Example: LCDML: graphic display with u8g
// ============================================================
// Author: Jomelo
// Last update: 21.01.2018
// License: MIT
// ============================================================
// Description:
// This example shows how to use the u8glib with the LCDMenuLib
// The menu can placed in a box that can be placed anywhere on
// the screen.
// ============================================================
// *********************************************************************
// special settings
// *********************************************************************
// enable this line when you are not usigng a standard arduino
// for example when your chip is an ESP or a STM or SAM or something else
//#define _LCDML_cfg_use_ram
// include libs
#include <LCDMenuLib2.h>
//extern char* g_LCDML_DISP_lang_lcdml_table[254]; // uncomment if you have got problem with lib compile and undefined g_LCDML_DISP_lang_lcdml_table
// U8g2lib
#include <Arduino.h>
#include <U8g2lib.h>
#ifdef U8X8_HAVE_HW_SPI
#include <SPI.h>
#endif
#ifdef U8X8_HAVE_HW_I2C
#include <Wire.h>
#endif
// *********************************************************************
// U8GLIB
// *********************************************************************
// U8g2 Constructor List (Frame Buffer)
// The complete list is available here: https://github.com/olikraus/u8g2/wiki/u8g2setupcpp
// Please update the pin numbers according to your setup. Use U8X8_PIN_NONE if the reset pin is not connected
//U8G2_ST7920_128X64_F_HW_SPI u8g2(U8G2_R0, /* CS=*/ 53, /* reset=*/ U8X8_PIN_NONE); // (MEGA, ...
//U8G2_ST7920_128X64_F_HW_SPI u8g2(U8G2_R0, /* CS=*/ 12, /* reset=*/ U8X8_PIN_NONE); // (Uno and co
U8G2_ST7920_128X64_F_SW_SPI u8g2(U8G2_R0, /* clock=*/ 25, /* data= /R/w */ 33, /* CS=*/ 32, /* reset= */ U8X8_PIN_NONE ); // ESP32
// settings for u8g lib and LCD
#define _LCDML_DISP_w 128 // LCD width
#define _LCDML_DISP_h 64 // LCD height
// font settings
#define _LCDML_DISP_font u8g2_font_squeezed_r7_tr // u8g_font_6x13 // u8glib font (more fonts under u8g.h line 1520 ...)
#define _LCDML_DISP_font_w 7 // font width
#define _LCDML_DISP_font_h 8 // font height
// cursor settings
#define _LCDML_DISP_cursor_char ">" // cursor char
#define _LCDML_DISP_cur_space_before 2 // cursor space between
#define _LCDML_DISP_cur_space_behind 4 // cursor space between
// menu position and size
#define _LCDML_DISP_box_x0 0 // start point (x0, y0)
#define _LCDML_DISP_box_y0 0 // start point (x0, y0)
#define _LCDML_DISP_box_x1 128 // width x (x0 + width)
#define _LCDML_DISP_box_y1 64 // hight y (y0 + height)
#define _LCDML_DISP_draw_frame 1 // draw a box around the menu
// scrollbar width
#define _LCDML_DISP_scrollbar_w 6 // scrollbar width (if this value is < 3, the scrollbar is disabled)
// nothing change here
#define _LCDML_DISP_cols_max ((_LCDML_DISP_box_x1-_LCDML_DISP_box_x0)/_LCDML_DISP_font_w)
#define _LCDML_DISP_rows_max ((_LCDML_DISP_box_y1-_LCDML_DISP_box_y0-((_LCDML_DISP_box_y1-_LCDML_DISP_box_y0)/_LCDML_DISP_font_h))/_LCDML_DISP_font_h)
// rows and cols
// when you use more rows or cols as allowed change in LCDMenuLib.h the define "_LCDML_DISP_cfg_max_rows" and "_LCDML_DISP_cfg_max_string_length"
// the program needs more ram with this changes
#define _LCDML_DISP_rows _LCDML_DISP_rows_max // max rows
#define _LCDML_DISP_cols 20 // max cols
// *********************************************************************
// Prototypes
// *********************************************************************
void lcdml_menu_display();
void lcdml_menu_clear();
void lcdml_menu_control();
// *********************************************************************
// Objects
// *********************************************************************
LCDMenuLib2_menu LCDML_0 (255, 0, 0, NULL, NULL); // root menu element (do not change)
LCDMenuLib2 LCDML(LCDML_0, _LCDML_DISP_rows, _LCDML_DISP_cols, lcdml_menu_display, lcdml_menu_clear, lcdml_menu_control);
// Modification for PlatformIO and similar platforms
#include <LCDML_display_dynFunction.h>
#include <LCDML_display_menu.h>
#include <LCDML_condition.h>
#include <LCDML_display_menuFunction.h>
#include <LCDML_control.h>
// *********************************************************************
// LCDML MENU/DISP
// *********************************************************************
// LCDML_0 => layer 0
// LCDML_0_X => layer 1
// LCDML_0_X_X => layer 2
// LCDML_0_X_X_X => layer 3
// LCDML_0_... => layer ...
// For beginners
// LCDML_add(id, prev_layer, new_num, lang_char_array, callback_function)
LCDML_add (0 , LCDML_0 , 1 , "Information" , mFunc_information); // this menu function can be found on "LCDML_display_menuFunction" tab
LCDML_add (1 , LCDML_0 , 2 , "Time info" , mFunc_timer_info); // this menu function can be found on "LCDML_display_menuFunction" tab
LCDML_add (2 , LCDML_0 , 3 , "Program" , NULL); // NULL = no menu function
LCDML_add (3 , LCDML_0_3 , 1 , "Program 1" , NULL); // NULL = no menu function
LCDML_add (4 , LCDML_0_3_1 , 1 , "P1 dummy" , NULL); // NULL = no menu function
LCDML_add (5 , LCDML_0_3_1 , 2 , "P1 Settings" , NULL); // NULL = no menu function
LCDML_add (6 , LCDML_0_3_1_2 , 1 , "Warm" , NULL); // NULL = no menu function
LCDML_add (7 , LCDML_0_3_1_2 , 2 , "Cold" , NULL); // NULL = no menu function
LCDML_add (8 , LCDML_0_3_1_2 , 3 , "Back" , mFunc_back); // this menu function can be found on "LCDML_display_menuFunction" tab
LCDML_add (9 , LCDML_0_3_1 , 3 , "Back" , mFunc_back); // this menu function can be found on "LCDML_display_menuFunction" tab
LCDML_add (10 , LCDML_0_3 , 2 , "Program 2" , mFunc_p2); // this menu function can be found on "LCDML_display_menuFunction" tab
LCDML_add (11 , LCDML_0_3 , 3 , "Back" , mFunc_back); // this menu function can be found on "LCDML_display_menuFunction" tab
LCDML_add (12 , LCDML_0 , 4 , "Special" , NULL); // NULL = no menu function
LCDML_add (13 , LCDML_0_4 , 1 , "Go to Root" , mFunc_goToRootMenu); // this menu function can be found on "LCDML_display_menuFunction" tab
LCDML_add (14 , LCDML_0_4 , 2 , "Jump to Time info", mFunc_jumpTo_timer_info); // this menu function can be found on "LCDML_display_menuFunction" tab
LCDML_add (15 , LCDML_0_4 , 3 , "Back" , mFunc_back); // this menu function can be found on "LCDML_display_menuFunction" tab
// Advanced menu (for profit) part with more settings
// Example for one function and different parameters
// It is recommend to use parameters for switching settings like, (small drink, medium drink, big drink) or (200ml, 400ml, 600ml, 800ml) ...
// the parameter change can also be released with dynParams on the next example
// LCDMenuLib_addAdvanced(id, prev_layer, new_num, condition, lang_char_array, callback_function, parameter (0-255), menu function type )
LCDML_addAdvanced (16 , LCDML_0 , 5 , NULL, "Parameter" , NULL, 0, _LCDML_TYPE_default); // NULL = no menu function
LCDML_addAdvanced (17 , LCDML_0_5 , 1 , NULL, "Parameter 1" , mFunc_para, 10, _LCDML_TYPE_default); // NULL = no menu function
LCDML_addAdvanced (18 , LCDML_0_5 , 2 , NULL, "Parameter 2" , mFunc_para, 20, _LCDML_TYPE_default); // NULL = no menu function
LCDML_addAdvanced (19 , LCDML_0_5 , 3 , NULL, "Parameter 3" , mFunc_para, 30, _LCDML_TYPE_default); // NULL = no menu function
LCDML_add (20 , LCDML_0_5 , 4 , "Back" , mFunc_back); // this menu function can be found on "LCDML_display_menuFunction" tab
// Example for dynamic content
// 1. set the string to ""
// 2. use type _LCDML_TYPE_dynParam instead of _LCDML_TYPE_default
// this function type can not be used in combination with different parameters
// LCDMenuLib_addAdvanced(id, prev_layer, new_num, condition, lang_char_array, callback_function, parameter (0-255), menu function type )
LCDML_addAdvanced (21 , LCDML_0 , 6 , NULL, "" , mDyn_para, 0, _LCDML_TYPE_dynParam); // NULL = no menu function
// Example for conditions (for example for a screensaver)
// 1. define a condition as a function of a boolean type -> return false = not displayed, return true = displayed
// 2. set the function name as callback (remove the braces '()' it gives bad errors)
// LCDMenuLib_addAdvanced(id, prev_layer, new_num, condition, lang_char_array, callback_function, parameter (0-255), menu function type )
LCDML_addAdvanced (22 , LCDML_0 , 7 , COND_hide, "screensaver" , mFunc_screensaver, 0, _LCDML_TYPE_default); // this menu function can be found on "LCDML_display_menuFunction" tab
// ***TIP*** Try to update _LCDML_DISP_cnt when you add a menu element.
// menu element count - last element id
// this value must be the same as the last menu element
#define _LCDML_DISP_cnt 22
// create menu
LCDML_createMenu(_LCDML_DISP_cnt);
// *********************************************************************
// SETUP
// *********************************************************************
void setup()
{
u8g2.begin();
// serial init; only be needed if serial control is used
Serial.begin(9600); // start serial
Serial.println(F(_LCDML_VERSION)); // only for examples
// LCDMenuLib Setup
LCDML_setup(_LCDML_DISP_cnt);
// Enable Menu Rollover
LCDML.MENU_enRollover();
// Enable Screensaver (screensaver menu function, time to activate in ms)
LCDML.SCREEN_enable(mFunc_screensaver, 60000); // set to 60 seconds
//LCDML.SCREEN_disable();
// Some needful methods
// You can jump to a menu function from anywhere with
//LCDML.OTHER_jumpToFunc(mFunc_p2); // the parameter is the function name
}
// *********************************************************************
// LOOP
// *********************************************************************
void loop()
{
// this function must called here, do not delete it
LCDML.loop();
}
// *********************************************************************
// check some errors - do not change here anything
// *********************************************************************
# if(_LCDML_glcd_tft_box_x1 > _LCDML_glcd_tft_w)
# error _LCDML_glcd_tft_box_x1 is to big
# endif
# if(_LCDML_glcd_tft_box_y1 > _LCDML_glcd_tft_h)
# error _LCDML_glcd_tft_box_y1 is to big
# endif
<commit_msg>v2.2.7<commit_after>// ============================================================
// Example: LCDML: graphic display with u8g
// ============================================================
// Author: Jomelo
// Last update: 21.01.2018
// License: MIT
// ============================================================
// Description:
// This example shows how to use the u8glib with the LCDMenuLib
// The menu can placed in a box that can be placed anywhere on
// the screen.
// ============================================================
// *********************************************************************
// special settings
// *********************************************************************
// enable this line when you are not usigng a standard arduino
// for example when your chip is an ESP or a STM or SAM or something else
//#define _LCDML_cfg_use_ram
// include libs
#include <LCDMenuLib2.h>
//extern char* g_LCDML_DISP_lang_lcdml_table[254]; // uncomment if you have got problem with lib compile and undefined g_LCDML_DISP_lang_lcdml_table
// U8g2lib
#include <Arduino.h>
#include <U8g2lib.h>
#ifdef U8X8_HAVE_HW_SPI
#include <SPI.h>
#endif
#ifdef U8X8_HAVE_HW_I2C
#include <Wire.h>
#endif
// *********************************************************************
// U8GLIB
// *********************************************************************
// U8g2 Constructor List (Frame Buffer)
// The complete list is available here: https://github.com/olikraus/u8g2/wiki/u8g2setupcpp
// Please update the pin numbers according to your setup. Use U8X8_PIN_NONE if the reset pin is not connected
//U8G2_ST7920_128X64_F_HW_SPI u8g2(U8G2_R0, /* CS=*/ 53, /* reset=*/ U8X8_PIN_NONE); // (MEGA, ...
//U8G2_ST7920_128X64_F_HW_SPI u8g2(U8G2_R0, /* CS=*/ 12, /* reset=*/ U8X8_PIN_NONE); // (Uno and co
U8G2_ST7920_128X64_F_SW_SPI u8g2(U8G2_R0, /* clock=*/ 25, /* data= /R/w */ 33, /* CS=*/ 32, /* reset= */ U8X8_PIN_NONE ); // ESP32
// settings for u8g lib and LCD
#define _LCDML_DISP_w 128 // LCD width
#define _LCDML_DISP_h 64 // LCD height
// font settings
#define _LCDML_DISP_font u8g2_font_squeezed_r7_tr // u8g_font_6x13 // u8glib font (more fonts under u8g.h line 1520 ...)
#define _LCDML_DISP_font_w 7 // font width
#define _LCDML_DISP_font_h 8 // font height
// cursor settings
#define _LCDML_DISP_cursor_char ">" // cursor char
#define _LCDML_DISP_cur_space_before 2 // cursor space between
#define _LCDML_DISP_cur_space_behind 4 // cursor space between
// menu position and size
#define _LCDML_DISP_box_x0 0 // start point (x0, y0)
#define _LCDML_DISP_box_y0 0 // start point (x0, y0)
#define _LCDML_DISP_box_x1 128 // width x (x0 + width)
#define _LCDML_DISP_box_y1 64 // hight y (y0 + height)
#define _LCDML_DISP_draw_frame 1 // draw a box around the menu
// scrollbar width
#define _LCDML_DISP_scrollbar_w 6 // scrollbar width (if this value is < 3, the scrollbar is disabled)
// nothing change here
#define _LCDML_DISP_cols_max ((_LCDML_DISP_box_x1-_LCDML_DISP_box_x0)/_LCDML_DISP_font_w)
#define _LCDML_DISP_rows_max ((_LCDML_DISP_box_y1-_LCDML_DISP_box_y0-((_LCDML_DISP_box_y1-_LCDML_DISP_box_y0)/_LCDML_DISP_font_h))/_LCDML_DISP_font_h)
// rows and cols
// when you use more rows or cols as allowed change in LCDMenuLib.h the define "_LCDML_DISP_cfg_max_rows" and "_LCDML_DISP_cfg_max_string_length"
// the program needs more ram with this changes
#define _LCDML_DISP_rows _LCDML_DISP_rows_max // max rows
#define _LCDML_DISP_cols 20 // max cols
// *********************************************************************
// Prototypes
// *********************************************************************
void lcdml_menu_display();
void lcdml_menu_clear();
void lcdml_menu_control();
// *********************************************************************
// Objects
// *********************************************************************
LCDMenuLib2_menu LCDML_0 (255, 0, 0, NULL, NULL); // root menu element (do not change)
LCDMenuLib2 LCDML(LCDML_0, _LCDML_DISP_rows, _LCDML_DISP_cols, lcdml_menu_display, lcdml_menu_clear, lcdml_menu_control);
// Modification for PlatformIO and similar platforms
#include <LCDML_display_dynFunction.h>
#include <LCDML_display_menu.h>
#include <LCDML_condition.h>
#include <LCDML_display_menuFunction.h>
#include <LCDML_control.h>
// *********************************************************************
// LCDML MENU/DISP
// *********************************************************************
// LCDML_0 => layer 0
// LCDML_0_X => layer 1
// LCDML_0_X_X => layer 2
// LCDML_0_X_X_X => layer 3
// LCDML_0_... => layer ...
// For beginners
// LCDML_add(id, prev_layer, new_num, lang_char_array, callback_function)
LCDML_add (0 , LCDML_0 , 1 , "Information" , mFunc_information); // this menu function can be found on "LCDML_display_menuFunction" tab
LCDML_add (1 , LCDML_0 , 2 , "Time info" , mFunc_timer_info); // this menu function can be found on "LCDML_display_menuFunction" tab
LCDML_add (2 , LCDML_0 , 3 , "Program" , NULL); // NULL = no menu function
LCDML_add (3 , LCDML_0_3 , 1 , "Program 1" , NULL); // NULL = no menu function
LCDML_add (4 , LCDML_0_3_1 , 1 , "P1 dummy" , NULL); // NULL = no menu function
LCDML_add (5 , LCDML_0_3_1 , 2 , "P1 Settings" , NULL); // NULL = no menu function
LCDML_add (6 , LCDML_0_3_1_2 , 1 , "Warm" , NULL); // NULL = no menu function
LCDML_add (7 , LCDML_0_3_1_2 , 2 , "Cold" , NULL); // NULL = no menu function
LCDML_add (8 , LCDML_0_3_1_2 , 3 , "Back" , mFunc_back); // this menu function can be found on "LCDML_display_menuFunction" tab
LCDML_add (9 , LCDML_0_3_1 , 3 , "Back" , mFunc_back); // this menu function can be found on "LCDML_display_menuFunction" tab
LCDML_add (10 , LCDML_0_3 , 2 , "Program 2" , mFunc_p2); // this menu function can be found on "LCDML_display_menuFunction" tab
LCDML_add (11 , LCDML_0_3 , 3 , "Back" , mFunc_back); // this menu function can be found on "LCDML_display_menuFunction" tab
LCDML_add (12 , LCDML_0 , 4 , "Special" , NULL); // NULL = no menu function
LCDML_add (13 , LCDML_0_4 , 1 , "Go to Root" , mFunc_goToRootMenu); // this menu function can be found on "LCDML_display_menuFunction" tab
LCDML_add (14 , LCDML_0_4 , 2 , "Jump to Time info", mFunc_jumpTo_timer_info); // this menu function can be found on "LCDML_display_menuFunction" tab
LCDML_add (15 , LCDML_0_4 , 3 , "Back" , mFunc_back); // this menu function can be found on "LCDML_display_menuFunction" tab
// Advanced menu (for profit) part with more settings
// Example for one function and different parameters
// It is recommend to use parameters for switching settings like, (small drink, medium drink, big drink) or (200ml, 400ml, 600ml, 800ml) ...
// the parameter change can also be released with dynParams on the next example
// LCDMenuLib_addAdvanced(id, prev_layer, new_num, condition, lang_char_array, callback_function, parameter (0-255), menu function type )
LCDML_addAdvanced (16 , LCDML_0 , 5 , NULL, "Parameter" , NULL, 0, _LCDML_TYPE_default); // NULL = no menu function
LCDML_addAdvanced (17 , LCDML_0_5 , 1 , NULL, "Parameter 1" , mFunc_para, 10, _LCDML_TYPE_default); // NULL = no menu function
LCDML_addAdvanced (18 , LCDML_0_5 , 2 , NULL, "Parameter 2" , mFunc_para, 20, _LCDML_TYPE_default); // NULL = no menu function
LCDML_addAdvanced (19 , LCDML_0_5 , 3 , NULL, "Parameter 3" , mFunc_para, 30, _LCDML_TYPE_default); // NULL = no menu function
LCDML_add (20 , LCDML_0_5 , 4 , "Back" , mFunc_back); // this menu function can be found on "LCDML_display_menuFunction" tab
// Example for dynamic content
// 1. set the string to ""
// 2. use type _LCDML_TYPE_dynParam instead of _LCDML_TYPE_default
// this function type can not be used in combination with different parameters
// LCDMenuLib_addAdvanced(id, prev_layer, new_num, condition, lang_char_array, callback_function, parameter (0-255), menu function type )
LCDML_addAdvanced (21 , LCDML_0 , 6 , NULL, "" , mDyn_para, 0, _LCDML_TYPE_dynParam); // NULL = no menu function
// Example for conditions (for example for a screensaver)
// 1. define a condition as a function of a boolean type -> return false = not displayed, return true = displayed
// 2. set the function name as callback (remove the braces '()' it gives bad errors)
// LCDMenuLib_addAdvanced(id, prev_layer, new_num, condition, lang_char_array, callback_function, parameter (0-255), menu function type )
LCDML_addAdvanced (22 , LCDML_0 , 7 , COND_hide, "screensaver" , mFunc_screensaver, 0, _LCDML_TYPE_default); // this menu function can be found on "LCDML_display_menuFunction" tab
// ***TIP*** Try to update _LCDML_DISP_cnt when you add a menu element.
// menu element count - last element id
// this value must be the same as the last menu element
#define _LCDML_DISP_cnt 22
// create menu
LCDML_createMenu(_LCDML_DISP_cnt);
// *********************************************************************
// SETUP
// *********************************************************************
void setup()
{
u8g2.begin();
// serial init; only be needed if serial control is used
Serial.begin(9600); // start serial
Serial.println(F(_LCDML_VERSION)); // only for examples
// LCDMenuLib Setup
LCDML_setup(_LCDML_DISP_cnt);
// Enable Menu Rollover
LCDML.MENU_enRollover();
// Enable Screensaver (screensaver menu function, time to activate in ms)
LCDML.SCREEN_enable(mFunc_screensaver, 60000); // set to 60 seconds
//LCDML.SCREEN_disable();
// Some needful methods
// You can jump to a menu function from anywhere with
//LCDML.OTHER_jumpToFunc(mFunc_p2); // the parameter is the function name
}
// *********************************************************************
// LOOP
// *********************************************************************
void loop()
{
// this function must called here, do not delete it
LCDML.loop();
}
// *********************************************************************
// check some errors - do not change here anything
// *********************************************************************
# if(_LCDML_glcd_tft_box_x1 > _LCDML_glcd_tft_w)
# error _LCDML_glcd_tft_box_x1 is to big
# endif
# if(_LCDML_glcd_tft_box_y1 > _LCDML_glcd_tft_h)
# error _LCDML_glcd_tft_box_y1 is to big
# endif<|endoftext|>
|
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "QmitkOtsuAction.h"
// MITK
#include <itkOtsuMultipleThresholdsImageFilter.h>
#include <mitkRenderingManager.h>
#include <mitkImage.h>
#include <mitkImageCast.h>
#include <mitkITKImageImport.h>
#include <mitkLevelWindowProperty.h>
// ITK
#include <itkMultiplyImageFilter.h>
// Qt
#include <QDialog>
#include <QVBoxLayout>
#include <QApplication>
#include <QList>
#include <QLabel>
#include <QMessageBox>
using namespace berry;
using namespace mitk;
using namespace std;
QmitkOtsuAction::QmitkOtsuAction()
: m_OtsuSegmentationDialog(NULL)
{
}
QmitkOtsuAction::~QmitkOtsuAction()
{
}
void QmitkOtsuAction::Run(const QList<DataNode::Pointer> &selectedNodes)
{
this->m_DataNode = selectedNodes[0];
//this->m_selectedNodes = selectedNodes;
m_OtsuSegmentationDialog = new QDialog(QApplication::activeWindow());
QVBoxLayout *layout = new QVBoxLayout;
layout->setContentsMargins(0, 0, 0, 0);
m_OtsuSpinBox = new QSpinBox;
m_OtsuSpinBox->setRange(2, 32);
m_OtsuSpinBox->setValue(2);
m_OtsuPushButton = new QPushButton("OK");
connect(m_OtsuPushButton, SIGNAL(clicked()), this, SLOT(OtsuSegmentationDone()));
QLabel* numberOfThresholdsLabel = new QLabel("Select number of Regions of Interest:");
//numberOfThresholdsLabel->setAlignment(Qt::AlignmentFlag::AlignHCenter);
//numberOfThresholdsLabel->setAlignment(Qt::AlignmentFlag::AlignVCenter);
numberOfThresholdsLabel->setAlignment(Qt::AlignVCenter | Qt::AlignHCenter);
layout->addWidget(numberOfThresholdsLabel);
layout->addWidget(m_OtsuSpinBox);
layout->addWidget(m_OtsuPushButton);
m_OtsuSegmentationDialog->setLayout(layout);
m_OtsuSegmentationDialog->setFixedSize(300, 80);
m_OtsuSegmentationDialog->open();
}
void QmitkOtsuAction::OtsuSegmentationDone()
{
/*
if (result == QDialog::Rejected)
m_ThresholdingToolManager->ActivateTool(-1);*/
this->PerformOtsuSegmentation();
m_OtsuSegmentationDialog->deleteLater();
m_OtsuSegmentationDialog = NULL;
//m_ThresholdingToolManager->SetReferenceData(NULL);
//m_ThresholdingToolManager->SetWorkingData(NULL);
RenderingManager::GetInstance()->RequestUpdateAll();
}
void QmitkOtsuAction::SetDataStorage(DataStorage *dataStorage)
{
m_DataStorage = dataStorage;
}
void QmitkOtsuAction::SetFunctionality(QtViewPart* /*functionality*/)
{
}
void QmitkOtsuAction::PerformOtsuSegmentation()
{
int numberOfThresholds = this->m_OtsuSpinBox->value() - 1;
int proceed;
QMessageBox* messageBox = new QMessageBox(QMessageBox::Question, NULL, "The otsu segmentation computation may take several minutes depending on the number of Regions you selected. Proceed anyway?", QMessageBox::Ok | QMessageBox::Cancel);
if (numberOfThresholds >= 5)
{
proceed = messageBox->exec();
if (proceed != QMessageBox::Ok) return;
}
mitk::Image::Pointer mitkImage = 0;
mitkImage = dynamic_cast<mitk::Image*>( this->m_DataNode->GetData() );
try
{
// get selected mitk image
const unsigned short dim = 3;
typedef short InputPixelType;
typedef unsigned char OutputPixelType;
typedef itk::Image< InputPixelType, dim > InputImageType;
typedef itk::Image< OutputPixelType, dim > OutputImageType;
//typedef itk::OtsuThresholdImageFilter< InputImageType, OutputImageType > FilterType;
typedef itk::OtsuMultipleThresholdsImageFilter< InputImageType, OutputImageType > FilterType;
//typedef itk::MultiplyImageFilter< OutputImageType, OutputImageType, OutputImageType> MultiplyFilterType;
//typedef itk::RandomImageSource< OutputImageType> RandomImageSourceType;
//typedef itk::ImageRegionIterator< OutputImageType > ImageIteratorType;
FilterType::Pointer filter = FilterType::New();
//MultiplyFilterType::Pointer multiplyImageFilter = MultiplyFilterType::New();
//RandomImageSourceType::Pointer randomImageSource = RandomImageSourceType::New();
filter->SetNumberOfThresholds(numberOfThresholds);
//filter->SetLabelOffset(0);
/*
filter->SetOutsideValue( 1 );
filter->SetInsideValue( 0 );*/
InputImageType::Pointer itkImage;
mitk::CastToItkImage(mitkImage, itkImage);
filter->SetInput( itkImage );
// filter->UpdateOutputInformation();
//multiplyImageFilter->SetInput1(filter->GetOutput());
//OutputImageType::Pointer constantImage = OutputImageType::New();
//constantImage->SetLargestPossibleRegion(filter->GetOutput()->GetLargestPossibleRegion());
//constantImage->SetBufferedRegion(filter->GetOutput()->GetLargestPossibleRegion());
//constantImage->Allocate();
//ImageIteratorType it(constantImage, constantImage->GetLargestPossibleRegion());
//while (!it.IsAtEnd())
//{
// it.Set(1);
// ++it;
//}
////randomImageSource->SetSize(filter->GetOutput()->GetLargestPossibleRegion().GetSize());
////multiplyImageFilter->SetInput2(randomImageSource->GetOutput());
//multiplyImageFilter->SetInput2(constantImage);
filter->Update();
//multiplyImageFilter->Update();
mitk::DataNode::Pointer resultNode = mitk::DataNode::New();
std::string nameOfResultImage = this->m_DataNode->GetName();
nameOfResultImage.append("Otsu");
resultNode->SetProperty("name", mitk::StringProperty::New(nameOfResultImage) );
resultNode->SetProperty("binary", mitk::BoolProperty::New(false) );
resultNode->SetProperty("use color", mitk::BoolProperty::New(false) );
mitk::LevelWindowProperty::Pointer levWinProp = mitk::LevelWindowProperty::New();
mitk::LevelWindow levelwindow;
levelwindow.SetRangeMinMax(0, numberOfThresholds);
levWinProp->SetLevelWindow( levelwindow );
resultNode->SetProperty( "levelwindow", levWinProp );
//resultNode->SetData( mitk::ImportItkImage ( filter->GetOutput() ) );
resultNode->SetData( mitk::ImportItkImage ( filter->GetOutput() ) );
this->m_DataStorage->Add(resultNode, this->m_DataNode);
}
catch( std::exception& err )
{
MITK_ERROR(this->GetClassName()) << err.what();
}
}<commit_msg>COMP: added a cancel button to the Otsu Segmentation Dialog.<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "QmitkOtsuAction.h"
// MITK
#include <itkOtsuMultipleThresholdsImageFilter.h>
#include <mitkRenderingManager.h>
#include <mitkImage.h>
#include <mitkImageCast.h>
#include <mitkITKImageImport.h>
#include <mitkLevelWindowProperty.h>
// ITK
#include <itkMultiplyImageFilter.h>
// Qt
#include <QDialog>
#include <QVBoxLayout>
#include <QApplication>
#include <QList>
#include <QLabel>
#include <QMessageBox>
using namespace berry;
using namespace mitk;
using namespace std;
QmitkOtsuAction::QmitkOtsuAction()
: m_OtsuSegmentationDialog(NULL)
{
}
QmitkOtsuAction::~QmitkOtsuAction()
{
}
void QmitkOtsuAction::Run(const QList<DataNode::Pointer> &selectedNodes)
{
this->m_DataNode = selectedNodes[0];
//this->m_selectedNodes = selectedNodes;
m_OtsuSegmentationDialog = new QDialog(QApplication::activeWindow());
QVBoxLayout *layout = new QVBoxLayout;
layout->setContentsMargins(0, 0, 0, 0);
QHBoxLayout* spinBoxLayout = new QHBoxLayout;
QHBoxLayout* buttonLayout = new QHBoxLayout;
m_OtsuSpinBox = new QSpinBox;
m_OtsuSpinBox->setRange(2, 32);
m_OtsuSpinBox->setValue(2);
m_OtsuPushButton = new QPushButton("OK");
QPushButton* CancelButton = new QPushButton("Cancel");
connect(m_OtsuPushButton, SIGNAL(clicked()), this, SLOT(OtsuSegmentationDone()));
connect(CancelButton, SIGNAL(clicked()), m_OtsuSegmentationDialog, SLOT(reject()));
QLabel* numberOfThresholdsLabel = new QLabel("Select number of Regions of Interest:");
numberOfThresholdsLabel->setAlignment(Qt::AlignVCenter | Qt::AlignHCenter);
layout->addWidget(numberOfThresholdsLabel);
layout->addLayout(spinBoxLayout);
spinBoxLayout->addSpacing(50);
spinBoxLayout->addWidget(m_OtsuSpinBox);
spinBoxLayout->addSpacing(50);
layout->addLayout(buttonLayout);
buttonLayout->addWidget(m_OtsuPushButton);
buttonLayout->addWidget(CancelButton);
m_OtsuSegmentationDialog->setLayout(layout);
m_OtsuSegmentationDialog->setFixedSize(300, 80);
m_OtsuSegmentationDialog->open();
}
void QmitkOtsuAction::OtsuSegmentationDone()
{
/*
if (result == QDialog::Rejected)
m_ThresholdingToolManager->ActivateTool(-1);*/
this->PerformOtsuSegmentation();
m_OtsuSegmentationDialog->deleteLater();
m_OtsuSegmentationDialog = NULL;
//m_ThresholdingToolManager->SetReferenceData(NULL);
//m_ThresholdingToolManager->SetWorkingData(NULL);
RenderingManager::GetInstance()->RequestUpdateAll();
}
void QmitkOtsuAction::SetDataStorage(DataStorage *dataStorage)
{
m_DataStorage = dataStorage;
}
void QmitkOtsuAction::SetFunctionality(QtViewPart* /*functionality*/)
{
}
void QmitkOtsuAction::PerformOtsuSegmentation()
{
int numberOfThresholds = this->m_OtsuSpinBox->value() - 1;
int proceed;
QMessageBox* messageBox = new QMessageBox(QMessageBox::Question, NULL, "The otsu segmentation computation may take several minutes depending on the number of Regions you selected. Proceed anyway?", QMessageBox::Ok | QMessageBox::Cancel);
if (numberOfThresholds >= 5)
{
proceed = messageBox->exec();
if (proceed != QMessageBox::Ok) return;
}
mitk::Image::Pointer mitkImage = 0;
mitkImage = dynamic_cast<mitk::Image*>( this->m_DataNode->GetData() );
try
{
// get selected mitk image
const unsigned short dim = 3;
typedef short InputPixelType;
typedef unsigned char OutputPixelType;
typedef itk::Image< InputPixelType, dim > InputImageType;
typedef itk::Image< OutputPixelType, dim > OutputImageType;
//typedef itk::OtsuThresholdImageFilter< InputImageType, OutputImageType > FilterType;
typedef itk::OtsuMultipleThresholdsImageFilter< InputImageType, OutputImageType > FilterType;
//typedef itk::MultiplyImageFilter< OutputImageType, OutputImageType, OutputImageType> MultiplyFilterType;
//typedef itk::RandomImageSource< OutputImageType> RandomImageSourceType;
//typedef itk::ImageRegionIterator< OutputImageType > ImageIteratorType;
FilterType::Pointer filter = FilterType::New();
//MultiplyFilterType::Pointer multiplyImageFilter = MultiplyFilterType::New();
//RandomImageSourceType::Pointer randomImageSource = RandomImageSourceType::New();
filter->SetNumberOfThresholds(numberOfThresholds);
//filter->SetLabelOffset(0);
/*
filter->SetOutsideValue( 1 );
filter->SetInsideValue( 0 );*/
InputImageType::Pointer itkImage;
mitk::CastToItkImage(mitkImage, itkImage);
filter->SetInput( itkImage );
// filter->UpdateOutputInformation();
//multiplyImageFilter->SetInput1(filter->GetOutput());
//OutputImageType::Pointer constantImage = OutputImageType::New();
//constantImage->SetLargestPossibleRegion(filter->GetOutput()->GetLargestPossibleRegion());
//constantImage->SetBufferedRegion(filter->GetOutput()->GetLargestPossibleRegion());
//constantImage->Allocate();
//ImageIteratorType it(constantImage, constantImage->GetLargestPossibleRegion());
//while (!it.IsAtEnd())
//{
// it.Set(1);
// ++it;
//}
////randomImageSource->SetSize(filter->GetOutput()->GetLargestPossibleRegion().GetSize());
////multiplyImageFilter->SetInput2(randomImageSource->GetOutput());
//multiplyImageFilter->SetInput2(constantImage);
filter->Update();
//multiplyImageFilter->Update();
mitk::DataNode::Pointer resultNode = mitk::DataNode::New();
std::string nameOfResultImage = this->m_DataNode->GetName();
nameOfResultImage.append("Otsu");
resultNode->SetProperty("name", mitk::StringProperty::New(nameOfResultImage) );
resultNode->SetProperty("binary", mitk::BoolProperty::New(false) );
resultNode->SetProperty("use color", mitk::BoolProperty::New(false) );
mitk::LevelWindowProperty::Pointer levWinProp = mitk::LevelWindowProperty::New();
mitk::LevelWindow levelwindow;
levelwindow.SetRangeMinMax(0, numberOfThresholds);
levWinProp->SetLevelWindow( levelwindow );
resultNode->SetProperty( "levelwindow", levWinProp );
//resultNode->SetData( mitk::ImportItkImage ( filter->GetOutput() ) );
resultNode->SetData( mitk::ImportItkImage ( filter->GetOutput() ) );
this->m_DataStorage->Add(resultNode, this->m_DataNode);
}
catch( std::exception& err )
{
MITK_ERROR(this->GetClassName()) << err.what();
}
}<|endoftext|>
|
<commit_before>//===- PowerPCSubtarget.cpp - PPC Subtarget Information ---------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Nate Begeman and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the PPC specific subclass of TargetSubtarget.
//
//===----------------------------------------------------------------------===//
#include "PPCSubtarget.h"
#include "PPC.h"
#include "llvm/Module.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Target/SubtargetFeature.h"
#include "PPCGenSubtarget.inc"
using namespace llvm;
PPCTargetEnum llvm::PPCTarget = TargetDefault;
namespace llvm {
cl::opt<PPCTargetEnum, true>
PPCTargetArg(cl::desc("Force generation of code for a specific PPC target:"),
cl::values(
clEnumValN(TargetAIX, "aix", " Enable AIX codegen"),
clEnumValN(TargetDarwin,"darwin",
" Enable Darwin codegen"),
clEnumValEnd),
cl::location(PPCTarget), cl::init(TargetDefault));
}
/// Length of FeatureKV.
static const unsigned FeatureKVSize = sizeof(FeatureKV)
/ sizeof(SubtargetFeatureKV);
/// Length of SubTypeKV.
static const unsigned SubTypeKVSize = sizeof(SubTypeKV)
/ sizeof(SubtargetFeatureKV);
#if defined(__APPLE__)
#include <mach/mach.h>
#include <mach/mach_host.h>
#include <mach/host_info.h>
#include <mach/machine.h>
/// GetCurrentPowerPCFeatures - Returns the current CPUs features.
static const char *GetCurrentPowerPCCPU() {
host_basic_info_data_t hostInfo;
mach_msg_type_number_t infoCount;
infoCount = HOST_BASIC_INFO_COUNT;
host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo,
&infoCount);
if (hostInfo.cpu_type != CPU_TYPE_POWERPC) return "generic";
switch(hostInfo.cpu_subtype) {
case CPU_SUBTYPE_POWERPC_601: return "601";
case CPU_SUBTYPE_POWERPC_602: return "602";
case CPU_SUBTYPE_POWERPC_603: return "603";
case CPU_SUBTYPE_POWERPC_603e: return "603e";
case CPU_SUBTYPE_POWERPC_603ev: return "603ev";
case CPU_SUBTYPE_POWERPC_604: return "604";
case CPU_SUBTYPE_POWERPC_604e: return "604e";
case CPU_SUBTYPE_POWERPC_620: return "620";
case CPU_SUBTYPE_POWERPC_750: return "750";
case CPU_SUBTYPE_POWERPC_7400: return "7400";
case CPU_SUBTYPE_POWERPC_7450: return "7450";
case CPU_SUBTYPE_POWERPC_970: return "970";
default: ;
}
return "generic";
}
#endif
PPCSubtarget::PPCSubtarget(const Module &M, const std::string &FS)
: StackAlignment(16), IsGigaProcessor(false), IsAIX(false), IsDarwin(false) {
// Determine default and user specified characteristics
std::string CPU = "generic";
#if defined(__APPLE__)
CPU = GetCurrentPowerPCCPU();
#endif
uint32_t Bits =
SubtargetFeatures::Parse(FS, CPU,
SubTypeKV, SubTypeKVSize, FeatureKV, FeatureKVSize);
IsGigaProcessor = (Bits & FeatureGPUL ) != 0;
Is64Bit = (Bits & Feature64Bit) != 0;
HasFSQRT = (Bits & FeatureFSqrt) != 0;
Has64BitRegs = (Bits & Feature64BitRegs) != 0;
// Set the boolean corresponding to the current target triple, or the default
// if one cannot be determined, to true.
const std::string& TT = M.getTargetTriple();
if (TT.length() > 5) {
IsDarwin = TT.find("darwin") != std::string::npos;
} else if (TT.empty()) {
#if defined(_POWER)
IsAIX = true;
#elif defined(__APPLE__)
IsDarwin = true;
#endif
}
}
<commit_msg>Simplify this, matching changes in the tblgen emitter<commit_after>//===- PowerPCSubtarget.cpp - PPC Subtarget Information ---------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Nate Begeman and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the PPC specific subclass of TargetSubtarget.
//
//===----------------------------------------------------------------------===//
#include "PPCSubtarget.h"
#include "PPC.h"
#include "llvm/Module.h"
#include "llvm/Support/CommandLine.h"
#include "PPCGenSubtarget.inc"
using namespace llvm;
PPCTargetEnum llvm::PPCTarget = TargetDefault;
namespace llvm {
cl::opt<PPCTargetEnum, true>
PPCTargetArg(cl::desc("Force generation of code for a specific PPC target:"),
cl::values(
clEnumValN(TargetAIX, "aix", " Enable AIX codegen"),
clEnumValN(TargetDarwin,"darwin",
" Enable Darwin codegen"),
clEnumValEnd),
cl::location(PPCTarget), cl::init(TargetDefault));
}
#if defined(__APPLE__)
#include <mach/mach.h>
#include <mach/mach_host.h>
#include <mach/host_info.h>
#include <mach/machine.h>
/// GetCurrentPowerPCFeatures - Returns the current CPUs features.
static const char *GetCurrentPowerPCCPU() {
host_basic_info_data_t hostInfo;
mach_msg_type_number_t infoCount;
infoCount = HOST_BASIC_INFO_COUNT;
host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo,
&infoCount);
if (hostInfo.cpu_type != CPU_TYPE_POWERPC) return "generic";
switch(hostInfo.cpu_subtype) {
case CPU_SUBTYPE_POWERPC_601: return "601";
case CPU_SUBTYPE_POWERPC_602: return "602";
case CPU_SUBTYPE_POWERPC_603: return "603";
case CPU_SUBTYPE_POWERPC_603e: return "603e";
case CPU_SUBTYPE_POWERPC_603ev: return "603ev";
case CPU_SUBTYPE_POWERPC_604: return "604";
case CPU_SUBTYPE_POWERPC_604e: return "604e";
case CPU_SUBTYPE_POWERPC_620: return "620";
case CPU_SUBTYPE_POWERPC_750: return "750";
case CPU_SUBTYPE_POWERPC_7400: return "7400";
case CPU_SUBTYPE_POWERPC_7450: return "7450";
case CPU_SUBTYPE_POWERPC_970: return "970";
default: ;
}
return "generic";
}
#endif
PPCSubtarget::PPCSubtarget(const Module &M, const std::string &FS)
: StackAlignment(16), IsGigaProcessor(false), IsAIX(false), IsDarwin(false) {
// Determine default and user specified characteristics
std::string CPU = "generic";
#if defined(__APPLE__)
CPU = GetCurrentPowerPCCPU();
#endif
uint32_t Bits =
SubtargetFeatures::Parse(FS, CPU,
SubTypeKV, SubTypeKVSize, FeatureKV, FeatureKVSize);
IsGigaProcessor = (Bits & FeatureGPUL ) != 0;
Is64Bit = (Bits & Feature64Bit) != 0;
HasFSQRT = (Bits & FeatureFSqrt) != 0;
Has64BitRegs = (Bits & Feature64BitRegs) != 0;
// Set the boolean corresponding to the current target triple, or the default
// if one cannot be determined, to true.
const std::string& TT = M.getTargetTriple();
if (TT.length() > 5) {
IsDarwin = TT.find("darwin") != std::string::npos;
} else if (TT.empty()) {
#if defined(_POWER)
IsAIX = true;
#elif defined(__APPLE__)
IsDarwin = true;
#endif
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2011 James Peach
*
* 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 <ts/ts.h>
#include <stdlib.h>
#include <spdy/spdy.h>
#include <base/logging.h>
#include "io.h"
#include "protocol.h"
static int spdy_vconn_io(TSCont, TSEvent, void *);
static void
recv_rst_stream(
const spdy::message_header& header,
spdy_io_control * io,
const uint8_t __restrict * ptr)
{
spdy::rst_stream_message rst;
rst = spdy::rst_stream_message::parse(ptr, header.datalen);
debug_protocol("[%p/%u] received %s frame stream=%u status_code=%s (%u)",
io, rst.stream_id,
cstringof(header.control.type), rst.stream_id,
cstringof((spdy::error)rst.status_code), rst.status_code);
io->destroy_stream(rst.stream_id);
}
static void
recv_syn_stream(
const spdy::message_header& header,
spdy_io_control * io,
const uint8_t __restrict * ptr)
{
spdy::syn_stream_message syn;
spdy_io_stream * stream;
syn = spdy::syn_stream_message::parse(ptr, header.datalen);
debug_protocol(
"[%p/%u] received %s frame stream=%u associated=%u priority=%u",
io, syn.stream_id,
cstringof(header.control.type), syn.stream_id,
syn.associated_id, syn.priority);
if (!io->valid_client_stream_id(syn.stream_id)) {
debug_protocol("[%p/%u] invalid stream-id %u",
io, syn.stream_id, syn.stream_id);
spdy_send_reset_stream(io, syn.stream_id, spdy::PROTOCOL_ERROR);
return;
}
switch (header.control.version) {
case spdy::PROTOCOL_VERSION_2: // fallthru
case spdy::PROTOCOL_VERSION_3: break;
default:
debug_protocol("[%p/%u] bad protocol version %d",
io, syn.stream_id, header.control.version);
spdy_send_reset_stream(io, syn.stream_id, spdy::PROTOCOL_ERROR);
return;
}
spdy::key_value_block kvblock(
spdy::key_value_block::parse(
(spdy::protocol_version)header.control.version,
io->decompressor,
ptr + spdy::syn_stream_message::size,
header.datalen - spdy::syn_stream_message::size)
);
if (!kvblock.url().is_complete()) {
debug_protocol("[%p/%u] incomplete URL", io, syn.stream_id);
// XXX missing URL, protocol error
// 3.2.1 400 Bad Request
spdy_send_reset_stream(io, syn.stream_id, spdy::INVALID_STREAM);
// XXX send_http_txn_result()
return;
}
if ((stream = io->create_stream(syn.stream_id)) == 0) {
debug_protocol("[%p/%u] failed to create stream %u",
io, syn.stream_id, syn.stream_id);
spdy_send_reset_stream(io, syn.stream_id, spdy::INVALID_STREAM);
return;
}
stream->io = io;
stream->version = (spdy::protocol_version)header.control.version;
stream->open(kvblock);
}
static void
recv_ping(
const spdy::message_header& header,
spdy_io_control * io,
const uint8_t __restrict * ptr)
{
spdy::ping_message ping;
ping = spdy::ping_message::parse(ptr, header.datalen);
debug_protocol("[%p] received PING id=%u", io, ping.ping_id);
// Client must send even ping-ids. Ignore the odd ones since
// we never send them.
if ((ping.ping_id % 2) == 0) {
return;
}
spdy_send_ping(io, (spdy::protocol_version)header.control.version, ping.ping_id);
}
static void
dispatch_spdy_control_frame(
const spdy::message_header& header,
spdy_io_control * io,
const uint8_t __restrict * ptr)
{
switch (header.control.type) {
case spdy::CONTROL_SYN_STREAM:
recv_syn_stream(header, io, ptr);
break;
case spdy::CONTROL_SYN_REPLY:
case spdy::CONTROL_RST_STREAM:
recv_rst_stream(header, io, ptr);
break;
case spdy::CONTROL_PING:
recv_ping(header, io, ptr);
break;
case spdy::CONTROL_SETTINGS:
case spdy::CONTROL_GOAWAY:
case spdy::CONTROL_HEADERS:
case spdy::CONTROL_WINDOW_UPDATE:
debug_protocol(
"[%p] SPDY control frame, version=%u type=%s flags=0x%x, %u bytes",
io, header.control.version, cstringof(header.control.type),
header.flags, header.datalen);
break;
default:
// SPDY 2.2.1 - MUST ignore unrecognized control frames
TSError("[spdy] ignoring invalid control frame type %u", header.control.type);
}
io->reenable();
}
static void
consume_spdy_frame(spdy_io_control * io)
{
spdy::message_header header;
TSIOBufferBlock blk;
const uint8_t * ptr;
int64_t nbytes;
next_frame:
blk = TSIOBufferStart(io->input.buffer);
ptr = (const uint8_t *)TSIOBufferBlockReadStart(blk, io->input.reader, &nbytes);
TSReleaseAssert(nbytes >= spdy::message_header::size);
header = spdy::message_header::parse(ptr, (size_t)nbytes);
TSAssert(header.datalen > 0); // XXX
if (header.is_control) {
if (header.control.version != spdy::PROTOCOL_VERSION) {
TSError("[spdy] client is version %u, but we implement version %u",
header.control.version, spdy::PROTOCOL_VERSION);
}
} else {
debug_protocol("[%p] SPDY data frame, stream=%u flags=0x%x, %zu bytes",
io, header.data.stream_id, header.flags, header.datalen);
}
if (header.datalen >= spdy::MAX_FRAME_LENGTH) {
// XXX puke
}
if (header.datalen <= (nbytes - spdy::message_header::size)) {
// We have all the data in-hand ... parse it.
io->input.consume(spdy::message_header::size);
io->input.consume(header.datalen);
ptr += spdy::message_header::size;
if (header.is_control) {
dispatch_spdy_control_frame(header, io, ptr);
} else {
TSError("[spdy] no data frame support yet");
}
if (TSIOBufferReaderAvail(io->input.reader) >= spdy::message_header::size) {
goto next_frame;
}
}
// Push the high water mark to the end of the frame so that we don't get
// called back until we have the whole thing.
io->input.watermark(spdy::message_header::size + header.datalen);
}
static int
spdy_vconn_io(TSCont contp, TSEvent ev, void * edata)
{
TSVIO vio = (TSVIO)edata;
int nbytes;
spdy_io_control * io;
(void)vio;
// Experimentally, we recieve the read or write TSVIO pointer as the
// callback data.
//debug_plugin("received IO event %s, VIO=%p", cstringof(ev), vio);
switch (ev) {
case TS_EVENT_VCONN_READ_READY:
case TS_EVENT_VCONN_READ_COMPLETE:
io = spdy_io_control::get(contp);
nbytes = TSIOBufferReaderAvail(io->input.reader);
debug_plugin("received %d bytes", nbytes);
if ((unsigned)nbytes >= spdy::message_header::size) {
consume_spdy_frame(io);
}
// XXX frame parsing can throw. If it does, best to catch it, log it
// and drop the connection.
break;
case TS_EVENT_VCONN_WRITE_READY:
case TS_EVENT_VCONN_WRITE_COMPLETE:
// No need to handle write events. We have already pushed all the data
// we have into the write buffer.
break;
case TS_EVENT_VCONN_EOS: // fallthru
default:
if (ev != TS_EVENT_VCONN_EOS) {
debug_plugin("unexpected accept event %s", cstringof(ev));
}
io = spdy_io_control::get(contp);
TSVConnClose(io->vconn);
release(io);
}
return TS_EVENT_NONE;
}
static int
spdy_accept_io(TSCont contp, TSEvent ev, void * edata)
{
TSVConn vconn = (TSVConn)edata;;
spdy_io_control * io = nullptr;
TSVIO read_vio, write_vio;
switch (ev) {
case TS_EVENT_NET_ACCEPT:
io = retain(new spdy_io_control(vconn));
io->input.watermark(spdy::message_header::size);
io->output.watermark(spdy::message_header::size);
// XXX is contp leaked here?
contp = TSContCreate(spdy_vconn_io, TSMutexCreate());
TSContDataSet(contp, io);
read_vio = TSVConnRead(vconn, contp, io->input.buffer, INT64_MAX);
write_vio = TSVConnWrite(vconn, contp, io->output.reader, INT64_MAX);
debug_protocol("accepted new SPDY session %p", io);
break;
default:
debug_plugin("unexpected accept event %s", cstringof(ev));
}
return TS_EVENT_NONE;
}
static void
spdy_initialize(uint16_t port)
{
TSCont contp;
TSAction action;
contp = TSContCreate(spdy_accept_io, TSMutexCreate());
action = TSNetAccept(contp, port, -1 /* domain */, 1 /* accept threads */);
if (TSActionDone(action)) {
debug_plugin("accept action done?");
}
}
void
TSPluginInit(int argc, const char *argv[])
{
int port;
TSPluginRegistrationInfo info;
info.plugin_name = (char *)"spdy";
info.vendor_name = (char *)"James Peach";
info.support_email = (char *)"jamespeach@me.com";
if (TSPluginRegister(TS_SDK_VERSION_3_0, &info) != TS_SUCCESS) {
TSError("[%s] Plugin registration failed", __func__);
}
debug_plugin("initializing");
if (argc != 2) {
TSError("[%s] Usage: spdy.so PORT", __func__);
return;
}
port = atoi(argv[1]);
if (port <= 1 || port > UINT16_MAX) {
TSError("[%s] invalid port number: %s", __func__, argv[1]);
return;
}
spdy_initialize((uint16_t)port);
}
/* vim: set sw=4 tw=79 ts=4 et ai : */
<commit_msg>Switch to TSIOBufferReaderStart<commit_after>/*
* Copyright (c) 2011 James Peach
*
* 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 <ts/ts.h>
#include <stdlib.h>
#include <spdy/spdy.h>
#include <base/logging.h>
#include "io.h"
#include "protocol.h"
static int spdy_vconn_io(TSCont, TSEvent, void *);
static void
recv_rst_stream(
const spdy::message_header& header,
spdy_io_control * io,
const uint8_t __restrict * ptr)
{
spdy::rst_stream_message rst;
rst = spdy::rst_stream_message::parse(ptr, header.datalen);
debug_protocol("[%p/%u] received %s frame stream=%u status_code=%s (%u)",
io, rst.stream_id,
cstringof(header.control.type), rst.stream_id,
cstringof((spdy::error)rst.status_code), rst.status_code);
io->destroy_stream(rst.stream_id);
}
static void
recv_syn_stream(
const spdy::message_header& header,
spdy_io_control * io,
const uint8_t __restrict * ptr)
{
spdy::syn_stream_message syn;
spdy_io_stream * stream;
syn = spdy::syn_stream_message::parse(ptr, header.datalen);
debug_protocol(
"[%p/%u] received %s frame stream=%u associated=%u priority=%u",
io, syn.stream_id,
cstringof(header.control.type), syn.stream_id,
syn.associated_id, syn.priority);
if (!io->valid_client_stream_id(syn.stream_id)) {
debug_protocol("[%p/%u] invalid stream-id %u",
io, syn.stream_id, syn.stream_id);
spdy_send_reset_stream(io, syn.stream_id, spdy::PROTOCOL_ERROR);
return;
}
switch (header.control.version) {
case spdy::PROTOCOL_VERSION_2: // fallthru
case spdy::PROTOCOL_VERSION_3: break;
default:
debug_protocol("[%p/%u] bad protocol version %d",
io, syn.stream_id, header.control.version);
spdy_send_reset_stream(io, syn.stream_id, spdy::PROTOCOL_ERROR);
return;
}
spdy::key_value_block kvblock(
spdy::key_value_block::parse(
(spdy::protocol_version)header.control.version,
io->decompressor,
ptr + spdy::syn_stream_message::size,
header.datalen - spdy::syn_stream_message::size)
);
if (!kvblock.url().is_complete()) {
debug_protocol("[%p/%u] incomplete URL", io, syn.stream_id);
// XXX missing URL, protocol error
// 3.2.1 400 Bad Request
spdy_send_reset_stream(io, syn.stream_id, spdy::INVALID_STREAM);
// XXX send_http_txn_result()
return;
}
if ((stream = io->create_stream(syn.stream_id)) == 0) {
debug_protocol("[%p/%u] failed to create stream %u",
io, syn.stream_id, syn.stream_id);
spdy_send_reset_stream(io, syn.stream_id, spdy::INVALID_STREAM);
return;
}
stream->io = io;
stream->version = (spdy::protocol_version)header.control.version;
stream->open(kvblock);
}
static void
recv_ping(
const spdy::message_header& header,
spdy_io_control * io,
const uint8_t __restrict * ptr)
{
spdy::ping_message ping;
ping = spdy::ping_message::parse(ptr, header.datalen);
debug_protocol("[%p] received PING id=%u", io, ping.ping_id);
// Client must send even ping-ids. Ignore the odd ones since
// we never send them.
if ((ping.ping_id % 2) == 0) {
return;
}
spdy_send_ping(io, (spdy::protocol_version)header.control.version, ping.ping_id);
}
static void
dispatch_spdy_control_frame(
const spdy::message_header& header,
spdy_io_control * io,
const uint8_t __restrict * ptr)
{
switch (header.control.type) {
case spdy::CONTROL_SYN_STREAM:
recv_syn_stream(header, io, ptr);
break;
case spdy::CONTROL_SYN_REPLY:
case spdy::CONTROL_RST_STREAM:
recv_rst_stream(header, io, ptr);
break;
case spdy::CONTROL_PING:
recv_ping(header, io, ptr);
break;
case spdy::CONTROL_SETTINGS:
case spdy::CONTROL_GOAWAY:
case spdy::CONTROL_HEADERS:
case spdy::CONTROL_WINDOW_UPDATE:
debug_protocol(
"[%p] SPDY control frame, version=%u type=%s flags=0x%x, %u bytes",
io, header.control.version, cstringof(header.control.type),
header.flags, header.datalen);
break;
default:
// SPDY 2.2.1 - MUST ignore unrecognized control frames
TSError("[spdy] ignoring invalid control frame type %u", header.control.type);
}
io->reenable();
}
static size_t
count_bytes_available(
TSIOBuffer buffer,
TSIOBufferReader reader)
{
TSIOBufferBlock block;
size_t count = 0;
block = TSIOBufferStart(buffer);
while (block) {
const char * ptr;
int64_t nbytes;
ptr = TSIOBufferBlockReadStart(block, reader, &nbytes);
if (ptr && nbytes) {
count += nbytes;
}
block = TSIOBufferBlockNext(block);
}
return count;
}
static void
consume_spdy_frame(spdy_io_control * io)
{
spdy::message_header header;
TSIOBufferBlock blk;
const uint8_t * ptr;
int64_t nbytes;
next_frame:
blk = TSIOBufferReaderStart(io->input.reader);
ptr = (const uint8_t *)TSIOBufferBlockReadStart(blk, io->input.reader, &nbytes);
if (!ptr) {
// This should not fail because we only try to consume the header when
// there are enough bytes to read the header. Experimentally, however,
// it does fail. I wonder why.
TSError("TSIOBufferBlockReadStart failed unexpectedly");
return;
}
if (nbytes < spdy::message_header::size) {
// We should never get here, because we check for space before
// entering. Unfortunately this does happen :(
debug_plugin("short read %lld bytes, expected at least %u, real count %zu",
nbytes, spdy::message_header::size,
count_bytes_available(io->input.buffer, io->input.reader));
return;
}
header = spdy::message_header::parse(ptr, (size_t)nbytes);
TSAssert(header.datalen > 0); // XXX
if (header.is_control) {
if (header.control.version != spdy::PROTOCOL_VERSION) {
TSError("[spdy] client is version %u, but we implement version %u",
header.control.version, spdy::PROTOCOL_VERSION);
}
} else {
debug_protocol("[%p] SPDY data frame, stream=%u flags=0x%x, %zu bytes",
io, header.data.stream_id, header.flags, header.datalen);
}
if (header.datalen >= spdy::MAX_FRAME_LENGTH) {
// XXX puke
}
if (header.datalen <= (nbytes - spdy::message_header::size)) {
// We have all the data in-hand ... parse it.
io->input.consume(spdy::message_header::size);
io->input.consume(header.datalen);
ptr += spdy::message_header::size;
if (header.is_control) {
dispatch_spdy_control_frame(header, io, ptr);
} else {
TSError("[spdy] no data frame support yet");
}
if (TSIOBufferReaderAvail(io->input.reader) >= spdy::message_header::size) {
goto next_frame;
}
}
// Push the high water mark to the end of the frame so that we don't get
// called back until we have the whole thing.
io->input.watermark(spdy::message_header::size + header.datalen);
}
static int
spdy_vconn_io(TSCont contp, TSEvent ev, void * edata)
{
TSVIO vio = (TSVIO)edata;
int nbytes;
spdy_io_control * io;
(void)vio;
// Experimentally, we recieve the read or write TSVIO pointer as the
// callback data.
//debug_plugin("received IO event %s, VIO=%p", cstringof(ev), vio);
switch (ev) {
case TS_EVENT_VCONN_READ_READY:
case TS_EVENT_VCONN_READ_COMPLETE:
io = spdy_io_control::get(contp);
nbytes = TSIOBufferReaderAvail(io->input.reader);
debug_plugin("received %d bytes", nbytes);
if ((unsigned)nbytes >= spdy::message_header::size) {
consume_spdy_frame(io);
}
// XXX frame parsing can throw. If it does, best to catch it, log it
// and drop the connection.
break;
case TS_EVENT_VCONN_WRITE_READY:
case TS_EVENT_VCONN_WRITE_COMPLETE:
// No need to handle write events. We have already pushed all the data
// we have into the write buffer.
break;
case TS_EVENT_VCONN_EOS: // fallthru
default:
if (ev != TS_EVENT_VCONN_EOS) {
debug_plugin("unexpected accept event %s", cstringof(ev));
}
io = spdy_io_control::get(contp);
TSVConnClose(io->vconn);
release(io);
}
return TS_EVENT_NONE;
}
static int
spdy_accept_io(TSCont contp, TSEvent ev, void * edata)
{
TSVConn vconn = (TSVConn)edata;;
spdy_io_control * io = nullptr;
TSVIO read_vio, write_vio;
switch (ev) {
case TS_EVENT_NET_ACCEPT:
io = retain(new spdy_io_control(vconn));
io->input.watermark(spdy::message_header::size);
io->output.watermark(spdy::message_header::size);
// XXX is contp leaked here?
contp = TSContCreate(spdy_vconn_io, TSMutexCreate());
TSContDataSet(contp, io);
read_vio = TSVConnRead(vconn, contp, io->input.buffer, INT64_MAX);
write_vio = TSVConnWrite(vconn, contp, io->output.reader, INT64_MAX);
debug_protocol("accepted new SPDY session %p", io);
break;
default:
debug_plugin("unexpected accept event %s", cstringof(ev));
}
return TS_EVENT_NONE;
}
static void
spdy_initialize(uint16_t port)
{
TSCont contp;
TSAction action;
contp = TSContCreate(spdy_accept_io, TSMutexCreate());
action = TSNetAccept(contp, port, -1 /* domain */, 1 /* accept threads */);
if (TSActionDone(action)) {
debug_plugin("accept action done?");
}
}
void
TSPluginInit(int argc, const char *argv[])
{
int port;
TSPluginRegistrationInfo info;
info.plugin_name = (char *)"spdy";
info.vendor_name = (char *)"James Peach";
info.support_email = (char *)"jamespeach@me.com";
if (TSPluginRegister(TS_SDK_VERSION_3_0, &info) != TS_SUCCESS) {
TSError("[%s] Plugin registration failed", __func__);
}
debug_plugin("initializing");
if (argc != 2) {
TSError("[%s] Usage: spdy.so PORT", __func__);
return;
}
port = atoi(argv[1]);
if (port <= 1 || port > UINT16_MAX) {
TSError("[%s] invalid port number: %s", __func__, argv[1]);
return;
}
spdy_initialize((uint16_t)port);
}
/* vim: set sw=4 tw=79 ts=4 et ai : */
<|endoftext|>
|
<commit_before>#pragma once
#include <charconv>
#include <cstdint>
#include <optional>
#include <string>
namespace fly::detail {
/**
* Helper struct to convert a std::string to a plain-old-data type, e.g. int or float.
*
* Ideally, this entire helper can be removed when the STL supports floating point types with
* std::from_chars. However, only integral types are currently supported. Thus, integral types will
* use std::from_chars, and floating point types will use the std::stof family of functions.
*
* https://en.cppreference.com/w/cpp/compiler_support
*
* @author Timothy Flynn (trflynn89@pm.me)
* @version March 21, 2019
*/
template <typename T>
struct Converter
{
static std::optional<T> convert(const std::string &value)
{
const auto *begin = value.data();
const auto *end = begin + value.size();
T converted {};
auto result = std::from_chars(begin, end, converted);
if ((result.ptr != end) || (result.ec != std::errc()))
{
return std::nullopt;
}
return converted;
}
};
//==================================================================================================
template <>
struct Converter<float>
{
static std::optional<float> convert(const std::string &value)
{
std::size_t index = 0;
float result {};
try
{
result = std::stof(value, &index);
}
catch (...)
{
return std::nullopt;
}
if (index != value.length())
{
return std::nullopt;
}
return result;
}
};
//==================================================================================================
template <>
struct Converter<double>
{
static std::optional<double> convert(const std::string &value)
{
std::size_t index = 0;
double result {};
try
{
result = std::stod(value, &index);
}
catch (...)
{
return std::nullopt;
}
if (index != value.length())
{
return std::nullopt;
}
return result;
}
};
//==================================================================================================
template <>
struct Converter<long double>
{
static std::optional<long double> convert(const std::string &value)
{
std::size_t index = 0;
long double result {};
try
{
result = std::stold(value, &index);
}
catch (...)
{
return std::nullopt;
}
if (index != value.length())
{
return std::nullopt;
}
return result;
}
};
} // namespace fly::detail
<commit_msg>Use std::to_chars for converting floating-point values where available<commit_after>#pragma once
#include "fly/fly.hpp"
#include <charconv>
#include <cstdint>
#include <optional>
#include <string>
namespace fly::detail {
/**
* Helper struct to convert a std::string to a plain-old-data type, e.g. int or float.
*
* Ideally, this entire helper can be removed when the STL supports floating point types with
* std::from_chars. However, only integral types are currently supported. Thus, integral types will
* use std::from_chars, and floating point types will use the std::stof family of functions.
*
* https://en.cppreference.com/w/cpp/compiler_support
*
* @author Timothy Flynn (trflynn89@pm.me)
* @version March 21, 2019
*/
template <typename T>
struct Converter
{
static std::optional<T> convert(const std::string &value)
{
const char *begin = value.data();
const char *end = begin + value.size();
T converted {};
auto result = std::from_chars(begin, end, converted);
if ((result.ptr != end) || (result.ec != std::errc {}))
{
return std::nullopt;
}
return converted;
}
};
#if !defined(FLY_COMPILER_SUPPORTS_FP_CHARCONV)
//==================================================================================================
template <>
struct Converter<float>
{
static std::optional<float> convert(const std::string &value)
{
std::size_t index = 0;
float result {};
try
{
result = std::stof(value, &index);
}
catch (...)
{
return std::nullopt;
}
if (index != value.length())
{
return std::nullopt;
}
return result;
}
};
//==================================================================================================
template <>
struct Converter<double>
{
static std::optional<double> convert(const std::string &value)
{
std::size_t index = 0;
double result {};
try
{
result = std::stod(value, &index);
}
catch (...)
{
return std::nullopt;
}
if (index != value.length())
{
return std::nullopt;
}
return result;
}
};
//==================================================================================================
template <>
struct Converter<long double>
{
static std::optional<long double> convert(const std::string &value)
{
std::size_t index = 0;
long double result {};
try
{
result = std::stold(value, &index);
}
catch (...)
{
return std::nullopt;
}
if (index != value.length())
{
return std::nullopt;
}
return result;
}
};
#endif
} // namespace fly::detail
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: toolboxdocumenthandler.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: kz $ $Date: 2004-02-25 17:41: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 __FRAMEWORK_XML_TOOLBOXDOCUMENTHANDLER_HXX_
#define __FRAMEWORK_XML_TOOLBOXDOCUMENTHANDLER_HXX_
#ifndef __FRAMEWORK_XML_TOOLBOXCONFIGURATION_HXX_
#include <xml/toolboxconfiguration.hxx>
#endif
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#ifndef __COM_SUN_STAR_XML_SAX_XDOCUMENTHANDLER_HPP_
#include <com/sun/star/xml/sax/XDocumentHandler.hpp>
#endif
//_________________________________________________________________________________________________________________
// other includes
//_________________________________________________________________________________________________________________
#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif
#ifndef _RTL_USTRING_
#include <rtl/ustring.hxx>
#endif
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef __SGI_STL_HASH_MAP
#include <hash_map>
#endif
#ifndef __FRAMEWORK_STDTYPES_H_
#include <stdtypes.h>
#endif
//_________________________________________________________________________________________________________________
// namespace
//_________________________________________________________________________________________________________________
namespace framework{
//*****************************************************************************************************************
// Hash code function for using in all hash maps of follow implementation.
class OReadToolBoxDocumentHandler : public ::com::sun::star::xml::sax::XDocumentHandler,
private ThreadHelpBase, // Struct for right initalization of lock member! Must be first of baseclasses.
public ::cppu::OWeakObject
{
public:
enum ToolBox_XML_Entry
{
TB_ELEMENT_TOOLBAR,
TB_ELEMENT_TOOLBARITEM,
TB_ELEMENT_TOOLBARSPACE,
TB_ELEMENT_TOOLBARBREAK,
TB_ELEMENT_TOOLBARSEPARATOR,
TB_ATTRIBUTE_TEXT,
TB_ATTRIBUTE_BITMAP,
TB_ATTRIBUTE_URL,
TB_ATTRIBUTE_ITEMBITS,
TB_ATTRIBUTE_VISIBLE,
TB_ATTRIBUTE_WIDTH,
TB_ATTRIBUTE_USER,
TB_ATTRIBUTE_HELPID,
TB_ATTRIBUTE_STYLE,
TB_XML_ENTRY_COUNT
};
enum ToolBox_XML_Namespace
{
TB_NS_TOOLBAR,
TB_NS_XLINK,
TB_XML_NAMESPACES_COUNT
};
OReadToolBoxDocumentHandler( ToolBoxDescriptor& aToolBoxItems );
virtual ~OReadToolBoxDocumentHandler();
// XInterface
virtual void SAL_CALL acquire() throw()
{ OWeakObject::acquire(); }
virtual void SAL_CALL release() throw()
{ OWeakObject::release(); }
virtual ::com::sun::star::uno::Any SAL_CALL queryInterface(
const ::com::sun::star::uno::Type & rType ) throw( ::com::sun::star::uno::RuntimeException );
// XDocumentHandler
virtual void SAL_CALL startDocument(void)
throw ( ::com::sun::star::xml::sax::SAXException,
::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL endDocument(void)
throw( ::com::sun::star::xml::sax::SAXException,
::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL startElement(
const rtl::OUString& aName,
const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > &xAttribs)
throw( ::com::sun::star::xml::sax::SAXException,
::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL endElement(const rtl::OUString& aName)
throw( ::com::sun::star::xml::sax::SAXException,
::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL characters(const rtl::OUString& aChars)
throw( ::com::sun::star::xml::sax::SAXException,
::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL ignorableWhitespace(const rtl::OUString& aWhitespaces)
throw( ::com::sun::star::xml::sax::SAXException,
::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL processingInstruction(const rtl::OUString& aTarget,
const rtl::OUString& aData)
throw( ::com::sun::star::xml::sax::SAXException,
::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL setDocumentLocator(
const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XLocator > &xLocator)
throw( ::com::sun::star::xml::sax::SAXException,
::com::sun::star::uno::RuntimeException );
private:
::rtl::OUString getErrorLineString();
class ToolBoxHashMap : public ::std::hash_map< ::rtl::OUString ,
ToolBox_XML_Entry ,
OUStringHashCode ,
::std::equal_to< ::rtl::OUString > >
{
public:
inline void free()
{
ToolBoxHashMap().swap( *this );
}
};
sal_Bool m_bToolBarStartFound;
sal_Bool m_bToolBarEndFound;
sal_Bool m_bToolBarItemStartFound;
sal_Bool m_bToolBarSpaceStartFound;
sal_Bool m_bToolBarBreakStartFound;
sal_Bool m_bToolBarSeparatorStartFound;
ToolBoxHashMap m_aToolBoxMap;
ToolBoxDescriptor& m_aToolBoxItems;
::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XLocator > m_xLocator;
sal_Int32 m_nHashCode_Style_Radio;
sal_Int32 m_nHashCode_Style_Auto;
sal_Int32 m_nHashCode_Style_Left;
sal_Int32 m_nHashCode_Style_AutoSize;
sal_Int32 m_nHashCode_Style_DropDown;
sal_Int32 m_nHashCode_Style_Repeat;
};
class OWriteToolBoxDocumentHandler : private ThreadHelpBase // Struct for right initalization of lock member! Must be first of baseclasses.
{
public:
OWriteToolBoxDocumentHandler(
const ToolBoxDescriptor& aToolBoxItems,
::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XDocumentHandler > );
virtual ~OWriteToolBoxDocumentHandler();
void WriteToolBoxDocument() throw
( ::com::sun::star::xml::sax::SAXException,
::com::sun::star::uno::RuntimeException );
protected:
virtual void WriteToolBoxItem( const ToolBoxItemDescriptor* ) throw
( ::com::sun::star::xml::sax::SAXException,
::com::sun::star::uno::RuntimeException );
virtual void WriteToolBoxSpace() throw
( ::com::sun::star::xml::sax::SAXException,
::com::sun::star::uno::RuntimeException );
virtual void WriteToolBoxBreak() throw
( ::com::sun::star::xml::sax::SAXException,
::com::sun::star::uno::RuntimeException );
virtual void WriteToolBoxSeparator() throw
( ::com::sun::star::xml::sax::SAXException,
::com::sun::star::uno::RuntimeException );
const ToolBoxDescriptor& m_aToolBoxItems;
::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XDocumentHandler > m_xWriteDocumentHandler;
::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > m_xEmptyList;
::rtl::OUString m_aXMLToolbarNS;
::rtl::OUString m_aXMLXlinkNS;
::rtl::OUString m_aAttributeType;
::rtl::OUString m_aAttributeURL;
};
} // namespace framework
#endif
<commit_msg>INTEGRATION: CWS docking1 (1.2.4); FILE MERGED 2004/06/01 10:55:36 cd 1.2.4.3: #i10000# Fixed merge problems 2004/04/21 06:54:33 cd 1.2.4.2: #i24937# Additional property to load/store customized UI name for toolbars 2004/04/05 07:57:37 cd 1.2.4.1: #i26252# New internal structure to transport toolbar data<commit_after>/*************************************************************************
*
* $RCSfile: toolboxdocumenthandler.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: obo $ $Date: 2004-07-06 16:55:36 $
*
* 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 __FRAMEWORK_XML_TOOLBOXDOCUMENTHANDLER_HXX_
#define __FRAMEWORK_XML_TOOLBOXDOCUMENTHANDLER_HXX_
#ifndef __FRAMEWORK_XML_TOOLBOXCONFIGURATION_HXX_
#include <xml/toolboxconfiguration.hxx>
#endif
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#ifndef _COM_SUN_STAR_XML_SAX_XDOCUMENTHANDLER_HPP_
#include <com/sun/star/xml/sax/XDocumentHandler.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
//_________________________________________________________________________________________________________________
// other includes
//_________________________________________________________________________________________________________________
#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif
#ifndef _RTL_USTRING_
#include <rtl/ustring.hxx>
#endif
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef __SGI_STL_HASH_MAP
#include <hash_map>
#endif
#ifndef __FRAMEWORK_STDTYPES_H_
#include <stdtypes.h>
#endif
//_________________________________________________________________________________________________________________
// namespace
//_________________________________________________________________________________________________________________
namespace framework{
//*****************************************************************************************************************
// Hash code function for using in all hash maps of follow implementation.
class OReadToolBoxDocumentHandler : public ::com::sun::star::xml::sax::XDocumentHandler,
private ThreadHelpBase, // Struct for right initalization of lock member! Must be first of baseclasses.
public ::cppu::OWeakObject
{
public:
enum ToolBox_XML_Entry
{
TB_ELEMENT_TOOLBAR,
TB_ELEMENT_TOOLBARITEM,
TB_ELEMENT_TOOLBARSPACE,
TB_ELEMENT_TOOLBARBREAK,
TB_ELEMENT_TOOLBARSEPARATOR,
TB_ATTRIBUTE_TEXT,
TB_ATTRIBUTE_BITMAP,
TB_ATTRIBUTE_URL,
TB_ATTRIBUTE_ITEMBITS,
TB_ATTRIBUTE_VISIBLE,
TB_ATTRIBUTE_WIDTH,
TB_ATTRIBUTE_USER,
TB_ATTRIBUTE_HELPID,
TB_ATTRIBUTE_STYLE,
TB_ATTRIBUTE_UINAME,
TB_XML_ENTRY_COUNT
};
enum ToolBox_XML_Namespace
{
TB_NS_TOOLBAR,
TB_NS_XLINK,
TB_XML_NAMESPACES_COUNT
};
OReadToolBoxDocumentHandler( const ::com::sun::star::uno::Reference< com::sun::star::container::XIndexContainer >& rItemContainer );
virtual ~OReadToolBoxDocumentHandler();
// XInterface
virtual void SAL_CALL acquire() throw()
{ OWeakObject::acquire(); }
virtual void SAL_CALL release() throw()
{ OWeakObject::release(); }
virtual ::com::sun::star::uno::Any SAL_CALL queryInterface(
const ::com::sun::star::uno::Type & rType ) throw( ::com::sun::star::uno::RuntimeException );
// XDocumentHandler
virtual void SAL_CALL startDocument(void)
throw ( ::com::sun::star::xml::sax::SAXException,
::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL endDocument(void)
throw( ::com::sun::star::xml::sax::SAXException,
::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL startElement(
const rtl::OUString& aName,
const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > &xAttribs)
throw( ::com::sun::star::xml::sax::SAXException,
::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL endElement(const rtl::OUString& aName)
throw( ::com::sun::star::xml::sax::SAXException,
::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL characters(const rtl::OUString& aChars)
throw( ::com::sun::star::xml::sax::SAXException,
::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL ignorableWhitespace(const rtl::OUString& aWhitespaces)
throw( ::com::sun::star::xml::sax::SAXException,
::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL processingInstruction(const rtl::OUString& aTarget,
const rtl::OUString& aData)
throw( ::com::sun::star::xml::sax::SAXException,
::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL setDocumentLocator(
const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XLocator > &xLocator)
throw( ::com::sun::star::xml::sax::SAXException,
::com::sun::star::uno::RuntimeException );
private:
::rtl::OUString getErrorLineString();
class ToolBoxHashMap : public ::std::hash_map< ::rtl::OUString ,
ToolBox_XML_Entry ,
OUStringHashCode ,
::std::equal_to< ::rtl::OUString > >
{
public:
inline void free()
{
ToolBoxHashMap().swap( *this );
}
};
sal_Bool m_bToolBarStartFound;
sal_Bool m_bToolBarEndFound;
sal_Bool m_bToolBarItemStartFound;
sal_Bool m_bToolBarSpaceStartFound;
sal_Bool m_bToolBarBreakStartFound;
sal_Bool m_bToolBarSeparatorStartFound;
ToolBoxHashMap m_aToolBoxMap;
com::sun::star::uno::Reference< com::sun::star::container::XIndexContainer > m_rItemContainer;
::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XLocator > m_xLocator;
sal_Int32 m_nHashCode_Style_Radio;
sal_Int32 m_nHashCode_Style_Auto;
sal_Int32 m_nHashCode_Style_Left;
sal_Int32 m_nHashCode_Style_AutoSize;
sal_Int32 m_nHashCode_Style_DropDown;
sal_Int32 m_nHashCode_Style_Repeat;
};
class OWriteToolBoxDocumentHandler : private ThreadHelpBase // Struct for right initalization of lock member! Must be first of baseclasses.
{
public:
OWriteToolBoxDocumentHandler(
const ::com::sun::star::uno::Reference< com::sun::star::container::XIndexAccess >& rItemAccess,
::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XDocumentHandler >& rDocumentHandler );
virtual ~OWriteToolBoxDocumentHandler();
void WriteToolBoxDocument() throw
( ::com::sun::star::xml::sax::SAXException,
::com::sun::star::uno::RuntimeException );
protected:
virtual void WriteToolBoxItem( const rtl::OUString& aCommandURL, const rtl::OUString& aLabel, const rtl::OUString& aHelpURL,
sal_Bool bVisible ) throw
( ::com::sun::star::xml::sax::SAXException,
::com::sun::star::uno::RuntimeException );
virtual void WriteToolBoxSpace() throw
( ::com::sun::star::xml::sax::SAXException,
::com::sun::star::uno::RuntimeException );
virtual void WriteToolBoxBreak() throw
( ::com::sun::star::xml::sax::SAXException,
::com::sun::star::uno::RuntimeException );
virtual void WriteToolBoxSeparator() throw
( ::com::sun::star::xml::sax::SAXException,
::com::sun::star::uno::RuntimeException );
::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XDocumentHandler > m_xWriteDocumentHandler;
::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > m_xEmptyList;
com::sun::star::uno::Reference< com::sun::star::container::XIndexAccess > m_rItemAccess;
::rtl::OUString m_aXMLToolbarNS;
::rtl::OUString m_aXMLXlinkNS;
::rtl::OUString m_aAttributeType;
::rtl::OUString m_aAttributeURL;
};
} // namespace framework
#endif
<|endoftext|>
|
<commit_before>// Tetris3D.cpp : Defines the entry point for the application.
//
#include "stdafx.hpp"
#include "Tetris3D.hpp"
inline void Tetris3D::SetWindowIcon()
{
#ifdef SFML_SYSTEM_WINDOWS
HINSTANCE hinst = (HINSTANCE)GetModuleHandle(NULL);
HICON IconBig = (HICON)LoadImage(hinst, MAKEINTRESOURCE(IDI_TETRIS3D), IMAGE_ICON, NULL, NULL, LR_DEFAULTCOLOR | LR_LOADTRANSPARENT);
HICON IconSmall = (HICON)LoadImage(hinst, MAKEINTRESOURCE(IDI_SMALL), IMAGE_ICON, NULL, NULL, LR_DEFAULTCOLOR | LR_LOADTRANSPARENT);
SendMessage(Window->getSystemHandle(), WM_SETICON, ICON_BIG, (LPARAM)IconBig);
SendMessage(Window->getSystemHandle(), WM_SETICON, ICON_SMALL, (LPARAM)IconSmall);
#elif SFML_SYSTEM_LINUX
# TODO: For Linux
#endif
}
inline void Tetris3D::InitializeOpenGL()
{
// Enable Z-buffer read and write
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_TRUE);
glClearDepth(1.f);
// Disable lighting
glDisable(GL_LIGHTING);
// Configure the viewport (the same size as the window)
glViewport(0, 0, Window->getSize().x, Window->getSize().y);
// Setup a perspective projection
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
GLfloat ratio = static_cast<float>(Window->getSize().x) / Window->getSize().y;
glFrustum(-ratio, ratio, -1.f, 1.f, 1.f, 500.f);
}
Tetris3D::Tetris3D()
{
// Request a 32-bits depth buffer when creating the window
sf::ContextSettings contextSettings;
contextSettings.depthBits = 32;
Window = new sf::RenderWindow(sf::VideoMode(800, 600), "Tetris3D", sf::Style::Default, contextSettings);
// Make it the active window for OpenGL calls
Window->setActive();
SetWindowIcon();
InitializeOpenGL();
}
Tetris3D::~Tetris3D()
{
delete Window;
}
void Tetris3D::Run()
{
while (Window->isOpen())
{
sf::Event event;
while (Window->pollEvent(event))
{
switch (event.type)
{
case sf::Event::Closed: // Close window : exit
Window->close();
break;
case sf::Event::Resized:
// Adjust the viewport when the window is resized
glViewport(0, 0, event.size.width, event.size.height);
break;
case sf::Event::KeyPressed:
switch (event.key.code)
{
case sf::Keyboard::Escape: // Escape key : exit
Window->close();
break;
}
}
}
Window->display();
}
}
<commit_msg>Izmantot pilnekrāna režīmu<commit_after>// Tetris3D.cpp : Defines the entry point for the application.
//
#include "stdafx.hpp"
#include "Tetris3D.hpp"
inline void Tetris3D::SetWindowIcon()
{
#ifdef SFML_SYSTEM_WINDOWS
HINSTANCE hinst = (HINSTANCE)GetModuleHandle(NULL);
HICON IconBig = (HICON)LoadImage(hinst, MAKEINTRESOURCE(IDI_TETRIS3D), IMAGE_ICON, NULL, NULL, LR_DEFAULTCOLOR | LR_LOADTRANSPARENT);
HICON IconSmall = (HICON)LoadImage(hinst, MAKEINTRESOURCE(IDI_SMALL), IMAGE_ICON, NULL, NULL, LR_DEFAULTCOLOR | LR_LOADTRANSPARENT);
SendMessage(Window->getSystemHandle(), WM_SETICON, ICON_BIG, (LPARAM)IconBig);
SendMessage(Window->getSystemHandle(), WM_SETICON, ICON_SMALL, (LPARAM)IconSmall);
#elif SFML_SYSTEM_LINUX
# TODO: For Linux
#endif
}
inline void Tetris3D::InitializeOpenGL()
{
// Enable Z-buffer read and write
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_TRUE);
glClearDepth(1.f);
// Disable lighting
glDisable(GL_LIGHTING);
// Configure the viewport (the same size as the window)
glViewport(0, 0, Window->getSize().x, Window->getSize().y);
// Setup a perspective projection
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
GLfloat ratio = static_cast<float>(Window->getSize().x) / Window->getSize().y;
glFrustum(-ratio, ratio, -1.f, 1.f, 1.f, 500.f);
}
Tetris3D::Tetris3D()
{
// Request a 32-bits depth buffer when creating the window
sf::ContextSettings contextSettings;
contextSettings.depthBits = 32;
Window = new sf::RenderWindow(sf::VideoMode::getFullscreenModes()[0], "Tetris3D", sf::Style::Fullscreen, contextSettings);
// Make it the active window for OpenGL calls
Window->setActive();
SetWindowIcon();
InitializeOpenGL();
}
Tetris3D::~Tetris3D()
{
delete Window;
}
void Tetris3D::Run()
{
while (Window->isOpen())
{
sf::Event event;
while (Window->pollEvent(event))
{
switch (event.type)
{
case sf::Event::Closed: // Close window : exit
Window->close();
break;
case sf::Event::Resized:
// Adjust the viewport when the window is resized
glViewport(0, 0, event.size.width, event.size.height);
break;
case sf::Event::KeyPressed:
switch (event.key.code)
{
case sf::Keyboard::Escape: // Escape key : exit
Window->close();
break;
}
}
}
Window->display();
}
}
<|endoftext|>
|
<commit_before>/*
** Copyright (C) 2012 Aldebaran Robotics
** See COPYING for the license
*/
#include <map>
#include <qi/atomic.hpp>
#include <boost/thread/recursive_mutex.hpp>
#include <boost/make_shared.hpp>
#include <qitype/signal.hpp>
#include <qitype/genericvalue.hpp>
#include <qitype/genericobject.hpp>
#include "object_p.hpp"
#include "signal_p.hpp"
qiLogCategory("qitype.signal");
namespace qi {
SignalSubscriber::SignalSubscriber(qi::ObjectPtr target, unsigned int method)
: weakLock(0), threadingModel(MetaCallType_Direct), target(new qi::ObjectWeakPtr(target)), method(method), enabled(true)
{ // The slot has its own threading model: be synchronous
}
SignalSubscriber::SignalSubscriber(GenericFunction func, MetaCallType model, detail::WeakLock* lock)
: handler(func), weakLock(lock), threadingModel(model), target(0), method(0), enabled(true)
{
}
SignalSubscriber::~SignalSubscriber()
{
delete target;
delete weakLock;
}
SignalSubscriber::SignalSubscriber(const SignalSubscriber& b)
: weakLock(0), target(0)
{
*this = b;
}
void SignalSubscriber::operator=(const SignalSubscriber& b)
{
source = b.source;
linkId = b.linkId;
handler = b.handler;
weakLock = b.weakLock?b.weakLock->clone():0;
threadingModel = b.threadingModel;
target = b.target?new ObjectWeakPtr(*b.target):0;
method = b.method;
enabled = b.enabled;
}
static qi::Atomic<int> linkUid = 1;
void SignalBase::setCallType(MetaCallType callType)
{
if (!_p)
{
_p = boost::make_shared<SignalBasePrivate>();
}
_p->defaultCallType = callType;
}
void SignalBase::operator()(
qi::AutoGenericValuePtr p1,
qi::AutoGenericValuePtr p2,
qi::AutoGenericValuePtr p3,
qi::AutoGenericValuePtr p4,
qi::AutoGenericValuePtr p5,
qi::AutoGenericValuePtr p6,
qi::AutoGenericValuePtr p7,
qi::AutoGenericValuePtr p8)
{
qi::AutoGenericValuePtr* vals[8]= {&p1, &p2, &p3, &p4, &p5, &p6, &p7, &p8};
std::vector<qi::GenericValuePtr> params;
for (unsigned i = 0; i < 8; ++i)
if (vals[i]->value)
params.push_back(*vals[i]);
qi::Signature signature = qi::makeTupleSignature(params);
if (signature != _p->signature)
{
qiLogError() << "Dropping emit: signature mismatch: " << signature.toString() <<" " << _p->signature.toString();
return;
}
trigger(params, _p->defaultCallType);
}
void SignalBase::trigger(const GenericFunctionParameters& params, MetaCallType callType)
{
MetaCallType mct = callType;
if (!_p)
return;
if (mct == qi::MetaCallType_Auto)
mct = _p->defaultCallType;
SignalSubscriberMap copy;
{
boost::recursive_mutex::scoped_lock sl(_p->mutex);
copy = _p->subscriberMap;
}
qiLogDebug() << (void*)this << " Invoking signal subscribers: " << copy.size();
SignalSubscriberMap::iterator i;
for (i = copy.begin(); i != copy.end(); ++i)
{
qiLogDebug() << (void*)this << " Invoking signal subscriber";
SignalSubscriberPtr s = i->second; // hold s alive
s->call(params, mct);
}
qiLogDebug() << (void*)this << " done invoking signal subscribers";
}
class FunctorCall
{
public:
FunctorCall(GenericFunctionParameters* params, SignalSubscriberPtr* sub)
: params(params)
, sub(sub)
{
}
FunctorCall(const FunctorCall& b)
{
*this = b;
}
void operator=(const FunctorCall& b)
{
params = b.params;
sub = b.sub;
}
void operator() ()
{
try
{
{
SignalSubscriberPtr s;
boost::mutex::scoped_lock sl((*sub)->mutex);
// verify-enabled-then-register-active op must be locked
if (!(*sub)->enabled)
{
s = *sub; // delay destruction until after we leave the scoped_lock
delete sub;
params->destroy();
delete params;
return;
}
(*sub)->addActive(false);
} // end mutex-protected scope
(*sub)->handler(*params);
}
catch(const std::exception& e)
{
qiLogVerbose() << "Exception caught from signal subscriber: " << e.what();
}
catch (...) {
qiLogVerbose() << "Unknown exception caught from signal subscriber";
}
(*sub)->removeActive(true);
params->destroy();
delete params;
if ((*sub)->weakLock)
(*sub)->weakLock->unlock();
delete sub;
}
public:
GenericFunctionParameters* params;
SignalSubscriberPtr* sub;
};
void SignalSubscriber::call(const GenericFunctionParameters& args, MetaCallType callType)
{
// this is held alive by caller
if (handler)
{
// Try to acquire weakLock, for both the sync and async cases
if (weakLock)
{
bool locked = weakLock->tryLock();
if (!locked)
{
source->disconnect(linkId);
return;
}
}
bool async = true;
if (threadingModel != MetaCallType_Auto)
async = (threadingModel == MetaCallType_Queued);
else if (callType != MetaCallType_Auto)
async = (callType == MetaCallType_Queued);
qiLogDebug() << "subscriber call async=" << async <<" ct " << callType <<" tm " << threadingModel;
if (async)
{
GenericFunctionParameters* copy = new GenericFunctionParameters(args.copy());
// We will check enabled when we will be scheduled in the target
// thread, and we hold this SignalSubscriber alive, so no need to
// explicitly track the asynccall
getDefaultThreadPoolEventLoop()->post(FunctorCall(copy, new SignalSubscriberPtr(shared_from_this())));
}
else
{
// verify-enabled-then-register-active op must be locked
{
boost::mutex::scoped_lock sl(mutex);
if (!enabled)
return;
addActive(false);
}
//do not throw
handler(args);
if (weakLock)
weakLock->unlock();
removeActive(true);
}
}
else if (target)
{
ObjectPtr lockedTarget = target->lock();
if (!lockedTarget)
{
source->disconnect(linkId);
}
else // no need to keep anything locked, whatever happens this is not used
lockedTarget->metaPost(method, args);
}
}
//check if we are called from the same thread that triggered us.
//in that case, do not wait.
void SignalSubscriber::waitForInactive()
{
boost::thread::id tid = boost::this_thread::get_id();
while (true)
{
{
boost::mutex::scoped_lock sl(mutex);
if (activeThreads.empty())
return;
// There cannot be two activeThreads entry for the same tid
// because activeThreads is not set at the post() stage
if (activeThreads.size() == 1
&& *activeThreads.begin() == tid)
{ // One active callback in this thread, means above us in call stack
// So we cannot wait for it
return;
}
}
os::msleep(1); // FIXME too long use a condition
}
}
void SignalSubscriber::addActive(bool acquireLock, boost::thread::id id)
{
if (acquireLock)
{
boost::mutex::scoped_lock sl(mutex);
activeThreads.push_back(id);
}
else
activeThreads.push_back(id);
}
void SignalSubscriber::removeActive(bool acquireLock, boost::thread::id id)
{
boost::mutex::scoped_lock sl(mutex, boost::defer_lock_t());
if (acquireLock)
sl.lock();
for (unsigned i=0; i<activeThreads.size(); ++i)
{
if (activeThreads[i] == id)
{ // fast remove by swapping with last and then pop_back
activeThreads[i] = activeThreads[activeThreads.size() - 1];
activeThreads.pop_back();
}
}
}
SignalSubscriber& SignalBase::connect(GenericFunction callback, MetaCallType model)
{
return connect(SignalSubscriber(callback, model));
}
SignalSubscriber& SignalBase::connect(qi::ObjectPtr o, unsigned int slot)
{
return connect(SignalSubscriber(o, slot));
}
SignalSubscriber& SignalBase::connect(const SignalSubscriber& src)
{
qiLogDebug() << (void*)this << " connecting new subscriber";
static SignalSubscriber invalid;
if (!_p)
{
_p = boost::make_shared<SignalBasePrivate>();
}
// Check arity. Does not require to acquire weakLock.
int sigArity = Signature(signature()).begin().children().size();
int subArity = -1;
if (src.handler)
{
if (src.handler.functionType() == dynamicFunctionType())
goto proceed; // no arity checking is possible
subArity = src.handler.argumentsType().size();
}
else if (src.target)
{
ObjectPtr locked = src.target->lock();
if (!locked)
{
qiLogVerbose() << "connecting a dead slot (weak ptr out)";
return invalid;
}
const MetaMethod* ms = locked->metaObject().method(src.method);
if (!ms)
{
qiLogWarning() << "Method " << src.method <<" not found, proceeding anyway";
goto proceed;
}
else
subArity = Signature(ms->parametersSignature()).size();
}
if (sigArity != subArity)
{
qiLogWarning() << "Subscriber has incorrect arity (expected "
<< sigArity << " , got " << subArity <<")";
return invalid;
}
proceed:
boost::recursive_mutex::scoped_lock sl(_p->mutex);
Link res = ++linkUid;
SignalSubscriberPtr s = boost::make_shared<SignalSubscriber>(src);
s->linkId = res;
s->source = this;
bool first = _p->subscriberMap.empty();
_p->subscriberMap[res] = s;
if (first && _p->onSubscribers)
_p->onSubscribers(true);
return *s.get();
}
bool SignalBase::disconnectAll() {
if (_p)
return _p->reset();
return false;
}
SignalBase::SignalBase(const qi::Signature& sig, OnSubscribers onSubscribers)
: _p(new SignalBasePrivate)
{
_p->onSubscribers = onSubscribers;
_p->signature = sig;
}
SignalBase::SignalBase(OnSubscribers onSubscribers)
: _p(new SignalBasePrivate)
{
_p->onSubscribers = onSubscribers;
}
SignalBase::SignalBase(const SignalBase& b)
{
(*this) = b;
}
SignalBase& SignalBase::operator=(const SignalBase& b)
{
if (!b._p)
{
const_cast<SignalBase&>(b)._p = boost::make_shared<SignalBasePrivate>();
}
_p = b._p;
return *this;
}
qi::Signature SignalBase::signature() const
{
return _p ? _p->signature : qi::Signature();
}
void SignalBase::_setSignature(const qi::Signature& s)
{
_p->signature = s;
}
bool SignalBasePrivate::disconnect(const SignalBase::Link& l)
{
SignalSubscriberPtr s;
// Acquire signal mutex
boost::recursive_mutex::scoped_lock sigLock(mutex);
SignalSubscriberMap::iterator it = subscriberMap.find(l);
if (it == subscriberMap.end())
return false;
s = it->second;
// Remove from map (but SignalSubscriber object still good)
subscriberMap.erase(it);
// Acquire subscriber mutex before releasing mutex
boost::mutex::scoped_lock subLock(s->mutex);
// Release signal mutex
sigLock.release()->unlock();
// Ensure no call on subscriber occurrs once this function returns
s->enabled = false;
if (subscriberMap.empty() && onSubscribers)
onSubscribers(false);
if ( s->activeThreads.empty()
|| (s->activeThreads.size() == 1
&& *s->activeThreads.begin() == boost::this_thread::get_id()))
{ // One active callback in this thread, means above us in call stack
// So we cannot trash s right now
return true;
}
// More than one active callback, or one in a state that prevent us
// from knowing in which thread it will run
subLock.release()->unlock();
s->waitForInactive();
return true;
}
bool SignalBase::disconnect(const Link &link) {
if (!_p)
return false;
else
return _p->disconnect(link);
}
SignalBase::~SignalBase()
{
if (!_p)
return;
_p->onSubscribers = OnSubscribers();
boost::shared_ptr<SignalBasePrivate> p(_p);
_p.reset();
SignalSubscriberMap::iterator i;
std::vector<Link> links;
for (i = p->subscriberMap.begin(); i!= p->subscriberMap.end(); ++i)
{
links.push_back(i->first);
}
for (unsigned i=0; i<links.size(); ++i)
p->disconnect(links[i]);
}
std::vector<SignalSubscriber> SignalBase::subscribers()
{
std::vector<SignalSubscriber> res;
if (!_p)
return res;
boost::recursive_mutex::scoped_lock sl(_p->mutex);
SignalSubscriberMap::iterator i;
for (i = _p->subscriberMap.begin(); i!= _p->subscriberMap.end(); ++i)
res.push_back(*i->second);
return res;
}
bool SignalBasePrivate::reset() {
bool ret = true;
boost::recursive_mutex::scoped_lock sl(mutex);
SignalSubscriberMap::iterator it = subscriberMap.begin();
while (it != subscriberMap.end()) {
bool b = disconnect(it->first);
if (!b)
ret = false;
it = subscriberMap.begin();
}
return ret;
}
QITYPE_API const SignalBase::Link SignalBase::invalidLink = ((unsigned int)-1);
}
<commit_msg>Signal: validate signature compatibility when connecting.<commit_after>/*
** Copyright (C) 2012 Aldebaran Robotics
** See COPYING for the license
*/
#include <map>
#include <qi/atomic.hpp>
#include <boost/thread/recursive_mutex.hpp>
#include <boost/make_shared.hpp>
#include <qitype/signal.hpp>
#include <qitype/genericvalue.hpp>
#include <qitype/genericobject.hpp>
#include "object_p.hpp"
#include "signal_p.hpp"
qiLogCategory("qitype.signal");
namespace qi {
SignalSubscriber::SignalSubscriber(qi::ObjectPtr target, unsigned int method)
: weakLock(0), threadingModel(MetaCallType_Direct), target(new qi::ObjectWeakPtr(target)), method(method), enabled(true)
{ // The slot has its own threading model: be synchronous
}
SignalSubscriber::SignalSubscriber(GenericFunction func, MetaCallType model, detail::WeakLock* lock)
: handler(func), weakLock(lock), threadingModel(model), target(0), method(0), enabled(true)
{
}
SignalSubscriber::~SignalSubscriber()
{
delete target;
delete weakLock;
}
SignalSubscriber::SignalSubscriber(const SignalSubscriber& b)
: weakLock(0), target(0)
{
*this = b;
}
void SignalSubscriber::operator=(const SignalSubscriber& b)
{
source = b.source;
linkId = b.linkId;
handler = b.handler;
weakLock = b.weakLock?b.weakLock->clone():0;
threadingModel = b.threadingModel;
target = b.target?new ObjectWeakPtr(*b.target):0;
method = b.method;
enabled = b.enabled;
}
static qi::Atomic<int> linkUid = 1;
void SignalBase::setCallType(MetaCallType callType)
{
if (!_p)
{
_p = boost::make_shared<SignalBasePrivate>();
}
_p->defaultCallType = callType;
}
void SignalBase::operator()(
qi::AutoGenericValuePtr p1,
qi::AutoGenericValuePtr p2,
qi::AutoGenericValuePtr p3,
qi::AutoGenericValuePtr p4,
qi::AutoGenericValuePtr p5,
qi::AutoGenericValuePtr p6,
qi::AutoGenericValuePtr p7,
qi::AutoGenericValuePtr p8)
{
qi::AutoGenericValuePtr* vals[8]= {&p1, &p2, &p3, &p4, &p5, &p6, &p7, &p8};
std::vector<qi::GenericValuePtr> params;
for (unsigned i = 0; i < 8; ++i)
if (vals[i]->value)
params.push_back(*vals[i]);
qi::Signature signature = qi::makeTupleSignature(params);
if (signature != _p->signature)
{
qiLogError() << "Dropping emit: signature mismatch: " << signature.toString() <<" " << _p->signature.toString();
return;
}
trigger(params, _p->defaultCallType);
}
void SignalBase::trigger(const GenericFunctionParameters& params, MetaCallType callType)
{
MetaCallType mct = callType;
if (!_p)
return;
if (mct == qi::MetaCallType_Auto)
mct = _p->defaultCallType;
SignalSubscriberMap copy;
{
boost::recursive_mutex::scoped_lock sl(_p->mutex);
copy = _p->subscriberMap;
}
qiLogDebug() << (void*)this << " Invoking signal subscribers: " << copy.size();
SignalSubscriberMap::iterator i;
for (i = copy.begin(); i != copy.end(); ++i)
{
qiLogDebug() << (void*)this << " Invoking signal subscriber";
SignalSubscriberPtr s = i->second; // hold s alive
s->call(params, mct);
}
qiLogDebug() << (void*)this << " done invoking signal subscribers";
}
class FunctorCall
{
public:
FunctorCall(GenericFunctionParameters* params, SignalSubscriberPtr* sub)
: params(params)
, sub(sub)
{
}
FunctorCall(const FunctorCall& b)
{
*this = b;
}
void operator=(const FunctorCall& b)
{
params = b.params;
sub = b.sub;
}
void operator() ()
{
try
{
{
SignalSubscriberPtr s;
boost::mutex::scoped_lock sl((*sub)->mutex);
// verify-enabled-then-register-active op must be locked
if (!(*sub)->enabled)
{
s = *sub; // delay destruction until after we leave the scoped_lock
delete sub;
params->destroy();
delete params;
return;
}
(*sub)->addActive(false);
} // end mutex-protected scope
(*sub)->handler(*params);
}
catch(const std::exception& e)
{
qiLogVerbose() << "Exception caught from signal subscriber: " << e.what();
}
catch (...) {
qiLogVerbose() << "Unknown exception caught from signal subscriber";
}
(*sub)->removeActive(true);
params->destroy();
delete params;
if ((*sub)->weakLock)
(*sub)->weakLock->unlock();
delete sub;
}
public:
GenericFunctionParameters* params;
SignalSubscriberPtr* sub;
};
void SignalSubscriber::call(const GenericFunctionParameters& args, MetaCallType callType)
{
// this is held alive by caller
if (handler)
{
// Try to acquire weakLock, for both the sync and async cases
if (weakLock)
{
bool locked = weakLock->tryLock();
if (!locked)
{
source->disconnect(linkId);
return;
}
}
bool async = true;
if (threadingModel != MetaCallType_Auto)
async = (threadingModel == MetaCallType_Queued);
else if (callType != MetaCallType_Auto)
async = (callType == MetaCallType_Queued);
qiLogDebug() << "subscriber call async=" << async <<" ct " << callType <<" tm " << threadingModel;
if (async)
{
GenericFunctionParameters* copy = new GenericFunctionParameters(args.copy());
// We will check enabled when we will be scheduled in the target
// thread, and we hold this SignalSubscriber alive, so no need to
// explicitly track the asynccall
getDefaultThreadPoolEventLoop()->post(FunctorCall(copy, new SignalSubscriberPtr(shared_from_this())));
}
else
{
// verify-enabled-then-register-active op must be locked
{
boost::mutex::scoped_lock sl(mutex);
if (!enabled)
return;
addActive(false);
}
//do not throw
handler(args);
if (weakLock)
weakLock->unlock();
removeActive(true);
}
}
else if (target)
{
ObjectPtr lockedTarget = target->lock();
if (!lockedTarget)
{
source->disconnect(linkId);
}
else // no need to keep anything locked, whatever happens this is not used
lockedTarget->metaPost(method, args);
}
}
//check if we are called from the same thread that triggered us.
//in that case, do not wait.
void SignalSubscriber::waitForInactive()
{
boost::thread::id tid = boost::this_thread::get_id();
while (true)
{
{
boost::mutex::scoped_lock sl(mutex);
if (activeThreads.empty())
return;
// There cannot be two activeThreads entry for the same tid
// because activeThreads is not set at the post() stage
if (activeThreads.size() == 1
&& *activeThreads.begin() == tid)
{ // One active callback in this thread, means above us in call stack
// So we cannot wait for it
return;
}
}
os::msleep(1); // FIXME too long use a condition
}
}
void SignalSubscriber::addActive(bool acquireLock, boost::thread::id id)
{
if (acquireLock)
{
boost::mutex::scoped_lock sl(mutex);
activeThreads.push_back(id);
}
else
activeThreads.push_back(id);
}
void SignalSubscriber::removeActive(bool acquireLock, boost::thread::id id)
{
boost::mutex::scoped_lock sl(mutex, boost::defer_lock_t());
if (acquireLock)
sl.lock();
for (unsigned i=0; i<activeThreads.size(); ++i)
{
if (activeThreads[i] == id)
{ // fast remove by swapping with last and then pop_back
activeThreads[i] = activeThreads[activeThreads.size() - 1];
activeThreads.pop_back();
}
}
}
SignalSubscriber& SignalBase::connect(GenericFunction callback, MetaCallType model)
{
return connect(SignalSubscriber(callback, model));
}
SignalSubscriber& SignalBase::connect(qi::ObjectPtr o, unsigned int slot)
{
return connect(SignalSubscriber(o, slot));
}
SignalSubscriber& SignalBase::connect(const SignalSubscriber& src)
{
qiLogDebug() << (void*)this << " connecting new subscriber";
static SignalSubscriber invalid;
if (!_p)
{
_p = boost::make_shared<SignalBasePrivate>();
}
// Check arity. Does not require to acquire weakLock.
int sigArity = Signature(signature()).begin().children().size();
int subArity = -1;
Signature subSignature;
if (src.handler)
{
if (src.handler.functionType() == dynamicFunctionType())
goto proceed; // no arity checking is possible
subArity = src.handler.argumentsType().size();
subSignature = src.handler.parametersSignature();
}
else if (src.target)
{
ObjectPtr locked = src.target->lock();
if (!locked)
{
qiLogVerbose() << "connecting a dead slot (weak ptr out)";
return invalid;
}
const MetaMethod* ms = locked->metaObject().method(src.method);
if (!ms)
{
qiLogWarning() << "Method " << src.method <<" not found, proceeding anyway";
goto proceed;
}
else
{
subSignature = ms->parametersSignature();
subArity = subSignature.size();
}
}
if (sigArity != subArity)
{
qiLogWarning() << "Subscriber has incorrect arity (expected "
<< sigArity << " , got " << subArity <<")";
return invalid;
}
if (!signature().isConvertibleTo(subSignature))
{
qiLogWarning() << "Subscriber is not compatible to signal : "
<< signature().toString() << " vs " << subSignature.toString();
return invalid;
}
proceed:
boost::recursive_mutex::scoped_lock sl(_p->mutex);
Link res = ++linkUid;
SignalSubscriberPtr s = boost::make_shared<SignalSubscriber>(src);
s->linkId = res;
s->source = this;
bool first = _p->subscriberMap.empty();
_p->subscriberMap[res] = s;
if (first && _p->onSubscribers)
_p->onSubscribers(true);
return *s.get();
}
bool SignalBase::disconnectAll() {
if (_p)
return _p->reset();
return false;
}
SignalBase::SignalBase(const qi::Signature& sig, OnSubscribers onSubscribers)
: _p(new SignalBasePrivate)
{
_p->onSubscribers = onSubscribers;
_p->signature = sig;
}
SignalBase::SignalBase(OnSubscribers onSubscribers)
: _p(new SignalBasePrivate)
{
_p->onSubscribers = onSubscribers;
}
SignalBase::SignalBase(const SignalBase& b)
{
(*this) = b;
}
SignalBase& SignalBase::operator=(const SignalBase& b)
{
if (!b._p)
{
const_cast<SignalBase&>(b)._p = boost::make_shared<SignalBasePrivate>();
}
_p = b._p;
return *this;
}
qi::Signature SignalBase::signature() const
{
return _p ? _p->signature : qi::Signature();
}
void SignalBase::_setSignature(const qi::Signature& s)
{
_p->signature = s;
}
bool SignalBasePrivate::disconnect(const SignalBase::Link& l)
{
SignalSubscriberPtr s;
// Acquire signal mutex
boost::recursive_mutex::scoped_lock sigLock(mutex);
SignalSubscriberMap::iterator it = subscriberMap.find(l);
if (it == subscriberMap.end())
return false;
s = it->second;
// Remove from map (but SignalSubscriber object still good)
subscriberMap.erase(it);
// Acquire subscriber mutex before releasing mutex
boost::mutex::scoped_lock subLock(s->mutex);
// Release signal mutex
sigLock.release()->unlock();
// Ensure no call on subscriber occurrs once this function returns
s->enabled = false;
if (subscriberMap.empty() && onSubscribers)
onSubscribers(false);
if ( s->activeThreads.empty()
|| (s->activeThreads.size() == 1
&& *s->activeThreads.begin() == boost::this_thread::get_id()))
{ // One active callback in this thread, means above us in call stack
// So we cannot trash s right now
return true;
}
// More than one active callback, or one in a state that prevent us
// from knowing in which thread it will run
subLock.release()->unlock();
s->waitForInactive();
return true;
}
bool SignalBase::disconnect(const Link &link) {
if (!_p)
return false;
else
return _p->disconnect(link);
}
SignalBase::~SignalBase()
{
if (!_p)
return;
_p->onSubscribers = OnSubscribers();
boost::shared_ptr<SignalBasePrivate> p(_p);
_p.reset();
SignalSubscriberMap::iterator i;
std::vector<Link> links;
for (i = p->subscriberMap.begin(); i!= p->subscriberMap.end(); ++i)
{
links.push_back(i->first);
}
for (unsigned i=0; i<links.size(); ++i)
p->disconnect(links[i]);
}
std::vector<SignalSubscriber> SignalBase::subscribers()
{
std::vector<SignalSubscriber> res;
if (!_p)
return res;
boost::recursive_mutex::scoped_lock sl(_p->mutex);
SignalSubscriberMap::iterator i;
for (i = _p->subscriberMap.begin(); i!= _p->subscriberMap.end(); ++i)
res.push_back(*i->second);
return res;
}
bool SignalBasePrivate::reset() {
bool ret = true;
boost::recursive_mutex::scoped_lock sl(mutex);
SignalSubscriberMap::iterator it = subscriberMap.begin();
while (it != subscriberMap.end()) {
bool b = disconnect(it->first);
if (!b)
ret = false;
it = subscriberMap.begin();
}
return ret;
}
QITYPE_API const SignalBase::Link SignalBase::invalidLink = ((unsigned int)-1);
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.