text
stringlengths 54
60.6k
|
---|
<commit_before>//===- PrettyStackTrace.cpp - Pretty Crash Handling -----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines some helpful functions for dealing with the possibility of
// Unix signals occurring while your program is running.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm-c/ErrorHandling.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Config/config.h" // Get autoconf configuration settings
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/Watchdog.h"
#include "llvm/Support/raw_ostream.h"
#include <cstdarg>
#include <cstdio>
#include <tuple>
#ifdef HAVE_CRASHREPORTERCLIENT_H
#include <CrashReporterClient.h>
#endif
using namespace llvm;
// If backtrace support is not enabled, compile out support for pretty stack
// traces. This has the secondary effect of not requiring thread local storage
// when backtrace support is disabled.
#if defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES
// We need a thread local pointer to manage the stack of our stack trace
// objects, but we *really* cannot tolerate destructors running and do not want
// to pay any overhead of synchronizing. As a consequence, we use a raw
// thread-local variable.
static LLVM_THREAD_LOCAL PrettyStackTraceEntry *PrettyStackTraceHead = nullptr;
namespace llvm {
PrettyStackTraceEntry *ReverseStackTrace(PrettyStackTraceEntry *Head) {
PrettyStackTraceEntry *Prev = nullptr;
while (Head)
std::tie(Prev, Head, Head->NextEntry) =
std::make_tuple(Head, Head->NextEntry, Prev);
return Prev;
}
}
static void PrintStack(raw_ostream &OS) {
// Print out the stack in reverse order. To avoid recursion (which is likely
// to fail if we crashed due to stack overflow), we do an up-front pass to
// reverse the stack, then print it, then reverse it again.
unsigned ID = 0;
PrettyStackTraceEntry *ReversedStack =
llvm::ReverseStackTrace(PrettyStackTraceHead);
for (const PrettyStackTraceEntry *Entry = ReversedStack; Entry;
Entry = Entry->getNextEntry()) {
OS << ID++ << ".\t";
sys::Watchdog W(5);
Entry->print(OS);
}
llvm::ReverseStackTrace(ReversedStack);
}
/// PrintCurStackTrace - Print the current stack trace to the specified stream.
static void PrintCurStackTrace(raw_ostream &OS) {
// Don't print an empty trace.
if (!PrettyStackTraceHead) return;
// If there are pretty stack frames registered, walk and emit them.
OS << "Stack dump:\n";
PrintStack(OS);
OS.flush();
}
// Integrate with crash reporter libraries.
#if defined (__APPLE__) && defined(HAVE_CRASHREPORTERCLIENT_H)
// If any clients of llvm try to link to libCrashReporterClient.a themselves,
// only one crash info struct will be used.
extern "C" {
CRASH_REPORTER_CLIENT_HIDDEN
struct crashreporter_annotations_t gCRAnnotations
__attribute__((section("__DATA," CRASHREPORTER_ANNOTATIONS_SECTION)))
#if CRASHREPORTER_ANNOTATIONS_VERSION < 5
= { CRASHREPORTER_ANNOTATIONS_VERSION, 0, 0, 0, 0, 0, 0 };
#else
= { CRASHREPORTER_ANNOTATIONS_VERSION, 0, 0, 0, 0, 0, 0, 0 };
#endif
}
#elif defined(__APPLE__) && HAVE_CRASHREPORTER_INFO
extern "C" const char *__crashreporter_info__
__attribute__((visibility("hidden"))) = 0;
asm(".desc ___crashreporter_info__, 0x10");
#endif
/// CrashHandler - This callback is run if a fatal signal is delivered to the
/// process, it prints the pretty stack trace.
static void CrashHandler(void *) {
#ifndef __APPLE__
// On non-apple systems, just emit the crash stack trace to stderr.
PrintCurStackTrace(errs());
#else
// Otherwise, emit to a smallvector of chars, send *that* to stderr, but also
// put it into __crashreporter_info__.
SmallString<2048> TmpStr;
{
raw_svector_ostream Stream(TmpStr);
PrintCurStackTrace(Stream);
}
if (!TmpStr.empty()) {
#ifdef HAVE_CRASHREPORTERCLIENT_H
// Cast to void to avoid warning.
(void)CRSetCrashLogMessage(TmpStr.c_str());
#elif HAVE_CRASHREPORTER_INFO
__crashreporter_info__ = strdup(TmpStr.c_str());
#endif
errs() << TmpStr.str();
}
#endif
}
// defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES
#endif
PrettyStackTraceEntry::PrettyStackTraceEntry() {
#if defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES
// Link ourselves.
NextEntry = PrettyStackTraceHead;
PrettyStackTraceHead = this;
#endif
}
PrettyStackTraceEntry::~PrettyStackTraceEntry() {
#if defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES
assert(PrettyStackTraceHead == this &&
"Pretty stack trace entry destruction is out of order");
PrettyStackTraceHead = NextEntry;
#endif
}
void PrettyStackTraceString::print(raw_ostream &OS) const { OS << Str << "\n"; }
PrettyStackTraceFormat::PrettyStackTraceFormat(const char *Format, ...) {
va_list AP;
va_start(AP, Format);
const int SizeOrError = vsnprintf(nullptr, 0, Format, AP);
va_end(AP);
if (SizeOrError < 0) {
return;
}
const int Size = SizeOrError + 1; // '\0'
Str.resize(Size);
va_start(AP, Format);
vsnprintf(Str.data(), Size, Format, AP);
va_end(AP);
}
void PrettyStackTraceFormat::print(raw_ostream &OS) const { OS << Str << "\n"; }
void PrettyStackTraceProgram::print(raw_ostream &OS) const {
OS << "Program arguments: ";
// Print the argument list.
for (unsigned i = 0, e = ArgC; i != e; ++i)
OS << ArgV[i] << ' ';
OS << '\n';
}
#if defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES
static bool RegisterCrashPrinter() {
sys::AddSignalHandler(CrashHandler, nullptr);
return false;
}
#endif
void llvm::EnablePrettyStackTrace() {
#if defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES
// The first time this is called, we register the crash printer.
static bool HandlerRegistered = RegisterCrashPrinter();
(void)HandlerRegistered;
#endif
}
const void *llvm::SavePrettyStackState() {
#if defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES
return PrettyStackTraceHead;
#else
return nullptr;
#endif
}
void llvm::RestorePrettyStackState(const void *Top) {
#if defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES
PrettyStackTraceHead =
static_cast<PrettyStackTraceEntry *>(const_cast<void *>(Top));
#endif
}
void LLVMEnablePrettyStackTrace() {
EnablePrettyStackTrace();
}
<commit_msg>Support: enable backtraces on Windows<commit_after>//===- PrettyStackTrace.cpp - Pretty Crash Handling -----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines some helpful functions for dealing with the possibility of
// Unix signals occurring while your program is running.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm-c/ErrorHandling.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Config/config.h" // Get autoconf configuration settings
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/Watchdog.h"
#include "llvm/Support/raw_ostream.h"
#include <cstdarg>
#include <cstdio>
#include <tuple>
#ifdef HAVE_CRASHREPORTERCLIENT_H
#include <CrashReporterClient.h>
#endif
using namespace llvm;
// If backtrace support is not enabled, compile out support for pretty stack
// traces. This has the secondary effect of not requiring thread local storage
// when backtrace support is disabled.
#if ENABLE_BACKTRACES
// We need a thread local pointer to manage the stack of our stack trace
// objects, but we *really* cannot tolerate destructors running and do not want
// to pay any overhead of synchronizing. As a consequence, we use a raw
// thread-local variable.
static LLVM_THREAD_LOCAL PrettyStackTraceEntry *PrettyStackTraceHead = nullptr;
namespace llvm {
PrettyStackTraceEntry *ReverseStackTrace(PrettyStackTraceEntry *Head) {
PrettyStackTraceEntry *Prev = nullptr;
while (Head)
std::tie(Prev, Head, Head->NextEntry) =
std::make_tuple(Head, Head->NextEntry, Prev);
return Prev;
}
}
static void PrintStack(raw_ostream &OS) {
// Print out the stack in reverse order. To avoid recursion (which is likely
// to fail if we crashed due to stack overflow), we do an up-front pass to
// reverse the stack, then print it, then reverse it again.
unsigned ID = 0;
PrettyStackTraceEntry *ReversedStack =
llvm::ReverseStackTrace(PrettyStackTraceHead);
for (const PrettyStackTraceEntry *Entry = ReversedStack; Entry;
Entry = Entry->getNextEntry()) {
OS << ID++ << ".\t";
sys::Watchdog W(5);
Entry->print(OS);
}
llvm::ReverseStackTrace(ReversedStack);
}
/// PrintCurStackTrace - Print the current stack trace to the specified stream.
static void PrintCurStackTrace(raw_ostream &OS) {
// Don't print an empty trace.
if (!PrettyStackTraceHead) return;
// If there are pretty stack frames registered, walk and emit them.
OS << "Stack dump:\n";
PrintStack(OS);
OS.flush();
}
// Integrate with crash reporter libraries.
#if defined (__APPLE__) && defined(HAVE_CRASHREPORTERCLIENT_H)
// If any clients of llvm try to link to libCrashReporterClient.a themselves,
// only one crash info struct will be used.
extern "C" {
CRASH_REPORTER_CLIENT_HIDDEN
struct crashreporter_annotations_t gCRAnnotations
__attribute__((section("__DATA," CRASHREPORTER_ANNOTATIONS_SECTION)))
#if CRASHREPORTER_ANNOTATIONS_VERSION < 5
= { CRASHREPORTER_ANNOTATIONS_VERSION, 0, 0, 0, 0, 0, 0 };
#else
= { CRASHREPORTER_ANNOTATIONS_VERSION, 0, 0, 0, 0, 0, 0, 0 };
#endif
}
#elif defined(__APPLE__) && HAVE_CRASHREPORTER_INFO
extern "C" const char *__crashreporter_info__
__attribute__((visibility("hidden"))) = 0;
asm(".desc ___crashreporter_info__, 0x10");
#endif
/// CrashHandler - This callback is run if a fatal signal is delivered to the
/// process, it prints the pretty stack trace.
static void CrashHandler(void *) {
#ifndef __APPLE__
// On non-apple systems, just emit the crash stack trace to stderr.
PrintCurStackTrace(errs());
#else
// Otherwise, emit to a smallvector of chars, send *that* to stderr, but also
// put it into __crashreporter_info__.
SmallString<2048> TmpStr;
{
raw_svector_ostream Stream(TmpStr);
PrintCurStackTrace(Stream);
}
if (!TmpStr.empty()) {
#ifdef HAVE_CRASHREPORTERCLIENT_H
// Cast to void to avoid warning.
(void)CRSetCrashLogMessage(TmpStr.c_str());
#elif HAVE_CRASHREPORTER_INFO
__crashreporter_info__ = strdup(TmpStr.c_str());
#endif
errs() << TmpStr.str();
}
#endif
}
#endif // ENABLE_BACKTRACES
PrettyStackTraceEntry::PrettyStackTraceEntry() {
#if ENABLE_BACKTRACES
// Link ourselves.
NextEntry = PrettyStackTraceHead;
PrettyStackTraceHead = this;
#endif
}
PrettyStackTraceEntry::~PrettyStackTraceEntry() {
#if ENABLE_BACKTRACES
assert(PrettyStackTraceHead == this &&
"Pretty stack trace entry destruction is out of order");
PrettyStackTraceHead = NextEntry;
#endif
}
void PrettyStackTraceString::print(raw_ostream &OS) const { OS << Str << "\n"; }
PrettyStackTraceFormat::PrettyStackTraceFormat(const char *Format, ...) {
va_list AP;
va_start(AP, Format);
const int SizeOrError = vsnprintf(nullptr, 0, Format, AP);
va_end(AP);
if (SizeOrError < 0) {
return;
}
const int Size = SizeOrError + 1; // '\0'
Str.resize(Size);
va_start(AP, Format);
vsnprintf(Str.data(), Size, Format, AP);
va_end(AP);
}
void PrettyStackTraceFormat::print(raw_ostream &OS) const { OS << Str << "\n"; }
void PrettyStackTraceProgram::print(raw_ostream &OS) const {
OS << "Program arguments: ";
// Print the argument list.
for (unsigned i = 0, e = ArgC; i != e; ++i)
OS << ArgV[i] << ' ';
OS << '\n';
}
#if ENABLE_BACKTRACES
static bool RegisterCrashPrinter() {
sys::AddSignalHandler(CrashHandler, nullptr);
return false;
}
#endif
void llvm::EnablePrettyStackTrace() {
#if ENABLE_BACKTRACES
// The first time this is called, we register the crash printer.
static bool HandlerRegistered = RegisterCrashPrinter();
(void)HandlerRegistered;
#endif
}
const void *llvm::SavePrettyStackState() {
#if ENABLE_BACKTRACES
return PrettyStackTraceHead;
#else
return nullptr;
#endif
}
void llvm::RestorePrettyStackState(const void *Top) {
#if ENABLE_BACKTRACES
PrettyStackTraceHead =
static_cast<PrettyStackTraceEntry *>(const_cast<void *>(Top));
#endif
}
void LLVMEnablePrettyStackTrace() {
EnablePrettyStackTrace();
}
<|endoftext|> |
<commit_before>//===-- ARMAsmBackend.cpp - ARM Assembler Backend -------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "ARM.h"
#include "ARMAddressingModes.h"
#include "ARMFixupKinds.h"
#include "llvm/ADT/Twine.h"
#include "llvm/MC/MCAssembler.h"
#include "llvm/MC/MCDirectives.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCObjectFormat.h"
#include "llvm/MC/MCObjectWriter.h"
#include "llvm/MC/MCSectionELF.h"
#include "llvm/MC/MCSectionMachO.h"
#include "llvm/Object/MachOFormat.h"
#include "llvm/Support/ELF.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetAsmBackend.h"
#include "llvm/Target/TargetRegistry.h"
using namespace llvm;
namespace {
class ARMAsmBackend : public TargetAsmBackend {
bool isThumbMode; // Currently emitting Thumb code.
public:
ARMAsmBackend(const Target &T) : TargetAsmBackend(), isThumbMode(false) {}
bool MayNeedRelaxation(const MCInst &Inst) const;
void RelaxInstruction(const MCInst &Inst, MCInst &Res) const;
bool WriteNopData(uint64_t Count, MCObjectWriter *OW) const;
void HandleAssemblerFlag(MCAssemblerFlag Flag) {
switch (Flag) {
default: break;
case MCAF_Code16:
setIsThumb(true);
break;
case MCAF_Code32:
setIsThumb(false);
break;
}
}
unsigned getPointerSize() const { return 4; }
bool isThumb() const { return isThumbMode; }
void setIsThumb(bool it) { isThumbMode = it; }
};
} // end anonymous namespace
bool ARMAsmBackend::MayNeedRelaxation(const MCInst &Inst) const {
// FIXME: Thumb targets, different move constant targets..
return false;
}
void ARMAsmBackend::RelaxInstruction(const MCInst &Inst, MCInst &Res) const {
assert(0 && "ARMAsmBackend::RelaxInstruction() unimplemented");
return;
}
bool ARMAsmBackend::WriteNopData(uint64_t Count, MCObjectWriter *OW) const {
if (isThumb()) {
assert (((Count & 1) == 0) && "Unaligned Nop data fragment!");
// FIXME: 0xbf00 is the ARMv7 value. For v6 and before, we'll need to
// use 0x46c0 (which is a 'mov r8, r8' insn).
Count /= 2;
for (uint64_t i = 0; i != Count; ++i)
OW->Write16(0xbf00);
return true;
}
// ARM mode
Count /= 4;
for (uint64_t i = 0; i != Count; ++i)
OW->Write32(0xe1a00000);
return true;
}
static unsigned adjustFixupValue(unsigned Kind, uint64_t Value) {
switch (Kind) {
default:
llvm_unreachable("Unknown fixup kind!");
case FK_Data_4:
return Value;
case ARM::fixup_arm_movt_hi16:
case ARM::fixup_arm_movw_lo16: {
unsigned Hi4 = (Value & 0xF000) >> 12;
unsigned Lo12 = Value & 0x0FFF;
// inst{19-16} = Hi4;
// inst{11-0} = Lo12;
Value = (Hi4 << 16) | (Lo12);
return Value;
}
case ARM::fixup_arm_ldst_pcrel_12:
// ARM PC-relative values are offset by 8.
Value -= 4;
// FALLTHROUGH
case ARM::fixup_t2_ldst_pcrel_12: {
// Offset by 4, adjusted by two due to the half-word ordering of thumb.
Value -= 4;
bool isAdd = true;
if ((int64_t)Value < 0) {
Value = -Value;
isAdd = false;
}
assert ((Value < 4096) && "Out of range pc-relative fixup value!");
Value |= isAdd << 23;
// Same addressing mode as fixup_arm_pcrel_10,
// but with 16-bit halfwords swapped.
if (Kind == ARM::fixup_t2_ldst_pcrel_12) {
uint64_t swapped = (Value & 0xFFFF0000) >> 16;
swapped |= (Value & 0x0000FFFF) << 16;
return swapped;
}
return Value;
}
case ARM::fixup_arm_adr_pcrel_12: {
// ARM PC-relative values are offset by 8.
Value -= 8;
unsigned opc = 4; // bits {24-21}. Default to add: 0b0100
if ((int64_t)Value < 0) {
Value = -Value;
opc = 2; // 0b0010
}
assert(ARM_AM::getSOImmVal(Value) != -1 &&
"Out of range pc-relative fixup value!");
// Encode the immediate and shift the opcode into place.
return ARM_AM::getSOImmVal(Value) | (opc << 21);
}
case ARM::fixup_arm_branch:
// These values don't encode the low two bits since they're always zero.
// Offset by 8 just as above.
return 0xffffff & ((Value - 8) >> 2);
case ARM::fixup_t2_branch: {
Value = Value - 4;
Value >>= 1; // Low bit is not encoded.
uint64_t out = 0;
out |= (Value & 0x80000) << 7; // S bit
out |= (Value & 0x40000) >> 7; // J2 bit
out |= (Value & 0x20000) >> 4; // J1 bit
out |= (Value & 0x1F800) << 5; // imm6 field
out |= (Value & 0x007FF); // imm11 field
uint64_t swapped = (out & 0xFFFF0000) >> 16;
swapped |= (out & 0x0000FFFF) << 16;
return swapped;
}
case ARM::fixup_arm_thumb_bl: {
// The value doesn't encode the low bit (always zero) and is offset by
// four. The value is encoded into disjoint bit positions in the destination
// opcode. x = unchanged, I = immediate value bit, S = sign extension bit
//
// BL: xxxxxSIIIIIIIIII xxxxxIIIIIIIIIII
//
// Note that the halfwords are stored high first, low second; so we need
// to transpose the fixup value here to map properly.
unsigned isNeg = (int64_t(Value) < 0) ? 1 : 0;
uint32_t Binary = 0;
Value = 0x3fffff & ((Value - 4) >> 1);
Binary = (Value & 0x7ff) << 16; // Low imm11 value.
Binary |= (Value & 0x1ffc00) >> 11; // High imm10 value.
Binary |= isNeg << 10; // Sign bit.
return Binary;
}
case ARM::fixup_arm_thumb_blx: {
// The value doesn't encode the low two bits (always zero) and is offset by
// four (see fixup_arm_thumb_cp). The value is encoded into disjoint bit
// positions in the destination opcode. x = unchanged, I = immediate value
// bit, S = sign extension bit, 0 = zero.
//
// BLX: xxxxxSIIIIIIIIII xxxxxIIIIIIIIII0
//
// Note that the halfwords are stored high first, low second; so we need
// to transpose the fixup value here to map properly.
unsigned isNeg = (int64_t(Value) < 0) ? 1 : 0;
uint32_t Binary = 0;
Value = 0xfffff & ((Value - 2) >> 2);
Binary = (Value & 0x3ff) << 17; // Low imm10L value.
Binary |= (Value & 0xffc00) >> 10; // High imm10H value.
Binary |= isNeg << 10; // Sign bit.
return Binary;
}
case ARM::fixup_arm_thumb_cp:
// Offset by 4, and don't encode the low two bits. Two bytes of that
// 'off by 4' is implicitly handled by the half-word ordering of the
// Thumb encoding, so we only need to adjust by 2 here.
return ((Value - 2) >> 2) & 0xff;
case ARM::fixup_arm_thumb_cb: {
// Offset by 4 and don't encode the lower bit, which is always 0.
uint32_t Binary = (Value - 4) >> 1;
return ((Binary & 0x20) << 9) | ((Binary & 0x1f) << 3);
}
case ARM::fixup_arm_thumb_br:
// Offset by 4 and don't encode the lower bit, which is always 0.
return ((Value - 4) >> 1) & 0x7ff;
case ARM::fixup_arm_thumb_bcc:
// Offset by 4 and don't encode the lower bit, which is always 0.
return ((Value - 4) >> 1) & 0xff;
case ARM::fixup_arm_pcrel_10:
Value = Value - 4; // ARM fixups offset by an additional word and don't
// need to adjust for the half-word ordering.
// Fall through.
case ARM::fixup_t2_pcrel_10: {
// Offset by 4, adjusted by two due to the half-word ordering of thumb.
Value = Value - 4;
bool isAdd = true;
if ((int64_t)Value < 0) {
Value = -Value;
isAdd = false;
}
// These values don't encode the low two bits since they're always zero.
Value >>= 2;
assert ((Value < 256) && "Out of range pc-relative fixup value!");
Value |= isAdd << 23;
// Same addressing mode as fixup_arm_pcrel_10,
// but with 16-bit halfwords swapped.
if (Kind == ARM::fixup_t2_pcrel_10) {
uint64_t swapped = (Value & 0xFFFF0000) >> 16;
swapped |= (Value & 0x0000FFFF) << 16;
return swapped;
}
return Value;
}
}
}
namespace {
// FIXME: This should be in a separate file.
// ELF is an ELF of course...
class ELFARMAsmBackend : public ARMAsmBackend {
MCELFObjectFormat Format;
public:
Triple::OSType OSType;
ELFARMAsmBackend(const Target &T, Triple::OSType _OSType)
: ARMAsmBackend(T), OSType(_OSType) {
HasScatteredSymbols = true;
}
virtual const MCObjectFormat &getObjectFormat() const {
return Format;
}
void ApplyFixup(const MCFixup &Fixup, char *Data, unsigned DataSize,
uint64_t Value) const;
MCObjectWriter *createObjectWriter(raw_ostream &OS) const {
return createELFObjectWriter(OS, /*Is64Bit=*/false,
OSType, ELF::EM_ARM,
/*IsLittleEndian=*/true,
/*HasRelocationAddend=*/false);
}
};
// FIXME: Raise this to share code between Darwin and ELF.
void ELFARMAsmBackend::ApplyFixup(const MCFixup &Fixup, char *Data,
unsigned DataSize, uint64_t Value) const {
unsigned NumBytes = 4; // FIXME: 2 for Thumb
Value = adjustFixupValue(Fixup.getKind(), Value);
if (!Value) return; // Doesn't change encoding.
unsigned Offset = Fixup.getOffset();
assert(Offset % NumBytes == 0 && "Offset mod NumBytes is nonzero!");
// For each byte of the fragment that the fixup touches, mask in the bits from
// the fixup value. The Value has been "split up" into the appropriate
// bitfields above.
for (unsigned i = 0; i != NumBytes; ++i)
Data[Offset + i] |= uint8_t((Value >> (i * 8)) & 0xff);
}
// FIXME: This should be in a separate file.
class DarwinARMAsmBackend : public ARMAsmBackend {
MCMachOObjectFormat Format;
public:
DarwinARMAsmBackend(const Target &T) : ARMAsmBackend(T) {
HasScatteredSymbols = true;
}
virtual const MCObjectFormat &getObjectFormat() const {
return Format;
}
void ApplyFixup(const MCFixup &Fixup, char *Data, unsigned DataSize,
uint64_t Value) const;
MCObjectWriter *createObjectWriter(raw_ostream &OS) const {
// FIXME: Subtarget info should be derived. Force v7 for now.
return createMachObjectWriter(OS, /*Is64Bit=*/false,
object::mach::CTM_ARM,
object::mach::CSARM_V7,
/*IsLittleEndian=*/true);
}
virtual bool doesSectionRequireSymbols(const MCSection &Section) const {
return false;
}
};
/// getFixupKindNumBytes - The number of bytes the fixup may change.
static unsigned getFixupKindNumBytes(unsigned Kind) {
switch (Kind) {
default:
llvm_unreachable("Unknown fixup kind!");
case ARM::fixup_arm_thumb_bcc:
case ARM::fixup_arm_thumb_cp:
return 1;
case ARM::fixup_arm_thumb_br:
case ARM::fixup_arm_thumb_cb:
return 2;
case ARM::fixup_arm_ldst_pcrel_12:
case ARM::fixup_arm_pcrel_10:
case ARM::fixup_arm_adr_pcrel_12:
case ARM::fixup_arm_branch:
return 3;
case FK_Data_4:
case ARM::fixup_t2_ldst_pcrel_12:
case ARM::fixup_t2_branch:
case ARM::fixup_t2_pcrel_10:
case ARM::fixup_arm_thumb_bl:
case ARM::fixup_arm_thumb_blx:
return 4;
}
}
void DarwinARMAsmBackend::ApplyFixup(const MCFixup &Fixup, char *Data,
unsigned DataSize, uint64_t Value) const {
unsigned NumBytes = getFixupKindNumBytes(Fixup.getKind());
Value = adjustFixupValue(Fixup.getKind(), Value);
if (!Value) return; // Doesn't change encoding.
unsigned Offset = Fixup.getOffset();
assert(Offset + NumBytes <= DataSize && "Invalid fixup offset!");
// For each byte of the fragment that the fixup touches, mask in the
// bits from the fixup value.
for (unsigned i = 0; i != NumBytes; ++i)
Data[Offset + i] |= uint8_t((Value >> (i * 8)) & 0xff);
}
} // end anonymous namespace
TargetAsmBackend *llvm::createARMAsmBackend(const Target &T,
const std::string &TT) {
switch (Triple(TT).getOS()) {
case Triple::Darwin:
return new DarwinARMAsmBackend(T);
case Triple::MinGW32:
case Triple::Cygwin:
case Triple::Win32:
assert(0 && "Windows not supported on ARM");
default:
return new ELFARMAsmBackend(T, Triple(TT).getOS());
}
}
<commit_msg>Trailing whitespace.<commit_after>//===-- ARMAsmBackend.cpp - ARM Assembler Backend -------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "ARM.h"
#include "ARMAddressingModes.h"
#include "ARMFixupKinds.h"
#include "llvm/ADT/Twine.h"
#include "llvm/MC/MCAssembler.h"
#include "llvm/MC/MCDirectives.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCObjectFormat.h"
#include "llvm/MC/MCObjectWriter.h"
#include "llvm/MC/MCSectionELF.h"
#include "llvm/MC/MCSectionMachO.h"
#include "llvm/Object/MachOFormat.h"
#include "llvm/Support/ELF.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetAsmBackend.h"
#include "llvm/Target/TargetRegistry.h"
using namespace llvm;
namespace {
class ARMAsmBackend : public TargetAsmBackend {
bool isThumbMode; // Currently emitting Thumb code.
public:
ARMAsmBackend(const Target &T) : TargetAsmBackend(), isThumbMode(false) {}
bool MayNeedRelaxation(const MCInst &Inst) const;
void RelaxInstruction(const MCInst &Inst, MCInst &Res) const;
bool WriteNopData(uint64_t Count, MCObjectWriter *OW) const;
void HandleAssemblerFlag(MCAssemblerFlag Flag) {
switch (Flag) {
default: break;
case MCAF_Code16:
setIsThumb(true);
break;
case MCAF_Code32:
setIsThumb(false);
break;
}
}
unsigned getPointerSize() const { return 4; }
bool isThumb() const { return isThumbMode; }
void setIsThumb(bool it) { isThumbMode = it; }
};
} // end anonymous namespace
bool ARMAsmBackend::MayNeedRelaxation(const MCInst &Inst) const {
// FIXME: Thumb targets, different move constant targets..
return false;
}
void ARMAsmBackend::RelaxInstruction(const MCInst &Inst, MCInst &Res) const {
assert(0 && "ARMAsmBackend::RelaxInstruction() unimplemented");
return;
}
bool ARMAsmBackend::WriteNopData(uint64_t Count, MCObjectWriter *OW) const {
if (isThumb()) {
assert (((Count & 1) == 0) && "Unaligned Nop data fragment!");
// FIXME: 0xbf00 is the ARMv7 value. For v6 and before, we'll need to
// use 0x46c0 (which is a 'mov r8, r8' insn).
Count /= 2;
for (uint64_t i = 0; i != Count; ++i)
OW->Write16(0xbf00);
return true;
}
// ARM mode
Count /= 4;
for (uint64_t i = 0; i != Count; ++i)
OW->Write32(0xe1a00000);
return true;
}
static unsigned adjustFixupValue(unsigned Kind, uint64_t Value) {
switch (Kind) {
default:
llvm_unreachable("Unknown fixup kind!");
case FK_Data_4:
return Value;
case ARM::fixup_arm_movt_hi16:
case ARM::fixup_arm_movw_lo16: {
unsigned Hi4 = (Value & 0xF000) >> 12;
unsigned Lo12 = Value & 0x0FFF;
// inst{19-16} = Hi4;
// inst{11-0} = Lo12;
Value = (Hi4 << 16) | (Lo12);
return Value;
}
case ARM::fixup_arm_ldst_pcrel_12:
// ARM PC-relative values are offset by 8.
Value -= 4;
// FALLTHROUGH
case ARM::fixup_t2_ldst_pcrel_12: {
// Offset by 4, adjusted by two due to the half-word ordering of thumb.
Value -= 4;
bool isAdd = true;
if ((int64_t)Value < 0) {
Value = -Value;
isAdd = false;
}
assert ((Value < 4096) && "Out of range pc-relative fixup value!");
Value |= isAdd << 23;
// Same addressing mode as fixup_arm_pcrel_10,
// but with 16-bit halfwords swapped.
if (Kind == ARM::fixup_t2_ldst_pcrel_12) {
uint64_t swapped = (Value & 0xFFFF0000) >> 16;
swapped |= (Value & 0x0000FFFF) << 16;
return swapped;
}
return Value;
}
case ARM::fixup_arm_adr_pcrel_12: {
// ARM PC-relative values are offset by 8.
Value -= 8;
unsigned opc = 4; // bits {24-21}. Default to add: 0b0100
if ((int64_t)Value < 0) {
Value = -Value;
opc = 2; // 0b0010
}
assert(ARM_AM::getSOImmVal(Value) != -1 &&
"Out of range pc-relative fixup value!");
// Encode the immediate and shift the opcode into place.
return ARM_AM::getSOImmVal(Value) | (opc << 21);
}
case ARM::fixup_arm_branch:
// These values don't encode the low two bits since they're always zero.
// Offset by 8 just as above.
return 0xffffff & ((Value - 8) >> 2);
case ARM::fixup_t2_branch: {
Value = Value - 4;
Value >>= 1; // Low bit is not encoded.
uint64_t out = 0;
out |= (Value & 0x80000) << 7; // S bit
out |= (Value & 0x40000) >> 7; // J2 bit
out |= (Value & 0x20000) >> 4; // J1 bit
out |= (Value & 0x1F800) << 5; // imm6 field
out |= (Value & 0x007FF); // imm11 field
uint64_t swapped = (out & 0xFFFF0000) >> 16;
swapped |= (out & 0x0000FFFF) << 16;
return swapped;
}
case ARM::fixup_arm_thumb_bl: {
// The value doesn't encode the low bit (always zero) and is offset by
// four. The value is encoded into disjoint bit positions in the destination
// opcode. x = unchanged, I = immediate value bit, S = sign extension bit
//
// BL: xxxxxSIIIIIIIIII xxxxxIIIIIIIIIII
//
// Note that the halfwords are stored high first, low second; so we need
// to transpose the fixup value here to map properly.
unsigned isNeg = (int64_t(Value) < 0) ? 1 : 0;
uint32_t Binary = 0;
Value = 0x3fffff & ((Value - 4) >> 1);
Binary = (Value & 0x7ff) << 16; // Low imm11 value.
Binary |= (Value & 0x1ffc00) >> 11; // High imm10 value.
Binary |= isNeg << 10; // Sign bit.
return Binary;
}
case ARM::fixup_arm_thumb_blx: {
// The value doesn't encode the low two bits (always zero) and is offset by
// four (see fixup_arm_thumb_cp). The value is encoded into disjoint bit
// positions in the destination opcode. x = unchanged, I = immediate value
// bit, S = sign extension bit, 0 = zero.
//
// BLX: xxxxxSIIIIIIIIII xxxxxIIIIIIIIII0
//
// Note that the halfwords are stored high first, low second; so we need
// to transpose the fixup value here to map properly.
unsigned isNeg = (int64_t(Value) < 0) ? 1 : 0;
uint32_t Binary = 0;
Value = 0xfffff & ((Value - 2) >> 2);
Binary = (Value & 0x3ff) << 17; // Low imm10L value.
Binary |= (Value & 0xffc00) >> 10; // High imm10H value.
Binary |= isNeg << 10; // Sign bit.
return Binary;
}
case ARM::fixup_arm_thumb_cp:
// Offset by 4, and don't encode the low two bits. Two bytes of that
// 'off by 4' is implicitly handled by the half-word ordering of the
// Thumb encoding, so we only need to adjust by 2 here.
return ((Value - 2) >> 2) & 0xff;
case ARM::fixup_arm_thumb_cb: {
// Offset by 4 and don't encode the lower bit, which is always 0.
uint32_t Binary = (Value - 4) >> 1;
return ((Binary & 0x20) << 9) | ((Binary & 0x1f) << 3);
}
case ARM::fixup_arm_thumb_br:
// Offset by 4 and don't encode the lower bit, which is always 0.
return ((Value - 4) >> 1) & 0x7ff;
case ARM::fixup_arm_thumb_bcc:
// Offset by 4 and don't encode the lower bit, which is always 0.
return ((Value - 4) >> 1) & 0xff;
case ARM::fixup_arm_pcrel_10:
Value = Value - 4; // ARM fixups offset by an additional word and don't
// need to adjust for the half-word ordering.
// Fall through.
case ARM::fixup_t2_pcrel_10: {
// Offset by 4, adjusted by two due to the half-word ordering of thumb.
Value = Value - 4;
bool isAdd = true;
if ((int64_t)Value < 0) {
Value = -Value;
isAdd = false;
}
// These values don't encode the low two bits since they're always zero.
Value >>= 2;
assert ((Value < 256) && "Out of range pc-relative fixup value!");
Value |= isAdd << 23;
// Same addressing mode as fixup_arm_pcrel_10,
// but with 16-bit halfwords swapped.
if (Kind == ARM::fixup_t2_pcrel_10) {
uint64_t swapped = (Value & 0xFFFF0000) >> 16;
swapped |= (Value & 0x0000FFFF) << 16;
return swapped;
}
return Value;
}
}
}
namespace {
// FIXME: This should be in a separate file.
// ELF is an ELF of course...
class ELFARMAsmBackend : public ARMAsmBackend {
MCELFObjectFormat Format;
public:
Triple::OSType OSType;
ELFARMAsmBackend(const Target &T, Triple::OSType _OSType)
: ARMAsmBackend(T), OSType(_OSType) {
HasScatteredSymbols = true;
}
virtual const MCObjectFormat &getObjectFormat() const {
return Format;
}
void ApplyFixup(const MCFixup &Fixup, char *Data, unsigned DataSize,
uint64_t Value) const;
MCObjectWriter *createObjectWriter(raw_ostream &OS) const {
return createELFObjectWriter(OS, /*Is64Bit=*/false,
OSType, ELF::EM_ARM,
/*IsLittleEndian=*/true,
/*HasRelocationAddend=*/false);
}
};
// FIXME: Raise this to share code between Darwin and ELF.
void ELFARMAsmBackend::ApplyFixup(const MCFixup &Fixup, char *Data,
unsigned DataSize, uint64_t Value) const {
unsigned NumBytes = 4; // FIXME: 2 for Thumb
Value = adjustFixupValue(Fixup.getKind(), Value);
if (!Value) return; // Doesn't change encoding.
unsigned Offset = Fixup.getOffset();
assert(Offset % NumBytes == 0 && "Offset mod NumBytes is nonzero!");
// For each byte of the fragment that the fixup touches, mask in the bits from
// the fixup value. The Value has been "split up" into the appropriate
// bitfields above.
for (unsigned i = 0; i != NumBytes; ++i)
Data[Offset + i] |= uint8_t((Value >> (i * 8)) & 0xff);
}
// FIXME: This should be in a separate file.
class DarwinARMAsmBackend : public ARMAsmBackend {
MCMachOObjectFormat Format;
public:
DarwinARMAsmBackend(const Target &T) : ARMAsmBackend(T) {
HasScatteredSymbols = true;
}
virtual const MCObjectFormat &getObjectFormat() const {
return Format;
}
void ApplyFixup(const MCFixup &Fixup, char *Data, unsigned DataSize,
uint64_t Value) const;
MCObjectWriter *createObjectWriter(raw_ostream &OS) const {
// FIXME: Subtarget info should be derived. Force v7 for now.
return createMachObjectWriter(OS, /*Is64Bit=*/false,
object::mach::CTM_ARM,
object::mach::CSARM_V7,
/*IsLittleEndian=*/true);
}
virtual bool doesSectionRequireSymbols(const MCSection &Section) const {
return false;
}
};
/// getFixupKindNumBytes - The number of bytes the fixup may change.
static unsigned getFixupKindNumBytes(unsigned Kind) {
switch (Kind) {
default:
llvm_unreachable("Unknown fixup kind!");
case ARM::fixup_arm_thumb_bcc:
case ARM::fixup_arm_thumb_cp:
return 1;
case ARM::fixup_arm_thumb_br:
case ARM::fixup_arm_thumb_cb:
return 2;
case ARM::fixup_arm_ldst_pcrel_12:
case ARM::fixup_arm_pcrel_10:
case ARM::fixup_arm_adr_pcrel_12:
case ARM::fixup_arm_branch:
return 3;
case FK_Data_4:
case ARM::fixup_t2_ldst_pcrel_12:
case ARM::fixup_t2_branch:
case ARM::fixup_t2_pcrel_10:
case ARM::fixup_arm_thumb_bl:
case ARM::fixup_arm_thumb_blx:
return 4;
}
}
void DarwinARMAsmBackend::ApplyFixup(const MCFixup &Fixup, char *Data,
unsigned DataSize, uint64_t Value) const {
unsigned NumBytes = getFixupKindNumBytes(Fixup.getKind());
Value = adjustFixupValue(Fixup.getKind(), Value);
if (!Value) return; // Doesn't change encoding.
unsigned Offset = Fixup.getOffset();
assert(Offset + NumBytes <= DataSize && "Invalid fixup offset!");
// For each byte of the fragment that the fixup touches, mask in the
// bits from the fixup value.
for (unsigned i = 0; i != NumBytes; ++i)
Data[Offset + i] |= uint8_t((Value >> (i * 8)) & 0xff);
}
} // end anonymous namespace
TargetAsmBackend *llvm::createARMAsmBackend(const Target &T,
const std::string &TT) {
switch (Triple(TT).getOS()) {
case Triple::Darwin:
return new DarwinARMAsmBackend(T);
case Triple::MinGW32:
case Triple::Cygwin:
case Triple::Win32:
assert(0 && "Windows not supported on ARM");
default:
return new ELFARMAsmBackend(T, Triple(TT).getOS());
}
}
<|endoftext|> |
<commit_before>//===-- ARMAsmPrinter.cpp - ARM LLVM assembly writer ----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the "Instituto Nokia de Tecnologia" and
// is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains a printer that converts from our internal representation
// of machine-dependent LLVM code to GAS-format ARM assembly language.
//
//===----------------------------------------------------------------------===//
#include "ARM.h"
#include "ARMInstrInfo.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Module.h"
#include "llvm/Assembly/Writer.h"
#include "llvm/CodeGen/AsmPrinter.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineConstantPool.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Support/Mangler.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/MathExtras.h"
#include <cctype>
#include <iostream>
using namespace llvm;
namespace {
Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
struct ARMAsmPrinter : public AsmPrinter {
ARMAsmPrinter(std::ostream &O, TargetMachine &TM) : AsmPrinter(O, TM) {
Data16bitsDirective = "\t.half\t";
Data32bitsDirective = "\t.word\t";
Data64bitsDirective = 0;
ZeroDirective = "\t.skip\t";
CommentString = "!";
ConstantPoolSection = "\t.section \".rodata\",#alloc\n";
AlignmentIsInBytes = false;
}
/// We name each basic block in a Function with a unique number, so
/// that we can consistently refer to them later. This is cleared
/// at the beginning of each call to runOnMachineFunction().
///
typedef std::map<const Value *, unsigned> ValueMapTy;
ValueMapTy NumberForBB;
virtual const char *getPassName() const {
return "ARM Assembly Printer";
}
void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
printOperand(MI, OpNo + 1);
O << ", ";
printOperand(MI, OpNo);
}
void printOperand(const MachineInstr *MI, int opNum);
void printMemOperand(const MachineInstr *MI, int opNum,
const char *Modifier = 0);
void printCCOperand(const MachineInstr *MI, int opNum);
bool printInstruction(const MachineInstr *MI); // autogenerated.
bool runOnMachineFunction(MachineFunction &F);
bool doInitialization(Module &M);
bool doFinalization(Module &M);
};
} // end of anonymous namespace
#include "ARMGenAsmWriter.inc"
/// createARMCodePrinterPass - Returns a pass that prints the ARM
/// assembly code for a MachineFunction to the given output stream,
/// using the given target machine description. This should work
/// regardless of whether the function is in SSA form.
///
FunctionPass *llvm::createARMCodePrinterPass(std::ostream &o,
TargetMachine &tm) {
return new ARMAsmPrinter(o, tm);
}
/// runOnMachineFunction - This uses the printMachineInstruction()
/// method to print assembly for each instruction.
///
bool ARMAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
SetupMachineFunction(MF);
O << "\n\n";
// Print out constants referenced by the function
EmitConstantPool(MF.getConstantPool());
// Print out jump tables referenced by the function
EmitJumpTableInfo(MF.getJumpTableInfo());
// Print out labels for the function.
const Function *F = MF.getFunction();
switch (F->getLinkage()) {
default: assert(0 && "Unknown linkage type!");
case Function::InternalLinkage:
SwitchToTextSection("\t.text", F);
break;
case Function::ExternalLinkage:
SwitchToTextSection("\t.text", F);
O << "\t.globl\t" << CurrentFnName << "\n";
break;
case Function::WeakLinkage:
case Function::LinkOnceLinkage:
assert(0 && "Not implemented");
break;
}
EmitAlignment(2, F);
O << CurrentFnName << ":\n";
// Print out code for the function.
for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
I != E; ++I) {
// Print a label for the basic block.
if (I != MF.begin()) {
printBasicBlockLabel(I, true);
O << '\n';
}
for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
II != E; ++II) {
// Print the assembly for the instruction.
O << "\t";
printInstruction(II);
}
}
return false;
}
void ARMAsmPrinter::printOperand(const MachineInstr *MI, int opNum) {
const MachineOperand &MO = MI->getOperand (opNum);
const MRegisterInfo &RI = *TM.getRegisterInfo();
switch (MO.getType()) {
case MachineOperand::MO_Register:
if (MRegisterInfo::isPhysicalRegister(MO.getReg()))
O << LowercaseString (RI.get(MO.getReg()).Name);
else
assert(0 && "not implemented");
break;
case MachineOperand::MO_Immediate:
O << "#" << (int)MO.getImmedValue();
break;
case MachineOperand::MO_MachineBasicBlock:
assert(0 && "not implemented");
abort();
return;
case MachineOperand::MO_GlobalAddress: {
GlobalValue *GV = MO.getGlobal();
std::string Name = Mang->getValueName(GV);
O << Name;
}
break;
case MachineOperand::MO_ExternalSymbol:
assert(0 && "not implemented");
abort();
break;
case MachineOperand::MO_ConstantPoolIndex:
assert(0 && "not implemented");
abort();
break;
default:
O << "<unknown operand type>"; abort (); break;
}
}
void ARMAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
const char *Modifier) {
assert(0 && "not implemented");
}
void ARMAsmPrinter::printCCOperand(const MachineInstr *MI, int opNum) {
assert(0 && "not implemented");
}
bool ARMAsmPrinter::doInitialization(Module &M) {
Mang = new Mangler(M);
return false; // success
}
bool ARMAsmPrinter::doFinalization(Module &M) {
AsmPrinter::doFinalization(M);
return false; // success
}
<commit_msg>emit global constants<commit_after>//===-- ARMAsmPrinter.cpp - ARM LLVM assembly writer ----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the "Instituto Nokia de Tecnologia" and
// is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains a printer that converts from our internal representation
// of machine-dependent LLVM code to GAS-format ARM assembly language.
//
//===----------------------------------------------------------------------===//
#include "ARM.h"
#include "ARMInstrInfo.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Module.h"
#include "llvm/Assembly/Writer.h"
#include "llvm/CodeGen/AsmPrinter.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineConstantPool.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Support/Mangler.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/MathExtras.h"
#include <cctype>
#include <iostream>
using namespace llvm;
namespace {
Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
struct ARMAsmPrinter : public AsmPrinter {
ARMAsmPrinter(std::ostream &O, TargetMachine &TM) : AsmPrinter(O, TM) {
Data16bitsDirective = "\t.half\t";
Data32bitsDirective = "\t.word\t";
Data64bitsDirective = 0;
ZeroDirective = "\t.skip\t";
CommentString = "!";
ConstantPoolSection = "\t.section \".rodata\",#alloc\n";
AlignmentIsInBytes = false;
}
/// We name each basic block in a Function with a unique number, so
/// that we can consistently refer to them later. This is cleared
/// at the beginning of each call to runOnMachineFunction().
///
typedef std::map<const Value *, unsigned> ValueMapTy;
ValueMapTy NumberForBB;
virtual const char *getPassName() const {
return "ARM Assembly Printer";
}
void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
printOperand(MI, OpNo + 1);
O << ", ";
printOperand(MI, OpNo);
}
void printOperand(const MachineInstr *MI, int opNum);
void printMemOperand(const MachineInstr *MI, int opNum,
const char *Modifier = 0);
void printCCOperand(const MachineInstr *MI, int opNum);
bool printInstruction(const MachineInstr *MI); // autogenerated.
bool runOnMachineFunction(MachineFunction &F);
bool doInitialization(Module &M);
bool doFinalization(Module &M);
};
} // end of anonymous namespace
#include "ARMGenAsmWriter.inc"
/// createARMCodePrinterPass - Returns a pass that prints the ARM
/// assembly code for a MachineFunction to the given output stream,
/// using the given target machine description. This should work
/// regardless of whether the function is in SSA form.
///
FunctionPass *llvm::createARMCodePrinterPass(std::ostream &o,
TargetMachine &tm) {
return new ARMAsmPrinter(o, tm);
}
/// runOnMachineFunction - This uses the printMachineInstruction()
/// method to print assembly for each instruction.
///
bool ARMAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
SetupMachineFunction(MF);
O << "\n\n";
// Print out constants referenced by the function
EmitConstantPool(MF.getConstantPool());
// Print out jump tables referenced by the function
EmitJumpTableInfo(MF.getJumpTableInfo());
// Print out labels for the function.
const Function *F = MF.getFunction();
switch (F->getLinkage()) {
default: assert(0 && "Unknown linkage type!");
case Function::InternalLinkage:
SwitchToTextSection("\t.text", F);
break;
case Function::ExternalLinkage:
SwitchToTextSection("\t.text", F);
O << "\t.globl\t" << CurrentFnName << "\n";
break;
case Function::WeakLinkage:
case Function::LinkOnceLinkage:
assert(0 && "Not implemented");
break;
}
EmitAlignment(2, F);
O << CurrentFnName << ":\n";
// Print out code for the function.
for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
I != E; ++I) {
// Print a label for the basic block.
if (I != MF.begin()) {
printBasicBlockLabel(I, true);
O << '\n';
}
for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
II != E; ++II) {
// Print the assembly for the instruction.
O << "\t";
printInstruction(II);
}
}
return false;
}
void ARMAsmPrinter::printOperand(const MachineInstr *MI, int opNum) {
const MachineOperand &MO = MI->getOperand (opNum);
const MRegisterInfo &RI = *TM.getRegisterInfo();
switch (MO.getType()) {
case MachineOperand::MO_Register:
if (MRegisterInfo::isPhysicalRegister(MO.getReg()))
O << LowercaseString (RI.get(MO.getReg()).Name);
else
assert(0 && "not implemented");
break;
case MachineOperand::MO_Immediate:
O << "#" << (int)MO.getImmedValue();
break;
case MachineOperand::MO_MachineBasicBlock:
assert(0 && "not implemented");
abort();
return;
case MachineOperand::MO_GlobalAddress: {
GlobalValue *GV = MO.getGlobal();
std::string Name = Mang->getValueName(GV);
O << Name;
}
break;
case MachineOperand::MO_ExternalSymbol:
assert(0 && "not implemented");
abort();
break;
case MachineOperand::MO_ConstantPoolIndex:
assert(0 && "not implemented");
abort();
break;
default:
O << "<unknown operand type>"; abort (); break;
}
}
void ARMAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
const char *Modifier) {
assert(0 && "not implemented");
}
void ARMAsmPrinter::printCCOperand(const MachineInstr *MI, int opNum) {
assert(0 && "not implemented");
}
bool ARMAsmPrinter::doInitialization(Module &M) {
Mang = new Mangler(M);
return false; // success
}
bool ARMAsmPrinter::doFinalization(Module &M) {
const TargetData *TD = TM.getTargetData();
for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
I != E; ++I) {
if (!I->hasInitializer()) // External global require no code
continue;
if (EmitSpecialLLVMGlobal(I))
continue;
O << "\n\n";
std::string name = Mang->getValueName(I);
Constant *C = I->getInitializer();
unsigned Size = TD->getTypeSize(C->getType());
unsigned Align = TD->getTypeAlignment(C->getType());
assert (I->getLinkage() == GlobalValue::ExternalLinkage);
O << "\t.globl " << name << "\n";
assert (!C->isNullValue());
SwitchToDataSection(".data", I);
EmitAlignment(Align, I);
O << "\t.type " << name << ", %object\n";
O << "\t.size " << name << ", " << Size << "\n";
O << name << ":\n";
EmitGlobalConstant(C);
}
AsmPrinter::doFinalization(M);
return false; // success
}
<|endoftext|> |
<commit_before>//===-- X86AsmPrinter.cpp - Convert X86 LLVM IR to X86 assembly -----------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file the shared super class printer that converts from our internal
// representation of machine-dependent LLVM code to Intel and AT&T format
// assembly language.
// This printer is the output mechanism used by `llc'.
//
//===----------------------------------------------------------------------===//
#include "X86AsmPrinter.h"
#include "X86ATTAsmPrinter.h"
#include "X86IntelAsmPrinter.h"
#include "X86Subtarget.h"
#include "llvm/Constants.h"
#include "llvm/Module.h"
#include "llvm/Type.h"
#include "llvm/Assembly/Writer.h"
#include "llvm/Support/Mangler.h"
#include "llvm/Support/CommandLine.h"
using namespace llvm;
Statistic<> llvm::EmittedInsts("asm-printer",
"Number of machine instrs printed");
enum AsmWriterFlavorTy { att, intel };
cl::opt<AsmWriterFlavorTy>
AsmWriterFlavor("x86-asm-syntax",
cl::desc("Choose style of code to emit from X86 backend:"),
cl::values(
clEnumVal(att, " Emit AT&T-style assembly"),
clEnumVal(intel, " Emit Intel-style assembly"),
clEnumValEnd),
#ifdef _MSC_VER
cl::init(intel)
#else
cl::init(att)
#endif
);
/// doInitialization
bool X86SharedAsmPrinter::doInitialization(Module &M) {
PrivateGlobalPrefix = ".L";
DefaultTextSection = ".text";
DefaultDataSection = ".data";
switch (Subtarget->TargetType) {
case X86Subtarget::isDarwin:
AlignmentIsInBytes = false;
GlobalPrefix = "_";
Data64bitsDirective = 0; // we can't emit a 64-bit unit
ZeroDirective = "\t.space\t"; // ".space N" emits N zeros.
PrivateGlobalPrefix = "L"; // Marker for constant pool idxs
ConstantPoolSection = "\t.const\n";
JumpTableSection = "\t.const\n"; // FIXME: depends on PIC mode
LCOMMDirective = "\t.lcomm\t";
COMMDirectiveTakesAlignment = false;
HasDotTypeDotSizeDirective = false;
StaticCtorsSection = ".mod_init_func";
StaticDtorsSection = ".mod_term_func";
InlineAsmStart = "# InlineAsm Start";
InlineAsmEnd = "# InlineAsm End";
break;
case X86Subtarget::isCygwin:
GlobalPrefix = "_";
COMMDirectiveTakesAlignment = false;
HasDotTypeDotSizeDirective = false;
StaticCtorsSection = "\t.section .ctors,\"aw\"";
StaticDtorsSection = "\t.section .dtors,\"aw\"";
break;
case X86Subtarget::isWindows:
GlobalPrefix = "_";
HasDotTypeDotSizeDirective = false;
break;
default: break;
}
if (Subtarget->TargetType == X86Subtarget::isDarwin) {
// Emit initial debug information.
DW.BeginModule(&M);
}
return AsmPrinter::doInitialization(M);
}
bool X86SharedAsmPrinter::doFinalization(Module &M) {
// Note: this code is not shared by the Intel printer as it is too different
// from how MASM does things. When making changes here don't forget to look
// at X86IntelAsmPrinter::doFinalization().
const TargetData *TD = TM.getTargetData();
// Print out module-level global variables here.
for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
I != E; ++I) {
if (!I->hasInitializer()) continue; // External global require no code
// Check to see if this is a special global used by LLVM, if so, emit it.
if (EmitSpecialLLVMGlobal(I))
continue;
std::string name = Mang->getValueName(I);
Constant *C = I->getInitializer();
unsigned Size = TD->getTypeSize(C->getType());
unsigned Align = getPreferredAlignmentLog(I);
if (C->isNullValue() && /* FIXME: Verify correct */
(I->hasInternalLinkage() || I->hasWeakLinkage() ||
I->hasLinkOnceLinkage() ||
(Subtarget->TargetType == X86Subtarget::isDarwin &&
I->hasExternalLinkage() && !I->hasSection()))) {
if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
if (I->hasExternalLinkage()) {
O << "\t.globl\t" << name << "\n";
O << "\t.zerofill __DATA__, __common, " << name << ", "
<< Size << ", " << Align;
} else {
SwitchToDataSection(DefaultDataSection, I);
if (LCOMMDirective != NULL) {
if (I->hasInternalLinkage()) {
O << LCOMMDirective << name << "," << Size;
if (Subtarget->TargetType == X86Subtarget::isDarwin)
O << "," << (AlignmentIsInBytes ? (1 << Align) : Align);
} else
O << COMMDirective << name << "," << Size;
} else {
if (Subtarget->TargetType != X86Subtarget::isCygwin) {
if (I->hasInternalLinkage())
O << "\t.local\t" << name << "\n";
}
O << COMMDirective << name << "," << Size;
if (COMMDirectiveTakesAlignment)
O << "," << (AlignmentIsInBytes ? (1 << Align) : Align);
}
}
O << "\t\t" << CommentString << " " << I->getName() << "\n";
} else {
switch (I->getLinkage()) {
case GlobalValue::LinkOnceLinkage:
case GlobalValue::WeakLinkage:
if (Subtarget->TargetType == X86Subtarget::isDarwin) {
O << "\t.globl " << name << "\n"
<< "\t.weak_definition " << name << "\n";
SwitchToDataSection(".section __DATA,__datacoal_nt,coalesced", I);
} else if (Subtarget->TargetType == X86Subtarget::isCygwin) {
O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\"\n"
<< "\t.weak " << name << "\n";
} else {
O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n"
<< "\t.weak " << name << "\n";
}
break;
case GlobalValue::AppendingLinkage:
// FIXME: appending linkage variables should go into a section of
// their name or something. For now, just emit them as external.
case GlobalValue::ExternalLinkage:
// If external or appending, declare as a global symbol
O << "\t.globl " << name << "\n";
// FALL THROUGH
case GlobalValue::InternalLinkage:
SwitchToDataSection(DefaultDataSection, I);
break;
default:
assert(0 && "Unknown linkage type!");
}
EmitAlignment(Align, I);
O << name << ":\t\t\t\t" << CommentString << " " << I->getName()
<< "\n";
if (HasDotTypeDotSizeDirective)
O << "\t.size " << name << ", " << Size << "\n";
EmitGlobalConstant(C);
O << '\n';
}
}
if (Subtarget->TargetType == X86Subtarget::isDarwin) {
SwitchToDataSection("", 0);
// Output stubs for dynamically-linked functions
unsigned j = 1;
for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
i != e; ++i, ++j) {
SwitchToDataSection(".section __IMPORT,__jump_table,symbol_stubs,"
"self_modifying_code+pure_instructions,5", 0);
O << "L" << *i << "$stub:\n";
O << "\t.indirect_symbol " << *i << "\n";
O << "\thlt ; hlt ; hlt ; hlt ; hlt\n";
}
O << "\n";
// Output stubs for external and common global variables.
if (GVStubs.begin() != GVStubs.end())
SwitchToDataSection(
".section __IMPORT,__pointers,non_lazy_symbol_pointers", 0);
for (std::set<std::string>::iterator i = GVStubs.begin(), e = GVStubs.end();
i != e; ++i) {
O << "L" << *i << "$non_lazy_ptr:\n";
O << "\t.indirect_symbol " << *i << "\n";
O << "\t.long\t0\n";
}
// Emit initial debug information.
DW.EndModule();
// Funny Darwin hack: This flag tells the linker that no global symbols
// contain code that falls through to other global symbols (e.g. the obvious
// implementation of multiple entry points). If this doesn't occur, the
// linker can safely perform dead code stripping. Since LLVM never
// generates code that does this, it is always safe to set.
O << "\t.subsections_via_symbols\n";
}
AsmPrinter::doFinalization(M);
return false; // success
}
/// createX86CodePrinterPass - Returns a pass that prints the X86 assembly code
/// for a MachineFunction to the given output stream, using the given target
/// machine description.
///
FunctionPass *llvm::createX86CodePrinterPass(std::ostream &o,
X86TargetMachine &tm){
switch (AsmWriterFlavor) {
default:
assert(0 && "Unknown asm flavor!");
case intel:
return new X86IntelAsmPrinter(o, tm);
case att:
return new X86ATTAsmPrinter(o, tm);
}
}
<commit_msg>Be consistent with gcc.<commit_after>//===-- X86AsmPrinter.cpp - Convert X86 LLVM IR to X86 assembly -----------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file the shared super class printer that converts from our internal
// representation of machine-dependent LLVM code to Intel and AT&T format
// assembly language.
// This printer is the output mechanism used by `llc'.
//
//===----------------------------------------------------------------------===//
#include "X86AsmPrinter.h"
#include "X86ATTAsmPrinter.h"
#include "X86IntelAsmPrinter.h"
#include "X86Subtarget.h"
#include "llvm/Constants.h"
#include "llvm/Module.h"
#include "llvm/Type.h"
#include "llvm/Assembly/Writer.h"
#include "llvm/Support/Mangler.h"
#include "llvm/Support/CommandLine.h"
using namespace llvm;
Statistic<> llvm::EmittedInsts("asm-printer",
"Number of machine instrs printed");
enum AsmWriterFlavorTy { att, intel };
cl::opt<AsmWriterFlavorTy>
AsmWriterFlavor("x86-asm-syntax",
cl::desc("Choose style of code to emit from X86 backend:"),
cl::values(
clEnumVal(att, " Emit AT&T-style assembly"),
clEnumVal(intel, " Emit Intel-style assembly"),
clEnumValEnd),
#ifdef _MSC_VER
cl::init(intel)
#else
cl::init(att)
#endif
);
/// doInitialization
bool X86SharedAsmPrinter::doInitialization(Module &M) {
PrivateGlobalPrefix = ".L";
DefaultTextSection = ".text";
DefaultDataSection = ".data";
switch (Subtarget->TargetType) {
case X86Subtarget::isDarwin:
AlignmentIsInBytes = false;
GlobalPrefix = "_";
Data64bitsDirective = 0; // we can't emit a 64-bit unit
ZeroDirective = "\t.space\t"; // ".space N" emits N zeros.
PrivateGlobalPrefix = "L"; // Marker for constant pool idxs
ConstantPoolSection = "\t.const\n";
JumpTableSection = "\t.const\n"; // FIXME: depends on PIC mode
LCOMMDirective = "\t.lcomm\t";
COMMDirectiveTakesAlignment = false;
HasDotTypeDotSizeDirective = false;
StaticCtorsSection = ".mod_init_func";
StaticDtorsSection = ".mod_term_func";
InlineAsmStart = "# InlineAsm Start";
InlineAsmEnd = "# InlineAsm End";
break;
case X86Subtarget::isCygwin:
GlobalPrefix = "_";
COMMDirectiveTakesAlignment = false;
HasDotTypeDotSizeDirective = false;
StaticCtorsSection = "\t.section .ctors,\"aw\"";
StaticDtorsSection = "\t.section .dtors,\"aw\"";
break;
case X86Subtarget::isWindows:
GlobalPrefix = "_";
HasDotTypeDotSizeDirective = false;
break;
default: break;
}
if (Subtarget->TargetType == X86Subtarget::isDarwin) {
// Emit initial debug information.
DW.BeginModule(&M);
}
return AsmPrinter::doInitialization(M);
}
bool X86SharedAsmPrinter::doFinalization(Module &M) {
// Note: this code is not shared by the Intel printer as it is too different
// from how MASM does things. When making changes here don't forget to look
// at X86IntelAsmPrinter::doFinalization().
const TargetData *TD = TM.getTargetData();
// Print out module-level global variables here.
for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
I != E; ++I) {
if (!I->hasInitializer()) continue; // External global require no code
// Check to see if this is a special global used by LLVM, if so, emit it.
if (EmitSpecialLLVMGlobal(I))
continue;
std::string name = Mang->getValueName(I);
Constant *C = I->getInitializer();
unsigned Size = TD->getTypeSize(C->getType());
unsigned Align = getPreferredAlignmentLog(I);
if (C->isNullValue() && /* FIXME: Verify correct */
(I->hasInternalLinkage() || I->hasWeakLinkage() ||
I->hasLinkOnceLinkage() ||
(Subtarget->TargetType == X86Subtarget::isDarwin &&
I->hasExternalLinkage() && !I->hasSection()))) {
if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
if (I->hasExternalLinkage()) {
O << "\t.globl\t" << name << "\n";
O << "\t.zerofill __DATA__, __common, " << name << ", "
<< Size << ", " << Align;
} else {
SwitchToDataSection(DefaultDataSection, I);
if (LCOMMDirective != NULL) {
if (I->hasInternalLinkage()) {
O << LCOMMDirective << name << "," << Size;
if (Subtarget->TargetType == X86Subtarget::isDarwin)
O << "," << (AlignmentIsInBytes ? (1 << Align) : Align);
} else
O << COMMDirective << name << "," << Size;
} else {
if (Subtarget->TargetType != X86Subtarget::isCygwin) {
if (I->hasInternalLinkage())
O << "\t.local\t" << name << "\n";
}
O << COMMDirective << name << "," << Size;
if (COMMDirectiveTakesAlignment)
O << "," << (AlignmentIsInBytes ? (1 << Align) : Align);
}
}
O << "\t\t" << CommentString << " " << I->getName() << "\n";
} else {
switch (I->getLinkage()) {
case GlobalValue::LinkOnceLinkage:
case GlobalValue::WeakLinkage:
if (Subtarget->TargetType == X86Subtarget::isDarwin) {
O << "\t.globl " << name << "\n"
<< "\t.weak_definition " << name << "\n";
SwitchToDataSection(".section __DATA,__const_coal,coalesced", I);
} else if (Subtarget->TargetType == X86Subtarget::isCygwin) {
O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\"\n"
<< "\t.weak " << name << "\n";
} else {
O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n"
<< "\t.weak " << name << "\n";
}
break;
case GlobalValue::AppendingLinkage:
// FIXME: appending linkage variables should go into a section of
// their name or something. For now, just emit them as external.
case GlobalValue::ExternalLinkage:
// If external or appending, declare as a global symbol
O << "\t.globl " << name << "\n";
// FALL THROUGH
case GlobalValue::InternalLinkage:
SwitchToDataSection(DefaultDataSection, I);
break;
default:
assert(0 && "Unknown linkage type!");
}
EmitAlignment(Align, I);
O << name << ":\t\t\t\t" << CommentString << " " << I->getName()
<< "\n";
if (HasDotTypeDotSizeDirective)
O << "\t.size " << name << ", " << Size << "\n";
EmitGlobalConstant(C);
O << '\n';
}
}
if (Subtarget->TargetType == X86Subtarget::isDarwin) {
SwitchToDataSection("", 0);
// Output stubs for dynamically-linked functions
unsigned j = 1;
for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
i != e; ++i, ++j) {
SwitchToDataSection(".section __IMPORT,__jump_table,symbol_stubs,"
"self_modifying_code+pure_instructions,5", 0);
O << "L" << *i << "$stub:\n";
O << "\t.indirect_symbol " << *i << "\n";
O << "\thlt ; hlt ; hlt ; hlt ; hlt\n";
}
O << "\n";
// Output stubs for external and common global variables.
if (GVStubs.begin() != GVStubs.end())
SwitchToDataSection(
".section __IMPORT,__pointers,non_lazy_symbol_pointers", 0);
for (std::set<std::string>::iterator i = GVStubs.begin(), e = GVStubs.end();
i != e; ++i) {
O << "L" << *i << "$non_lazy_ptr:\n";
O << "\t.indirect_symbol " << *i << "\n";
O << "\t.long\t0\n";
}
// Emit initial debug information.
DW.EndModule();
// Funny Darwin hack: This flag tells the linker that no global symbols
// contain code that falls through to other global symbols (e.g. the obvious
// implementation of multiple entry points). If this doesn't occur, the
// linker can safely perform dead code stripping. Since LLVM never
// generates code that does this, it is always safe to set.
O << "\t.subsections_via_symbols\n";
}
AsmPrinter::doFinalization(M);
return false; // success
}
/// createX86CodePrinterPass - Returns a pass that prints the X86 assembly code
/// for a MachineFunction to the given output stream, using the given target
/// machine description.
///
FunctionPass *llvm::createX86CodePrinterPass(std::ostream &o,
X86TargetMachine &tm){
switch (AsmWriterFlavor) {
default:
assert(0 && "Unknown asm flavor!");
case intel:
return new X86IntelAsmPrinter(o, tm);
case att:
return new X86ATTAsmPrinter(o, tm);
}
}
<|endoftext|> |
<commit_before>//===-- GlobalDCE.cpp - DCE unreachable internal functions ----------------===//
//
// This transform is designed to eliminate unreachable internal globals
// FIXME: GlobalDCE should update the callgraph, not destroy it!
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/IPO.h"
#include "llvm/Module.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Analysis/CallGraph.h"
#include "Support/DepthFirstIterator.h"
#include "Support/Statistic.h"
#include <algorithm>
namespace {
Statistic<> NumFunctions("globaldce","Number of functions removed");
Statistic<> NumVariables("globaldce","Number of global variables removed");
Statistic<> NumCPRs("globaldce", "Number of const pointer refs removed");
Statistic<> NumConsts("globaldce", "Number of init constants removed");
bool RemoveUnreachableFunctions(Module &M, CallGraph &CallGraph) {
// Calculate which functions are reachable from the external functions in
// the call graph.
//
std::set<CallGraphNode*> ReachableNodes(df_begin(&CallGraph),
df_end(&CallGraph));
// Loop over the functions in the module twice. The first time is used to
// drop references that functions have to each other before they are
// deleted. The second pass removes the functions that need to be removed.
//
std::vector<CallGraphNode*> FunctionsToDelete; // Track unused functions
for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
CallGraphNode *N = CallGraph[I];
if (!ReachableNodes.count(N)) { // Not reachable??
I->dropAllReferences();
N->removeAllCalledFunctions();
FunctionsToDelete.push_back(N);
++NumFunctions;
}
}
// Nothing to do if no unreachable functions have been found...
if (FunctionsToDelete.empty()) return false;
// Unreachables functions have been found and should have no references to
// them, delete them now.
//
for (std::vector<CallGraphNode*>::iterator I = FunctionsToDelete.begin(),
E = FunctionsToDelete.end(); I != E; ++I)
delete CallGraph.removeFunctionFromModule(*I);
return true;
}
struct GlobalDCE : public Pass {
// run - Do the GlobalDCE pass on the specified module, optionally updating
// the specified callgraph to reflect the changes.
//
bool run(Module &M) {
return RemoveUnreachableFunctions(M, getAnalysis<CallGraph>()) |
RemoveUnreachableGlobalVariables(M);
}
// getAnalysisUsage - This function works on the call graph of a module.
// It is capable of updating the call graph to reflect the new state of the
// module.
//
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<CallGraph>();
}
private:
std::vector<GlobalValue*> WorkList;
inline bool RemoveIfDead(GlobalValue *GV);
void DestroyInitializer(Constant *C);
bool RemoveUnreachableGlobalVariables(Module &M);
bool RemoveUnusedConstantPointerRef(GlobalValue &GV);
bool SafeToDestroyConstant(Constant *C);
};
RegisterOpt<GlobalDCE> X("globaldce", "Dead Global Elimination");
}
Pass *createGlobalDCEPass() { return new GlobalDCE(); }
// RemoveIfDead - If this global value is dead, remove it from the current
// module and return true.
//
bool GlobalDCE::RemoveIfDead(GlobalValue *GV) {
// If there is only one use of the global value, it might be a
// ConstantPointerRef... which means that this global might actually be
// dead.
if (GV->use_size() == 1)
RemoveUnusedConstantPointerRef(*GV);
if (!GV->use_empty()) return false;
if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) {
// Eliminate all global variables that are unused, and that are internal, or
// do not have an initializer.
//
if (!GVar->hasExternalLinkage() || !GVar->hasInitializer()) {
Constant *Init = GVar->hasInitializer() ? GVar->getInitializer() : 0;
GV->getParent()->getGlobalList().erase(GVar);
++NumVariables;
// If there was an initializer for the global variable, try to destroy it
// now.
if (Init) DestroyInitializer(Init);
// If the global variable is still on the worklist, remove it now.
std::vector<GlobalValue*>::iterator I = std::find(WorkList.begin(),
WorkList.end(), GV);
while (I != WorkList.end())
I = std::find(WorkList.erase(I), WorkList.end(), GV);
return true;
}
} else {
Function *F = cast<Function>(GV);
// FIXME: TODO
}
return false;
}
// DestroyInitializer - A global variable was just destroyed and C is its
// initializer. If we can, destroy C and all of the constants it refers to.
//
void GlobalDCE::DestroyInitializer(Constant *C) {
// Cannot destroy constants still being used, and cannot destroy primitive
// types.
if (!C->use_empty() || C->getType()->isPrimitiveType()) return;
// If this is a CPR, the global value referred to may be dead now! Add it to
// the worklist.
//
if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) {
WorkList.push_back(CPR->getValue());
C->destroyConstant();
++NumCPRs;
} else {
bool DestroyContents = true;
// As an optimization to the GlobalDCE algorithm, do attempt to destroy the
// contents of an array of primitive types, because we know that this will
// never succeed, and there could be a lot of them.
//
if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
if (CA->getType()->getElementType()->isPrimitiveType())
DestroyContents = false; // Nothing we can do with the subcontents
// All other constants refer to other constants. Destroy them if possible
// as well.
//
std::vector<Value*> SubConstants;
if (DestroyContents) SubConstants.insert(SubConstants.end(),
C->op_begin(), C->op_end());
// Destroy the actual constant...
C->destroyConstant();
++NumConsts;
if (DestroyContents) {
// Remove duplicates from SubConstants, so that we do not call
// DestroyInitializer on the same constant twice (the first call might
// delete it, so this would be bad)
//
std::sort(SubConstants.begin(), SubConstants.end());
SubConstants.erase(std::unique(SubConstants.begin(), SubConstants.end()),
SubConstants.end());
// Loop over the subconstants, destroying them as well.
for (unsigned i = 0, e = SubConstants.size(); i != e; ++i)
DestroyInitializer(cast<Constant>(SubConstants[i]));
}
}
}
bool GlobalDCE::RemoveUnreachableGlobalVariables(Module &M) {
bool Changed = false;
WorkList.reserve(M.gsize());
// Insert all of the globals into the WorkList, making sure to run
// RemoveUnusedConstantPointerRef at least once on all globals...
//
for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
Changed |= RemoveUnusedConstantPointerRef(*I);
WorkList.push_back(I);
}
for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I) {
Changed |= RemoveUnusedConstantPointerRef(*I);
WorkList.push_back(I);
}
// Loop over the worklist, deleting global objects that we can. Whenever we
// delete something that might make something else dead, it gets added to the
// worklist.
//
while (!WorkList.empty()) {
GlobalValue *GV = WorkList.back();
WorkList.pop_back();
Changed |= RemoveIfDead(GV);
}
// Make sure that all memory is free'd from the worklist...
std::vector<GlobalValue*>().swap(WorkList);
return Changed;
}
// RemoveUnusedConstantPointerRef - Loop over all of the uses of the specified
// GlobalValue, looking for the constant pointer ref that may be pointing to it.
// If found, check to see if the constant pointer ref is safe to destroy, and if
// so, nuke it. This will reduce the reference count on the global value, which
// might make it deader.
//
bool GlobalDCE::RemoveUnusedConstantPointerRef(GlobalValue &GV) {
for (Value::use_iterator I = GV.use_begin(), E = GV.use_end(); I != E; ++I)
if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(*I))
if (SafeToDestroyConstant(CPR)) { // Only if unreferenced...
CPR->destroyConstant();
++NumCPRs;
return true;
}
return false;
}
// SafeToDestroyConstant - It is safe to destroy a constant iff it is only used
// by constants itself. Note that constants cannot be cyclic, so this test is
// pretty easy to implement recursively.
//
bool GlobalDCE::SafeToDestroyConstant(Constant *C) {
for (Value::use_iterator I = C->use_begin(), E = C->use_end(); I != E; ++I)
if (Constant *User = dyn_cast<Constant>(*I)) {
if (!SafeToDestroyConstant(User)) return false;
} else {
return false;
}
return true;
}
<commit_msg>Use methods that are more explanatory<commit_after>//===-- GlobalDCE.cpp - DCE unreachable internal functions ----------------===//
//
// This transform is designed to eliminate unreachable internal globals
// FIXME: GlobalDCE should update the callgraph, not destroy it!
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/IPO.h"
#include "llvm/Module.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Analysis/CallGraph.h"
#include "Support/DepthFirstIterator.h"
#include "Support/Statistic.h"
#include <algorithm>
namespace {
Statistic<> NumFunctions("globaldce","Number of functions removed");
Statistic<> NumVariables("globaldce","Number of global variables removed");
Statistic<> NumCPRs("globaldce", "Number of const pointer refs removed");
Statistic<> NumConsts("globaldce", "Number of init constants removed");
bool RemoveUnreachableFunctions(Module &M, CallGraph &CallGraph) {
// Calculate which functions are reachable from the external functions in
// the call graph.
//
std::set<CallGraphNode*> ReachableNodes(df_begin(&CallGraph),
df_end(&CallGraph));
// Loop over the functions in the module twice. The first time is used to
// drop references that functions have to each other before they are
// deleted. The second pass removes the functions that need to be removed.
//
std::vector<CallGraphNode*> FunctionsToDelete; // Track unused functions
for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
CallGraphNode *N = CallGraph[I];
if (!ReachableNodes.count(N)) { // Not reachable??
I->dropAllReferences();
N->removeAllCalledFunctions();
FunctionsToDelete.push_back(N);
++NumFunctions;
}
}
// Nothing to do if no unreachable functions have been found...
if (FunctionsToDelete.empty()) return false;
// Unreachables functions have been found and should have no references to
// them, delete them now.
//
for (std::vector<CallGraphNode*>::iterator I = FunctionsToDelete.begin(),
E = FunctionsToDelete.end(); I != E; ++I)
delete CallGraph.removeFunctionFromModule(*I);
return true;
}
struct GlobalDCE : public Pass {
// run - Do the GlobalDCE pass on the specified module, optionally updating
// the specified callgraph to reflect the changes.
//
bool run(Module &M) {
return RemoveUnreachableFunctions(M, getAnalysis<CallGraph>()) |
RemoveUnreachableGlobalVariables(M);
}
// getAnalysisUsage - This function works on the call graph of a module.
// It is capable of updating the call graph to reflect the new state of the
// module.
//
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<CallGraph>();
}
private:
std::vector<GlobalValue*> WorkList;
inline bool RemoveIfDead(GlobalValue *GV);
void DestroyInitializer(Constant *C);
bool RemoveUnreachableGlobalVariables(Module &M);
bool RemoveUnusedConstantPointerRef(GlobalValue &GV);
bool SafeToDestroyConstant(Constant *C);
};
RegisterOpt<GlobalDCE> X("globaldce", "Dead Global Elimination");
}
Pass *createGlobalDCEPass() { return new GlobalDCE(); }
// RemoveIfDead - If this global value is dead, remove it from the current
// module and return true.
//
bool GlobalDCE::RemoveIfDead(GlobalValue *GV) {
// If there is only one use of the global value, it might be a
// ConstantPointerRef... which means that this global might actually be
// dead.
if (GV->use_size() == 1)
RemoveUnusedConstantPointerRef(*GV);
if (!GV->use_empty()) return false;
if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) {
// Eliminate all global variables that are unused, and that are internal, or
// do not have an initializer.
//
if (GVar->hasInternalLinkage() || GVar->isExternal()) {
Constant *Init = GVar->hasInitializer() ? GVar->getInitializer() : 0;
GV->getParent()->getGlobalList().erase(GVar);
++NumVariables;
// If there was an initializer for the global variable, try to destroy it
// now.
if (Init) DestroyInitializer(Init);
// If the global variable is still on the worklist, remove it now.
std::vector<GlobalValue*>::iterator I = std::find(WorkList.begin(),
WorkList.end(), GV);
while (I != WorkList.end())
I = std::find(WorkList.erase(I), WorkList.end(), GV);
return true;
}
} else {
Function *F = cast<Function>(GV);
// FIXME: TODO
}
return false;
}
// DestroyInitializer - A global variable was just destroyed and C is its
// initializer. If we can, destroy C and all of the constants it refers to.
//
void GlobalDCE::DestroyInitializer(Constant *C) {
// Cannot destroy constants still being used, and cannot destroy primitive
// types.
if (!C->use_empty() || C->getType()->isPrimitiveType()) return;
// If this is a CPR, the global value referred to may be dead now! Add it to
// the worklist.
//
if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) {
WorkList.push_back(CPR->getValue());
C->destroyConstant();
++NumCPRs;
} else {
bool DestroyContents = true;
// As an optimization to the GlobalDCE algorithm, do attempt to destroy the
// contents of an array of primitive types, because we know that this will
// never succeed, and there could be a lot of them.
//
if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
if (CA->getType()->getElementType()->isPrimitiveType())
DestroyContents = false; // Nothing we can do with the subcontents
// All other constants refer to other constants. Destroy them if possible
// as well.
//
std::vector<Value*> SubConstants;
if (DestroyContents) SubConstants.insert(SubConstants.end(),
C->op_begin(), C->op_end());
// Destroy the actual constant...
C->destroyConstant();
++NumConsts;
if (DestroyContents) {
// Remove duplicates from SubConstants, so that we do not call
// DestroyInitializer on the same constant twice (the first call might
// delete it, so this would be bad)
//
std::sort(SubConstants.begin(), SubConstants.end());
SubConstants.erase(std::unique(SubConstants.begin(), SubConstants.end()),
SubConstants.end());
// Loop over the subconstants, destroying them as well.
for (unsigned i = 0, e = SubConstants.size(); i != e; ++i)
DestroyInitializer(cast<Constant>(SubConstants[i]));
}
}
}
bool GlobalDCE::RemoveUnreachableGlobalVariables(Module &M) {
bool Changed = false;
WorkList.reserve(M.gsize());
// Insert all of the globals into the WorkList, making sure to run
// RemoveUnusedConstantPointerRef at least once on all globals...
//
for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
Changed |= RemoveUnusedConstantPointerRef(*I);
WorkList.push_back(I);
}
for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I) {
Changed |= RemoveUnusedConstantPointerRef(*I);
WorkList.push_back(I);
}
// Loop over the worklist, deleting global objects that we can. Whenever we
// delete something that might make something else dead, it gets added to the
// worklist.
//
while (!WorkList.empty()) {
GlobalValue *GV = WorkList.back();
WorkList.pop_back();
Changed |= RemoveIfDead(GV);
}
// Make sure that all memory is free'd from the worklist...
std::vector<GlobalValue*>().swap(WorkList);
return Changed;
}
// RemoveUnusedConstantPointerRef - Loop over all of the uses of the specified
// GlobalValue, looking for the constant pointer ref that may be pointing to it.
// If found, check to see if the constant pointer ref is safe to destroy, and if
// so, nuke it. This will reduce the reference count on the global value, which
// might make it deader.
//
bool GlobalDCE::RemoveUnusedConstantPointerRef(GlobalValue &GV) {
for (Value::use_iterator I = GV.use_begin(), E = GV.use_end(); I != E; ++I)
if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(*I))
if (SafeToDestroyConstant(CPR)) { // Only if unreferenced...
CPR->destroyConstant();
++NumCPRs;
return true;
}
return false;
}
// SafeToDestroyConstant - It is safe to destroy a constant iff it is only used
// by constants itself. Note that constants cannot be cyclic, so this test is
// pretty easy to implement recursively.
//
bool GlobalDCE::SafeToDestroyConstant(Constant *C) {
for (Value::use_iterator I = C->use_begin(), E = C->use_end(); I != E; ++I)
if (Constant *User = dyn_cast<Constant>(*I)) {
if (!SafeToDestroyConstant(User)) return false;
} else {
return false;
}
return true;
}
<|endoftext|> |
<commit_before>// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "sky/shell/shell.h"
#include "base/bind.h"
#include "base/i18n/icu_util.h"
#include "base/single_thread_task_runner.h"
#include "mojo/common/message_pump_mojo.h"
#include "mojo/edk/embedder/embedder.h"
#include "mojo/edk/embedder/simple_platform_support.h"
#include "sky/shell/ui/engine.h"
#include "ui/gl/gl_surface.h"
namespace sky {
namespace shell {
namespace {
static Shell* g_shell = nullptr;
scoped_ptr<base::MessagePump> CreateMessagePumpMojo() {
return make_scoped_ptr(new mojo::common::MessagePumpMojo);
}
} // namespace
Shell::Shell(scoped_ptr<ServiceProviderContext> service_provider_context)
: service_provider_context_(service_provider_context.Pass()) {
DCHECK(!g_shell);
mojo::embedder::Init(scoped_ptr<mojo::embedder::PlatformSupport>(
new mojo::embedder::SimplePlatformSupport()));
base::Thread::Options options;
options.message_pump_factory = base::Bind(&CreateMessagePumpMojo);
gpu_thread_.reset(new base::Thread("gpu_thread"));
gpu_thread_->StartWithOptions(options);
ui_thread_.reset(new base::Thread("ui_thread"));
ui_thread_->StartWithOptions(options);
ui_task_runner()->PostTask(FROM_HERE, base::Bind(&Engine::Init));
}
Shell::~Shell() {
}
void Shell::Init(scoped_ptr<ServiceProviderContext> service_provider_context) {
CHECK(base::i18n::InitializeICU());
#if !defined(OS_LINUX)
CHECK(gfx::GLSurface::InitializeOneOff());
#endif
g_shell = new Shell(service_provider_context.Pass());
}
Shell& Shell::Shared() {
DCHECK(g_shell);
return *g_shell;
}
} // namespace shell
} // namespace sky
<commit_msg>Call DiscardableMemoryAllocator::SetInstance()<commit_after>// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "sky/shell/shell.h"
#include "base/bind.h"
#include "base/i18n/icu_util.h"
#include "base/lazy_instance.h"
#include "base/memory/discardable_memory.h"
#include "base/memory/discardable_memory_allocator.h"
#include "base/single_thread_task_runner.h"
#include "mojo/common/message_pump_mojo.h"
#include "mojo/edk/embedder/embedder.h"
#include "mojo/edk/embedder/simple_platform_support.h"
#include "sky/shell/ui/engine.h"
#include "ui/gl/gl_surface.h"
namespace sky {
namespace shell {
namespace {
static Shell* g_shell = nullptr;
scoped_ptr<base::MessagePump> CreateMessagePumpMojo() {
return make_scoped_ptr(new mojo::common::MessagePumpMojo);
}
class NonDiscardableMemory : public base::DiscardableMemory {
public:
explicit NonDiscardableMemory(size_t size) : data_(new uint8_t[size]) {}
bool Lock() override { return false; }
void Unlock() override {}
void* data() const override { return data_.get(); }
private:
scoped_ptr<uint8_t[]> data_;
};
class NonDiscardableMemoryAllocator : public base::DiscardableMemoryAllocator {
public:
scoped_ptr<base::DiscardableMemory> AllocateLockedDiscardableMemory(
size_t size) override {
return make_scoped_ptr(new NonDiscardableMemory(size));
}
};
base::LazyInstance<NonDiscardableMemoryAllocator> g_discardable;
} // namespace
Shell::Shell(scoped_ptr<ServiceProviderContext> service_provider_context)
: service_provider_context_(service_provider_context.Pass()) {
DCHECK(!g_shell);
mojo::embedder::Init(scoped_ptr<mojo::embedder::PlatformSupport>(
new mojo::embedder::SimplePlatformSupport()));
base::Thread::Options options;
options.message_pump_factory = base::Bind(&CreateMessagePumpMojo);
gpu_thread_.reset(new base::Thread("gpu_thread"));
gpu_thread_->StartWithOptions(options);
ui_thread_.reset(new base::Thread("ui_thread"));
ui_thread_->StartWithOptions(options);
ui_task_runner()->PostTask(FROM_HERE, base::Bind(&Engine::Init));
}
Shell::~Shell() {
}
void Shell::Init(scoped_ptr<ServiceProviderContext> service_provider_context) {
CHECK(base::i18n::InitializeICU());
#if !defined(OS_LINUX)
CHECK(gfx::GLSurface::InitializeOneOff());
#endif
base::DiscardableMemoryAllocator::SetInstance(&g_discardable.Get());
g_shell = new Shell(service_provider_context.Pass());
}
Shell& Shell::Shared() {
DCHECK(g_shell);
return *g_shell;
}
} // namespace shell
} // namespace sky
<|endoftext|> |
<commit_before>// Copyright 2014-2015 Project Vogue. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "elang/base/bit_set.h"
#include "base/logging.h"
#include "elang/base/zone.h"
namespace elang {
namespace {
const BitSet::Pack kOne = static_cast<BitSet::Pack>(1);
const int kPackSize = sizeof(BitSet::Pack) * 8;
const int kShiftCount = sizeof(BitSet::Pack) == 8 ? 6 : 5;
const int kShiftMask = (1 << kShiftCount) - 1;
int PackIndexOf(int index) {
return index >> kShiftCount;
}
int ShiftCountOf(int index) {
return index & kShiftMask;
}
BitSet::Pack BitMaskOf(int index) {
return kOne << ShiftCountOf(index);
}
} // namespace
//////////////////////////////////////////////////////////////////////
//
// BitSet::Iterator
//
BitSet::Iterator::Iterator(const BitSet* bit_set, int index)
: bit_set_(bit_set), index_(index) {
DCHECK_GE(index_, -1);
DCHECK_LE(index_, bit_set_->size_);
}
BitSet::Iterator::Iterator(const Iterator& other)
: Iterator(other.bit_set_, other.index_) {
}
BitSet::Iterator::~Iterator() {
}
int BitSet::Iterator::operator*() {
DCHECK_GE(index_, 0);
DCHECK_LT(index_, bit_set_->size());
return index_;
}
BitSet::Iterator& BitSet::Iterator::operator++() {
DCHECK_GE(index_, 0);
DCHECK_LE(index_ + 1, bit_set_->size());
index_ = bit_set_->IndexOf(index_ + 1);
return *this;
}
bool BitSet::Iterator::operator==(const Iterator& other) const {
DCHECK_EQ(bit_set_, other.bit_set_);
return index_ == other.index_;
}
bool BitSet::Iterator::operator!=(const Iterator& other) const {
return !operator==(other);
}
//////////////////////////////////////////////////////////////////////
//
// BitSet
//
BitSet::BitSet(Zone* zone, const BitSet& other)
: pack_size_(other.pack_size_),
size_(other.size_),
packs_(zone->AllocateObjects<Pack>(pack_size_)) {
CopyFrom(other);
}
BitSet::~BitSet() {
NOTREACHED();
}
BitSet::BitSet(Zone* zone, int size)
: pack_size_((size + kPackSize - 1) / kPackSize),
size_(size),
packs_(zone->AllocateObjects<Pack>(pack_size_)) {
DCHECK_GT(size_, 0);
Clear();
}
BitSet::Iterator BitSet::begin() const {
return Iterator(this, IndexOf(0));
}
BitSet::Iterator BitSet::end() const {
DCHECK_GT(size_, 0);
return Iterator(this, LastIndexOf(size_ - 1));
}
void BitSet::Add(int index) {
DCHECK_NE(BitMaskOf(index), 0u);
auto const pack_index = PackIndexOf(index);
DCHECK_LT(pack_index, pack_size_);
packs_[pack_index] |= BitMaskOf(index);
}
void BitSet::Clear() {
for (auto i = 0; i < pack_size_; ++i)
packs_[i] = 0;
}
bool BitSet::Contains(int index) const {
return (packs_[PackIndexOf(index)] & BitMaskOf(index)) != 0;
}
void BitSet::CopyFrom(const BitSet& other) {
DCHECK_GE(size_, other.size_);
for (int i = 0; i < other.pack_size_; ++i)
packs_[i] = other.packs_[i];
for (int i = other.pack_size_; i < pack_size_; ++i)
packs_[i] = 0;
}
bool BitSet::Equals(const BitSet& other) const {
DCHECK_EQ(size_, other.size_);
for (auto index = 0; index < pack_size_; ++index) {
if (packs_[index] != other.packs_[index])
return false;
}
return true;
}
// Returns an index where |packs_[index] == 1| from |start| until |size_| or
// |size_| if there are no one in |data|.
int BitSet::IndexOf(int start) const {
DCHECK_GE(start, 0);
DCHECK_LE(start, size_);
if (start == size_)
return size_;
auto index = start;
auto pack_index = PackIndexOf(index);
auto pack = packs_[pack_index] >> ShiftCountOf(index);
if (!pack) {
do {
++pack_index;
if (pack_index == pack_size_)
return -1;
pack = packs_[pack_index];
} while (!pack);
index = pack_index * kPackSize;
}
// We found pack which contains one, let's calculate index of one bit.
DCHECK_NE(pack, 0);
while (pack && (pack & 0xFF) == 0) {
pack >>= 8;
index += 8;
}
while (pack && (pack & 1) == 0) {
pack >>= 1;
++index;
}
DCHECK_LE(index, size_);
return index;
}
void BitSet::Intersect(const BitSet& other) {
DCHECK_EQ(size_, other.size_);
for (auto i = 0; i < pack_size_; ++i)
packs_[i] &= other.packs_[i];
}
bool BitSet::IsEmpty() const {
for (auto i = 0; i < pack_size_; ++i) {
if (packs_[i])
return false;
}
return true;
}
// Returns an last index where bit is one or |-1| if not found.
int BitSet::LastIndexOf(int start) const {
DCHECK_GE(start, 0);
DCHECK_LT(start, size_);
auto index = start;
auto pack_index = PackIndexOf(index);
auto pack = packs_[pack_index] >> ShiftCountOf(start);
if (!pack) {
do {
if (!pack_index)
return -1;
--pack_index;
pack = packs_[pack_index];
} while (!pack);
index = pack_index * kPackSize;
}
// We found pack which contains one, let's calculate index of MSB + 1.
DCHECK_NE(pack, 0);
while (pack && (pack && 0xFF) == 0) {
pack >>= 8;
index += 8;
}
while (pack) {
pack >>= 1;
++index;
}
DCHECK_LE(index, size_);
return index;
}
void BitSet::Remove(int index) {
packs_[PackIndexOf(index)] &= ~BitMaskOf(index);
}
void BitSet::Subtract(const BitSet& other) {
DCHECK_EQ(size_, other.size_);
for (auto i = 0; i < pack_size_; ++i)
packs_[i] &= ~other.packs_[i];
}
void BitSet::Union(const BitSet& other) {
DCHECK_EQ(size_, other.size_);
for (auto i = 0; i < pack_size_; ++i)
packs_[i] |= other.packs_[i];
}
std::ostream& operator<<(std::ostream& ostream, const BitSet& bit_set) {
ostream << "{";
auto separator = "";
for (auto const index : bit_set) {
ostream << separator << index;
separator = ", ";
}
return ostream << "}";
}
} // namespace elang
<commit_msg>elang/base: Utilize |CountLeadingZeros()| and |CountTrailingZeros()| in |BitSet| implementation.<commit_after>// Copyright 2014-2015 Project Vogue. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "elang/base/bit_set.h"
#include "base/logging.h"
#include "elang/base/bits.h"
#include "elang/base/zone.h"
namespace elang {
namespace {
const BitSet::Pack kOne = static_cast<BitSet::Pack>(1);
const int kPackSize = sizeof(BitSet::Pack) * 8;
const int kShiftCount = sizeof(BitSet::Pack) == 8 ? 6 : 5;
const int kShiftMask = (1 << kShiftCount) - 1;
int PackIndexOf(int index) {
return index >> kShiftCount;
}
int ShiftCountOf(int index) {
return index & kShiftMask;
}
BitSet::Pack BitMaskOf(int index) {
return kOne << ShiftCountOf(index);
}
} // namespace
//////////////////////////////////////////////////////////////////////
//
// BitSet::Iterator
//
BitSet::Iterator::Iterator(const BitSet* bit_set, int index)
: bit_set_(bit_set), index_(index) {
DCHECK_GE(index_, -1);
DCHECK_LE(index_, bit_set_->size_);
}
BitSet::Iterator::Iterator(const Iterator& other)
: Iterator(other.bit_set_, other.index_) {
}
BitSet::Iterator::~Iterator() {
}
int BitSet::Iterator::operator*() {
DCHECK_GE(index_, 0);
DCHECK_LT(index_, bit_set_->size());
return index_;
}
BitSet::Iterator& BitSet::Iterator::operator++() {
DCHECK_GE(index_, 0);
DCHECK_LE(index_ + 1, bit_set_->size());
index_ = bit_set_->IndexOf(index_ + 1);
return *this;
}
bool BitSet::Iterator::operator==(const Iterator& other) const {
DCHECK_EQ(bit_set_, other.bit_set_);
return index_ == other.index_;
}
bool BitSet::Iterator::operator!=(const Iterator& other) const {
return !operator==(other);
}
//////////////////////////////////////////////////////////////////////
//
// BitSet
//
BitSet::BitSet(Zone* zone, const BitSet& other)
: pack_size_(other.pack_size_),
size_(other.size_),
packs_(zone->AllocateObjects<Pack>(pack_size_)) {
CopyFrom(other);
}
BitSet::~BitSet() {
NOTREACHED();
}
BitSet::BitSet(Zone* zone, int size)
: pack_size_((size + kPackSize - 1) / kPackSize),
size_(size),
packs_(zone->AllocateObjects<Pack>(pack_size_)) {
DCHECK_GT(size_, 0);
Clear();
}
BitSet::Iterator BitSet::begin() const {
return Iterator(this, IndexOf(0));
}
BitSet::Iterator BitSet::end() const {
DCHECK_GT(size_, 0);
return Iterator(this, LastIndexOf(size_ - 1));
}
void BitSet::Add(int index) {
DCHECK_NE(BitMaskOf(index), 0u);
auto const pack_index = PackIndexOf(index);
DCHECK_LT(pack_index, pack_size_);
packs_[pack_index] |= BitMaskOf(index);
}
void BitSet::Clear() {
for (auto i = 0; i < pack_size_; ++i)
packs_[i] = 0;
}
bool BitSet::Contains(int index) const {
return (packs_[PackIndexOf(index)] & BitMaskOf(index)) != 0;
}
void BitSet::CopyFrom(const BitSet& other) {
DCHECK_GE(size_, other.size_);
for (int i = 0; i < other.pack_size_; ++i)
packs_[i] = other.packs_[i];
for (int i = other.pack_size_; i < pack_size_; ++i)
packs_[i] = 0;
}
bool BitSet::Equals(const BitSet& other) const {
DCHECK_EQ(size_, other.size_);
for (auto index = 0; index < pack_size_; ++index) {
if (packs_[index] != other.packs_[index])
return false;
}
return true;
}
// Returns an index where |packs_[index] == 1| from |start| until |size_| or
// |size_| if there are no one in |data|.
int BitSet::IndexOf(int start) const {
DCHECK_GE(start, 0);
DCHECK_LE(start, size_);
if (start == size_)
return size_;
auto index = start;
auto pack_index = PackIndexOf(index);
auto pack = packs_[pack_index] >> ShiftCountOf(index);
if (!pack) {
do {
++pack_index;
if (pack_index == pack_size_)
return -1;
pack = packs_[pack_index];
} while (!pack);
index = pack_index * kPackSize;
}
// We found pack which contains one, let's calculate index of one bit.
DCHECK_NE(pack, 0);
index += CountTrailingZeros(pack);
DCHECK_LE(index, size_);
return index;
}
void BitSet::Intersect(const BitSet& other) {
DCHECK_EQ(size_, other.size_);
for (auto i = 0; i < pack_size_; ++i)
packs_[i] &= other.packs_[i];
}
bool BitSet::IsEmpty() const {
for (auto i = 0; i < pack_size_; ++i) {
if (packs_[i])
return false;
}
return true;
}
// Returns an last index where bit is one or |-1| if not found.
int BitSet::LastIndexOf(int start) const {
DCHECK_GE(start, 0);
DCHECK_LT(start, size_);
auto index = start;
auto pack_index = PackIndexOf(index);
auto pack = packs_[pack_index] >> ShiftCountOf(start);
if (!pack) {
do {
if (!pack_index)
return -1;
--pack_index;
pack = packs_[pack_index];
} while (!pack);
index = pack_index * kPackSize;
}
// We found pack which contains one, let's calculate index of MSB + 1.
DCHECK_NE(pack, 0);
index += kPackSize - CountLeadingZeros(pack);
DCHECK_LE(index, size_);
return index;
}
void BitSet::Remove(int index) {
packs_[PackIndexOf(index)] &= ~BitMaskOf(index);
}
void BitSet::Subtract(const BitSet& other) {
DCHECK_EQ(size_, other.size_);
for (auto i = 0; i < pack_size_; ++i)
packs_[i] &= ~other.packs_[i];
}
void BitSet::Union(const BitSet& other) {
DCHECK_EQ(size_, other.size_);
for (auto i = 0; i < pack_size_; ++i)
packs_[i] |= other.packs_[i];
}
std::ostream& operator<<(std::ostream& ostream, const BitSet& bit_set) {
ostream << "{";
auto separator = "";
for (auto const index : bit_set) {
ostream << separator << index;
separator = ", ";
}
return ostream << "}";
}
} // namespace elang
<|endoftext|> |
<commit_before>/*
Cigarras
https://www.urionlinejudge.com.br/judge/pt/problems/view/2660
*/
#include <bits/stdc++.h>
using namespace std;
typedef unsigned long long int uint64;
uint64 mdc(uint64 a, uint64 b) {
if (a == 0) return b;
else return mdc(b % a, a);
}
uint64 mmc(uint64 a, uint64 b) {
return a / mdc(a, b) * b;
}
int main(void) {
ios::sync_with_stdio(false);
uint64 N, L,
cicloAtual = 1,
melhorCiclo,
tempoDeVida = 1;
cin >> N >> L;
for (uint64 i = 0; i < N; i++) {
uint64 n;
cin >> n;
cicloAtual = mmc(cicloAtual, n);
}
melhorCiclo = cicloAtual;
for (uint64 i = 1; i <= L; i++) {
uint64 ciclo = mmc(cicloAtual, i);
if (ciclo > melhorCiclo && ciclo <= L) {
melhorCiclo = ciclo;
tempoDeVida = i;
}
}
cout << tempoDeVida << endl;
return EXIT_SUCCESS;
}
<commit_msg>URI 2660 - Cigarras<commit_after>/*
Cigarras
https://www.urionlinejudge.com.br/judge/pt/problems/view/2660
*/
#include <bits/stdc++.h>
using namespace std;
typedef unsigned long long int uint64;
uint64 mdc(uint64 a, uint64 b) {
if (a == 0) return b;
else return mdc(b % a, a);
}
uint64 mmc(uint64 a, uint64 b) {
return a * b / mdc(a, b);
}
int main(void) {
ios::sync_with_stdio(false);
uint64 N, L,
cicloAtual = 1,
melhorCiclo,
tempoDeVida = 1;
cin >> N >> L;
for (uint64 i = 0; i < N; i++) {
uint64 n;
cin >> n;
cicloAtual = mmc(cicloAtual, n);
}
melhorCiclo = cicloAtual;
for (uint64 i = 1; i <= L; i++) {
uint64 ciclo = mmc(cicloAtual, i);
if (ciclo > melhorCiclo && ciclo <= L) {
melhorCiclo = ciclo;
tempoDeVida = i;
}
}
cout << tempoDeVida << endl;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>// This file is part of SWGANH which is released under the MIT license.
// See file LICENSE or go to http://swganh.com/LICENSE
#ifndef WIN32
#include <Python.h>
#endif
#include "swganh/app/swganh_app.h"
#include <algorithm>
#include <exception>
#include <fstream>
#include <iostream>
#ifdef WIN32
#include <regex>
#else
#include <boost/regex.hpp>
#endif
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/program_options.hpp>
#include "anh/logger.h"
#include "anh/database/database_manager_interface.h"
#include "anh/event_dispatcher.h"
#include "anh/plugin/plugin_manager.h"
#include "anh/service/datastore.h"
#include "anh/service/service_manager.h"
#include "swganh/app/swganh_kernel.h"
#include "swganh/combat/combat_service_interface.h"
#include "swganh/chat/chat_service_interface.h"
#include "swganh/character/character_service_interface.h"
#include "swganh/login/login_service_interface.h"
#include "swganh/connection/connection_service_interface.h"
#include "swganh/simulation/simulation_service_interface.h"
#include "swganh/scripting/utilities.h"
#include "version.h"
using namespace anh;
using namespace anh::app;
using namespace boost::asio;
using namespace boost::program_options;
using namespace std;
using namespace swganh::app;
using namespace swganh::chat;
using namespace swganh::login;
using namespace swganh::character;
using namespace swganh::connection;
using namespace swganh::simulation;
using namespace swganh::galaxy;
using anh::plugin::RegistrationMap;
#ifdef WIN32
using std::regex;
using std::smatch;
using std::regex_match;
#else
using boost::regex;
using boost::smatch;
using boost::regex_match;
#endif
options_description AppConfig::BuildConfigDescription() {
options_description desc;
desc.add_options()
("help,h", "Display help message and config options")
("server_mode", boost::program_options::value<std::string>(&server_mode)->default_value("all"),
"Specifies the service configuration mode to run the server in.")
("plugin,p", boost::program_options::value<std::vector<std::string>>(&plugins),
"Only used when single_server_mode is disabled, loads a module of the specified name")
("plugin_directory", value<string>(&plugin_directory)->default_value("plugins/"),
"Directory containing the application plugins")
("script_directory", value<string>(&script_directory)->default_value("scripts"),
"Directory containing the application scripts")
("tre_config", boost::program_options::value<std::string>(&tre_config),
"File containing the tre configuration (live.cfg)")
("galaxy_name", boost::program_options::value<std::string>(&galaxy_name),
"Name of the galaxy (cluster) to this process should run")
("resource_cache_size", boost::program_options::value<uint32_t>(&resource_cache_size),
"Available cache size for the resource manager (in Megabytes)")
("db.galaxy_manager.host", boost::program_options::value<std::string>(&galaxy_manager_db.host),
"Host address for the galaxy_manager datastore")
("db.galaxy_manager.schema", boost::program_options::value<std::string>(&galaxy_manager_db.schema),
"Schema name for the galaxy_manager datastore")
("db.galaxy_manager.username", boost::program_options::value<std::string>(&galaxy_manager_db.username),
"Username for authentication with the galaxy_manager datastore")
("db.galaxy_manager.password", boost::program_options::value<std::string>(&galaxy_manager_db.password),
"Password for authentication with the galaxy_manager datastore")
("db.galaxy.host", boost::program_options::value<std::string>(&galaxy_db.host),
"Host address for the galaxy datastore")
("db.galaxy.schema", boost::program_options::value<std::string>(&galaxy_db.schema),
"Schema name for the galaxy datastore")
("db.galaxy.username", boost::program_options::value<std::string>(&galaxy_db.username),
"Username for authentication with the galaxy datastore")
("db.galaxy.password", boost::program_options::value<std::string>(&galaxy_db.password),
"Password for authentication with the galaxy datastore")
("service.login.udp_port",
boost::program_options::value<uint16_t>(&login_config.listen_port),
"The port the login service will listen for incoming client connections on")
("service.login.address",
boost::program_options::value<string>(&login_config.listen_address),
"The public address the login service will listen for incoming client connections on")
("service.login.status_check_duration_secs",
boost::program_options::value<int>(&login_config.galaxy_status_check_duration_secs),
"The amount of time between checks for updated galaxy status")
("service.login.login_error_timeout_secs",
boost::program_options::value<int>(&login_config.login_error_timeout_secs)->default_value(5),
"The number of seconds to wait before disconnecting a client after failed login attempt")
("service.login.auto_registration",
boost::program_options::value<bool>(&login_config.login_auto_registration)->default_value(false),
"Auto Registration flag")
("service.connection.ping_port", boost::program_options::value<uint16_t>(&connection_config.ping_port),
"The port the connection service will listen for incoming client ping requests on")
("service.connection.udp_port", boost::program_options::value<uint16_t>(&connection_config.listen_port),
"The port the connection service will listen for incoming client connections on")
("service.connection.address", boost::program_options::value<string>(&connection_config.listen_address),
"The public address the connection service will listen for incoming client connections on")
;
return desc;
}
SwganhApp::SwganhApp(int argc, char* argv[])
: io_service_()
, io_work_(new boost::asio::io_service::work(io_service_))
{
kernel_ = make_shared<SwganhKernel>(io_service_);
running_ = false;
initialized_ = false;
Initialize(argc, argv);
Start();
}
SwganhApp::~SwganhApp()
{
Stop();
kernel_.reset();
io_work_.reset();
// join the threadpool threads until each one has exited.
for_each(io_threads_.begin(), io_threads_.end(), std::mem_fn(&boost::thread::join));
}
void SwganhApp::Initialize(int argc, char* argv[]) {
// Init Logging
SetupLogging_();
// Load the configuration
LoadAppConfig_(argc, argv);
auto app_config = kernel_->GetAppConfig();
// Initialize kernel resources
kernel_->GetDatabaseManager()->registerStorageType(
"galaxy_manager",
app_config.galaxy_manager_db.schema,
app_config.galaxy_manager_db.host,
app_config.galaxy_manager_db.username,
app_config.galaxy_manager_db.password);
kernel_->GetDatabaseManager()->registerStorageType(
"galaxy",
app_config.galaxy_db.schema,
app_config.galaxy_db.host,
app_config.galaxy_db.username,
app_config.galaxy_db.password);
CleanupServices_();
// append command dir
std::string py_path = "import sys; sys.path.append('.'); sys.path.append('" + app_config.script_directory + "');";
{
swganh::scripting::ScopedGilLock lock;
PyRun_SimpleString(py_path.c_str());
}
// Load the plugin configuration.
LoadPlugins_(app_config.plugins);
// Load core services
LoadCoreServices_();
initialized_ = true;
}
void SwganhApp::Start() {
if (!initialized_) {
throw std::runtime_error("Called application Start before Initialize");
}
running_ = true;
// Start up a threadpool for running io_service based tasks/active objects
// The increment starts at 2 because the main thread of execution already counts
// as thread in use as does the console thread.
for (uint32_t i = 1; i < boost::thread::hardware_concurrency(); ++i) {
boost::thread t([this] () {
io_service_.run();
});
#ifdef _WIN32
SetPriorityClass(t.native_handle(), REALTIME_PRIORITY_CLASS);
#endif
io_threads_.push_back(move(t));
}
kernel_->GetServiceManager()->Start();
}
void SwganhApp::Stop() {
running_ = false;
// Shutdown Event Dispatcher
kernel_->GetEventDispatcher()->Shutdown();
}
bool SwganhApp::IsRunning() {
return running_;
}
SwganhKernel* SwganhApp::GetAppKernel() const {
return kernel_.get();
}
void SwganhApp::StartInteractiveConsole()
{
swganh::scripting::ScopedGilLock lock;
anh::Logger::getInstance().DisableConsoleLogging();
#ifdef WIN32
std::system("cls");
#else
if (std::system("clear") != 0)
{
LOG(::error) << "Error clearing screen, ignoring console mode";
return;
}
#endif
std::cout << "swgpy console " << VERSION_MAJOR << "." << VERSION_MINOR << "." << VERSION_PATCH << std::endl;
boost::python::object main = boost::python::object (boost::python::handle<>(boost::python::borrowed(
PyImport_AddModule("__main__")
)));
auto global_dict = main.attr("__dict__");
global_dict["kernel"] = boost::python::ptr(GetAppKernel());
PyRun_InteractiveLoop(stdin, "<stdin>");
anh::Logger::getInstance().EnableConsoleLogging();
}
void SwganhApp::LoadAppConfig_(int argc, char* argv[]) {
auto config_description = kernel_->GetAppConfig().BuildConfigDescription();
variables_map vm;
store(parse_command_line(argc, argv, config_description), vm);
ifstream config_file("config/swganh.cfg");
if (!config_file.is_open()) {
throw runtime_error("Unable to open the configuration file at: config/swganh.cfg");
}
try {
store(parse_config_file(config_file, config_description, true), vm);
} catch(...) {
throw runtime_error("Unable to parse the configuration file at: config/swganh.cfg");
}
notify(vm);
config_file.close();
if (vm.count("help")) {
std::cout << config_description << "\n\n";
exit(0);
}
}
void SwganhApp::LoadPlugins_(vector<string> plugins) {
LOG(info) << "Loading plugins...";
if (!plugins.empty()) {
auto plugin_manager = kernel_->GetPluginManager();
auto plugin_directory = kernel_->GetAppConfig().plugin_directory;
for_each(plugins.begin(), plugins.end(), [plugin_manager, plugin_directory] (const string& plugin) {
LOG(info) << "Loading plugin " << plugin;
plugin_manager->LoadPlugin(plugin, plugin_directory);
});
}
LOG(info) << "Finished Loading plugins...";
}
void SwganhApp::CleanupServices_() {
auto service_directory = kernel_->GetServiceDirectory();
auto services = service_directory->getServiceSnapshot(service_directory->galaxy());
if (services.empty()) {
return;
}
LOG(warning) << "Services were not shutdown properly";
for_each(services.begin(), services.end(), [this, &service_directory] (anh::service::ServiceDescription& service) {
service_directory->removeService(service);
});
}
void SwganhApp::LoadCoreServices_()
{
auto plugin_manager = kernel_->GetPluginManager();
auto registration_map = plugin_manager->registration_map();
regex rx("(?:.*\\:\\:)(.*Service)");
smatch m;
for_each(registration_map.begin(), registration_map.end(), [this, &rx, &m] (RegistrationMap::value_type& entry) {
std::string name = entry.first;
if (entry.first.length() > 7 && regex_match(name, m, rx)) {
auto service_name = m[1].str();
LOG(info) << "Loading Service " << name << "...";
auto service = kernel_->GetPluginManager()->CreateObject<anh::service::ServiceInterface>(name);
kernel_->GetServiceManager()->AddService(service_name, service);
LOG(info) << "Loaded Service " << name;
}
});
auto app_config = kernel_->GetAppConfig();
if(strcmp("simulation", app_config.server_mode.c_str()) == 0 || strcmp("all", app_config.server_mode.c_str()) == 0)
{
auto simulation_service = kernel_->GetServiceManager()->GetService<SimulationServiceInterface>("SimulationService");
simulation_service->StartScene("corellia");
simulation_service->StartScene("naboo");
}
}
void SwganhApp::SetupLogging_()
{
anh::Logger::getInstance().init("swganh");
}<commit_msg>small tweak<commit_after>// This file is part of SWGANH which is released under the MIT license.
// See file LICENSE or go to http://swganh.com/LICENSE
#ifndef WIN32
#include <Python.h>
#endif
#include "swganh/app/swganh_app.h"
#include <algorithm>
#include <exception>
#include <fstream>
#include <iostream>
#ifdef WIN32
#include <regex>
#else
#include <boost/regex.hpp>
#endif
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/program_options.hpp>
#include "anh/logger.h"
#include "anh/database/database_manager_interface.h"
#include "anh/event_dispatcher.h"
#include "anh/plugin/plugin_manager.h"
#include "anh/service/datastore.h"
#include "anh/service/service_manager.h"
#include "swganh/app/swganh_kernel.h"
#include "swganh/combat/combat_service_interface.h"
#include "swganh/chat/chat_service_interface.h"
#include "swganh/character/character_service_interface.h"
#include "swganh/login/login_service_interface.h"
#include "swganh/connection/connection_service_interface.h"
#include "swganh/simulation/simulation_service_interface.h"
#include "swganh/scripting/utilities.h"
#include "version.h"
using namespace anh;
using namespace anh::app;
using namespace boost::asio;
using namespace boost::program_options;
using namespace std;
using namespace swganh::app;
using namespace swganh::chat;
using namespace swganh::login;
using namespace swganh::character;
using namespace swganh::connection;
using namespace swganh::simulation;
using namespace swganh::galaxy;
using anh::plugin::RegistrationMap;
#ifdef WIN32
using std::regex;
using std::smatch;
using std::regex_match;
#else
using boost::regex;
using boost::smatch;
using boost::regex_match;
#endif
options_description AppConfig::BuildConfigDescription() {
options_description desc;
desc.add_options()
("help,h", "Display help message and config options")
("server_mode", boost::program_options::value<std::string>(&server_mode)->default_value("all"),
"Specifies the service configuration mode to run the server in.")
("plugin,p", boost::program_options::value<std::vector<std::string>>(&plugins),
"Only used when single_server_mode is disabled, loads a module of the specified name")
("plugin_directory", value<string>(&plugin_directory)->default_value("plugins/"),
"Directory containing the application plugins")
("script_directory", value<string>(&script_directory)->default_value("scripts"),
"Directory containing the application scripts")
("tre_config", boost::program_options::value<std::string>(&tre_config),
"File containing the tre configuration (live.cfg)")
("galaxy_name", boost::program_options::value<std::string>(&galaxy_name),
"Name of the galaxy (cluster) to this process should run")
("resource_cache_size", boost::program_options::value<uint32_t>(&resource_cache_size),
"Available cache size for the resource manager (in Megabytes)")
("db.galaxy_manager.host", boost::program_options::value<std::string>(&galaxy_manager_db.host),
"Host address for the galaxy_manager datastore")
("db.galaxy_manager.schema", boost::program_options::value<std::string>(&galaxy_manager_db.schema),
"Schema name for the galaxy_manager datastore")
("db.galaxy_manager.username", boost::program_options::value<std::string>(&galaxy_manager_db.username),
"Username for authentication with the galaxy_manager datastore")
("db.galaxy_manager.password", boost::program_options::value<std::string>(&galaxy_manager_db.password),
"Password for authentication with the galaxy_manager datastore")
("db.galaxy.host", boost::program_options::value<std::string>(&galaxy_db.host),
"Host address for the galaxy datastore")
("db.galaxy.schema", boost::program_options::value<std::string>(&galaxy_db.schema),
"Schema name for the galaxy datastore")
("db.galaxy.username", boost::program_options::value<std::string>(&galaxy_db.username),
"Username for authentication with the galaxy datastore")
("db.galaxy.password", boost::program_options::value<std::string>(&galaxy_db.password),
"Password for authentication with the galaxy datastore")
("service.login.udp_port",
boost::program_options::value<uint16_t>(&login_config.listen_port),
"The port the login service will listen for incoming client connections on")
("service.login.address",
boost::program_options::value<string>(&login_config.listen_address),
"The public address the login service will listen for incoming client connections on")
("service.login.status_check_duration_secs",
boost::program_options::value<int>(&login_config.galaxy_status_check_duration_secs),
"The amount of time between checks for updated galaxy status")
("service.login.login_error_timeout_secs",
boost::program_options::value<int>(&login_config.login_error_timeout_secs)->default_value(5),
"The number of seconds to wait before disconnecting a client after failed login attempt")
("service.login.auto_registration",
boost::program_options::value<bool>(&login_config.login_auto_registration)->default_value(false),
"Auto Registration flag")
("service.connection.ping_port", boost::program_options::value<uint16_t>(&connection_config.ping_port),
"The port the connection service will listen for incoming client ping requests on")
("service.connection.udp_port", boost::program_options::value<uint16_t>(&connection_config.listen_port),
"The port the connection service will listen for incoming client connections on")
("service.connection.address", boost::program_options::value<string>(&connection_config.listen_address),
"The public address the connection service will listen for incoming client connections on")
;
return desc;
}
SwganhApp::SwganhApp(int argc, char* argv[])
: io_service_()
, io_work_(new boost::asio::io_service::work(io_service_))
{
kernel_ = make_shared<SwganhKernel>(io_service_);
running_ = false;
initialized_ = false;
Initialize(argc, argv);
Start();
}
SwganhApp::~SwganhApp()
{
Stop();
// Shutdown Event Dispatcher
kernel_->GetEventDispatcher()->Shutdown();
kernel_.reset();
io_work_.reset();
// join the threadpool threads until each one has exited.
for_each(io_threads_.begin(), io_threads_.end(), std::mem_fn(&boost::thread::join));
}
void SwganhApp::Initialize(int argc, char* argv[]) {
// Init Logging
SetupLogging_();
// Load the configuration
LoadAppConfig_(argc, argv);
auto app_config = kernel_->GetAppConfig();
// Initialize kernel resources
kernel_->GetDatabaseManager()->registerStorageType(
"galaxy_manager",
app_config.galaxy_manager_db.schema,
app_config.galaxy_manager_db.host,
app_config.galaxy_manager_db.username,
app_config.galaxy_manager_db.password);
kernel_->GetDatabaseManager()->registerStorageType(
"galaxy",
app_config.galaxy_db.schema,
app_config.galaxy_db.host,
app_config.galaxy_db.username,
app_config.galaxy_db.password);
CleanupServices_();
// append command dir
std::string py_path = "import sys; sys.path.append('.'); sys.path.append('" + app_config.script_directory + "');";
{
swganh::scripting::ScopedGilLock lock;
PyRun_SimpleString(py_path.c_str());
}
// Load the plugin configuration.
LoadPlugins_(app_config.plugins);
// Load core services
LoadCoreServices_();
initialized_ = true;
}
void SwganhApp::Start() {
if (!initialized_) {
throw std::runtime_error("Called application Start before Initialize");
}
running_ = true;
// Start up a threadpool for running io_service based tasks/active objects
// The increment starts at 2 because the main thread of execution already counts
// as thread in use as does the console thread.
for (uint32_t i = 1; i < boost::thread::hardware_concurrency(); ++i) {
boost::thread t([this] () {
io_service_.run();
});
#ifdef _WIN32
SetPriorityClass(t.native_handle(), REALTIME_PRIORITY_CLASS);
#endif
io_threads_.push_back(move(t));
}
kernel_->GetServiceManager()->Start();
}
void SwganhApp::Stop() {
running_ = false;
}
bool SwganhApp::IsRunning() {
return running_;
}
SwganhKernel* SwganhApp::GetAppKernel() const {
return kernel_.get();
}
void SwganhApp::StartInteractiveConsole()
{
swganh::scripting::ScopedGilLock lock;
anh::Logger::getInstance().DisableConsoleLogging();
#ifdef WIN32
std::system("cls");
#else
if (std::system("clear") != 0)
{
LOG(::error) << "Error clearing screen, ignoring console mode";
return;
}
#endif
std::cout << "swgpy console " << VERSION_MAJOR << "." << VERSION_MINOR << "." << VERSION_PATCH << std::endl;
boost::python::object main = boost::python::object (boost::python::handle<>(boost::python::borrowed(
PyImport_AddModule("__main__")
)));
auto global_dict = main.attr("__dict__");
global_dict["kernel"] = boost::python::ptr(GetAppKernel());
PyRun_InteractiveLoop(stdin, "<stdin>");
anh::Logger::getInstance().EnableConsoleLogging();
}
void SwganhApp::LoadAppConfig_(int argc, char* argv[]) {
auto config_description = kernel_->GetAppConfig().BuildConfigDescription();
variables_map vm;
store(parse_command_line(argc, argv, config_description), vm);
ifstream config_file("config/swganh.cfg");
if (!config_file.is_open()) {
throw runtime_error("Unable to open the configuration file at: config/swganh.cfg");
}
try {
store(parse_config_file(config_file, config_description, true), vm);
} catch(...) {
throw runtime_error("Unable to parse the configuration file at: config/swganh.cfg");
}
notify(vm);
config_file.close();
if (vm.count("help")) {
std::cout << config_description << "\n\n";
exit(0);
}
}
void SwganhApp::LoadPlugins_(vector<string> plugins) {
LOG(info) << "Loading plugins...";
if (!plugins.empty()) {
auto plugin_manager = kernel_->GetPluginManager();
auto plugin_directory = kernel_->GetAppConfig().plugin_directory;
for_each(plugins.begin(), plugins.end(), [plugin_manager, plugin_directory] (const string& plugin) {
LOG(info) << "Loading plugin " << plugin;
plugin_manager->LoadPlugin(plugin, plugin_directory);
});
}
LOG(info) << "Finished Loading plugins...";
}
void SwganhApp::CleanupServices_() {
auto service_directory = kernel_->GetServiceDirectory();
auto services = service_directory->getServiceSnapshot(service_directory->galaxy());
if (services.empty()) {
return;
}
LOG(warning) << "Services were not shutdown properly";
for_each(services.begin(), services.end(), [this, &service_directory] (anh::service::ServiceDescription& service) {
service_directory->removeService(service);
});
}
void SwganhApp::LoadCoreServices_()
{
auto plugin_manager = kernel_->GetPluginManager();
auto registration_map = plugin_manager->registration_map();
regex rx("(?:.*\\:\\:)(.*Service)");
smatch m;
for_each(registration_map.begin(), registration_map.end(), [this, &rx, &m] (RegistrationMap::value_type& entry) {
std::string name = entry.first;
if (entry.first.length() > 7 && regex_match(name, m, rx)) {
auto service_name = m[1].str();
LOG(info) << "Loading Service " << name << "...";
auto service = kernel_->GetPluginManager()->CreateObject<anh::service::ServiceInterface>(name);
kernel_->GetServiceManager()->AddService(service_name, service);
LOG(info) << "Loaded Service " << name;
}
});
auto app_config = kernel_->GetAppConfig();
if(strcmp("simulation", app_config.server_mode.c_str()) == 0 || strcmp("all", app_config.server_mode.c_str()) == 0)
{
auto simulation_service = kernel_->GetServiceManager()->GetService<SimulationServiceInterface>("SimulationService");
simulation_service->StartScene("corellia");
simulation_service->StartScene("naboo");
}
}
void SwganhApp::SetupLogging_()
{
anh::Logger::getInstance().init("swganh");
}<|endoftext|> |
<commit_before>/*****************************************************************************
Licensed to Accellera Systems Initiative Inc. (Accellera) under one or
more contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright ownership.
Accellera licenses this file to you under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with the
License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
*****************************************************************************/
/*****************************************************************************
sc_bit.cpp -- Bit class.
Original Author: Gene Bushuyev, Synopsys, Inc.
*****************************************************************************/
/*****************************************************************************
MODIFICATION LOG - modifiers, enter your name, affiliation, date and
changes you are making here.
Name, Affiliation, Date:
Description of Modification:
*****************************************************************************/
// $Log: sc_bit.cpp,v $
// Revision 1.1.1.1 2006/12/15 20:20:04 acg
// SystemC 2.3
//
// Revision 1.6 2006/04/12 20:17:52 acg
// Andy Goodrich: enabled deprecation message for sc_bit.
//
// Revision 1.5 2006/01/25 00:31:15 acg
// Andy Goodrich: Changed over to use a standard message id of
// SC_ID_IEEE_1666_DEPRECATION for all deprecation messages.
//
// Revision 1.4 2006/01/24 20:50:55 acg
// Andy Goodrich: added warnings indicating that sc_bit is deprecated and that
// the C bool data type should be used in its place.
//
// Revision 1.3 2006/01/13 18:53:53 acg
// Andy Goodrich: added $Log command so that CVS comments are reproduced in
// the source.
//
#include <sstream>
#include "systemc/ext/dt/bit/sc_bit.hh"
#include "systemc/ext/dt/bit/sc_logic.hh"
#include "systemc/ext/utils/sc_report_handler.hh"
namespace sc_dt
{
// ----------------------------------------------------------------------------
// CLASS : sc_bit
//
// Bit class.
// Note: VSIA compatibility indicated.
// ----------------------------------------------------------------------------
// support methods
void
sc_bit::invalid_value(char c)
{
std::stringstream msg;
msg << "sc_bit('" << c << "')";
SC_REPORT_ERROR("value is not valid", msg.str().c_str());
sc_core::sc_abort(); // can't recover from here
}
void
sc_bit::invalid_value(int i)
{
std::stringstream msg;
msg << "sc_bit(" << i << ")";
SC_REPORT_ERROR("value is not valid", msg.str().c_str());
sc_core::sc_abort(); // can't recover from here
}
// constructors
sc_bit::sc_bit(const sc_logic &a) : m_val(a.to_bool()) // non-VSIA
{
sc_deprecated_sc_bit();
}
// assignment operators
sc_bit &
sc_bit::operator = (const sc_logic &b) // non-VSIA
{
return (*this = sc_bit(b));
}
// other methods
void
sc_bit::scan(::std::istream &is)
{
bool b;
is >> b;
*this = b;
}
void
sc_deprecated_sc_bit()
{
static bool warn_sc_bit_deprecated = true;
if (warn_sc_bit_deprecated) {
warn_sc_bit_deprecated = false;
SC_REPORT_INFO("/IEEE_Std_1666/deprecated",
"sc_bit is deprecated, use bool instead");
}
}
} // namespace sc_dt
<commit_msg>systemc: Adjust a warning to match Accellera.<commit_after>/*****************************************************************************
Licensed to Accellera Systems Initiative Inc. (Accellera) under one or
more contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright ownership.
Accellera licenses this file to you under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with the
License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
*****************************************************************************/
/*****************************************************************************
sc_bit.cpp -- Bit class.
Original Author: Gene Bushuyev, Synopsys, Inc.
*****************************************************************************/
/*****************************************************************************
MODIFICATION LOG - modifiers, enter your name, affiliation, date and
changes you are making here.
Name, Affiliation, Date:
Description of Modification:
*****************************************************************************/
// $Log: sc_bit.cpp,v $
// Revision 1.1.1.1 2006/12/15 20:20:04 acg
// SystemC 2.3
//
// Revision 1.6 2006/04/12 20:17:52 acg
// Andy Goodrich: enabled deprecation message for sc_bit.
//
// Revision 1.5 2006/01/25 00:31:15 acg
// Andy Goodrich: Changed over to use a standard message id of
// SC_ID_IEEE_1666_DEPRECATION for all deprecation messages.
//
// Revision 1.4 2006/01/24 20:50:55 acg
// Andy Goodrich: added warnings indicating that sc_bit is deprecated and that
// the C bool data type should be used in its place.
//
// Revision 1.3 2006/01/13 18:53:53 acg
// Andy Goodrich: added $Log command so that CVS comments are reproduced in
// the source.
//
#include <sstream>
#include "systemc/ext/dt/bit/sc_bit.hh"
#include "systemc/ext/dt/bit/sc_logic.hh"
#include "systemc/ext/utils/sc_report_handler.hh"
namespace sc_dt
{
// ----------------------------------------------------------------------------
// CLASS : sc_bit
//
// Bit class.
// Note: VSIA compatibility indicated.
// ----------------------------------------------------------------------------
// support methods
void
sc_bit::invalid_value(char c)
{
std::stringstream msg;
msg << "sc_bit('" << c << "')";
SC_REPORT_ERROR("value is not valid", msg.str().c_str());
sc_core::sc_abort(); // can't recover from here
}
void
sc_bit::invalid_value(int i)
{
std::stringstream msg;
msg << "sc_bit(" << i << ")";
SC_REPORT_ERROR("value is not valid", msg.str().c_str());
sc_core::sc_abort(); // can't recover from here
}
// constructors
sc_bit::sc_bit(const sc_logic &a) : m_val(a.to_bool()) // non-VSIA
{
sc_deprecated_sc_bit();
}
// assignment operators
sc_bit &
sc_bit::operator = (const sc_logic &b) // non-VSIA
{
return (*this = sc_bit(b));
}
// other methods
void
sc_bit::scan(::std::istream &is)
{
bool b;
is >> b;
*this = b;
}
void
sc_deprecated_sc_bit()
{
static bool warn_sc_bit_deprecated = true;
if (warn_sc_bit_deprecated) {
warn_sc_bit_deprecated = false;
SC_REPORT_INFO("(I804) /IEEE_Std_1666/deprecated",
"sc_bit is deprecated, use bool instead");
}
}
} // namespace sc_dt
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: salvd.cxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: bmahbod $ $Date: 2001-03-12 23:15:32 $
*
* 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): _______________________________________
*
*
************************************************************************/
#define _SV_SALVD_CXX
#ifndef _SV_SALVD_HXX
#include <salvd.hxx>
#endif
// =======================================================================
// =======================================================================
static BOOL InitVirtualDeviceGWorld ( SalVirDevDataPtr rSalVirDevData )
{
BOOL bVirtualDeviceGWorldInited = FALSE;
if ( ( rSalVirDevData != NULL )
&& ( rSalVirDevData->mpGraphics != NULL )
)
{
Rect aBoundsRect;
short nRectLeft = 0;
short nRectTop = 0;
short nRectRight = rSalVirDevData->mnWidth;
short nRectBottom = rSalVirDevData->mnHeight;
short nPixelDepth = rSalVirDevData->mnBitCount;
GWorldPtr pGWorld = NULL;
CTabHandle hCTable = NULL;
GDHandle hGDevice = NULL;
GWorldFlags nFlags = noNewDevice;
OSStatus nOSStatus = noErr;
// Set the dimensions of the GWorldPtr
MacSetRect( &aBoundsRect, nRectLeft, nRectTop, nRectRight, nRectBottom );
// Create the offscreen graphics context
nOSStatus = NewGWorld( &pGWorld,
nPixelDepth,
&aBoundsRect,
hCTable,
hGDevice,
nFlags
);
// If NewGWorld failed, try again with different flags
if ( nOSStatus != noErr )
{
nFlags = noErr;
nOSStatus = NewGWorld( &pGWorld,
nPixelDepth,
&aBoundsRect,
hCTable,
hGDevice,
nFlags
);
} // if
if ( ( nOSStatus == noErr )
&& ( pGWorld != NULL )
)
{
// Lock the virtual GWorld's port bits
rSalVirDevData->mpGraphics->maGraphicsData.mnOSStatus
= LockPortBits( pGWorld );
if ( rSalVirDevData->mpGraphics->maGraphicsData.mnOSStatus == noErr )
{
// Initialize the virtual graph port
rSalVirDevData->mpGraphics->maGraphicsData.mpCGrafPort
= pGWorld;
rSalVirDevData->mpGraphics->maGraphicsData.mpGWorld
= pGWorld;
// Initialize virtual port's GWorld attributes
rSalVirDevData->mpGraphics->maGraphicsData.mhGWorldPixMap
= GetGWorldPixMap( pGWorld );
// Unlock virtual GWorld's port bits
UnlockPortBits( pGWorld );
} // if
// Initialize virtual port's GWorld attributes
rSalVirDevData->mpGraphics->maGraphicsData.mbGWorldPixelsLocked = FALSE;
rSalVirDevData->mpGraphics->maGraphicsData.mbGWorldPixelsCopy = FALSE;
rSalVirDevData->mpGraphics->maGraphicsData.mbGWorldPixelsNew = FALSE;
rSalVirDevData->mpGraphics->maGraphicsData.mnGWorldFlags = noErr;
// Initialize the virtual port's brush attributes
rSalVirDevData->mpGraphics->maGraphicsData.mbBrushTransparent = FALSE;
rSalVirDevData->mpGraphics->maGraphicsData.maBrushColor = GetBlackColor( );
// Initialize the virtual port's font attributes
rSalVirDevData->mpGraphics->maGraphicsData.maFontColor = GetBlackColor( );
rSalVirDevData->mpGraphics->maGraphicsData.mnFontID = kFontIDGeneva;
rSalVirDevData->mpGraphics->maGraphicsData.mnFontSize = 10;
rSalVirDevData->mpGraphics->maGraphicsData.mnFontStyle = normal;
// Initialize virtual port's clip regions
rSalVirDevData->mpGraphics->maGraphicsData.mhClipRgn = NULL;
rSalVirDevData->mpGraphics->maGraphicsData.mbClipRgnChanged = FALSE;
// Initilaize virtual port's status flags
rSalVirDevData->mpGraphics->maGraphicsData.mbPrinter = FALSE;
rSalVirDevData->mpGraphics->maGraphicsData.mbVirDev = TRUE;
rSalVirDevData->mpGraphics->maGraphicsData.mbWindow = FALSE;
rSalVirDevData->mpGraphics->maGraphicsData.mbScreen = TRUE;
bVirtualDeviceGWorldInited = TRUE;
} // if
} // if
return bVirtualDeviceGWorldInited;
} //InitVirtualDeviceGWorld
// =======================================================================
// =======================================================================
SalVirtualDevice::SalVirtualDevice()
{
maVirDevData.mpGraphics = NULL;
maVirDevData.mnBitCount = 0;
maVirDevData.mnWidth = 0;
maVirDevData.mnHeight = 0;
maVirDevData.mbGraphics = FALSE;
} // Constructor
// -----------------------------------------------------------------------
SalVirtualDevice::~SalVirtualDevice()
{
if ( maVirDevData.mpGraphics != NULL )
{
// Delete exisiting clip regions, offscreen graphic world,
// and its associated colour graph port
delete maVirDevData.mpGraphics;
} // if
} // Destructor
// -----------------------------------------------------------------------
SalGraphics* SalVirtualDevice::GetGraphics()
{
if ( maVirDevData.mbGraphics )
{
return NULL;
} // if
if ( !maVirDevData.mpGraphics )
{
maVirDevData.mpGraphics = new SalGraphics;
maVirDevData.mbGraphics = InitVirtualDeviceGWorld( &maVirDevData );
if ( !maVirDevData.mbGraphics )
{
delete maVirDevData.mpGraphics;
maVirDevData.mpGraphics = NULL;
} // if
} // if
return maVirDevData.mpGraphics;
} // SalVirtualDevice::GetGraphics
// -----------------------------------------------------------------------
void SalVirtualDevice::ReleaseGraphics( SalGraphics *pGraphics )
{
maVirDevData.mbGraphics = FALSE;
} // SalVirtualDevice::ReleaseGraphics
// -----------------------------------------------------------------------
BOOL SalVirtualDevice::SetSize( long nDX, long nDY )
{
BOOL bSizeSet = FALSE;
// If we have already created a graphics context, dispose of it,
// by deleting exisiting clip regions, offscreen graphic worlds,
// and its associated colour graph port
if ( ( ( maVirDevData.mpGraphics->maGraphicsData.mbGWorldPixelsCopy == TRUE )
|| ( maVirDevData.mpGraphics->maGraphicsData.mbGWorldPixelsNew == TRUE )
)
&& ( maVirDevData.mpGraphics->maGraphicsData.mhGWorldPixMap != NULL )
)
{
DisposePixMap( maVirDevData.mpGraphics->maGraphicsData.mhGWorldPixMap );
} // if
if ( maVirDevData.mpGraphics->maGraphicsData.mhClipRgn != NULL )
{
DisposeRgn( maVirDevData.mpGraphics->maGraphicsData.mhClipRgn );
} // if
if ( maVirDevData.mpGraphics->maGraphicsData.mpCGrafPort != NULL )
{
DisposeGWorld( maVirDevData.mpGraphics->maGraphicsData.mpCGrafPort );
maVirDevData.mpGraphics->maGraphicsData.mpGWorld = NULL;
maVirDevData.mpGraphics->maGraphicsData.mpCGrafPort = NULL;
} // if
// Create the offscreen graphics context
maVirDevData.mnWidth = nDX;
maVirDevData.mnHeight = nDY;
bSizeSet = InitVirtualDeviceGWorld( &maVirDevData );
return bSizeSet;
} // SalVirtualDevice::SetSize
// =======================================================================
// =======================================================================
<commit_msg>#101685#,#i6886#: merge OOO_STABLE_1_PORTS (1.13-1.13.22.1) -> HEAD<commit_after>/*************************************************************************
*
* $RCSfile: salvd.cxx,v $
*
* $Revision: 1.14 $
*
* last change: $Author: hr $ $Date: 2002-08-27 11:39:22 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#define _SV_SALVD_CXX
#ifndef _SV_SALVD_HXX
#include <salvd.hxx>
#endif
// =======================================================================
// =======================================================================
static BOOL InitVirtualDeviceGWorld ( SalVirDevDataPtr rSalVirDevData )
{
BOOL bVirtualDeviceGWorldInited = FALSE;
if ( ( rSalVirDevData != NULL )
&& ( rSalVirDevData->mpGraphics != NULL )
)
{
Rect aBoundsRect;
short nRectLeft = 0;
short nRectTop = 0;
short nRectRight = rSalVirDevData->mnWidth;
short nRectBottom = rSalVirDevData->mnHeight;
short nPixelDepth = rSalVirDevData->mnBitCount;
GWorldPtr pGWorld = NULL;
CTabHandle hCTable = NULL;
GDHandle hGDevice = NULL;
GWorldFlags nFlags = 0; // [ed] 12/1/01 Allow offscreen gworlds
OSStatus nOSStatus = noErr;
// Set the dimensions of the GWorldPtr
MacSetRect( &aBoundsRect, nRectLeft, nRectTop, nRectRight, nRectBottom );
// Create the offscreen graphics context
nOSStatus = NewGWorld( &pGWorld,
nPixelDepth,
&aBoundsRect,
hCTable,
hGDevice,
nFlags
);
// If NewGWorld failed, try again with different flags
if ( nOSStatus != noErr )
{
nFlags = noErr;
nOSStatus = NewGWorld( &pGWorld,
nPixelDepth,
&aBoundsRect,
hCTable,
hGDevice,
nFlags
);
} // if
if ( ( nOSStatus == noErr )
&& ( pGWorld != NULL )
)
{
// Lock the virtual GWorld's port bits
rSalVirDevData->mpGraphics->maGraphicsData.mnOSStatus
= LockPortBits( pGWorld );
if ( rSalVirDevData->mpGraphics->maGraphicsData.mnOSStatus == noErr )
{
// Initialize the virtual graph port
rSalVirDevData->mpGraphics->maGraphicsData.mpCGrafPort
= pGWorld;
rSalVirDevData->mpGraphics->maGraphicsData.mpGWorld
= pGWorld;
// Initialize virtual port's GWorld attributes
rSalVirDevData->mpGraphics->maGraphicsData.mhGWorldPixMap
= GetGWorldPixMap( pGWorld );
// Unlock virtual GWorld's port bits
UnlockPortBits( pGWorld );
} // if
// Initialize virtual port's GWorld attributes
rSalVirDevData->mpGraphics->maGraphicsData.mbGWorldPixelsLocked = FALSE;
rSalVirDevData->mpGraphics->maGraphicsData.mbGWorldPixelsCopy = FALSE;
rSalVirDevData->mpGraphics->maGraphicsData.mbGWorldPixelsNew = FALSE;
rSalVirDevData->mpGraphics->maGraphicsData.mnGWorldFlags = noErr;
// Initialize the virtual port's brush attributes
rSalVirDevData->mpGraphics->maGraphicsData.mbBrushTransparent = FALSE;
rSalVirDevData->mpGraphics->maGraphicsData.maBrushColor = GetBlackColor( );
// Initialize the virtual port's font attributes
rSalVirDevData->mpGraphics->maGraphicsData.maFontColor = GetBlackColor( );
rSalVirDevData->mpGraphics->maGraphicsData.mnFontID = kFontIDGeneva;
rSalVirDevData->mpGraphics->maGraphicsData.mnFontSize = 10;
rSalVirDevData->mpGraphics->maGraphicsData.mnFontStyle = normal;
// Initialize virtual port's clip regions
rSalVirDevData->mpGraphics->maGraphicsData.mhClipRgn = NULL;
rSalVirDevData->mpGraphics->maGraphicsData.mbClipRgnChanged = FALSE;
// Initilaize virtual port's status flags
rSalVirDevData->mpGraphics->maGraphicsData.mbPrinter = FALSE;
rSalVirDevData->mpGraphics->maGraphicsData.mbVirDev = TRUE;
rSalVirDevData->mpGraphics->maGraphicsData.mbWindow = FALSE;
rSalVirDevData->mpGraphics->maGraphicsData.mbScreen = TRUE;
bVirtualDeviceGWorldInited = TRUE;
} // if
} // if
return bVirtualDeviceGWorldInited;
} //InitVirtualDeviceGWorld
// =======================================================================
// =======================================================================
SalVirtualDevice::SalVirtualDevice()
{
maVirDevData.mpGraphics = NULL;
maVirDevData.mnBitCount = 0;
maVirDevData.mnWidth = 0;
maVirDevData.mnHeight = 0;
maVirDevData.mbGraphics = FALSE;
} // Constructor
// -----------------------------------------------------------------------
SalVirtualDevice::~SalVirtualDevice()
{
if ( maVirDevData.mpGraphics != NULL )
{
// Delete exisiting clip regions, offscreen graphic world,
// and its associated colour graph port
delete maVirDevData.mpGraphics;
} // if
} // Destructor
// -----------------------------------------------------------------------
SalGraphics* SalVirtualDevice::GetGraphics()
{
if ( maVirDevData.mbGraphics )
{
return NULL;
} // if
if ( !maVirDevData.mpGraphics )
{
maVirDevData.mpGraphics = new SalGraphics;
maVirDevData.mbGraphics = InitVirtualDeviceGWorld( &maVirDevData );
if ( !maVirDevData.mbGraphics )
{
delete maVirDevData.mpGraphics;
maVirDevData.mpGraphics = NULL;
} // if
} // if
return maVirDevData.mpGraphics;
} // SalVirtualDevice::GetGraphics
// -----------------------------------------------------------------------
void SalVirtualDevice::ReleaseGraphics( SalGraphics *pGraphics )
{
maVirDevData.mbGraphics = FALSE;
} // SalVirtualDevice::ReleaseGraphics
// -----------------------------------------------------------------------
BOOL SalVirtualDevice::SetSize( long nDX, long nDY )
{
BOOL bSizeSet = FALSE;
// If we have already created a graphics context, dispose of it,
// by deleting exisiting clip regions, offscreen graphic worlds,
// and its associated colour graph port
if ( ( ( maVirDevData.mpGraphics->maGraphicsData.mbGWorldPixelsCopy == TRUE )
|| ( maVirDevData.mpGraphics->maGraphicsData.mbGWorldPixelsNew == TRUE )
)
&& ( maVirDevData.mpGraphics->maGraphicsData.mhGWorldPixMap != NULL )
)
{
DisposePixMap( maVirDevData.mpGraphics->maGraphicsData.mhGWorldPixMap );
} // if
if ( maVirDevData.mpGraphics->maGraphicsData.mhClipRgn != NULL )
{
DisposeRgn( maVirDevData.mpGraphics->maGraphicsData.mhClipRgn );
} // if
if ( maVirDevData.mpGraphics->maGraphicsData.mpCGrafPort != NULL )
{
DisposeGWorld( maVirDevData.mpGraphics->maGraphicsData.mpCGrafPort );
maVirDevData.mpGraphics->maGraphicsData.mpGWorld = NULL;
maVirDevData.mpGraphics->maGraphicsData.mpCGrafPort = NULL;
} // if
// Create the offscreen graphics context
maVirDevData.mnWidth = nDX;
maVirDevData.mnHeight = nDY;
bSizeSet = InitVirtualDeviceGWorld( &maVirDevData );
return bSizeSet;
} // SalVirtualDevice::SetSize
// =======================================================================
// =======================================================================
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: tabpage.cxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: obo $ $Date: 2006-09-17 12:22:35 $
*
* 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_vcl.hxx"
#include <tools/ref.hxx>
#ifndef _SV_RC_H
#include <tools/rc.h>
#endif
#ifndef _SV_SVDATA_HXX
#include <svdata.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <svapp.hxx>
#endif
#ifndef _SV_EVENT_HXX
#include <event.hxx>
#endif
#ifndef _SV_TABPAGE_HXX
#include <tabpage.hxx>
#endif
#ifndef _SV_TABCTRL_HXX
#include <tabctrl.hxx>
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLE_HPP_
#include <com/sun/star/accessibility/XAccessible.hpp>
#endif
// =======================================================================
void TabPage::ImplInit( Window* pParent, WinBits nStyle )
{
if ( !(nStyle & WB_NODIALOGCONTROL) )
nStyle |= WB_DIALOGCONTROL;
Window::ImplInit( pParent, nStyle, NULL );
ImplInitSettings();
// if the tabpage is drawn (ie filled) by a native widget, make sure all contols will have transparent background
// otherwise they will paint with a wrong background
if( IsNativeControlSupported(CTRL_TAB_BODY, PART_ENTIRE_CONTROL) && GetParent() && (GetParent()->GetType() == WINDOW_TABCONTROL) )
EnableChildTransparentMode( TRUE );
}
// -----------------------------------------------------------------------
void TabPage::ImplInitSettings()
{
Window* pParent = GetParent();
if ( pParent->IsChildTransparentModeEnabled() && !IsControlBackground() )
{
EnableChildTransparentMode( TRUE );
SetParentClipMode( PARENTCLIPMODE_NOCLIP );
SetPaintTransparent( TRUE );
SetBackground();
}
else
{
EnableChildTransparentMode( FALSE );
SetParentClipMode( 0 );
SetPaintTransparent( FALSE );
if ( IsControlBackground() )
SetBackground( GetControlBackground() );
else
SetBackground( pParent->GetBackground() );
}
}
// -----------------------------------------------------------------------
TabPage::TabPage( Window* pParent, WinBits nStyle ) :
Window( WINDOW_TABPAGE )
{
ImplInit( pParent, nStyle );
}
// -----------------------------------------------------------------------
TabPage::TabPage( Window* pParent, const ResId& rResId ) :
Window( WINDOW_TABPAGE )
{
rResId.SetRT( RSC_TABPAGE );
WinBits nStyle = ImplInitRes( rResId );
ImplInit( pParent, nStyle );
ImplLoadRes( rResId );
if ( !(nStyle & WB_HIDE) )
Show();
}
// -----------------------------------------------------------------------
void TabPage::StateChanged( StateChangedType nType )
{
Window::StateChanged( nType );
if ( nType == STATE_CHANGE_INITSHOW )
{
if ( GetSettings().GetStyleSettings().GetAutoMnemonic() )
ImplWindowAutoMnemonic( this );
}
else if ( nType == STATE_CHANGE_CONTROLBACKGROUND )
{
ImplInitSettings();
Invalidate();
}
}
// -----------------------------------------------------------------------
void TabPage::DataChanged( const DataChangedEvent& rDCEvt )
{
Window::DataChanged( rDCEvt );
if ( (rDCEvt.GetType() == DATACHANGED_SETTINGS) &&
(rDCEvt.GetFlags() & SETTINGS_STYLE) )
{
ImplInitSettings();
Invalidate();
}
}
// -----------------------------------------------------------------------
void TabPage::Paint( const Rectangle& )
{
// draw native tabpage only inside tabcontrols, standalone tabpages look ugly (due to bad dialog design)
if( IsNativeControlSupported(CTRL_TAB_BODY, PART_ENTIRE_CONTROL) && GetParent() && (GetParent()->GetType() == WINDOW_TABCONTROL) )
{
const ImplControlValue aControlValue( BUTTONVALUE_DONTKNOW, rtl::OUString(), 0 );
ControlState nState = CTRL_STATE_ENABLED;
int part = PART_ENTIRE_CONTROL;
if ( !IsEnabled() )
nState &= ~CTRL_STATE_ENABLED;
if ( HasFocus() )
nState |= CTRL_STATE_FOCUSED;
Point aPoint;
// pass the whole window region to NWF as the tab body might be a gradient or bitmap
// that has to be scaled properly, clipping makes sure that we do not paint too much
Region aCtrlRegion( Rectangle( aPoint, GetOutputSizePixel() ) );
DrawNativeControl( CTRL_TAB_BODY, part, aCtrlRegion, nState,
aControlValue, rtl::OUString() );
}
}
// -----------------------------------------------------------------------
void TabPage::ActivatePage()
{
}
// -----------------------------------------------------------------------
void TabPage::DeactivatePage()
{
}
// -----------------------------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > TabPage::CreateAccessible()
{
// TODO: remove this method (incompatible)
return Window::CreateAccessible();
}
<commit_msg>INTEGRATION: CWS jl61 (1.13.230); FILE MERGED 2007/06/13 08:23:02 ab 1.13.230.1: #i76438# TabPage::Draw()<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: tabpage.cxx,v $
*
* $Revision: 1.14 $
*
* last change: $Author: kz $ $Date: 2007-06-20 10:38:36 $
*
* 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_vcl.hxx"
#include <tools/ref.hxx>
#ifndef _SV_RC_H
#include <tools/rc.h>
#endif
#ifndef _SV_SVDATA_HXX
#include <svdata.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <svapp.hxx>
#endif
#ifndef _SV_EVENT_HXX
#include <event.hxx>
#endif
#ifndef _SV_TABPAGE_HXX
#include <tabpage.hxx>
#endif
#ifndef _SV_TABCTRL_HXX
#include <tabctrl.hxx>
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLE_HPP_
#include <com/sun/star/accessibility/XAccessible.hpp>
#endif
// =======================================================================
void TabPage::ImplInit( Window* pParent, WinBits nStyle )
{
if ( !(nStyle & WB_NODIALOGCONTROL) )
nStyle |= WB_DIALOGCONTROL;
Window::ImplInit( pParent, nStyle, NULL );
ImplInitSettings();
// if the tabpage is drawn (ie filled) by a native widget, make sure all contols will have transparent background
// otherwise they will paint with a wrong background
if( IsNativeControlSupported(CTRL_TAB_BODY, PART_ENTIRE_CONTROL) && GetParent() && (GetParent()->GetType() == WINDOW_TABCONTROL) )
EnableChildTransparentMode( TRUE );
}
// -----------------------------------------------------------------------
void TabPage::ImplInitSettings()
{
Window* pParent = GetParent();
if ( pParent->IsChildTransparentModeEnabled() && !IsControlBackground() )
{
EnableChildTransparentMode( TRUE );
SetParentClipMode( PARENTCLIPMODE_NOCLIP );
SetPaintTransparent( TRUE );
SetBackground();
}
else
{
EnableChildTransparentMode( FALSE );
SetParentClipMode( 0 );
SetPaintTransparent( FALSE );
if ( IsControlBackground() )
SetBackground( GetControlBackground() );
else
SetBackground( pParent->GetBackground() );
}
}
// -----------------------------------------------------------------------
TabPage::TabPage( Window* pParent, WinBits nStyle ) :
Window( WINDOW_TABPAGE )
{
ImplInit( pParent, nStyle );
}
// -----------------------------------------------------------------------
TabPage::TabPage( Window* pParent, const ResId& rResId ) :
Window( WINDOW_TABPAGE )
{
rResId.SetRT( RSC_TABPAGE );
WinBits nStyle = ImplInitRes( rResId );
ImplInit( pParent, nStyle );
ImplLoadRes( rResId );
if ( !(nStyle & WB_HIDE) )
Show();
}
// -----------------------------------------------------------------------
void TabPage::StateChanged( StateChangedType nType )
{
Window::StateChanged( nType );
if ( nType == STATE_CHANGE_INITSHOW )
{
if ( GetSettings().GetStyleSettings().GetAutoMnemonic() )
ImplWindowAutoMnemonic( this );
}
else if ( nType == STATE_CHANGE_CONTROLBACKGROUND )
{
ImplInitSettings();
Invalidate();
}
}
// -----------------------------------------------------------------------
void TabPage::DataChanged( const DataChangedEvent& rDCEvt )
{
Window::DataChanged( rDCEvt );
if ( (rDCEvt.GetType() == DATACHANGED_SETTINGS) &&
(rDCEvt.GetFlags() & SETTINGS_STYLE) )
{
ImplInitSettings();
Invalidate();
}
}
// -----------------------------------------------------------------------
void TabPage::Paint( const Rectangle& )
{
// draw native tabpage only inside tabcontrols, standalone tabpages look ugly (due to bad dialog design)
if( IsNativeControlSupported(CTRL_TAB_BODY, PART_ENTIRE_CONTROL) && GetParent() && (GetParent()->GetType() == WINDOW_TABCONTROL) )
{
const ImplControlValue aControlValue( BUTTONVALUE_DONTKNOW, rtl::OUString(), 0 );
ControlState nState = CTRL_STATE_ENABLED;
int part = PART_ENTIRE_CONTROL;
if ( !IsEnabled() )
nState &= ~CTRL_STATE_ENABLED;
if ( HasFocus() )
nState |= CTRL_STATE_FOCUSED;
Point aPoint;
// pass the whole window region to NWF as the tab body might be a gradient or bitmap
// that has to be scaled properly, clipping makes sure that we do not paint too much
Region aCtrlRegion( Rectangle( aPoint, GetOutputSizePixel() ) );
DrawNativeControl( CTRL_TAB_BODY, part, aCtrlRegion, nState,
aControlValue, rtl::OUString() );
}
}
// -----------------------------------------------------------------------
void TabPage::Draw( OutputDevice* pDev, const Point& rPos, const Size& rSize, ULONG )
{
Point aPos = pDev->LogicToPixel( rPos );
Size aSize = pDev->LogicToPixel( rSize );
ImplInitSettings();
pDev->Push();
pDev->SetMapMode();
pDev->SetLineColor();
pDev->SetFillColor( GetSettings().GetStyleSettings().GetDialogColor() );
pDev->DrawRect( Rectangle( aPos, aSize ) );
pDev->Pop();
}
// -----------------------------------------------------------------------
void TabPage::ActivatePage()
{
}
// -----------------------------------------------------------------------
void TabPage::DeactivatePage()
{
}
// -----------------------------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > TabPage::CreateAccessible()
{
// TODO: remove this method (incompatible)
return Window::CreateAccessible();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: salogl.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: hr $ $Date: 2004-05-10 15:59:38 $
*
* 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 <salunx.h>
#ifndef _SV_SALDATA_HXX
#include <saldata.hxx>
#endif
#ifndef _SV_SALDISP_HXX
#include <saldisp.hxx>
#endif
#ifndef _SV_SALOGL_H
#include <salogl.h>
#endif
#ifndef _SV_SALGDI_H
#include <salgdi.h>
#endif
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
using namespace rtl;
// ------------
// - Lib-Name -
// ------------
#ifdef MACOSX
#define OGL_LIBNAME "libGL.dylib"
#else
#define OGL_LIBNAME "libGL.so"
#endif
// ----------
// - Macros -
// ----------
// -----------------
// - Statics init. -
// -----------------
// Members
GLXContext X11SalOpenGL::maGLXContext = 0;
Display* X11SalOpenGL::mpDisplay = 0;
XVisualInfo* X11SalOpenGL::mpVisualInfo = 0;
BOOL X11SalOpenGL::mbHaveGLVisual = FALSE;
#ifdef MACOSX
oslModule X11SalOpenGL::mpGLLib = 0;
#else
void * X11SalOpenGL::mpGLLib = 0;
#endif
ULONG X11SalOpenGL::mnOGLState = OGL_STATE_UNLOADED;
GLXContext (*X11SalOpenGL::pCreateContext)( Display *, XVisualInfo *, GLXContext, Bool ) = 0;
void (*X11SalOpenGL::pDestroyContext)( Display *, GLXContext ) = 0;
GLXContext (*X11SalOpenGL::pGetCurrentContext)( ) = 0;
Bool (*X11SalOpenGL::pMakeCurrent)( Display *, GLXDrawable, GLXContext ) = 0;
void (*X11SalOpenGL::pSwapBuffers)( Display*, GLXDrawable ) = 0;
int (*X11SalOpenGL::pGetConfig)( Display*, XVisualInfo*, int, int* ) = 0;
void (*X11SalOpenGL::pFlush)() = 0;
// -------------
// - X11SalOpenGL -
// -------------
X11SalOpenGL::X11SalOpenGL( SalGraphics* pSGraphics )
{
X11SalGraphics* pGraphics = static_cast<X11SalGraphics*>(pSGraphics);
mpDisplay = pGraphics->GetXDisplay();
mpVisualInfo = pGraphics->GetDisplay()->GetVisual();
maDrawable = pGraphics->GetDrawable();
}
// ------------------------------------------------------------------------
X11SalOpenGL::~X11SalOpenGL()
{
}
// ------------------------------------------------------------------------
bool X11SalOpenGL::IsValid()
{
if( OGL_STATE_UNLOADED == mnOGLState )
{
BOOL bHasGLX = FALSE;
char **ppExtensions;
int nExtensions;
if( *DisplayString( mpDisplay ) == ':' ||
! strncmp( DisplayString( mpDisplay ), "localhost:", 10 )
)
{
// GLX only on local displays due to strange problems
// with remote GLX
ppExtensions = XListExtensions( mpDisplay, &nExtensions );
for( int i=0; i < nExtensions; i++ )
{
if( ! strncmp( "GLX", ppExtensions[ i ], 3 ) )
{
bHasGLX = TRUE;
break;
}
}
XFreeExtensionList( ppExtensions );
#if OSL_DEBUG_LEVEL > 1
if( ! bHasGLX )
fprintf( stderr, "XServer does not support GLX extension\n" );
#endif
if( bHasGLX )
{
/*
* #82406# the XFree4.0 GLX module does not seem
* to work that great, at least not the one that comes
* with the default installation and Matrox cards.
* Since these are common we disable usage of
* OpenGL per default.
*/
static const char* pOverrideGLX = getenv( "SAL_ENABLE_GLX_XFREE4" );
if( ! strncmp( ServerVendor( mpDisplay ), "The XFree86 Project, Inc", 24 ) &&
VendorRelease( mpDisplay ) >= 4000 &&
! pOverrideGLX
)
{
#if OSL_DEBUG_LEVEL > 1
fprintf( stderr, "disabling GLX usage on XFree >= 4.0\n" );
#endif
bHasGLX = FALSE;
}
}
}
if( bHasGLX && mpVisualInfo->c_class == TrueColor && ImplInit() )
{
int nDoubleBuffer = 0;
int nHaveGL = 0;
pGetConfig( mpDisplay, mpVisualInfo,
GLX_USE_GL, &nHaveGL );
pGetConfig( mpDisplay, mpVisualInfo,
GLX_DOUBLEBUFFER, &nDoubleBuffer );
if( nHaveGL && ! nDoubleBuffer )
{
SalDisplay* pSalDisplay = GetSalData()->GetDisplay();
BOOL bPreviousState =
pSalDisplay->GetXLib()->GetIgnoreXErrors();
pSalDisplay->GetXLib()->SetIgnoreXErrors( TRUE );
mbHaveGLVisual = TRUE;
maGLXContext = pCreateContext( mpDisplay, mpVisualInfo, 0, True );
if( pSalDisplay->GetXLib()->WasXError() )
mbHaveGLVisual = FALSE;
else
pMakeCurrent( mpDisplay, maDrawable, maGLXContext );
if( pSalDisplay->GetXLib()->WasXError() )
mbHaveGLVisual = FALSE;
pSalDisplay->GetXLib()->SetIgnoreXErrors( bPreviousState );
if( mbHaveGLVisual )
mnOGLState = OGL_STATE_VALID;
else
maGLXContext = None;
}
}
if( mnOGLState != OGL_STATE_VALID )
{
ImplFreeLib();
mnOGLState = OGL_STATE_INVALID;
}
#if OSL_DEBUG_LEVEL > 1
if( mnOGLState == OGL_STATE_VALID )
fprintf( stderr, "Using GLX on visual id %x.\n", mpVisualInfo->visualid );
else
fprintf( stderr, "Not using GLX.\n" );
#endif
}
return mnOGLState == OGL_STATE_VALID ? TRUE : FALSE;
}
// ------------------------------------------------------------------------
void X11SalOpenGL::Release()
{
ImplFreeLib();
}
// ------------------------------------------------------------------------
void* X11SalOpenGL::GetOGLFnc( const char *pFncName )
{
return resolveSymbol( pFncName );
}
// ------------------------------------------------------------------------
void X11SalOpenGL::OGLEntry( SalGraphics* pGraphics )
{
GLXDrawable aDrawable = static_cast<X11SalGraphics*>(pGraphics)->GetDrawable();
if( aDrawable != maDrawable )
{
maDrawable = aDrawable;
pMakeCurrent( mpDisplay, maDrawable, maGLXContext );
}
}
// ------------------------------------------------------------------------
void X11SalOpenGL::OGLExit( SalGraphics* pGraphics )
{
}
// ------------------------------------------------------------------------
void X11SalOpenGL::ImplFreeLib()
{
if( mpGLLib )
{
if( maGLXContext && pDestroyContext )
pDestroyContext( mpDisplay, maGLXContext );
#ifdef MACOSX
osl_unloadModule( (oslModule) mpGLLib );
#else
osl_unloadModule( mpGLLib );
#endif
mpGLLib = 0;
pCreateContext = 0;
pDestroyContext = 0;
pGetCurrentContext = 0;
pMakeCurrent = 0;
pSwapBuffers = 0;
pGetConfig = 0;
}
}
// ------------------------------------------------------------------------
void* X11SalOpenGL::resolveSymbol( const char* pSymbol )
{
void* pSym = NULL;
if( mpGLLib )
{
OUString aSym = OUString::createFromAscii( pSymbol );
#ifdef MACOSX
pSym = osl_getSymbol( (oslModule) mpGLLib, aSym.pData );
#else
pSym = osl_getSymbol( mpGLLib, aSym.pData );
#endif
}
return pSym;
}
BOOL X11SalOpenGL::ImplInit()
{
if( ! mpGLLib )
{
ByteString sNoGL( getenv( "SAL_NOOPENGL" ) );
if( sNoGL.ToLowerAscii() == "true" )
return FALSE;
OUString aLibName( RTL_CONSTASCII_USTRINGPARAM( OGL_LIBNAME ) );
mpGLLib = osl_loadModule( aLibName.pData, SAL_LOADMODULE_NOW );
}
if( ! mpGLLib )
{
#if OSL_DEBUG_LEVEL > 1
fprintf( stderr, OGL_LIBNAME "could not be opened\n" );
#endif
return FALSE;
}
// Internal use
pCreateContext = (GLXContext(*)(Display*,XVisualInfo*,GLXContext,Bool ))
resolveSymbol( "glXCreateContext" );
pDestroyContext = (void(*)(Display*,GLXContext))
resolveSymbol( "glXDestroyContext" );
pGetCurrentContext = (GLXContext(*)())
resolveSymbol( "glXGetCurrentContext" );
pMakeCurrent = (Bool(*)(Display*,GLXDrawable,GLXContext))
resolveSymbol( "glXMakeCurrent" );
pSwapBuffers=(void(*)(Display*, GLXDrawable))
resolveSymbol( "glXSwapBuffers" );
pGetConfig = (int(*)(Display*, XVisualInfo*, int, int* ))
resolveSymbol( "glXGetConfig" );
pFlush = (void(*)())
resolveSymbol( "glFlush" );
BOOL bRet = pCreateContext && pDestroyContext && pGetCurrentContext && pMakeCurrent && pSwapBuffers && pGetConfig ? TRUE : FALSE;
#if OSL_DEBUG_LEVEL > 1
if( ! bRet )
fprintf( stderr, "could not find all needed symbols in " OGL_LIBNAME "\n" );
#endif
return bRet;
}
void X11SalOpenGL::StartScene( SalGraphics* pGraphics )
{
// flush pending operations which otherwise might be drawn
// at the wrong time
XSync( mpDisplay, False );
}
void X11SalOpenGL::StopScene()
{
if( maDrawable )
{
pSwapBuffers( mpDisplay, maDrawable );
pFlush();
}
}
void X11SalOpenGL::MakeVisualWeights( Display* pDisplay,
XVisualInfo* pInfos,
int *pWeights,
int nVisuals )
{
BOOL bHasGLX = FALSE;
char **ppExtensions;
int nExtensions,i ;
// GLX only on local displays due to strange problems
// with remote GLX
if( ! ( *DisplayString( pDisplay ) == ':' ||
!strncmp( DisplayString( pDisplay ), "localhost:", 10 )
) )
return;
ppExtensions = XListExtensions( pDisplay, &nExtensions );
for( i=0; i < nExtensions; i++ )
{
if( ! strncmp( "GLX", ppExtensions[ i ], 3 ) )
{
bHasGLX = TRUE;
break;
}
}
XFreeExtensionList( ppExtensions );
if( ! bHasGLX )
return;
if( ! ImplInit() )
{
ImplFreeLib();
return;
}
for( i = 0; i < nVisuals; i++ )
{
int nDoubleBuffer = 0;
int nHaveGL = 0;
// a weight lesser than zero indicates an invalid visual (wrong screen)
if( pInfos[i].c_class == TrueColor && pWeights[i] >= 0)
{
pGetConfig( pDisplay, &pInfos[ i ], GLX_USE_GL, &nHaveGL );
pGetConfig( pDisplay, &pInfos[ i ], GLX_DOUBLEBUFFER, &nDoubleBuffer );
if( nHaveGL && ! nDoubleBuffer )
{
mbHaveGLVisual = TRUE;
pWeights[ i ] += 65536;
}
}
}
ImplFreeLib();
}
<commit_msg>INTEGRATION: CWS vcl30 (1.11.146); FILE MERGED 2004/11/09 17:28:06 pl 1.11.146.3: #i36899# Motif needed if JVM and GL want to coexist 2004/11/08 18:19:03 pl 1.11.146.2: #i36866# fix an obscure OpenGL <-> JVM interaction on Solaris 2004/11/02 13:23:10 pl 1.11.146.1: #i35773# do not unload GL lib before XCloseDisplay<commit_after>/*************************************************************************
*
* $RCSfile: salogl.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: obo $ $Date: 2004-11-15 12:10:40 $
*
* 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 <salunx.h>
#ifndef _SV_SALDATA_HXX
#include <saldata.hxx>
#endif
#ifndef _SV_SALDISP_HXX
#include <saldisp.hxx>
#endif
#ifndef _SV_SALOGL_H
#include <salogl.h>
#endif
#ifndef _SV_SALGDI_H
#include <salgdi.h>
#endif
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
using namespace rtl;
// ------------
// - Lib-Name -
// ------------
#ifdef MACOSX
#define OGL_LIBNAME "libGL.dylib"
#else
#define OGL_LIBNAME "libGL.so"
#endif
// ----------
// - Macros -
// ----------
// -----------------
// - Statics init. -
// -----------------
// Members
GLXContext X11SalOpenGL::maGLXContext = 0;
Display* X11SalOpenGL::mpDisplay = 0;
XVisualInfo* X11SalOpenGL::mpVisualInfo = 0;
BOOL X11SalOpenGL::mbHaveGLVisual = FALSE;
oslModule X11SalOpenGL::mpGLLib = 0;
#ifdef SOLARIS
oslModule aMotifLib;
#endif
ULONG X11SalOpenGL::mnOGLState = OGL_STATE_UNLOADED;
GLXContext (*X11SalOpenGL::pCreateContext)( Display *, XVisualInfo *, GLXContext, Bool ) = 0;
void (*X11SalOpenGL::pDestroyContext)( Display *, GLXContext ) = 0;
GLXContext (*X11SalOpenGL::pGetCurrentContext)( ) = 0;
Bool (*X11SalOpenGL::pMakeCurrent)( Display *, GLXDrawable, GLXContext ) = 0;
void (*X11SalOpenGL::pSwapBuffers)( Display*, GLXDrawable ) = 0;
int (*X11SalOpenGL::pGetConfig)( Display*, XVisualInfo*, int, int* ) = 0;
void (*X11SalOpenGL::pFlush)() = 0;
// -------------
// - X11SalOpenGL -
// -------------
X11SalOpenGL::X11SalOpenGL( SalGraphics* pSGraphics )
{
X11SalGraphics* pGraphics = static_cast<X11SalGraphics*>(pSGraphics);
mpDisplay = pGraphics->GetXDisplay();
mpVisualInfo = pGraphics->GetDisplay()->GetVisual();
maDrawable = pGraphics->GetDrawable();
}
// ------------------------------------------------------------------------
X11SalOpenGL::~X11SalOpenGL()
{
}
// ------------------------------------------------------------------------
bool X11SalOpenGL::IsValid()
{
if( OGL_STATE_UNLOADED == mnOGLState )
{
BOOL bHasGLX = FALSE;
char **ppExtensions;
int nExtensions;
if( *DisplayString( mpDisplay ) == ':' ||
! strncmp( DisplayString( mpDisplay ), "localhost:", 10 )
)
{
// GLX only on local displays due to strange problems
// with remote GLX
ppExtensions = XListExtensions( mpDisplay, &nExtensions );
for( int i=0; i < nExtensions; i++ )
{
if( ! strncmp( "GLX", ppExtensions[ i ], 3 ) )
{
bHasGLX = TRUE;
break;
}
}
XFreeExtensionList( ppExtensions );
#if OSL_DEBUG_LEVEL > 1
if( ! bHasGLX )
fprintf( stderr, "XServer does not support GLX extension\n" );
#endif
if( bHasGLX )
{
/*
* #82406# the XFree4.0 GLX module does not seem
* to work that great, at least not the one that comes
* with the default installation and Matrox cards.
* Since these are common we disable usage of
* OpenGL per default.
*/
static const char* pOverrideGLX = getenv( "SAL_ENABLE_GLX_XFREE4" );
if( ! strncmp( ServerVendor( mpDisplay ), "The XFree86 Project, Inc", 24 ) &&
VendorRelease( mpDisplay ) >= 4000 &&
! pOverrideGLX
)
{
#if OSL_DEBUG_LEVEL > 1
fprintf( stderr, "disabling GLX usage on XFree >= 4.0\n" );
#endif
bHasGLX = FALSE;
}
}
}
if( bHasGLX && mpVisualInfo->c_class == TrueColor && ImplInit() )
{
int nDoubleBuffer = 0;
int nHaveGL = 0;
pGetConfig( mpDisplay, mpVisualInfo,
GLX_USE_GL, &nHaveGL );
pGetConfig( mpDisplay, mpVisualInfo,
GLX_DOUBLEBUFFER, &nDoubleBuffer );
if( nHaveGL && ! nDoubleBuffer )
{
SalDisplay* pSalDisplay = GetSalData()->GetDisplay();
BOOL bPreviousState =
pSalDisplay->GetXLib()->GetIgnoreXErrors();
pSalDisplay->GetXLib()->SetIgnoreXErrors( TRUE );
mbHaveGLVisual = TRUE;
maGLXContext = pCreateContext( mpDisplay, mpVisualInfo, 0, True );
if( pSalDisplay->GetXLib()->WasXError() )
mbHaveGLVisual = FALSE;
else
pMakeCurrent( mpDisplay, maDrawable, maGLXContext );
if( pSalDisplay->GetXLib()->WasXError() )
mbHaveGLVisual = FALSE;
pSalDisplay->GetXLib()->SetIgnoreXErrors( bPreviousState );
if( mbHaveGLVisual )
mnOGLState = OGL_STATE_VALID;
else
maGLXContext = None;
}
}
if( mnOGLState != OGL_STATE_VALID )
mnOGLState = OGL_STATE_INVALID;
#if OSL_DEBUG_LEVEL > 1
if( mnOGLState == OGL_STATE_VALID )
fprintf( stderr, "Using GLX on visual id %x.\n", mpVisualInfo->visualid );
else
fprintf( stderr, "Not using GLX.\n" );
#endif
}
return mnOGLState == OGL_STATE_VALID ? TRUE : FALSE;
}
void X11SalOpenGL::Release()
{
if( maGLXContext && pDestroyContext )
pDestroyContext( mpDisplay, maGLXContext );
}
// ------------------------------------------------------------------------
void X11SalOpenGL::ReleaseLib()
{
if( mpGLLib )
{
osl_unloadModule( mpGLLib );
#ifdef SOLARIS
if( aMotifLib )
osl_unloadModule( aMotifLib );
#endif
mpGLLib = 0;
pCreateContext = 0;
pDestroyContext = 0;
pGetCurrentContext = 0;
pMakeCurrent = 0;
pSwapBuffers = 0;
pGetConfig = 0;
mnOGLState = OGL_STATE_UNLOADED;
}
}
// ------------------------------------------------------------------------
void* X11SalOpenGL::GetOGLFnc( const char *pFncName )
{
return resolveSymbol( pFncName );
}
// ------------------------------------------------------------------------
void X11SalOpenGL::OGLEntry( SalGraphics* pGraphics )
{
GLXDrawable aDrawable = static_cast<X11SalGraphics*>(pGraphics)->GetDrawable();
if( aDrawable != maDrawable )
{
maDrawable = aDrawable;
pMakeCurrent( mpDisplay, maDrawable, maGLXContext );
}
}
// ------------------------------------------------------------------------
void X11SalOpenGL::OGLExit( SalGraphics* pGraphics )
{
}
// ------------------------------------------------------------------------
void* X11SalOpenGL::resolveSymbol( const char* pSymbol )
{
void* pSym = NULL;
if( mpGLLib )
{
OUString aSym = OUString::createFromAscii( pSymbol );
pSym = osl_getSymbol( mpGLLib, aSym.pData );
}
return pSym;
}
BOOL X11SalOpenGL::ImplInit()
{
if( ! mpGLLib )
{
ByteString sNoGL( getenv( "SAL_NOOPENGL" ) );
if( sNoGL.ToLowerAscii() == "true" )
return FALSE;
sal_Int32 nRtldMode = SAL_LOADMODULE_NOW;
#ifdef SOLARIS
/* #i36866# an obscure interaction with jvm can let java crash
* if we do not use SAL_LOADMODULE_GLOBAL here
*/
nRtldMode |= SAL_LOADMODULE_GLOBAL;
/* #i36899# and we need Xm, too, else jvm will not work properly.
*/
OUString aMotifName( RTL_CONSTASCII_USTRINGPARAM( "libXm.so" ) );
aMotifLib = osl_loadModule( aMotifName.pData, nRtldMode );
#endif
OUString aLibName( RTL_CONSTASCII_USTRINGPARAM( OGL_LIBNAME ) );
mpGLLib = osl_loadModule( aLibName.pData, nRtldMode );
}
if( ! mpGLLib )
{
#if OSL_DEBUG_LEVEL > 1
fprintf( stderr, OGL_LIBNAME "could not be opened\n" );
#endif
return FALSE;
}
// Internal use
pCreateContext = (GLXContext(*)(Display*,XVisualInfo*,GLXContext,Bool ))
resolveSymbol( "glXCreateContext" );
pDestroyContext = (void(*)(Display*,GLXContext))
resolveSymbol( "glXDestroyContext" );
pGetCurrentContext = (GLXContext(*)())
resolveSymbol( "glXGetCurrentContext" );
pMakeCurrent = (Bool(*)(Display*,GLXDrawable,GLXContext))
resolveSymbol( "glXMakeCurrent" );
pSwapBuffers=(void(*)(Display*, GLXDrawable))
resolveSymbol( "glXSwapBuffers" );
pGetConfig = (int(*)(Display*, XVisualInfo*, int, int* ))
resolveSymbol( "glXGetConfig" );
pFlush = (void(*)())
resolveSymbol( "glFlush" );
BOOL bRet = pCreateContext && pDestroyContext && pGetCurrentContext && pMakeCurrent && pSwapBuffers && pGetConfig ? TRUE : FALSE;
#if OSL_DEBUG_LEVEL > 1
if( ! bRet )
fprintf( stderr, "could not find all needed symbols in " OGL_LIBNAME "\n" );
#endif
return bRet;
}
void X11SalOpenGL::StartScene( SalGraphics* pGraphics )
{
// flush pending operations which otherwise might be drawn
// at the wrong time
XSync( mpDisplay, False );
}
void X11SalOpenGL::StopScene()
{
if( maDrawable )
{
pSwapBuffers( mpDisplay, maDrawable );
pFlush();
}
}
void X11SalOpenGL::MakeVisualWeights( Display* pDisplay,
XVisualInfo* pInfos,
int *pWeights,
int nVisuals )
{
BOOL bHasGLX = FALSE;
char **ppExtensions;
int nExtensions,i ;
// GLX only on local displays due to strange problems
// with remote GLX
if( ! ( *DisplayString( pDisplay ) == ':' ||
!strncmp( DisplayString( pDisplay ), "localhost:", 10 )
) )
return;
ppExtensions = XListExtensions( pDisplay, &nExtensions );
for( i=0; i < nExtensions; i++ )
{
if( ! strncmp( "GLX", ppExtensions[ i ], 3 ) )
{
bHasGLX = TRUE;
break;
}
}
XFreeExtensionList( ppExtensions );
if( ! bHasGLX )
return;
if( ! ImplInit() )
return;
for( i = 0; i < nVisuals; i++ )
{
int nDoubleBuffer = 0;
int nHaveGL = 0;
// a weight lesser than zero indicates an invalid visual (wrong screen)
if( pInfos[i].c_class == TrueColor && pWeights[i] >= 0)
{
pGetConfig( pDisplay, &pInfos[ i ], GLX_USE_GL, &nHaveGL );
pGetConfig( pDisplay, &pInfos[ i ], GLX_DOUBLEBUFFER, &nDoubleBuffer );
if( nHaveGL && ! nDoubleBuffer )
{
mbHaveGLVisual = TRUE;
pWeights[ i ] += 65536;
}
}
}
}
<|endoftext|> |
<commit_before>//
// Copyright 2011-2015 Jeff Bush
//
// 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 <iostream>
#include "Vverilator_tb.h"
#include "verilated.h"
#if VM_TRACE
#include <verilated_vcd_c.h>
#endif
using namespace std;
namespace
{
vluint64_t currentTime = 0;
}
// Called whenever the $time variable is accessed.
double sc_time_stamp()
{
return currentTime;
}
int main(int argc, char **argv, char **env)
{
unsigned int randomSeed;
unsigned int randomizeRegs;
Verilated::commandArgs(argc, argv);
Verilated::debug(0);
// Initialize random seed.
if (VL_VALUEPLUSARGS_II(32, "randseed=", 'd', randomSeed))
srand48(randomSeed);
else
{
time_t t1;
time(&t1);
srand48((long) t1);
VL_PRINTF("Random seed is %li\n", t1);
}
if (!VL_VALUEPLUSARGS_II(32, "randomize=", 'd', randomizeRegs))
randomizeRegs = 1;
if (randomizeRegs)
Verilated::randReset(2);
else
Verilated::randReset(0);
Vverilator_tb* testbench = new Vverilator_tb;
testbench->reset = 1;
testbench->clk = 0;
#if VM_TRACE // If verilator was invoked with --trace
Verilated::traceEverOn(true);
VL_PRINTF("Writing waveform to trace.vcd\n");
VerilatedVcdC* tfp = new VerilatedVcdC;
testbench->trace(tfp, 99);
tfp->open("trace.vcd");
#endif
while (!Verilated::gotFinish())
{
if (currentTime > 10)
testbench->reset = 0; // Deassert reset
// Toggle clock
testbench->clk = !testbench->clk;
testbench->eval();
#if VM_TRACE
tfp->dump(currentTime); // Create waveform trace for this timestamp
#endif
currentTime++;
}
#if VM_TRACE
tfp->close();
#endif
testbench->final();
delete testbench;
return 0;
}
<commit_msg>Add clarifying comment<commit_after>//
// Copyright 2011-2015 Jeff Bush
//
// 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 <iostream>
#include "Vverilator_tb.h"
#include "verilated.h"
#if VM_TRACE
#include <verilated_vcd_c.h>
#endif
using namespace std;
namespace
{
vluint64_t currentTime = 0;
}
// Called whenever the $time variable is accessed.
double sc_time_stamp()
{
return currentTime;
}
int main(int argc, char **argv, char **env)
{
unsigned int randomSeed;
unsigned int randomizeRegs;
Verilated::commandArgs(argc, argv);
Verilated::debug(0);
// Initialize random seed.
if (VL_VALUEPLUSARGS_II(32, "randseed=", 'd', randomSeed))
srand48(randomSeed);
else
{
time_t t1;
time(&t1);
srand48((long) t1);
VL_PRINTF("Random seed is %li\n", t1);
}
if (!VL_VALUEPLUSARGS_II(32, "randomize=", 'd', randomizeRegs))
randomizeRegs = 1;
// If this is set, randomize the initial values of registers and
// SRAMs.
if (randomizeRegs)
Verilated::randReset(2);
else
Verilated::randReset(0);
Vverilator_tb* testbench = new Vverilator_tb;
testbench->reset = 1;
testbench->clk = 0;
#if VM_TRACE // If verilator was invoked with --trace
Verilated::traceEverOn(true);
VL_PRINTF("Writing waveform to trace.vcd\n");
VerilatedVcdC* tfp = new VerilatedVcdC;
testbench->trace(tfp, 99);
tfp->open("trace.vcd");
#endif
while (!Verilated::gotFinish())
{
if (currentTime > 10)
testbench->reset = 0; // Deassert reset
// Toggle clock
testbench->clk = !testbench->clk;
testbench->eval();
#if VM_TRACE
tfp->dump(currentTime); // Create waveform trace for this timestamp
#endif
currentTime++;
}
#if VM_TRACE
tfp->close();
#endif
testbench->final();
delete testbench;
return 0;
}
<|endoftext|> |
<commit_before>//|||||||||||||||||||||||||||||||||||||||||||||||
#include "OgreChess.h"
#include <OgreLight.h>
#include <OgreWindowEventUtilities.h>
#include "OgreText.h"
Chess::Chess()
{
boardNode = 0;
boardEntity = 0;
whiteQueenNode = 0;
whiteQueenEntity = 0;
whiteKingNode = 0;
whiteKingEntity = 0;
whitePawnNode = 0;
whitePawnEntity = 0;
whitePawnNode2 = 0;
whitePawnEntity2 = 0;
}
Chess::~Chess()
{
#ifdef INCLUDE_RTSHADER_SYSTEM
mShaderGenerator->removeSceneManager(OgreFramework::getSingletonPtr()->m_pSceneMgr);
destroyRTShaderSystem();
#endif
delete OgreFramework::getSingletonPtr();
}
#ifdef INCLUDE_RTSHADER_SYSTEM
/*-----------------------------------------------------------------------------
| Initialize the RT Shader system.
-----------------------------------------------------------------------------*/
bool Chess::initialiseRTShaderSystem(Ogre::SceneManager* sceneMgr)
{
if (Ogre::RTShader::ShaderGenerator::initialize())
{
mShaderGenerator = Ogre::RTShader::ShaderGenerator::getSingletonPtr();
mShaderGenerator->addSceneManager(sceneMgr);
// Setup core libraries and shader cache path.
Ogre::StringVector groupVector = Ogre::ResourceGroupManager::getSingleton().getResourceGroups();
Ogre::StringVector::iterator itGroup = groupVector.begin();
Ogre::StringVector::iterator itGroupEnd = groupVector.end();
Ogre::String shaderCoreLibsPath;
Ogre::String shaderCachePath;
for (; itGroup != itGroupEnd; ++itGroup)
{
Ogre::ResourceGroupManager::LocationList resLocationsList = Ogre::ResourceGroupManager::getSingleton().getResourceLocationList(*itGroup);
Ogre::ResourceGroupManager::LocationList::iterator it = resLocationsList.begin();
Ogre::ResourceGroupManager::LocationList::iterator itEnd = resLocationsList.end();
bool coreLibsFound = false;
// Try to find the location of the core shader lib functions and use it
// as shader cache path as well - this will reduce the number of generated files
// when running from different directories.
for (; it != itEnd; ++it)
{
if ((*it)->archive->getName().find("RTShaderLib") != Ogre::String::npos)
{
shaderCoreLibsPath = (*it)->archive->getName() + "/";
shaderCachePath = shaderCoreLibsPath;
coreLibsFound = true;
break;
}
}
// Core libs path found in the current group.
if (coreLibsFound)
break;
}
// Core shader libs not found -> shader generating will fail.
if (shaderCoreLibsPath.empty())
return false;
// Create and register the material manager listener.
mMaterialMgrListener = new ShaderGeneratorTechniqueResolverListener(mShaderGenerator);
Ogre::MaterialManager::getSingleton().addListener(mMaterialMgrListener);
}
return true;
}
/*-----------------------------------------------------------------------------
| Destroy the RT Shader system.
-----------------------------------------------------------------------------*/
void Chess::destroyRTShaderSystem()
{
// Restore default scheme.
Ogre::MaterialManager::getSingleton().setActiveScheme(Ogre::MaterialManager::DEFAULT_SCHEME_NAME);
// Unregister the material manager listener.
if (mMaterialMgrListener != NULL)
{
Ogre::MaterialManager::getSingleton().removeListener(mMaterialMgrListener);
delete mMaterialMgrListener;
mMaterialMgrListener = NULL;
}
// Destroy RTShader system.
if (mShaderGenerator != NULL)
{
Ogre::RTShader::ShaderGenerator::destroy();
mShaderGenerator = NULL;
}
}
#endif // INCLUDE_RTSHADER_SYSTEM
void Chess::startDemo()
{
new OgreFramework();
if(!OgreFramework::getSingletonPtr()->initOgre("Chess", this, 0))
return;
m_bShutdown = false;
OgreFramework::getSingletonPtr()->m_pLog->logMessage("Demo initialized!");
#ifdef INCLUDE_RTSHADER_SYSTEM
initialiseRTShaderSystem(OgreFramework::getSingletonPtr()->m_pSceneMgr);
Ogre::MaterialPtr baseWhite = Ogre::MaterialManager::getSingleton().getByName("BaseWhite", Ogre::ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME);
baseWhite->setLightingEnabled(false);
mShaderGenerator->createShaderBasedTechnique(
"BaseWhite",
Ogre::MaterialManager::DEFAULT_SCHEME_NAME,
Ogre::RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME);
mShaderGenerator->validateMaterial(Ogre::RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME,
"BaseWhite");
baseWhite->getTechnique(0)->getPass(0)->setVertexProgram(
baseWhite->getTechnique(1)->getPass(0)->getVertexProgram()->getName());
baseWhite->getTechnique(0)->getPass(0)->setFragmentProgram(
baseWhite->getTechnique(1)->getPass(0)->getFragmentProgram()->getName());
// creates shaders for base material BaseWhiteNoLighting using the RTSS
mShaderGenerator->createShaderBasedTechnique(
"BaseWhiteNoLighting",
Ogre::MaterialManager::DEFAULT_SCHEME_NAME,
Ogre::RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME);
mShaderGenerator->validateMaterial(Ogre::RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME,
"BaseWhiteNoLighting");
Ogre::MaterialPtr baseWhiteNoLighting = Ogre::MaterialManager::getSingleton().getByName("BaseWhiteNoLighting", Ogre::ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME);
baseWhiteNoLighting->getTechnique(0)->getPass(0)->setVertexProgram(
baseWhiteNoLighting->getTechnique(1)->getPass(0)->getVertexProgram()->getName());
baseWhiteNoLighting->getTechnique(0)->getPass(0)->setFragmentProgram(
baseWhiteNoLighting->getTechnique(1)->getPass(0)->getFragmentProgram()->getName());
#endif
setupChessScene();
#if !((OGRE_PLATFORM == OGRE_PLATFORM_APPLE) && __LP64__)
runDemo();
#endif
}
void Chess::setupChessScene()
{
Ogre::SceneManager *sManager = OgreFramework::getSingletonPtr()->m_pSceneMgr;
// sManager->setSkyBox(true, "Examples/SceneCubeMap2");
Ogre::Light* spotLight = sManager->createLight("spotLight");
spotLight->setType(Ogre::Light::LT_SPOTLIGHT);
spotLight->setDiffuseColour(0.8, 0.8, 0.8);
spotLight->setSpecularColour(0.8, 0.8, 0.8);
spotLight->setDirection(-1, -1, 0);
spotLight->setPosition(Ogre::Vector3(40, 40, 0));
spotLight->setSpotlightRange(Ogre::Degree(10), Ogre::Degree(28));
boardEntity = sManager->createEntity("boardEntity", "board.mesh");
boardNode = sManager->getRootSceneNode()->createChildSceneNode("boardNode");
boardNode->attachObject(boardEntity);
boardNode->setPosition(0, 0, 0);
whiteQueenEntity = sManager->createEntity("whiteQueenEntity", "QueenA.mesh");
whiteQueenNode = boardNode->createChildSceneNode("whiteQueenNode");
whiteQueenNode->attachObject(whiteQueenEntity);
whiteQueenNode->translate(7.1, 1.5, -1);
whiteKingEntity = sManager->createEntity("whiteKingEntity", "KingA.mesh");
whiteKingNode = boardNode->createChildSceneNode("whiteKingNode");
whiteKingNode->attachObject(whiteKingEntity);
whiteKingNode->translate(9.1, 1.35, -1);
float pawnZ = -7.5f;
float pawnY = -.2f;
whitePawnEntity = sManager->createEntity("whitePawnEntity", "PawnA01.mesh");
whitePawnNode = boardNode->createChildSceneNode("whitePawnNode");
whitePawnNode->attachObject(whitePawnEntity);
whitePawnNode->translate(7.3, pawnY, pawnZ);
whitePawnEntity2 = sManager->createEntity("whitePawnEntity2", "PawnA01.mesh");
whitePawnNode2 = boardNode->createChildSceneNode("whitePawnNode2");
whitePawnNode2->attachObject(whitePawnEntity2);
whitePawnNode2->translate(9.3, pawnY, pawnZ);
whitePawnEntity3 = sManager->createEntity("whitePawnEntity3", "PawnA01.mesh");
whitePawnNode3 = boardNode->createChildSceneNode("whitePawnNode3");
whitePawnNode3->attachObject(whitePawnEntity3);
whitePawnNode3->translate(11.3, pawnY, pawnZ);
whitePawnEntity4 = sManager->createEntity("whitePawnEntity4", "PawnA01.mesh");
whitePawnNode4 = boardNode->createChildSceneNode("whitePawnNode4");
whitePawnNode4->attachObject(whitePawnEntity4);
whitePawnNode4->translate(13.3, pawnY, pawnZ);
whitePawnEntity5 = sManager->createEntity("whitePawnEntity5", "PawnA01.mesh");
whitePawnNode5 = boardNode->createChildSceneNode("whitePawnNode5");
whitePawnNode5->attachObject(whitePawnEntity5);
whitePawnNode5->translate(15.3, pawnY, pawnZ);
whitePawnEntity6 = sManager->createEntity("whitePawnEntity6", "PawnA01.mesh");
whitePawnNode6 = boardNode->createChildSceneNode("whitePawnNode6");
whitePawnNode6->attachObject(whitePawnEntity6);
whitePawnNode6->translate(17.3, pawnY, pawnZ);
whitePawnEntity7 = sManager->createEntity("whitePawnEntity7", "PawnA01.mesh");
whitePawnNode7 = boardNode->createChildSceneNode("whitePawnNode7");
whitePawnNode7->attachObject(whitePawnEntity7);
whitePawnNode7->translate(19.3, pawnY, pawnZ);
whitePawnEntity8 = sManager->createEntity("whitePawnEntity8", "PawnA01.mesh");
whitePawnNode8 = boardNode->createChildSceneNode("whitePawnNode8");
whitePawnNode8->attachObject(whitePawnEntity8);
whitePawnNode8->translate(21.3, pawnY, pawnZ);
whiteRookEntity1 = sManager->createEntity("whiteRookEntity1", "TowerA01.mesh");
whiteRookNode1 = boardNode->createChildSceneNode("whiteRookNode1");
whiteRookNode1->attachObject(whiteRookEntity1);
whiteRookNode1->translate(1.1, 0.8, -1);
whiteRookEntity2 = sManager->createEntity("whiteRookEntity2", "TowerA01.mesh");
whiteRookNode2 = boardNode->createChildSceneNode("whiteRookNode2");
whiteRookNode2->attachObject(whiteRookEntity2);
whiteRookNode2->translate(15.1, 0.8, -1);
whiteKnightEntity1 = sManager->createEntity("whiteKnightEntity1", "HorseA01.mesh");
whiteKnightNode1 = boardNode->createChildSceneNode("whiteKnightNode1");
whiteKnightNode1->attachObject(whiteKnightEntity1);
whiteKnightNode1->translate(3.1, 0.7f, -1);
whiteKnightEntity2 = sManager->createEntity("whiteKnightEntity2", "HorseA01.mesh");
whiteKnightNode2 = boardNode->createChildSceneNode("whiteKnightNode2");
whiteKnightNode2->attachObject(whiteKnightEntity2);
whiteKnightNode2->translate(13.1, 0.7, -1);
whiteKnightNode2->roll(Degree(-90));
whiteBishopEntity1 = sManager->createEntity("whiteBishopEntity1", "Bishop.mesh");
whiteBishopNode1 = boardNode->createChildSceneNode("whiteBishopNode1");
whiteBishopNode1->attachObject(whiteBishopEntity1);
whiteBishopNode1->translate(5.1, 0.6, -1);
whiteBishopEntity2 = sManager->createEntity("whiteBishopEntity2", "Bishop.mesh");
whiteBishopNode2 = boardNode->createChildSceneNode("whiteBishopNode2");
whiteBishopNode2->attachObject(whiteBishopEntity2);
whiteBishopNode2->translate(11.1, 0.6, -1);
whiteBishopNode2->yaw(Degree(90));
}
void Chess::runDemo()
{
OgreFramework::getSingletonPtr()->m_pLog->logMessage("Start main loop...");
double timeSinceLastFrame = 0;
double startTime = 0;
OgreFramework::getSingletonPtr()->m_pRenderWnd->resetStatistics();
#if (!defined(OGRE_IS_IOS)) && !((OGRE_PLATFORM == OGRE_PLATFORM_APPLE) && __LP64__)
while(!m_bShutdown && !OgreFramework::getSingletonPtr()->isOgreToBeShutDown())
{
if(OgreFramework::getSingletonPtr()->m_pRenderWnd->isClosed())m_bShutdown = true;
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_LINUX || OGRE_PLATFORM == OGRE_PLATFORM_APPLE
Ogre::WindowEventUtilities::messagePump();
#endif
if(OgreFramework::getSingletonPtr()->m_pRenderWnd->isActive())
{
startTime = OgreFramework::getSingletonPtr()->m_pTimer->getMillisecondsCPU();
#if !OGRE_IS_IOS
OgreFramework::getSingletonPtr()->m_pKeyboard->capture();
#endif
OgreFramework::getSingletonPtr()->m_pMouse->capture();
OgreFramework::getSingletonPtr()->updateOgre(timeSinceLastFrame);
OgreFramework::getSingletonPtr()->m_pRoot->renderOneFrame();
timeSinceLastFrame = OgreFramework::getSingletonPtr()->m_pTimer->getMillisecondsCPU() - startTime;
}
else
{
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
Sleep(1000);
#else
sleep(1);
#endif
}
}
#endif
#if !defined(OGRE_IS_IOS)
OgreFramework::getSingletonPtr()->m_pLog->logMessage("Main loop quit");
OgreFramework::getSingletonPtr()->m_pLog->logMessage("Shutdown OGRE...");
#endif
}
bool Chess::keyPressed(const OIS::KeyEvent &keyEventRef)
{
#if !defined(OGRE_IS_IOS)
OgreFramework::getSingletonPtr()->keyPressed(keyEventRef);
if(OgreFramework::getSingletonPtr()->m_pKeyboard->isKeyDown(OIS::KC_F))
{
OgreText *textItem = new OgreText;
textItem->setText("Hello World!"); // Text to be displayed
// Now it is possible to use the Ogre::String as parameter too
textItem->setPos(0.1f,0.1f); // Text position, using relative co-ordinates
textItem->setCol(1.0f,1.0f,1.0f,0.5f); // Text colour (Red, Green, Blue, Alpha)
}
#endif
return true;
}
bool Chess::keyReleased(const OIS::KeyEvent &keyEventRef)
{
#if !defined(OGRE_IS_IOS)
OgreFramework::getSingletonPtr()->keyReleased(keyEventRef);
#endif
return true;
}<commit_msg>log camera position when press "f"<commit_after>//|||||||||||||||||||||||||||||||||||||||||||||||
#include "OgreChess.h"
#include <OgreLight.h>
#include <OgreWindowEventUtilities.h>
#include "OgreText.h"
Chess::Chess()
{
boardNode = 0;
boardEntity = 0;
whiteQueenNode = 0;
whiteQueenEntity = 0;
whiteKingNode = 0;
whiteKingEntity = 0;
whitePawnNode = 0;
whitePawnEntity = 0;
whitePawnNode2 = 0;
whitePawnEntity2 = 0;
}
Chess::~Chess()
{
#ifdef INCLUDE_RTSHADER_SYSTEM
mShaderGenerator->removeSceneManager(OgreFramework::getSingletonPtr()->m_pSceneMgr);
destroyRTShaderSystem();
#endif
delete OgreFramework::getSingletonPtr();
}
#ifdef INCLUDE_RTSHADER_SYSTEM
/*-----------------------------------------------------------------------------
| Initialize the RT Shader system.
-----------------------------------------------------------------------------*/
bool Chess::initialiseRTShaderSystem(Ogre::SceneManager* sceneMgr)
{
if (Ogre::RTShader::ShaderGenerator::initialize())
{
mShaderGenerator = Ogre::RTShader::ShaderGenerator::getSingletonPtr();
mShaderGenerator->addSceneManager(sceneMgr);
// Setup core libraries and shader cache path.
Ogre::StringVector groupVector = Ogre::ResourceGroupManager::getSingleton().getResourceGroups();
Ogre::StringVector::iterator itGroup = groupVector.begin();
Ogre::StringVector::iterator itGroupEnd = groupVector.end();
Ogre::String shaderCoreLibsPath;
Ogre::String shaderCachePath;
for (; itGroup != itGroupEnd; ++itGroup)
{
Ogre::ResourceGroupManager::LocationList resLocationsList = Ogre::ResourceGroupManager::getSingleton().getResourceLocationList(*itGroup);
Ogre::ResourceGroupManager::LocationList::iterator it = resLocationsList.begin();
Ogre::ResourceGroupManager::LocationList::iterator itEnd = resLocationsList.end();
bool coreLibsFound = false;
// Try to find the location of the core shader lib functions and use it
// as shader cache path as well - this will reduce the number of generated files
// when running from different directories.
for (; it != itEnd; ++it)
{
if ((*it)->archive->getName().find("RTShaderLib") != Ogre::String::npos)
{
shaderCoreLibsPath = (*it)->archive->getName() + "/";
shaderCachePath = shaderCoreLibsPath;
coreLibsFound = true;
break;
}
}
// Core libs path found in the current group.
if (coreLibsFound)
break;
}
// Core shader libs not found -> shader generating will fail.
if (shaderCoreLibsPath.empty())
return false;
// Create and register the material manager listener.
mMaterialMgrListener = new ShaderGeneratorTechniqueResolverListener(mShaderGenerator);
Ogre::MaterialManager::getSingleton().addListener(mMaterialMgrListener);
}
return true;
}
/*-----------------------------------------------------------------------------
| Destroy the RT Shader system.
-----------------------------------------------------------------------------*/
void Chess::destroyRTShaderSystem()
{
// Restore default scheme.
Ogre::MaterialManager::getSingleton().setActiveScheme(Ogre::MaterialManager::DEFAULT_SCHEME_NAME);
// Unregister the material manager listener.
if (mMaterialMgrListener != NULL)
{
Ogre::MaterialManager::getSingleton().removeListener(mMaterialMgrListener);
delete mMaterialMgrListener;
mMaterialMgrListener = NULL;
}
// Destroy RTShader system.
if (mShaderGenerator != NULL)
{
Ogre::RTShader::ShaderGenerator::destroy();
mShaderGenerator = NULL;
}
}
#endif // INCLUDE_RTSHADER_SYSTEM
void Chess::startDemo()
{
new OgreFramework();
if(!OgreFramework::getSingletonPtr()->initOgre("Chess", this, 0))
return;
m_bShutdown = false;
OgreFramework::getSingletonPtr()->m_pLog->logMessage("Demo initialized!");
#ifdef INCLUDE_RTSHADER_SYSTEM
initialiseRTShaderSystem(OgreFramework::getSingletonPtr()->m_pSceneMgr);
Ogre::MaterialPtr baseWhite = Ogre::MaterialManager::getSingleton().getByName("BaseWhite", Ogre::ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME);
baseWhite->setLightingEnabled(false);
mShaderGenerator->createShaderBasedTechnique(
"BaseWhite",
Ogre::MaterialManager::DEFAULT_SCHEME_NAME,
Ogre::RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME);
mShaderGenerator->validateMaterial(Ogre::RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME,
"BaseWhite");
baseWhite->getTechnique(0)->getPass(0)->setVertexProgram(
baseWhite->getTechnique(1)->getPass(0)->getVertexProgram()->getName());
baseWhite->getTechnique(0)->getPass(0)->setFragmentProgram(
baseWhite->getTechnique(1)->getPass(0)->getFragmentProgram()->getName());
// creates shaders for base material BaseWhiteNoLighting using the RTSS
mShaderGenerator->createShaderBasedTechnique(
"BaseWhiteNoLighting",
Ogre::MaterialManager::DEFAULT_SCHEME_NAME,
Ogre::RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME);
mShaderGenerator->validateMaterial(Ogre::RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME,
"BaseWhiteNoLighting");
Ogre::MaterialPtr baseWhiteNoLighting = Ogre::MaterialManager::getSingleton().getByName("BaseWhiteNoLighting", Ogre::ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME);
baseWhiteNoLighting->getTechnique(0)->getPass(0)->setVertexProgram(
baseWhiteNoLighting->getTechnique(1)->getPass(0)->getVertexProgram()->getName());
baseWhiteNoLighting->getTechnique(0)->getPass(0)->setFragmentProgram(
baseWhiteNoLighting->getTechnique(1)->getPass(0)->getFragmentProgram()->getName());
#endif
setupChessScene();
#if !((OGRE_PLATFORM == OGRE_PLATFORM_APPLE) && __LP64__)
runDemo();
#endif
}
void Chess::setupChessScene()
{
Ogre::SceneManager *sManager = OgreFramework::getSingletonPtr()->m_pSceneMgr;
// sManager->setSkyBox(true, "Examples/SceneCubeMap2");
Ogre::Light* spotLight = sManager->createLight("spotLight");
spotLight->setType(Ogre::Light::LT_SPOTLIGHT);
spotLight->setDiffuseColour(0.8, 0.8, 0.8);
spotLight->setSpecularColour(0.8, 0.8, 0.8);
spotLight->setDirection(-1, -1, 0);
spotLight->setPosition(Ogre::Vector3(40, 40, 0));
spotLight->setSpotlightRange(Ogre::Degree(10), Ogre::Degree(28));
boardEntity = sManager->createEntity("boardEntity", "board.mesh");
boardNode = sManager->getRootSceneNode()->createChildSceneNode("boardNode");
boardNode->attachObject(boardEntity);
boardNode->setPosition(0, 0, 0);
whiteQueenEntity = sManager->createEntity("whiteQueenEntity", "QueenA.mesh");
whiteQueenNode = boardNode->createChildSceneNode("whiteQueenNode");
whiteQueenNode->attachObject(whiteQueenEntity);
whiteQueenNode->translate(7.1, 1.5, -1);
whiteKingEntity = sManager->createEntity("whiteKingEntity", "KingA.mesh");
whiteKingNode = boardNode->createChildSceneNode("whiteKingNode");
whiteKingNode->attachObject(whiteKingEntity);
whiteKingNode->translate(9.1, 1.35, -1);
float pawnZ = -7.5f;
float pawnY = -.2f;
whitePawnEntity = sManager->createEntity("whitePawnEntity", "PawnA01.mesh");
whitePawnNode = boardNode->createChildSceneNode("whitePawnNode");
whitePawnNode->attachObject(whitePawnEntity);
whitePawnNode->translate(7.3, pawnY, pawnZ);
whitePawnEntity2 = sManager->createEntity("whitePawnEntity2", "PawnA01.mesh");
whitePawnNode2 = boardNode->createChildSceneNode("whitePawnNode2");
whitePawnNode2->attachObject(whitePawnEntity2);
whitePawnNode2->translate(9.3, pawnY, pawnZ);
whitePawnEntity3 = sManager->createEntity("whitePawnEntity3", "PawnA01.mesh");
whitePawnNode3 = boardNode->createChildSceneNode("whitePawnNode3");
whitePawnNode3->attachObject(whitePawnEntity3);
whitePawnNode3->translate(11.3, pawnY, pawnZ);
whitePawnEntity4 = sManager->createEntity("whitePawnEntity4", "PawnA01.mesh");
whitePawnNode4 = boardNode->createChildSceneNode("whitePawnNode4");
whitePawnNode4->attachObject(whitePawnEntity4);
whitePawnNode4->translate(13.3, pawnY, pawnZ);
whitePawnEntity5 = sManager->createEntity("whitePawnEntity5", "PawnA01.mesh");
whitePawnNode5 = boardNode->createChildSceneNode("whitePawnNode5");
whitePawnNode5->attachObject(whitePawnEntity5);
whitePawnNode5->translate(15.3, pawnY, pawnZ);
whitePawnEntity6 = sManager->createEntity("whitePawnEntity6", "PawnA01.mesh");
whitePawnNode6 = boardNode->createChildSceneNode("whitePawnNode6");
whitePawnNode6->attachObject(whitePawnEntity6);
whitePawnNode6->translate(17.3, pawnY, pawnZ);
whitePawnEntity7 = sManager->createEntity("whitePawnEntity7", "PawnA01.mesh");
whitePawnNode7 = boardNode->createChildSceneNode("whitePawnNode7");
whitePawnNode7->attachObject(whitePawnEntity7);
whitePawnNode7->translate(19.3, pawnY, pawnZ);
whitePawnEntity8 = sManager->createEntity("whitePawnEntity8", "PawnA01.mesh");
whitePawnNode8 = boardNode->createChildSceneNode("whitePawnNode8");
whitePawnNode8->attachObject(whitePawnEntity8);
whitePawnNode8->translate(21.3, pawnY, pawnZ);
whiteRookEntity1 = sManager->createEntity("whiteRookEntity1", "TowerA01.mesh");
whiteRookNode1 = boardNode->createChildSceneNode("whiteRookNode1");
whiteRookNode1->attachObject(whiteRookEntity1);
whiteRookNode1->translate(1.1, 0.8, -1);
whiteRookEntity2 = sManager->createEntity("whiteRookEntity2", "TowerA01.mesh");
whiteRookNode2 = boardNode->createChildSceneNode("whiteRookNode2");
whiteRookNode2->attachObject(whiteRookEntity2);
whiteRookNode2->translate(15.1, 0.8, -1);
whiteKnightEntity1 = sManager->createEntity("whiteKnightEntity1", "HorseA01.mesh");
whiteKnightNode1 = boardNode->createChildSceneNode("whiteKnightNode1");
whiteKnightNode1->attachObject(whiteKnightEntity1);
whiteKnightNode1->translate(3.1, 0.7f, -1);
whiteKnightEntity2 = sManager->createEntity("whiteKnightEntity2", "HorseA01.mesh");
whiteKnightNode2 = boardNode->createChildSceneNode("whiteKnightNode2");
whiteKnightNode2->attachObject(whiteKnightEntity2);
whiteKnightNode2->translate(13.1, 0.7, -1);
whiteKnightNode2->roll(Degree(-90));
whiteBishopEntity1 = sManager->createEntity("whiteBishopEntity1", "Bishop.mesh");
whiteBishopNode1 = boardNode->createChildSceneNode("whiteBishopNode1");
whiteBishopNode1->attachObject(whiteBishopEntity1);
whiteBishopNode1->translate(5.1, 0.6, -1);
whiteBishopEntity2 = sManager->createEntity("whiteBishopEntity2", "Bishop.mesh");
whiteBishopNode2 = boardNode->createChildSceneNode("whiteBishopNode2");
whiteBishopNode2->attachObject(whiteBishopEntity2);
whiteBishopNode2->translate(11.1, 0.6, -1);
whiteBishopNode2->yaw(Degree(90));
}
void Chess::runDemo()
{
OgreFramework::getSingletonPtr()->m_pLog->logMessage("Start main loop...");
double timeSinceLastFrame = 0;
double startTime = 0;
OgreFramework::getSingletonPtr()->m_pRenderWnd->resetStatistics();
#if (!defined(OGRE_IS_IOS)) && !((OGRE_PLATFORM == OGRE_PLATFORM_APPLE) && __LP64__)
while(!m_bShutdown && !OgreFramework::getSingletonPtr()->isOgreToBeShutDown())
{
if(OgreFramework::getSingletonPtr()->m_pRenderWnd->isClosed())m_bShutdown = true;
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_LINUX || OGRE_PLATFORM == OGRE_PLATFORM_APPLE
Ogre::WindowEventUtilities::messagePump();
#endif
if(OgreFramework::getSingletonPtr()->m_pRenderWnd->isActive())
{
startTime = OgreFramework::getSingletonPtr()->m_pTimer->getMillisecondsCPU();
#if !OGRE_IS_IOS
OgreFramework::getSingletonPtr()->m_pKeyboard->capture();
#endif
OgreFramework::getSingletonPtr()->m_pMouse->capture();
OgreFramework::getSingletonPtr()->updateOgre(timeSinceLastFrame);
OgreFramework::getSingletonPtr()->m_pRoot->renderOneFrame();
timeSinceLastFrame = OgreFramework::getSingletonPtr()->m_pTimer->getMillisecondsCPU() - startTime;
}
else
{
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
Sleep(1000);
#else
sleep(1);
#endif
}
}
#endif
#if !defined(OGRE_IS_IOS)
OgreFramework::getSingletonPtr()->m_pLog->logMessage("Main loop quit");
OgreFramework::getSingletonPtr()->m_pLog->logMessage("Shutdown OGRE...");
#endif
}
bool Chess::keyPressed(const OIS::KeyEvent &keyEventRef)
{
#if !defined(OGRE_IS_IOS)
OgreFramework::getSingletonPtr()->keyPressed(keyEventRef);
if(OgreFramework::getSingletonPtr()->m_pKeyboard->isKeyDown(OIS::KC_F))
{
OgreText *textItem = new OgreText;
Ogre::Vector3 cameraPosition = OgreFramework::getSingletonPtr()->m_pCamera->getPosition();
printf("Camera x: %f, y: %f, z: %f", cameraPosition.x, cameraPosition.y, cameraPosition.z);
//textItem->setText("Camera x: %f, y: %f, z: %f", cameraPosition.x, cameraPosition.y, cameraPosition.z); // Text to be displayed
// Now it is possible to use the Ogre::String as parameter too
textItem->setPos(0.1f,0.1f); // Text position, using relative co-ordinates
textItem->setCol(1.0f,1.0f,1.0f,0.5f); // Text colour (Red, Green, Blue, Alpha)
}
#endif
return true;
}
bool Chess::keyReleased(const OIS::KeyEvent &keyEventRef)
{
#if !defined(OGRE_IS_IOS)
OgreFramework::getSingletonPtr()->keyReleased(keyEventRef);
#endif
return true;
}<|endoftext|> |
<commit_before>#include <string>
#include <sstream>
#include <iomanip>
#include <teraranger_array/teraranger_multiflex.h>
#include <teraranger_array/helper_lib.h>
#include <ros/console.h>
namespace teraranger_array
{
TerarangerHubMultiflex::TerarangerHubMultiflex()
{
// Get parameters
ros::NodeHandle private_node_handle_("~");
private_node_handle_.param("portname", portname_, std::string("/dev/ttyACM0"));
// Publishers
range_publisher_ = nh_.advertise<sensor_msgs::Range>("teraranger_hub_multiflex", 8);
// Create serial port
serial_port_.setPort(portname_);
serial_port_.setBaudrate(115200);
serial_port_.setParity(serial::parity_none);
serial_port_.setStopbits(serial::stopbits_one);
serial_port_.setBytesize(serial::eightbits);
serial::Timeout to = serial::Timeout::simpleTimeout(1000);
serial_port_.setTimeout(to);
serial_port_.open();
if(!serial_port_.isOpen())
{
ROS_ERROR("Could not open : %s ", portname_.c_str());
ros::shutdown();
return;
}
// Output loaded parameters to console for double checking
ROS_INFO("[%s] is up and running with the following parameters:", ros::this_node::getName().c_str());
ROS_INFO("[%s] portname: %s", ros::this_node::getName().c_str(), portname_.c_str());
ns_ = ros::this_node::getNamespace();
ns_ = ros::names::clean(ns_);
std::string str = ns_.c_str();
ROS_INFO("node namespace: [%s]", ns_.c_str());
// Set operation Mode
setMode(BINARY_MODE);
// Initialize all active sensors
// Dynamic reconfigure
dyn_param_server_callback_function_ = boost::bind(&TerarangerHubMultiflex::dynParamCallback, this, _1, _2);
dyn_param_server_.setCallback(dyn_param_server_callback_function_);
}
TerarangerHubMultiflex::~TerarangerHubMultiflex()
{
}
void TerarangerHubMultiflex::parseCommand(uint8_t *input_buffer, uint8_t len)
{
static int int_min_range = (int)(MIN_RANGE * 1000);
static int int_max_range = (int)(MAX_RANGE * 1000);
static int seq_ctr = 0;
sensor_msgs::Range sensors[SENSOR_COUNT];
for (uint8_t i = 0; i < SENSOR_COUNT; i++)
{
sensors[i].field_of_view = FIELD_OF_VIEW;
sensors[i].max_range = MAX_RANGE;
sensors[i].min_range = MIN_RANGE;
sensors[i].radiation_type = sensor_msgs::Range::INFRARED;
std::string frame = "base_range_";
std::string frame_id = frame + IntToString(i);
sensors[i].header.frame_id = ros::names::append(ns_, frame_id);
}
uint8_t crc = HelperLib::crc8(input_buffer, len);
if (crc == input_buffer[len])
{
int16_t ranges[SENSOR_COUNT];
for (int i = 0; i < SENSOR_COUNT; i++)
{
ranges[i] = input_buffer[i * 2 + 2] << 8;
ranges[i] |= input_buffer[i * 2 + 3];
}
uint8_t bitmask = input_buffer[BITMASK_POS];
uint8_t bit_compare = 1;
for (int i = 0; i < SENSOR_COUNT; i++)
{
if ((bitmask & bit_compare) == bit_compare)
{
if (ranges[i] < int_max_range && ranges[i] > int_min_range)
{
sensors[i].header.stamp = ros::Time::now();
sensors[i].header.seq = seq_ctr++;
sensors[i].range = ranges[i] * 0.001; // convert to m
range_publisher_.publish(sensors[i]);
}
else
{
sensors[i].header.stamp = ros::Time::now();
sensors[i].header.seq = seq_ctr++;
sensors[i].range = -1;
range_publisher_.publish(sensors[i]);
}
}
else
{
ROS_WARN_ONCE("Not all sensors activated set proper bitmask using rosrun rqt_reconfigure rqt_reconfigure");
}
bit_compare <<= 1;
}
}
else
{
ROS_ERROR("[%s] crc missmatch", ros::this_node::getName().c_str());
}
}
std::string TerarangerHubMultiflex::arrayToString(uint8_t *input_buffer, uint8_t len)
{
std::ostringstream convert;
for (int a = 0; a < len; a++)
{
convert << std::uppercase << std::hex << std::setfill('0') << std::setw(2) << (int)input_buffer[a];
convert << std::uppercase << std::hex << " ";
}
std::string str = convert.str();
return str;
}
void TerarangerHubMultiflex::serialDataCallback(uint8_t single_character)
{
static uint8_t input_buffer[BUFFER_SIZE];
static int buffer_ctr = 0;
static int size_frame = REPLY_MSG_LEN;
static char first_char = REPLY_CHAR;
if (single_character == MF_CHAR && buffer_ctr == 0)
{
size_frame = MF_MSG_LEN;
first_char = MF_CHAR;
input_buffer[buffer_ctr] = single_character;
buffer_ctr++;
}
else if (single_character == REPLY_CHAR && buffer_ctr == 0)
{
size_frame = REPLY_MSG_LEN;
first_char = REPLY_CHAR;
input_buffer[buffer_ctr] = single_character;
buffer_ctr++;
}
else if (first_char == REPLY_CHAR && buffer_ctr < size_frame)
{
input_buffer[buffer_ctr] = single_character;
buffer_ctr++;
if (buffer_ctr == size_frame)
{
std::string str = arrayToString(input_buffer, size_frame);
ROS_DEBUG_STREAM("Respond frame received... : " << str);
// reset
buffer_ctr = 0;
// clear struct
bzero(&input_buffer, BUFFER_SIZE);
}
}
else if (first_char == MF_CHAR && buffer_ctr < size_frame)
{
input_buffer[buffer_ctr] = single_character;
buffer_ctr++;
if (buffer_ctr == size_frame)
{
std::string str = arrayToString(input_buffer, size_frame);
ROS_DEBUG_STREAM("Frame received... : " << str);
parseCommand(input_buffer, 19);
// reset
buffer_ctr = 0;
// clear struct
bzero(&input_buffer, BUFFER_SIZE);
}
}
else
{
ROS_DEBUG("Received uknown character %x", single_character);
// reset
buffer_ctr = 0;
// clear struct
bzero(&input_buffer, BUFFER_SIZE);
}
}
void TerarangerHubMultiflex::setMode(const char *c)
{
if(!serial_port_.write((uint8_t*)c, 4))
{
ROS_ERROR("Timeout or error while writing serial");
}
serial_port_.flushOutput();
}
void TerarangerHubMultiflex::setSensorBitMask(int *sensor_bit_mask_ptr)
{
uint8_t bit_mask_hex = 0x00;
for (int i = 0; i < SENSOR_COUNT; i++)
{
bit_mask_hex |= *(sensor_bit_mask_ptr + 7 - i) << (7 - i);
}
// calculate crc
uint8_t command[4] = {0x00, 0x52, 0x03, bit_mask_hex};
int8_t crc = HelperLib::crc8(command, 4);
//send command
char full_command[5] = {(char)0x00, (char)0x52, (char)0x03, (char)bit_mask_hex, (char)crc};
if(!serial_port_.write((uint8_t*)full_command, 5))
{
ROS_ERROR("Timeout or error while sending command");
}
serial_port_.flushOutput();
}
void TerarangerHubMultiflex::dynParamCallback(const teraranger_mutliflex_cfg::TerarangerHubMultiflexConfig &config, uint32_t level)
{
if (level == 1)
{
sensor_bit_mask[0] = config.Sensor_0 ? 1 : 0;
sensor_bit_mask[1] = config.Sensor_1 ? 1 : 0;
sensor_bit_mask[2] = config.Sensor_2 ? 1 : 0;
sensor_bit_mask[3] = config.Sensor_3 ? 1 : 0;
sensor_bit_mask[4] = config.Sensor_4 ? 1 : 0;
sensor_bit_mask[5] = config.Sensor_5 ? 1 : 0;
sensor_bit_mask[6] = config.Sensor_6 ? 1 : 0;
sensor_bit_mask[7] = config.Sensor_7 ? 1 : 0;
sensor_bit_mask_ptr = sensor_bit_mask;
setSensorBitMask(sensor_bit_mask_ptr);
for (int i = 0; i < SENSOR_COUNT; i++)
{
ROS_INFO("Sensor %d is set to %d", i, sensor_bit_mask[i]);
}
}
// TODO: Re-enable when multiple modes are supported by Multiflex
// else if (level == 0)
// {
// if (config.Mode == teraranger_mutliflex_cfg::TerarangerHubMultiflex_Fast)
// {
// setMode(FAST_MODE);
// ROS_INFO("Fast mode set");
// }
//
// if (config.Mode == teraranger_mutliflex_cfg::TerarangerHubMultiflex_Precise)
// {
// setMode(PRECISE_MODE);
// ROS_INFO("Precise mode set");
// }
//
// if (config.Mode == teraranger_mutliflex_cfg::TerarangerHubMultiflex_LongRange)
// {
// setMode(LONG_RANGE_MODE);
// ROS_INFO("Long range mode set");
// }
// }
else
{
ROS_DEBUG("Dynamic reconfigure, got %d", level);
}
}
std::string TerarangerHubMultiflex::IntToString(int number)
{
std::ostringstream oss;
oss << number;
return oss.str();
}
void TerarangerHubMultiflex::spin()
{
static uint8_t buffer[1];
while(ros::ok())
{
if(serial_port_.read(buffer, 1))
{
serialDataCallback(buffer[0]);
}
else
{
ROS_ERROR("Timeout or error while reading serial");
}
ros::spinOnce();
}
}
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "teraranger_hub_multiflex");
teraranger_array::TerarangerHubMultiflex multiflex;
multiflex.spin();
return 0;
}
<commit_msg>Increase serial timeout for multiflex to avoid error after reconfigure<commit_after>#include <string>
#include <sstream>
#include <iomanip>
#include <teraranger_array/teraranger_multiflex.h>
#include <teraranger_array/helper_lib.h>
#include <ros/console.h>
namespace teraranger_array
{
TerarangerHubMultiflex::TerarangerHubMultiflex()
{
// Get parameters
ros::NodeHandle private_node_handle_("~");
private_node_handle_.param("portname", portname_, std::string("/dev/ttyACM0"));
// Publishers
range_publisher_ = nh_.advertise<sensor_msgs::Range>("teraranger_hub_multiflex", 8);
// Create serial port
serial_port_.setPort(portname_);
serial_port_.setBaudrate(115200);
serial_port_.setParity(serial::parity_none);
serial_port_.setStopbits(serial::stopbits_one);
serial_port_.setBytesize(serial::eightbits);
// Timeout to wait after a reconf
serial::Timeout to = serial::Timeout::simpleTimeout(2000);
serial_port_.setTimeout(to);
serial_port_.open();
if(!serial_port_.isOpen())
{
ROS_ERROR("Could not open : %s ", portname_.c_str());
ros::shutdown();
return;
}
// Output loaded parameters to console for double checking
ROS_INFO("[%s] is up and running with the following parameters:", ros::this_node::getName().c_str());
ROS_INFO("[%s] portname: %s", ros::this_node::getName().c_str(), portname_.c_str());
ns_ = ros::this_node::getNamespace();
ns_ = ros::names::clean(ns_);
std::string str = ns_.c_str();
ROS_INFO("node namespace: [%s]", ns_.c_str());
// Set operation Mode
setMode(BINARY_MODE);
// Initialize all active sensors
// Dynamic reconfigure
dyn_param_server_callback_function_ = boost::bind(&TerarangerHubMultiflex::dynParamCallback, this, _1, _2);
dyn_param_server_.setCallback(dyn_param_server_callback_function_);
}
TerarangerHubMultiflex::~TerarangerHubMultiflex()
{
}
void TerarangerHubMultiflex::parseCommand(uint8_t *input_buffer, uint8_t len)
{
static int int_min_range = (int)(MIN_RANGE * 1000);
static int int_max_range = (int)(MAX_RANGE * 1000);
static int seq_ctr = 0;
sensor_msgs::Range sensors[SENSOR_COUNT];
for (uint8_t i = 0; i < SENSOR_COUNT; i++)
{
sensors[i].field_of_view = FIELD_OF_VIEW;
sensors[i].max_range = MAX_RANGE;
sensors[i].min_range = MIN_RANGE;
sensors[i].radiation_type = sensor_msgs::Range::INFRARED;
std::string frame = "base_range_";
std::string frame_id = frame + IntToString(i);
sensors[i].header.frame_id = ros::names::append(ns_, frame_id);
}
uint8_t crc = HelperLib::crc8(input_buffer, len);
if (crc == input_buffer[len])
{
int16_t ranges[SENSOR_COUNT];
for (int i = 0; i < SENSOR_COUNT; i++)
{
ranges[i] = input_buffer[i * 2 + 2] << 8;
ranges[i] |= input_buffer[i * 2 + 3];
}
uint8_t bitmask = input_buffer[BITMASK_POS];
uint8_t bit_compare = 1;
for (int i = 0; i < SENSOR_COUNT; i++)
{
if ((bitmask & bit_compare) == bit_compare)
{
if (ranges[i] < int_max_range && ranges[i] > int_min_range)
{
sensors[i].header.stamp = ros::Time::now();
sensors[i].header.seq = seq_ctr++;
sensors[i].range = ranges[i] * 0.001; // convert to m
range_publisher_.publish(sensors[i]);
}
else
{
sensors[i].header.stamp = ros::Time::now();
sensors[i].header.seq = seq_ctr++;
sensors[i].range = -1;
range_publisher_.publish(sensors[i]);
}
}
else
{
ROS_WARN_ONCE("Not all sensors activated set proper bitmask using rosrun rqt_reconfigure rqt_reconfigure");
}
bit_compare <<= 1;
}
}
else
{
ROS_ERROR("[%s] crc missmatch", ros::this_node::getName().c_str());
}
}
std::string TerarangerHubMultiflex::arrayToString(uint8_t *input_buffer, uint8_t len)
{
std::ostringstream convert;
for (int a = 0; a < len; a++)
{
convert << std::uppercase << std::hex << std::setfill('0') << std::setw(2) << (int)input_buffer[a];
convert << std::uppercase << std::hex << " ";
}
std::string str = convert.str();
return str;
}
void TerarangerHubMultiflex::serialDataCallback(uint8_t single_character)
{
static uint8_t input_buffer[BUFFER_SIZE];
static int buffer_ctr = 0;
static int size_frame = REPLY_MSG_LEN;
static char first_char = REPLY_CHAR;
if (single_character == MF_CHAR && buffer_ctr == 0)
{
size_frame = MF_MSG_LEN;
first_char = MF_CHAR;
input_buffer[buffer_ctr] = single_character;
buffer_ctr++;
}
else if (single_character == REPLY_CHAR && buffer_ctr == 0)
{
size_frame = REPLY_MSG_LEN;
first_char = REPLY_CHAR;
input_buffer[buffer_ctr] = single_character;
buffer_ctr++;
}
else if (first_char == REPLY_CHAR && buffer_ctr < size_frame)
{
input_buffer[buffer_ctr] = single_character;
buffer_ctr++;
if (buffer_ctr == size_frame)
{
std::string str = arrayToString(input_buffer, size_frame);
ROS_DEBUG_STREAM("Respond frame received... : " << str);
// reset
buffer_ctr = 0;
// clear struct
bzero(&input_buffer, BUFFER_SIZE);
}
}
else if (first_char == MF_CHAR && buffer_ctr < size_frame)
{
input_buffer[buffer_ctr] = single_character;
buffer_ctr++;
if (buffer_ctr == size_frame)
{
std::string str = arrayToString(input_buffer, size_frame);
ROS_DEBUG_STREAM("Frame received... : " << str);
parseCommand(input_buffer, 19);
// reset
buffer_ctr = 0;
// clear struct
bzero(&input_buffer, BUFFER_SIZE);
}
}
else
{
ROS_DEBUG("Received uknown character %x", single_character);
// reset
buffer_ctr = 0;
// clear struct
bzero(&input_buffer, BUFFER_SIZE);
}
}
void TerarangerHubMultiflex::setMode(const char *c)
{
if(!serial_port_.write((uint8_t*)c, 4))
{
ROS_ERROR("Timeout or error while writing serial");
}
serial_port_.flushOutput();
}
void TerarangerHubMultiflex::setSensorBitMask(int *sensor_bit_mask_ptr)
{
uint8_t bit_mask_hex = 0x00;
for (int i = 0; i < SENSOR_COUNT; i++)
{
bit_mask_hex |= *(sensor_bit_mask_ptr + 7 - i) << (7 - i);
}
// calculate crc
uint8_t command[4] = {0x00, 0x52, 0x03, bit_mask_hex};
int8_t crc = HelperLib::crc8(command, 4);
//send command
char full_command[5] = {(char)0x00, (char)0x52, (char)0x03, (char)bit_mask_hex, (char)crc};
if(!serial_port_.write((uint8_t*)full_command, 5))
{
ROS_ERROR("Timeout or error while sending command");
}
serial_port_.flushOutput();
}
void TerarangerHubMultiflex::dynParamCallback(const teraranger_mutliflex_cfg::TerarangerHubMultiflexConfig &config, uint32_t level)
{
if (level == 1)
{
sensor_bit_mask[0] = config.Sensor_0 ? 1 : 0;
sensor_bit_mask[1] = config.Sensor_1 ? 1 : 0;
sensor_bit_mask[2] = config.Sensor_2 ? 1 : 0;
sensor_bit_mask[3] = config.Sensor_3 ? 1 : 0;
sensor_bit_mask[4] = config.Sensor_4 ? 1 : 0;
sensor_bit_mask[5] = config.Sensor_5 ? 1 : 0;
sensor_bit_mask[6] = config.Sensor_6 ? 1 : 0;
sensor_bit_mask[7] = config.Sensor_7 ? 1 : 0;
sensor_bit_mask_ptr = sensor_bit_mask;
setSensorBitMask(sensor_bit_mask_ptr);
for (int i = 0; i < SENSOR_COUNT; i++)
{
ROS_INFO("Sensor %d is set to %d", i, sensor_bit_mask[i]);
}
}
// TODO: Re-enable when multiple modes are supported by Multiflex
// else if (level == 0)
// {
// if (config.Mode == teraranger_mutliflex_cfg::TerarangerHubMultiflex_Fast)
// {
// setMode(FAST_MODE);
// ROS_INFO("Fast mode set");
// }
//
// if (config.Mode == teraranger_mutliflex_cfg::TerarangerHubMultiflex_Precise)
// {
// setMode(PRECISE_MODE);
// ROS_INFO("Precise mode set");
// }
//
// if (config.Mode == teraranger_mutliflex_cfg::TerarangerHubMultiflex_LongRange)
// {
// setMode(LONG_RANGE_MODE);
// ROS_INFO("Long range mode set");
// }
// }
else
{
ROS_DEBUG("Dynamic reconfigure, got %d", level);
}
}
std::string TerarangerHubMultiflex::IntToString(int number)
{
std::ostringstream oss;
oss << number;
return oss.str();
}
void TerarangerHubMultiflex::spin()
{
static uint8_t buffer[1];
while(ros::ok())
{
if(serial_port_.read(buffer, 1))
{
serialDataCallback(buffer[0]);
}
else
{
ROS_ERROR("Timeout or error while reading serial");
}
ros::spinOnce();
}
}
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "teraranger_hub_multiflex");
teraranger_array::TerarangerHubMultiflex multiflex;
multiflex.spin();
return 0;
}
<|endoftext|> |
<commit_before>#include "../test.h"
#if ((defined(_MSC_VER) && _MSC_VER >= 1700) || (__cplusplus >= 201103L && HAS_BOOST)) && !defined(__CYGWIN__)
#define CPPREST_EXCLUDE_WEBSOCKETS
#include "casablanca/Release/src/pch/stdafx.h"
#include "casablanca/Release/src/json/json.cpp"
#include "casablanca/Release/src/json/json_parsing.cpp"
#include "casablanca/Release/src/json/json_serialization.cpp"
#include "casablanca/Release/src/utilities/asyncrt_utils.cpp"
#include <strstream>
#include <sstream>
#ifdef _MSC_VER
#pragma comment (lib, "Winhttp.lib")
#pragma comment (lib, "Bcrypt.lib")
#pragma comment (lib, "Crypt32.lib")
#endif
using namespace web::json;
//using namespace utility::conversions;
static void GenStat(Stat& stat, const value& v) {
switch (v.type()) {
case value::value_type::Array:
for (auto const& element : v.as_array())
GenStat(stat, element);
stat.arrayCount++;
stat.elementCount += v.size();
break;
case value::value_type::Object:
for (auto const& kv : v.as_object()) {
GenStat(stat, kv.second);
stat.stringLength += kv.first.size();
}
stat.objectCount++;
stat.memberCount += v.size();
stat.stringCount += v.size(); // member names
break;
case value::value_type::String:
stat.stringCount++;
stat.stringLength += v.as_string().size();
break;
case value::value_type::Number:
stat.numberCount++;
break;
case value::value_type::Boolean:
if (v.as_bool())
stat.trueCount++;
else
stat.falseCount++;
break;
case value::value_type::Null:
stat.nullCount++;
break;
}
}
class CasablancaParseResult : public ParseResultBase {
public:
value root;
};
class CasablancaStringResult : public StringResultBase {
public:
virtual const char* c_str() const { return s.c_str(); }
std::string s;
};
class CasablancaTest : public TestBase {
public:
#if TEST_INFO
virtual const char* GetName() const { return "C++ REST SDK (C++11)"; }
virtual const char* GetFilename() const { return __FILE__; }
#endif
#if TEST_PARSE
virtual ParseResultBase* Parse(const char* json, size_t length) const {
(void)length;
CasablancaParseResult* pr = new CasablancaParseResult;
std::istrstream is (json);
try {
pr->root = value::parse(is);
}
catch (web::json::json_exception& e) {
printf("Parse error '%s'\n", e.what());
delete pr;
pr = 0;
}
catch (...) {
delete pr;
pr = 0;
}
return pr;
}
#endif
#if TEST_STRINGIFY
virtual StringResultBase* Stringify(const ParseResultBase* parseResult) const {
const CasablancaParseResult* pr = static_cast<const CasablancaParseResult*>(parseResult);
CasablancaStringResult* sr = new CasablancaStringResult;
std::ostringstream os;
pr->root.serialize(os);
sr->s = os.str();
return sr;
}
#endif
#if TEST_STATISTICS
virtual bool Statistics(const ParseResultBase* parseResult, Stat* stat) const {
const CasablancaParseResult* pr = static_cast<const CasablancaParseResult*>(parseResult);
memset(stat, 0, sizeof(Stat));
GenStat(*stat, pr->root);
return true;
}
#endif
#if TEST_CONFORMANCE
virtual bool ParseDouble(const char* json, double* d) const {
std::istrstream is(json);
try {
value root = value::parse(is);
*d = root.at(0).as_double();
return true;
}
catch (...) {
}
return false;
}
virtual bool ParseString(const char* json, std::string& s) const {
std::istrstream is(json);
try {
value root = value::parse(is);
s = root.at(0).as_string();
return true;
}
catch (...) {
}
return false;
}
#endif
};
REGISTER_TEST(CasablancaTest);
#endif<commit_msg>Make casablanca works again on Windows<commit_after>#include "../test.h"
#if ((defined(_MSC_VER) && _MSC_VER >= 1700) || (__cplusplus >= 201103L && HAS_BOOST)) && !defined(__CYGWIN__)
#define _NO_ASYNCRTIMP 1
#define CPPREST_EXCLUDE_WEBSOCKETS
#ifdef _WIN32
#include "casablanca/Release/src/utilities/web_utilities.cpp" // Must compile this first
#include "casablanca/Release/src/http/common/http_msg.cpp"
#include "casablanca/Release/src/http/common/http_helpers.cpp"
#include "casablanca/Release/src/http/client/http_client_msg.cpp"
#include "casablanca/Release/src/http/client/http_client_winhttp.cpp"
#include "casablanca/Release/src/http/oauth/oauth1.cpp"
#include "casablanca/Release/src/websockets/client/ws_client.cpp"
#include "casablanca/Release/src/uri/uri.cpp"
#include "casablanca/Release/src/uri/uri_builder.cpp"
#include "casablanca/Release/src/uri/uri_parser.cpp"
#include "casablanca/Release/src/utilities/base64.cpp"
#pragma comment (lib, "Winhttp.lib")
#pragma comment (lib, "Bcrypt.lib")
#pragma comment (lib, "Crypt32.lib")
#endif
#include "casablanca/Release/src/pch/stdafx.h"
#include "casablanca/Release/src/json/json.cpp"
#include "casablanca/Release/src/json/json_parsing.cpp"
#include "casablanca/Release/src/json/json_serialization.cpp"
#include "casablanca/Release/src/utilities/asyncrt_utils.cpp"
#include <strstream>
#include <sstream>
using namespace web::json;
static void GenStat(Stat& stat, const value& v) {
switch (v.type()) {
case value::value_type::Array:
for (auto const& element : v.as_array())
GenStat(stat, element);
stat.arrayCount++;
stat.elementCount += v.size();
break;
case value::value_type::Object:
for (auto const& kv : v.as_object()) {
GenStat(stat, kv.second);
stat.stringLength += kv.first.size();
}
stat.objectCount++;
stat.memberCount += v.size();
stat.stringCount += v.size(); // member names
break;
case value::value_type::String:
stat.stringCount++;
stat.stringLength += v.as_string().size();
break;
case value::value_type::Number:
stat.numberCount++;
break;
case value::value_type::Boolean:
if (v.as_bool())
stat.trueCount++;
else
stat.falseCount++;
break;
case value::value_type::Null:
stat.nullCount++;
break;
}
}
class CasablancaParseResult : public ParseResultBase {
public:
value root;
};
class CasablancaStringResult : public StringResultBase {
public:
virtual const char* c_str() const { return s.c_str(); }
std::string s;
};
class CasablancaTest : public TestBase {
public:
#if TEST_INFO
virtual const char* GetName() const { return "C++ REST SDK (C++11)"; }
virtual const char* GetFilename() const { return __FILE__; }
#endif
#if TEST_PARSE
virtual ParseResultBase* Parse(const char* json, size_t length) const {
(void)length;
CasablancaParseResult* pr = new CasablancaParseResult;
std::istrstream is (json);
try {
pr->root = value::parse(is);
}
catch (web::json::json_exception& e) {
printf("Parse error '%s'\n", e.what());
delete pr;
pr = 0;
}
catch (...) {
delete pr;
pr = 0;
}
return pr;
}
#endif
#if TEST_STRINGIFY
virtual StringResultBase* Stringify(const ParseResultBase* parseResult) const {
const CasablancaParseResult* pr = static_cast<const CasablancaParseResult*>(parseResult);
CasablancaStringResult* sr = new CasablancaStringResult;
std::ostringstream os;
pr->root.serialize(os);
sr->s = os.str();
return sr;
}
#endif
#if TEST_STATISTICS
virtual bool Statistics(const ParseResultBase* parseResult, Stat* stat) const {
const CasablancaParseResult* pr = static_cast<const CasablancaParseResult*>(parseResult);
memset(stat, 0, sizeof(Stat));
GenStat(*stat, pr->root);
return true;
}
#endif
#if TEST_CONFORMANCE
virtual bool ParseDouble(const char* json, double* d) const {
std::istrstream is(json);
try {
value root = value::parse(is);
*d = root.at(0).as_double();
return true;
}
catch (...) {
}
return false;
}
virtual bool ParseString(const char* json, std::string& s) const {
std::istrstream is(json);
try {
value root = value::parse(is);
s = to_utf8string(root.at(0).as_string());
return true;
}
catch (...) {
}
return false;
}
#endif
};
REGISTER_TEST(CasablancaTest);
#endif<|endoftext|> |
<commit_before>// Copyright (c) 2007-2010 Paul Hodge. All rights reserved.
#include "circa.h"
namespace circa {
namespace if_block_tests {
void test_if_joining()
{
Branch branch;
// Test that a name defined in one branch is not rebound in outer scope
branch.eval("if true\napple = 5\nend");
test_assert(!branch.contains("apple"));
// Test that a name which exists in the outer scope is rebound
Term* original_banana = create_int(branch, 10, "banana");
branch.eval("if true\nbanana = 15\nend");
test_assert(branch["banana"] != original_banana);
// Test that if a name is defined in both 'if' and 'else branches, that it gets defined
// in the outer scope.
branch.eval("if true\nCardiff = 5\nelse\nCardiff = 11\nend");
test_assert(branch.contains("Cardiff"));
}
void test_if_joining_on_bool()
{
// The following code once had a bug where cond wouldn't work
// if one of its inputs was missing value.
Branch branch;
Term* s = branch.eval("hey = true");
test_assert(s->value_data.ptr != NULL);
branch.eval("if false\nhey = false\nend");
evaluate_branch(branch);
test_assert(branch["hey"]->asBool() == true);
}
void test_if_elif_else()
{
Branch branch;
branch.eval("if true; a = 1; elif true; a = 2; else; a = 3; end");
test_assert(branch.contains("a"));
test_assert(branch["a"]->asInt() == 1);
branch.eval("if false; b = 'apple'; elif false; b = 'orange'; else; b = 'pineapple'; end");
test_assert(branch.contains("b"));
test_assert(branch["b"]->asString() == "pineapple");
// try one without 'else'
branch.clear();
branch.eval("c = 0");
branch.eval("if false; c = 7; elif true; c = 8; end");
test_assert(branch.contains("c"));
test_assert(branch["c"]->asInt() == 8);
// try with some more complex conditions
branch.clear();
branch.eval("x = 5");
branch.eval("if x > 6; compare = 1; elif x < 6; compare = -1; else; compare = 0; end");
test_assert(branch.contains("compare"));
test_assert(branch["compare"]->asInt() == -1);
}
void test_dont_always_rebind_inner_names()
{
Branch branch;
branch.eval("if false; b = 1; elif false; c = 1; elif false; d = 1; else; e = 1; end");
test_assert(!branch.contains("b"));
test_assert(!branch.contains("c"));
test_assert(!branch.contains("d"));
test_assert(!branch.contains("e"));
}
std::vector<std::string> gSpyResults;
void spy_function(EvalContext*, Term* caller)
{
gSpyResults.push_back(as_string(caller->input(0)));
}
void test_execution()
{
Branch branch;
import_function(branch, spy_function, "spy(string)");
gSpyResults.clear();
// Start off with some simple expressions
branch.eval("if true\nspy('Success 1')\nend");
branch.eval("if false\nspy('Fail')\nend");
branch.eval("if (1 + 2) > 1\nspy('Success 2')\nend");
branch.eval("if (1 + 2) < 1\nspy('Fail')\nend");
branch.eval("if true; spy('Success 3'); end");
branch.eval("if false; spy('Fail'); end");
test_assert(branch);
test_assert(gSpyResults.size() == 3);
test_equals(gSpyResults[0], "Success 1");
test_equals(gSpyResults[1], "Success 2");
test_equals(gSpyResults[2], "Success 3");
gSpyResults.clear();
// Use 'else'
branch.eval("if true; spy('Success 1'); else; spy('Fail'); end");
branch.eval("if false; spy('Fail'); else; spy('Success 2'); end");
branch.eval("if true; spy('Success 3-1')\n spy('Success 3-2')\n spy('Success 3-3')\n"
"else; spy('Fail'); end");
branch.eval("if false; spy('Fail')\n spy('Fail 2')\n"
"else; spy('Success 4-1')\n spy('Success 4-2')\n spy('Success 4-3')\n end");
test_assert(branch);
test_assert(gSpyResults.size() == 8);
test_equals(gSpyResults[0], "Success 1");
test_equals(gSpyResults[1], "Success 2");
test_equals(gSpyResults[2], "Success 3-1");
test_equals(gSpyResults[3], "Success 3-2");
test_equals(gSpyResults[4], "Success 3-3");
test_equals(gSpyResults[5], "Success 4-1");
test_equals(gSpyResults[6], "Success 4-2");
test_equals(gSpyResults[7], "Success 4-3");
gSpyResults.clear();
// Do some nested blocks
branch.eval("if true; if false; spy('Error!'); else; spy('Nested 1'); end;"
"else; spy('Error!'); end");
test_assert(branch);
test_assert(gSpyResults.size() == 1);
test_equals(gSpyResults[0], "Nested 1");
gSpyResults.clear();
branch.eval("if false; spy('Error!'); else; if false; spy('Error!');"
"else; spy('Nested 2'); end; end");
test_assert(branch);
test_assert(gSpyResults.size() == 1);
test_equals(gSpyResults[0], "Nested 2");
gSpyResults.clear();
branch.eval("if false; spy('Error!');"
"else; if true; spy('Nested 3'); else; spy('Error!'); end; end");
test_assert(branch);
test_assert(gSpyResults.size() == 1);
test_equals(gSpyResults[0], "Nested 3");
gSpyResults.clear();
branch.eval("if true; if false; spy('Error!'); else; spy('Nested 4'); end;"
"else; spy('Error!'); end");
test_assert(branch);
test_assert(gSpyResults.size() == 1);
test_equals(gSpyResults[0], "Nested 4");
gSpyResults.clear();
branch.eval(
"if (false)\n"
"spy('Error!')\n"
"else\n"
"if (true)\n"
"if (false)\n"
"spy('Error!')\n"
"else\n"
"if (false)\n"
"spy('Error!')\n"
"else\n"
"if (true)\n"
"spy('Nested 5')\n"
"else\n"
"spy('Error!')\n"
"end\n"
"end\n"
"end\n"
"else\n"
"spy('Error!')\n"
"end\n"
"end");
test_assert(branch);
test_assert(gSpyResults.size() == 1);
test_equals(gSpyResults[0], "Nested 5");
gSpyResults.clear();
}
void test_execution_with_elif()
{
Branch branch;
import_function(branch, spy_function, "spy(string)");
gSpyResults.clear();
branch.eval("x = 5");
branch.eval("if x > 5; spy('Fail');"
"elif x < 5; spy('Fail');"
"elif x == 5; spy('Success');"
"else; spy('Fail'); end");
test_assert(branch);
test_assert(gSpyResults.size() == 1);
test_equals(gSpyResults[0], "Success");
gSpyResults.clear();
}
void test_parse_with_no_line_endings()
{
Branch branch;
branch.eval("a = 4");
branch.eval("if a < 5 a = 5 end");
test_assert(branch);
test_assert(branch["a"]->asInt() == 5);
branch.eval("if a > 7 a = 5 else a = 3 end");
test_assert(branch);
test_assert(branch["a"]->asInt() == 3);
branch.eval("if a == 2 a = 1 elif a == 3 a = 9 else a = 2 end");
test_assert(branch);
test_assert(branch["a"]->asInt() == 9);
}
void test_state_simple()
{
Branch branch;
// Simple test, condition never changes
Term* block = branch.compile("if true; state i = 0; i += 1; end");
Term* i = get_if_condition_block(block, 0)->findFirstBinding("i");
test_assert(as_int(i) == 0);
evaluate_branch(branch);
test_assert(as_int(i) == 1);
evaluate_branch(branch);
test_assert(as_int(i) == 2);
evaluate_branch(branch);
test_assert(as_int(i) == 3);
// Same test with elif
block = branch.compile("if false; elif true; state i = 0; i += 1; end");
i = get_if_condition_block(block, 1)->findFirstBinding("i");
test_assert(as_int(i) == 0);
evaluate_branch(branch);
test_assert(as_int(i) == 1);
evaluate_branch(branch);
test_assert(as_int(i) == 2);
evaluate_branch(branch);
test_assert(as_int(i) == 3);
// Same test with else
block = branch.compile("if false; else state i = 0; i += 1; end");
i = get_if_block_else_block(block)->findFirstBinding("i");
test_assert(as_int(i) == 0);
evaluate_branch(branch);
test_assert(as_int(i) == 1);
evaluate_branch(branch);
test_assert(as_int(i) == 2);
evaluate_branch(branch);
test_assert(as_int(i) == 3);
}
void test_state_in_function()
{
// Use state in an if block in a function, this should verify that state
// is being swapped in and out.
Branch branch;
branch.compile(
"def my_func() -> int; if true; state i = 0; i += 1; return i; else return 0 end end");
Term* call1 = branch.compile("my_func()");
Term* call2 = branch.compile("my_func()");
test_assert(as_int(call1) == 0);
test_assert(as_int(call2) == 0);
evaluate_term(call1);
evaluate_term(call1);
evaluate_term(call1);
test_equals(as_int(call1), 3);
evaluate_term(call2);
test_equals(as_int(call2), 1);
}
void test_state_is_reset_when_if_fails()
{
Branch branch;
Term* c = branch.compile("c = true");
Term* ifBlock = branch.compile("if c; state i = 0; i += 1; end");
Term* i = get_if_condition_block(ifBlock, 0)->findFirstBinding("i");
test_assert(as_int(i) == 0);
evaluate_branch(branch);
test_assert(as_int(i) == 1);
evaluate_branch(branch);
test_assert(as_int(i) == 2);
evaluate_branch(branch);
test_assert(as_int(i) == 3);
set_bool(c, false);
evaluate_branch(branch);
test_assert(as_int(i) == 0);
evaluate_branch(branch);
test_assert(as_int(i) == 0);
set_bool(c, true);
evaluate_branch(branch);
test_assert(as_int(i) == 1);
evaluate_branch(branch);
test_assert(as_int(i) == 2);
// Same thing with state in the else() block
branch.clear();
c = branch.compile("c = true");
ifBlock = branch.compile("if c; else state i = 0; i += 1; end");
i = get_if_condition_block(ifBlock, 1)->findFirstBinding("i");
test_assert(as_int(i) == 0);
evaluate_branch(branch);
test_assert(as_int(i) == 0);
set_bool(c, false);
evaluate_branch(branch);
test_assert(as_int(i) == 1);
evaluate_branch(branch);
test_assert(as_int(i) == 2);
set_bool(c, true);
evaluate_branch(branch);
test_assert(as_int(i) == 0);
evaluate_branch(branch);
test_assert(as_int(i) == 0);
}
void register_tests()
{
REGISTER_TEST_CASE(if_block_tests::test_if_joining);
REGISTER_TEST_CASE(if_block_tests::test_if_elif_else);
REGISTER_TEST_CASE(if_block_tests::test_dont_always_rebind_inner_names);
REGISTER_TEST_CASE(if_block_tests::test_execution);
REGISTER_TEST_CASE(if_block_tests::test_execution_with_elif);
REGISTER_TEST_CASE(if_block_tests::test_parse_with_no_line_endings);
REGISTER_TEST_CASE(if_block_tests::test_state_simple);
REGISTER_TEST_CASE(if_block_tests::test_state_in_function);
REGISTER_TEST_CASE(if_block_tests::test_state_is_reset_when_if_fails);
}
} // namespace if_block_tests
} // namespace circa
<commit_msg>Add another test for state in an if-block<commit_after>// Copyright (c) 2007-2010 Paul Hodge. All rights reserved.
#include "circa.h"
namespace circa {
namespace if_block_tests {
void test_if_joining()
{
Branch branch;
// Test that a name defined in one branch is not rebound in outer scope
branch.eval("if true\napple = 5\nend");
test_assert(!branch.contains("apple"));
// Test that a name which exists in the outer scope is rebound
Term* original_banana = create_int(branch, 10, "banana");
branch.eval("if true\nbanana = 15\nend");
test_assert(branch["banana"] != original_banana);
// Test that if a name is defined in both 'if' and 'else branches, that it gets defined
// in the outer scope.
branch.eval("if true\nCardiff = 5\nelse\nCardiff = 11\nend");
test_assert(branch.contains("Cardiff"));
}
void test_if_joining_on_bool()
{
// The following code once had a bug where cond wouldn't work
// if one of its inputs was missing value.
Branch branch;
Term* s = branch.eval("hey = true");
test_assert(s->value_data.ptr != NULL);
branch.eval("if false\nhey = false\nend");
evaluate_branch(branch);
test_assert(branch["hey"]->asBool() == true);
}
void test_if_elif_else()
{
Branch branch;
branch.eval("if true; a = 1; elif true; a = 2; else; a = 3; end");
test_assert(branch.contains("a"));
test_assert(branch["a"]->asInt() == 1);
branch.eval("if false; b = 'apple'; elif false; b = 'orange'; else; b = 'pineapple'; end");
test_assert(branch.contains("b"));
test_assert(branch["b"]->asString() == "pineapple");
// try one without 'else'
branch.clear();
branch.eval("c = 0");
branch.eval("if false; c = 7; elif true; c = 8; end");
test_assert(branch.contains("c"));
test_assert(branch["c"]->asInt() == 8);
// try with some more complex conditions
branch.clear();
branch.eval("x = 5");
branch.eval("if x > 6; compare = 1; elif x < 6; compare = -1; else; compare = 0; end");
test_assert(branch.contains("compare"));
test_assert(branch["compare"]->asInt() == -1);
}
void test_dont_always_rebind_inner_names()
{
Branch branch;
branch.eval("if false; b = 1; elif false; c = 1; elif false; d = 1; else; e = 1; end");
test_assert(!branch.contains("b"));
test_assert(!branch.contains("c"));
test_assert(!branch.contains("d"));
test_assert(!branch.contains("e"));
}
std::vector<std::string> gSpyResults;
void spy_function(EvalContext*, Term* caller)
{
gSpyResults.push_back(as_string(caller->input(0)));
}
void test_execution()
{
Branch branch;
import_function(branch, spy_function, "spy(string)");
gSpyResults.clear();
// Start off with some simple expressions
branch.eval("if true\nspy('Success 1')\nend");
branch.eval("if false\nspy('Fail')\nend");
branch.eval("if (1 + 2) > 1\nspy('Success 2')\nend");
branch.eval("if (1 + 2) < 1\nspy('Fail')\nend");
branch.eval("if true; spy('Success 3'); end");
branch.eval("if false; spy('Fail'); end");
test_assert(branch);
test_assert(gSpyResults.size() == 3);
test_equals(gSpyResults[0], "Success 1");
test_equals(gSpyResults[1], "Success 2");
test_equals(gSpyResults[2], "Success 3");
gSpyResults.clear();
// Use 'else'
branch.eval("if true; spy('Success 1'); else; spy('Fail'); end");
branch.eval("if false; spy('Fail'); else; spy('Success 2'); end");
branch.eval("if true; spy('Success 3-1')\n spy('Success 3-2')\n spy('Success 3-3')\n"
"else; spy('Fail'); end");
branch.eval("if false; spy('Fail')\n spy('Fail 2')\n"
"else; spy('Success 4-1')\n spy('Success 4-2')\n spy('Success 4-3')\n end");
test_assert(branch);
test_assert(gSpyResults.size() == 8);
test_equals(gSpyResults[0], "Success 1");
test_equals(gSpyResults[1], "Success 2");
test_equals(gSpyResults[2], "Success 3-1");
test_equals(gSpyResults[3], "Success 3-2");
test_equals(gSpyResults[4], "Success 3-3");
test_equals(gSpyResults[5], "Success 4-1");
test_equals(gSpyResults[6], "Success 4-2");
test_equals(gSpyResults[7], "Success 4-3");
gSpyResults.clear();
// Do some nested blocks
branch.eval("if true; if false; spy('Error!'); else; spy('Nested 1'); end;"
"else; spy('Error!'); end");
test_assert(branch);
test_assert(gSpyResults.size() == 1);
test_equals(gSpyResults[0], "Nested 1");
gSpyResults.clear();
branch.eval("if false; spy('Error!'); else; if false; spy('Error!');"
"else; spy('Nested 2'); end; end");
test_assert(branch);
test_assert(gSpyResults.size() == 1);
test_equals(gSpyResults[0], "Nested 2");
gSpyResults.clear();
branch.eval("if false; spy('Error!');"
"else; if true; spy('Nested 3'); else; spy('Error!'); end; end");
test_assert(branch);
test_assert(gSpyResults.size() == 1);
test_equals(gSpyResults[0], "Nested 3");
gSpyResults.clear();
branch.eval("if true; if false; spy('Error!'); else; spy('Nested 4'); end;"
"else; spy('Error!'); end");
test_assert(branch);
test_assert(gSpyResults.size() == 1);
test_equals(gSpyResults[0], "Nested 4");
gSpyResults.clear();
branch.eval(
"if (false)\n"
"spy('Error!')\n"
"else\n"
"if (true)\n"
"if (false)\n"
"spy('Error!')\n"
"else\n"
"if (false)\n"
"spy('Error!')\n"
"else\n"
"if (true)\n"
"spy('Nested 5')\n"
"else\n"
"spy('Error!')\n"
"end\n"
"end\n"
"end\n"
"else\n"
"spy('Error!')\n"
"end\n"
"end");
test_assert(branch);
test_assert(gSpyResults.size() == 1);
test_equals(gSpyResults[0], "Nested 5");
gSpyResults.clear();
}
void test_execution_with_elif()
{
Branch branch;
import_function(branch, spy_function, "spy(string)");
gSpyResults.clear();
branch.eval("x = 5");
branch.eval("if x > 5; spy('Fail');"
"elif x < 5; spy('Fail');"
"elif x == 5; spy('Success');"
"else; spy('Fail'); end");
test_assert(branch);
test_assert(gSpyResults.size() == 1);
test_equals(gSpyResults[0], "Success");
gSpyResults.clear();
}
void test_parse_with_no_line_endings()
{
Branch branch;
branch.eval("a = 4");
branch.eval("if a < 5 a = 5 end");
test_assert(branch);
test_assert(branch["a"]->asInt() == 5);
branch.eval("if a > 7 a = 5 else a = 3 end");
test_assert(branch);
test_assert(branch["a"]->asInt() == 3);
branch.eval("if a == 2 a = 1 elif a == 3 a = 9 else a = 2 end");
test_assert(branch);
test_assert(branch["a"]->asInt() == 9);
}
void test_state_simple()
{
Branch branch;
// Simple test, condition never changes
Term* block = branch.compile("if true; state i = 0; i += 1; end");
Term* i = get_if_condition_block(block, 0)->findFirstBinding("i");
test_assert(as_int(i) == 0);
evaluate_branch(branch);
test_assert(as_int(i) == 1);
evaluate_branch(branch);
test_assert(as_int(i) == 2);
evaluate_branch(branch);
test_assert(as_int(i) == 3);
// Same test with elif
block = branch.compile("if false; elif true; state i = 0; i += 1; end");
i = get_if_condition_block(block, 1)->findFirstBinding("i");
test_assert(as_int(i) == 0);
evaluate_branch(branch);
test_assert(as_int(i) == 1);
evaluate_branch(branch);
test_assert(as_int(i) == 2);
evaluate_branch(branch);
test_assert(as_int(i) == 3);
// Same test with else
block = branch.compile("if false; else state i = 0; i += 1; end");
i = get_if_block_else_block(block)->findFirstBinding("i");
test_assert(as_int(i) == 0);
evaluate_branch(branch);
test_assert(as_int(i) == 1);
evaluate_branch(branch);
test_assert(as_int(i) == 2);
evaluate_branch(branch);
test_assert(as_int(i) == 3);
}
void test_state_in_function()
{
// Use state in an if block in a function, this should verify that state
// is being swapped in and out.
Branch branch;
branch.compile(
"def my_func() -> int; if true; state i = 0; i += 1; return i; else return 0 end end");
Term* call1 = branch.compile("my_func()");
Term* call2 = branch.compile("my_func()");
test_assert(as_int(call1) == 0);
test_assert(as_int(call2) == 0);
evaluate_term(call1);
evaluate_term(call1);
evaluate_term(call1);
test_equals(as_int(call1), 3);
evaluate_term(call2);
test_equals(as_int(call2), 1);
}
void test_state_is_reset_when_if_fails()
{
Branch branch;
Term* c = branch.compile("c = true");
Term* ifBlock = branch.compile("if c; state i = 0; i += 1; end");
Term* i = get_if_condition_block(ifBlock, 0)->findFirstBinding("i");
test_assert(as_int(i) == 0);
evaluate_branch(branch);
test_assert(as_int(i) == 1);
evaluate_branch(branch);
test_assert(as_int(i) == 2);
evaluate_branch(branch);
test_assert(as_int(i) == 3);
set_bool(c, false);
evaluate_branch(branch);
test_assert(as_int(i) == 0);
evaluate_branch(branch);
test_assert(as_int(i) == 0);
set_bool(c, true);
evaluate_branch(branch);
test_assert(as_int(i) == 1);
evaluate_branch(branch);
test_assert(as_int(i) == 2);
// Same thing with state in the else() block
branch.clear();
c = branch.compile("c = true");
ifBlock = branch.compile("if c; else state i = 0; i += 1; end");
i = get_if_condition_block(ifBlock, 1)->findFirstBinding("i");
test_assert(as_int(i) == 0);
evaluate_branch(branch);
test_assert(as_int(i) == 0);
set_bool(c, false);
evaluate_branch(branch);
test_assert(as_int(i) == 1);
evaluate_branch(branch);
test_assert(as_int(i) == 2);
set_bool(c, true);
evaluate_branch(branch);
test_assert(as_int(i) == 0);
evaluate_branch(branch);
test_assert(as_int(i) == 0);
}
void test_nested_state()
{
Branch branch;
Term* block = branch.compile("if true; t = toggle(true); end");
Term* t = get_if_condition_block(block, 0)->findFirstBinding("t");
evaluate_branch(branch);
test_assert(as_bool(t) == true);
evaluate_branch(branch);
test_assert(as_bool(t) == false);
}
void register_tests()
{
REGISTER_TEST_CASE(if_block_tests::test_if_joining);
REGISTER_TEST_CASE(if_block_tests::test_if_elif_else);
REGISTER_TEST_CASE(if_block_tests::test_dont_always_rebind_inner_names);
REGISTER_TEST_CASE(if_block_tests::test_execution);
REGISTER_TEST_CASE(if_block_tests::test_execution_with_elif);
REGISTER_TEST_CASE(if_block_tests::test_parse_with_no_line_endings);
REGISTER_TEST_CASE(if_block_tests::test_state_simple);
REGISTER_TEST_CASE(if_block_tests::test_state_in_function);
REGISTER_TEST_CASE(if_block_tests::test_state_is_reset_when_if_fails);
REGISTER_TEST_CASE(if_block_tests::test_nested_state);
}
} // namespace if_block_tests
} // namespace circa
<|endoftext|> |
<commit_before>/* indivudal.cpp - CS 472 Project #2: Genetic Programming
* Copyright 2014 Andrew Schwartzmeyer
*
* Source file for Individual
*/
#include <cmath>
#include <iostream>
#include <memory>
#include <tuple>
#include <vector>
#include "individual.hpp"
#include "../problem/problem.hpp"
#include "../random/random_generator.hpp"
using namespace individual;
using namespace random_generator;
using problem::Problem;
Node::Node(const Problem & problem, const int & depth) {
if (depth < problem.max_depth) {
// Assign random internal type
int_dist dist(0, internal_types - 1); // Closed interval
type = Type(dist(engine));
// Recursively create subtrees
for (int i = 0; i < arity; i++)
children.emplace_back(Node(problem, depth + 1));
} else {
// Reached max depth, assign random terminal type
int_dist dist(internal_types, internal_types + terminal_types - 1); // Closed interval
type = Type(dist(engine));
// Setup constant type; input is provided on evaluation
if (type == CONSTANT) {
// Choose a random value between the problem's min and max
real_dist dist(problem.constant_min, problem.constant_max);
constant = dist(engine);
}
}
}
double Node::evaluate(const double & input) {
double left, right;
if (type != INPUT and type != CONSTANT) {
left = children[0].evaluate(input);
right = children[1].evaluate(input);
}
switch(type) {
case ADD:
return left + right;
case SUBTRACT:
return left - right;
case MULTIPLY:
return left * right;
case DIVIDE:
if (right == 0)
return 1;
return left / right;
case CONSTANT:
return constant;
case INPUT:
return input;
}
}
Size Node::size() {
// Recursively count children via pre-order traversal
// Keep track of internals, leafs, and total
Size size;
for (auto child : children) {
size.internals += child.size().internals;
size.leafs += child.size().leafs;
}
if (children.size() == 0) ++size.leafs;
else ++size.internals;
size.total = size.leafs + size.internals;
return size;
}
void Node::print(const int & depth) {
// Post-order traversal print of expression in RPN/posfix notation
std::cout << '(';
for (auto child : children)
child.print(depth + 1);
switch(type) {
case ADD:
std:: cout << " + ";
break;
case SUBTRACT:
std:: cout << " - ";
break;
case MULTIPLY:
std:: cout << " * ";
break;
case DIVIDE:
std:: cout << " / ";
break;
case CONSTANT:
std:: cout << constant;
break;
case INPUT:
std:: cout << "X";
break;
}
std:: cout << ')';
}
Individual::Individual(const Problem & p): problem(p), root(Node(problem)) {
size = root.size();
fitness = evaluate();
}
double Individual::evaluate() {
double fitness = 0;
for (auto pair : problem.values) {
double output = root.evaluate(std::get<0>(pair));
fitness += std::pow(output - std::get<1>(pair), 2);
}
return std::sqrt(fitness);
}
void Individual::print() {
std::cout << "Expression tree of size " << size.total
<< " with " << size.internals << " internals"
<< " and " << size.leafs << " leafs "
<< " has the following formula: " << std::endl;
root.print();
std::cout << std::endl
<< "Has a fitness of: " << evaluate() << std::endl;
}
<commit_msg>Style fixes<commit_after>/* indivudal.cpp - CS 472 Project #2: Genetic Programming
* Copyright 2014 Andrew Schwartzmeyer
*
* Source file for Individual
*/
#include <cmath>
#include <iostream>
#include <memory>
#include <tuple>
#include <vector>
#include "individual.hpp"
#include "../problem/problem.hpp"
#include "../random/random_generator.hpp"
using namespace individual;
using namespace random_generator;
using problem::Problem;
Node::Node(const Problem & problem, const int & depth) {
if (depth < problem.max_depth) {
// assign random internal type
int_dist dist(0, internal_types - 1); // closed interval
type = Type(dist(engine));
// recursively create subtrees
for (int i = 0; i < arity; i++)
children.emplace_back(Node(problem, depth + 1));
} else {
// reached max depth, assign random terminal type
int_dist dist(internal_types, internal_types + terminal_types - 1); // closed interval
type = Type(dist(engine));
// setup constant type; input is provided on evaluation
if (type == CONSTANT) {
// choose a random value between the problem's min and max
real_dist dist(problem.constant_min, problem.constant_max);
constant = dist(engine);
}
}
}
double Node::evaluate(const double & input) {
double left, right;
if (type != INPUT and type != CONSTANT) {
left = children[0].evaluate(input);
right = children[1].evaluate(input);
}
switch(type) {
case ADD:
return left + right;
case SUBTRACT:
return left - right;
case MULTIPLY:
return left * right;
case DIVIDE:
return right == 0 ? 1 : left / right; // protected
case CONSTANT:
return constant;
case INPUT:
return input;
}
}
Size Node::size() {
// Recursively count children via pre-order traversal
// Keep track of internals, leafs, and total
Size size;
for (auto child : children) {
size.internals += child.size().internals;
size.leafs += child.size().leafs;
}
if (children.size() == 0) ++size.leafs;
else ++size.internals;
size.total = size.leafs + size.internals;
return size;
}
void Node::print(const int & depth) {
// Post-order traversal print of expression in RPN/posfix notation
using std::cout;
cout << '(';
for (auto child : children)
child.print(depth + 1);
switch(type) {
case ADD:
cout << " + ";
break;
case SUBTRACT:
cout << " - ";
break;
case MULTIPLY:
cout << " * ";
break;
case DIVIDE:
cout << " / ";
break;
case CONSTANT:
cout << constant;
break;
case INPUT:
cout << "X";
break;
}
cout << ')';
}
Individual::Individual(const Problem & p): problem(p), root(Node(problem)) {
size = root.size();
fitness = evaluate();
}
double Individual::evaluate() {
double fitness = 0;
for (auto pair : problem.values) {
double output = root.evaluate(std::get<0>(pair));
fitness += std::pow(output - std::get<1>(pair), 2);
}
return std::sqrt(fitness);
}
void Individual::print() {
std::cout << "Expression tree of size " << size.total
<< " with " << size.internals << " internals"
<< " and " << size.leafs << " leafs"
<< " has the following formula: " << std::endl;
root.print();
std::cout << std::endl
<< "Has a fitness of: " << evaluate() << std::endl;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2007-2020 CM4all GmbH
* All rights reserved.
*
* author: Max Kellermann <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* 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
* FOUNDATION 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 "ConcatIstream.hxx"
#include "Sink.hxx"
#include "Bucket.hxx"
#include "UnusedPtr.hxx"
#include "pool/pool.hxx"
#include "util/DestructObserver.hxx"
#include "util/IntrusiveList.hxx"
#include "util/WritableBuffer.hxx"
#include <assert.h>
class CatIstream final : public Istream, DestructAnchor {
struct Input final : IstreamSink, IntrusiveListHook {
CatIstream &cat;
Input(CatIstream &_cat, UnusedIstreamPtr &&_istream) noexcept
:IstreamSink(std::move(_istream)), cat(_cat) {}
void SetDirect(FdTypeMask direct) noexcept {
input.SetDirect(direct);
}
off_t GetAvailable(bool partial) const noexcept {
return input.GetAvailable(partial);
}
off_t Skip(off_t length) noexcept {
return input.Skip(length);
}
void Read() noexcept {
input.Read();
}
void FillBucketList(IstreamBucketList &list) {
input.FillBucketList(list);
}
size_t ConsumeBucketList(size_t nbytes) noexcept {
return input.ConsumeBucketList(nbytes);
}
int AsFd() noexcept {
return input.AsFd();
}
/* virtual methods from class IstreamHandler */
bool OnIstreamReady() noexcept override {
return cat.OnInputReady(*this);
}
size_t OnData(const void *data, size_t length) noexcept override {
return cat.OnInputData(*this, data, length);
}
ssize_t OnDirect(FdType type, int fd, size_t max_length) noexcept override {
return cat.OnInputDirect(*this, type, fd, max_length);
}
void OnEof() noexcept override {
assert(input.IsDefined());
ClearInput();
cat.OnInputEof(*this);
}
void OnError(std::exception_ptr ep) noexcept override {
assert(input.IsDefined());
ClearInput();
cat.OnInputError(*this, ep);
}
struct Disposer {
void operator()(Input *input) noexcept {
input->~Input();
}
};
};
bool reading = false;
using InputList = IntrusiveList<Input>;
InputList inputs;
public:
CatIstream(struct pool &p, WritableBuffer<UnusedIstreamPtr> _inputs) noexcept;
private:
Input &GetCurrent() noexcept {
return inputs.front();
}
const Input &GetCurrent() const noexcept {
return inputs.front();
}
bool IsCurrent(const Input &input) const noexcept {
return &GetCurrent() == &input;
}
bool IsEOF() const noexcept {
return inputs.empty();
}
void CloseAllInputs() noexcept {
inputs.clear_and_dispose(Input::Disposer());
}
bool OnInputReady(Input &i) noexcept {
return IsCurrent(i)
? InvokeReady()
: false;
}
size_t OnInputData(Input &i, const void *data, size_t length) noexcept {
return IsCurrent(i)
? InvokeData(data, length)
: 0;
}
ssize_t OnInputDirect(gcc_unused Input &i, FdType type, int fd,
size_t max_length) noexcept {
return IsCurrent(i)
? InvokeDirect(type, fd, max_length)
: (ssize_t)ISTREAM_RESULT_BLOCKING;
}
void OnInputEof(Input &i) noexcept {
const bool current = IsCurrent(i);
i.unlink();
if (IsEOF()) {
assert(current);
DestroyEof();
} else if (current && !reading) {
/* only call Input::_Read() if this function was not called
from CatIstream:Read() - in this case,
istream_cat_read() would provide the loop. This is
advantageous because we avoid unnecessary recursing. */
GetCurrent().Read();
}
}
void OnInputError(Input &i, std::exception_ptr ep) noexcept {
i.unlink();
CloseAllInputs();
DestroyError(ep);
}
public:
/* virtual methods from class Istream */
void _SetDirect(FdTypeMask mask) noexcept override {
for (auto &i : inputs)
i.SetDirect(mask);
}
off_t _GetAvailable(bool partial) noexcept override;
off_t _Skip(gcc_unused off_t length) noexcept override;
void _Read() noexcept override;
void _FillBucketList(IstreamBucketList &list) override;
size_t _ConsumeBucketList(size_t nbytes) noexcept override;
int _AsFd() noexcept override;
void _Close() noexcept override;
};
/*
* istream implementation
*
*/
off_t
CatIstream::_GetAvailable(bool partial) noexcept
{
off_t available = 0;
for (const auto &input : inputs) {
const off_t a = input.GetAvailable(partial);
if (a != (off_t)-1)
available += a;
else if (!partial)
/* if the caller wants the exact number of bytes, and
one input cannot provide it, we cannot provide it
either */
return (off_t)-1;
}
return available;
}
off_t
CatIstream::_Skip(off_t length) noexcept
{
if (inputs.empty())
return 0;
off_t nbytes = inputs.front().Skip(length);
Consumed(nbytes);
return nbytes;
}
void
CatIstream::_Read() noexcept
{
if (IsEOF()) {
DestroyEof();
return;
}
const DestructObserver destructed(*this);
reading = true;
CatIstream::InputList::const_iterator prev;
do {
prev = inputs.begin();
GetCurrent().Read();
if (destructed)
return;
} while (!IsEOF() && inputs.begin() != prev);
reading = false;
}
void
CatIstream::_FillBucketList(IstreamBucketList &list)
{
assert(!list.HasMore());
for (auto &input : inputs) {
try {
input.FillBucketList(list);
} catch (...) {
input.unlink();
CloseAllInputs();
Destroy();
throw;
}
if (list.HasMore())
break;
}
}
size_t
CatIstream::_ConsumeBucketList(size_t nbytes) noexcept
{
size_t total = 0;
for (auto &input : inputs) {
size_t consumed = input.ConsumeBucketList(nbytes);
Consumed(consumed);
total += consumed;
nbytes -= consumed;
if (nbytes == 0)
break;
}
return total;
}
int
CatIstream::_AsFd() noexcept
{
/* we can safely forward the as_fd() call to our input if it's the
last one */
if (std::next(inputs.begin()) != inputs.end())
/* not on last input */
return -1;
auto &i = GetCurrent();
int fd = i.AsFd();
if (fd >= 0)
Destroy();
return fd;
}
void
CatIstream::_Close() noexcept
{
CloseAllInputs();
Destroy();
}
/*
* constructor
*
*/
inline CatIstream::CatIstream(struct pool &p, WritableBuffer<UnusedIstreamPtr> _inputs) noexcept
:Istream(p)
{
for (UnusedIstreamPtr &_input : _inputs) {
if (!_input)
continue;
auto *input = NewFromPool<Input>(p, *this, std::move(_input));
inputs.push_back(*input);
}
}
UnusedIstreamPtr
_istream_cat_new(struct pool &pool, UnusedIstreamPtr *const inputs, unsigned n_inputs)
{
return UnusedIstreamPtr(NewFromPool<CatIstream>(pool, pool,
WritableBuffer<UnusedIstreamPtr>(inputs, n_inputs)));
}
<commit_msg>istream/ConcatIstream: work around GCC8 bug<commit_after>/*
* Copyright 2007-2020 CM4all GmbH
* All rights reserved.
*
* author: Max Kellermann <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* 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
* FOUNDATION 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 "ConcatIstream.hxx"
#include "Sink.hxx"
#include "Bucket.hxx"
#include "UnusedPtr.hxx"
#include "pool/pool.hxx"
#include "util/DestructObserver.hxx"
#include "util/IntrusiveList.hxx"
#include "util/WritableBuffer.hxx"
#include <assert.h>
class CatIstream final : public Istream, DestructAnchor {
struct Input final : IstreamSink, IntrusiveListHook {
CatIstream &cat;
Input(CatIstream &_cat, UnusedIstreamPtr &&_istream) noexcept
:IstreamSink(std::move(_istream)), cat(_cat) {}
void SetDirect(FdTypeMask direct) noexcept {
input.SetDirect(direct);
}
off_t GetAvailable(bool partial) const noexcept {
return input.GetAvailable(partial);
}
off_t Skip(off_t length) noexcept {
return input.Skip(length);
}
void Read() noexcept {
input.Read();
}
void FillBucketList(IstreamBucketList &list) {
input.FillBucketList(list);
}
size_t ConsumeBucketList(size_t nbytes) noexcept {
return input.ConsumeBucketList(nbytes);
}
int AsFd() noexcept {
return input.AsFd();
}
/* virtual methods from class IstreamHandler */
bool OnIstreamReady() noexcept override {
return cat.OnInputReady(*this);
}
size_t OnData(const void *data, size_t length) noexcept override {
return cat.OnInputData(*this, data, length);
}
ssize_t OnDirect(FdType type, int fd, size_t max_length) noexcept override {
return cat.OnInputDirect(*this, type, fd, max_length);
}
void OnEof() noexcept override {
assert(input.IsDefined());
ClearInput();
cat.OnInputEof(*this);
}
void OnError(std::exception_ptr ep) noexcept override {
assert(input.IsDefined());
ClearInput();
cat.OnInputError(*this, ep);
}
struct Disposer {
void operator()(Input *input) noexcept {
input->~Input();
}
};
};
bool reading = false;
using InputList = IntrusiveList<Input>;
InputList inputs;
public:
CatIstream(struct pool &p, WritableBuffer<UnusedIstreamPtr> _inputs) noexcept;
private:
Input &GetCurrent() noexcept {
return inputs.front();
}
const Input &GetCurrent() const noexcept {
return inputs.front();
}
bool IsCurrent(const Input &input) const noexcept {
return &GetCurrent() == &input;
}
bool IsEOF() const noexcept {
return inputs.empty();
}
void CloseAllInputs() noexcept {
inputs.clear_and_dispose(Input::Disposer());
}
bool OnInputReady(Input &i) noexcept {
return IsCurrent(i)
? InvokeReady()
: false;
}
size_t OnInputData(Input &i, const void *data, size_t length) noexcept {
return IsCurrent(i)
? InvokeData(data, length)
: 0;
}
ssize_t OnInputDirect(gcc_unused Input &i, FdType type, int fd,
size_t max_length) noexcept {
return IsCurrent(i)
? InvokeDirect(type, fd, max_length)
: (ssize_t)ISTREAM_RESULT_BLOCKING;
}
void OnInputEof(Input &i) noexcept {
const bool current = IsCurrent(i);
i.unlink();
if (IsEOF()) {
assert(current);
DestroyEof();
} else if (current && !reading) {
/* only call Input::_Read() if this function was not called
from CatIstream:Read() - in this case,
istream_cat_read() would provide the loop. This is
advantageous because we avoid unnecessary recursing. */
GetCurrent().Read();
}
}
void OnInputError(Input &i, std::exception_ptr ep) noexcept {
i.unlink();
CloseAllInputs();
DestroyError(ep);
}
public:
/* virtual methods from class Istream */
void _SetDirect(FdTypeMask mask) noexcept override {
for (auto &i : inputs)
i.SetDirect(mask);
}
off_t _GetAvailable(bool partial) noexcept override;
off_t _Skip(gcc_unused off_t length) noexcept override;
void _Read() noexcept override;
void _FillBucketList(IstreamBucketList &list) override;
size_t _ConsumeBucketList(size_t nbytes) noexcept override;
int _AsFd() noexcept override;
void _Close() noexcept override;
};
/*
* istream implementation
*
*/
off_t
CatIstream::_GetAvailable(bool partial) noexcept
{
off_t available = 0;
for (const auto &input : inputs) {
const off_t a = input.GetAvailable(partial);
if (a != (off_t)-1)
available += a;
else if (!partial)
/* if the caller wants the exact number of bytes, and
one input cannot provide it, we cannot provide it
either */
return (off_t)-1;
}
return available;
}
off_t
CatIstream::_Skip(off_t length) noexcept
{
if (inputs.empty())
return 0;
off_t nbytes = inputs.front().Skip(length);
Consumed(nbytes);
return nbytes;
}
void
CatIstream::_Read() noexcept
{
if (IsEOF()) {
DestroyEof();
return;
}
const DestructObserver destructed(*this);
reading = true;
CatIstream::InputList::iterator prev;
do {
prev = inputs.begin();
GetCurrent().Read();
if (destructed)
return;
} while (!IsEOF() && inputs.begin() != prev);
reading = false;
}
void
CatIstream::_FillBucketList(IstreamBucketList &list)
{
assert(!list.HasMore());
for (auto &input : inputs) {
try {
input.FillBucketList(list);
} catch (...) {
input.unlink();
CloseAllInputs();
Destroy();
throw;
}
if (list.HasMore())
break;
}
}
size_t
CatIstream::_ConsumeBucketList(size_t nbytes) noexcept
{
size_t total = 0;
for (auto &input : inputs) {
size_t consumed = input.ConsumeBucketList(nbytes);
Consumed(consumed);
total += consumed;
nbytes -= consumed;
if (nbytes == 0)
break;
}
return total;
}
int
CatIstream::_AsFd() noexcept
{
/* we can safely forward the as_fd() call to our input if it's the
last one */
if (std::next(inputs.begin()) != inputs.end())
/* not on last input */
return -1;
auto &i = GetCurrent();
int fd = i.AsFd();
if (fd >= 0)
Destroy();
return fd;
}
void
CatIstream::_Close() noexcept
{
CloseAllInputs();
Destroy();
}
/*
* constructor
*
*/
inline CatIstream::CatIstream(struct pool &p, WritableBuffer<UnusedIstreamPtr> _inputs) noexcept
:Istream(p)
{
for (UnusedIstreamPtr &_input : _inputs) {
if (!_input)
continue;
auto *input = NewFromPool<Input>(p, *this, std::move(_input));
inputs.push_back(*input);
}
}
UnusedIstreamPtr
_istream_cat_new(struct pool &pool, UnusedIstreamPtr *const inputs, unsigned n_inputs)
{
return UnusedIstreamPtr(NewFromPool<CatIstream>(pool, pool,
WritableBuffer<UnusedIstreamPtr>(inputs, n_inputs)));
}
<|endoftext|> |
<commit_before>#include "smartplayer.h"
#include "board.h"
#include "move.h"
#include <list>
#include <iostream>
static Move negamax_move;
SmartPlayer::SmartPlayer(void)
: Player()
{
}
SmartPlayer::SmartPlayer(Player::Who who)
: Player(who)
{
}
Move SmartPlayer::move(Board *b, struct timeval *time_remain)
{
int i;
int alpha, beta;
for(i=1;i<7;i+=2)
{
alpha = -CFG_INFINITY;
beta = CFG_INFINITY;
if(negamax(b, who(), i, Move(), alpha, beta) == CFG_GAMEVAL_WIN)
return negamax_move;
}
return negamax_move;
}
int SmartPlayer::negamax(Board *b, Player::Who cur_player, int depth, const Move &move, int alpha, int beta)
{
Board *tmp_board;
std::list<Move> moves;
std::list<Move>::iterator itr;
// Check for end state
if(b->winner() != Player::None) {
if(b->winner() == cur_player) {
negamax_move = move;
alpha = CFG_GAMEVAL_WIN;
return alpha;
} else {
negamax_move = move;
alpha = CFG_GAMEVAL_LOSE;
return alpha;
}
}
// Check for max depth
if(depth == 0) {
negamax_move = Move();
alpha = boardEval(b, cur_player);
return alpha;
}
depth--;
// Load moves
b->validMoves(cur_player, moves);
// No movew -> Draw
if(moves.size() == 0) {
negamax_move = Move();
alpha = 0;
return alpha;
}
Move best_move = *(moves.begin());
int max_score = CFG_GAMEVAL_LOSE;
int tmp_score;
for(itr = moves.begin();itr != moves.end();itr++) {
tmp_board = new Board(*b);
tmp_board->move(*itr);
tmp_score = - negamax(tmp_board, Player::opponent(cur_player), depth, *itr, -beta, -alpha);
if(tmp_score > max_score) {
best_move = *itr;
max_score = tmp_score;
}
delete tmp_board;
if(max_score >= beta)
break;
}
negamax_move = best_move;
alpha = max_score;
return alpha;
}
int SmartPlayer::boardEval(Board *b, Player::Who cur_player)
{
Player::Who tmp_winner;
int score;
tmp_winner = b->winner();
if(tmp_winner != Player::None)
{
if(tmp_winner == cur_player)
score = CFG_GAMEVAL_WIN;
else
score = CFG_GAMEVAL_LOSE;
}
else
score = b->populationCount(cur_player) - b->populationCount(Player::opponent(cur_player));
return score;
}
<commit_msg>No valid moves is now a loss<commit_after>#include "smartplayer.h"
#include "board.h"
#include "move.h"
#include <list>
#include <iostream>
static Move negamax_move;
SmartPlayer::SmartPlayer(void)
: Player()
{
}
SmartPlayer::SmartPlayer(Player::Who who)
: Player(who)
{
}
Move SmartPlayer::move(Board *b, struct timeval *time_remain)
{
int i;
int alpha, beta;
for(i=1;i<7;i+=2)
{
alpha = -CFG_INFINITY;
beta = CFG_INFINITY;
if(negamax(b, who(), i, Move(), alpha, beta) == CFG_GAMEVAL_WIN)
return negamax_move;
}
return negamax_move;
}
int SmartPlayer::negamax(Board *b, Player::Who cur_player, int depth, const Move &move, int alpha, int beta)
{
Board *tmp_board;
std::list<Move> moves;
std::list<Move>::iterator itr;
// Check for end state
if(b->winner() != Player::None) {
if(b->winner() == cur_player) {
negamax_move = move;
alpha = CFG_GAMEVAL_WIN;
return alpha;
} else {
negamax_move = move;
alpha = CFG_GAMEVAL_LOSE;
return alpha;
}
}
// Check for max depth
if(depth == 0) {
negamax_move = Move();
alpha = boardEval(b, cur_player);
return alpha;
}
depth--;
// Load moves
b->validMoves(cur_player, moves);
// No movew -> Draw
if(moves.size() == 0) {
negamax_move = Move();
alpha = CFG_GAMEVAL_LOSE;
return alpha;
}
Move best_move = *(moves.begin());
int max_score = CFG_GAMEVAL_LOSE;
int tmp_score;
for(itr = moves.begin();itr != moves.end();itr++) {
tmp_board = new Board(*b);
tmp_board->move(*itr);
tmp_score = - negamax(tmp_board, Player::opponent(cur_player), depth, *itr, -beta, -alpha);
if(tmp_score > max_score) {
best_move = *itr;
max_score = tmp_score;
}
delete tmp_board;
if(max_score >= beta)
break;
}
negamax_move = best_move;
alpha = max_score;
return alpha;
}
int SmartPlayer::boardEval(Board *b, Player::Who cur_player)
{
Player::Who tmp_winner;
int score;
tmp_winner = b->winner();
if(tmp_winner != Player::None)
{
if(tmp_winner == cur_player)
score = CFG_GAMEVAL_WIN;
else
score = CFG_GAMEVAL_LOSE;
}
else
score = b->populationCount(cur_player) - b->populationCount(Player::opponent(cur_player));
return score;
}
<|endoftext|> |
<commit_before><commit_msg>vc/audio triggers: stop sending DMX values on deactivation<commit_after><|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// include ---------------------------------------------------------------
#include <vcl/svapp.hxx>
#include <vcl/msgbox.hxx>
#include <tools/stream.hxx>
#include <rtl/bootstrap.hxx>
#include <unotools/configmgr.hxx>
#include <unotools/bootstrap.hxx>
#include <com/sun/star/uno/Any.h>
#include <unotools/configmgr.hxx>
#include <vcl/svapp.hxx>
#include <vcl/graph.hxx>
#include <svtools/filter.hxx>
#include "com/sun/star/system/SystemShellExecuteFlags.hpp"
#include "com/sun/star/system/XSystemShellExecute.hpp"
#include <comphelper/processfactory.hxx>
#include "comphelper/anytostring.hxx"
#include "cppuhelper/exc_hlp.hxx"
#include "cppuhelper/bootstrap.hxx"
#include <sfx2/sfxuno.hxx>
#include <sfx2/sfxcommands.h>
#include "about.hxx"
#include "about.hrc"
#include <sfx2/sfxdefs.hxx>
#include <sfx2/app.hxx>
#include <rtl/ustrbuf.hxx>
using namespace ::com::sun::star;
// defines ---------------------------------------------------------------
#define SCROLL_OFFSET 1
#define SPACE_OFFSET 5
#define SCROLL_TIMER 30
/* get good version information */
static String
GetBuildId()
{
rtl::OUString sDefault;
rtl::OUString sBuildId( utl::Bootstrap::getBuildIdData( sDefault ) );
if (!sBuildId.isEmpty() && sBuildId.getLength() > 50)
{
rtl::OUStringBuffer aBuffer;
aBuffer.appendAscii(RTL_CONSTASCII_STRINGPARAM("\n\t"));
sal_Int32 nIndex = 0;
do
{
rtl::OUString aToken = sBuildId.getToken( 0, '-', nIndex );
if (!aToken.isEmpty())
{
aBuffer.append(aToken);
if (nIndex >= 0)
{
if (nIndex % 5)
aBuffer.append(static_cast<sal_Unicode>('-'));
else
aBuffer.appendAscii(RTL_CONSTASCII_STRINGPARAM("\n\t"));
}
}
}
while ( nIndex >= 0 );
sBuildId = aBuffer.makeStringAndClear();
}
OSL_ENSURE( !sBuildId.isEmpty(), "No BUILDID in bootstrap file" );
return sBuildId;
}
AboutDialog::AboutDialog( Window* pParent, const ResId& rId) :
SfxModalDialog ( pParent, rId ),
aVersionText ( this, ResId( ABOUT_FTXT_VERSION, *rId.GetResMgr() ) ),
aCopyrightText ( this, ResId( ABOUT_FTXT_COPYRIGHT, *rId.GetResMgr() ) ),
aInfoLink ( this, ResId( ABOUT_FTXT_LINK, *rId.GetResMgr() ) ),
aTdfLink ( this, ResId( ABOUT_TDFSTR_LINK, *rId.GetResMgr() ) ),
aFeaturesLink ( this, ResId( ABOUT_FEATURES_LINK, *rId.GetResMgr() ) ),
aVersionTextStr(ResId(ABOUT_STR_VERSION, *rId.GetResMgr())),
m_aVendorTextStr(ResId(ABOUT_STR_VENDOR, *rId.GetResMgr())),
m_aOracleCopyrightTextStr(ResId(ABOUT_STR_COPYRIGHT_ORACLE_DERIVED, *rId.GetResMgr())),
m_aAcknowledgementTextStr(ResId(ABOUT_STR_ACKNOWLEDGEMENT, *rId.GetResMgr())),
m_aLinkStr(ResId( ABOUT_STR_LINK, *rId.GetResMgr())),
m_aTdfLinkStr(ResId( ABOUT_TDF_LINK, *rId.GetResMgr())),
m_aFeaturesLinkStr(ResId( ABOUT_FEATURESSTR_LINK, *rId.GetResMgr())),
m_sBuildStr(ResId(ABOUT_STR_BUILD, *rId.GetResMgr()))
{
// load image from module path
aAppLogo = SfxApplication::GetApplicationLogo();
// Transparent Font
Font aFont = GetFont();
aFont.SetTransparent( sal_True );
SetFont( aFont );
// if necessary more info
String sVersion = aVersionTextStr;
sVersion.SearchAndReplaceAscii( "$(VER)", Application::GetDisplayName() );
sVersion += '\n';
sVersion += m_sBuildStr;
sVersion += ' ';
sVersion += GetBuildId();
#ifdef BUILD_VER_STRING
String aBuildString( DEFINE_CONST_UNICODE( BUILD_VER_STRING ) );
sVersion += '\n';
sVersion += aBuildString;
#endif
aVersionText.SetText( sVersion );
// set for background and text the correct system color
const StyleSettings& rSettings = GetSettings().GetStyleSettings();
Color aWhiteCol( rSettings.GetWindowColor() );
Wallpaper aWall( aWhiteCol );
SetBackground( aWall );
Font aNewFont( aCopyrightText.GetFont() );
aNewFont.SetTransparent( sal_True );
aVersionText.SetFont( aNewFont );
aCopyrightText.SetFont( aNewFont );
aVersionText.SetBackground();
aCopyrightText.SetBackground();
aInfoLink.SetURL(m_aLinkStr);
aInfoLink.SetBackground();
aInfoLink.SetClickHdl( LINK( this, AboutDialog, HandleHyperlink ) );
aTdfLink.SetURL(m_aTdfLinkStr);
aTdfLink.SetBackground();
aTdfLink.SetClickHdl( LINK( this, AboutDialog, HandleHyperlink ) );
aFeaturesLink.SetURL(m_aFeaturesLinkStr);
aFeaturesLink.SetBackground();
aFeaturesLink.SetClickHdl( LINK( this, AboutDialog, HandleHyperlink ) );
Color aTextColor( rSettings.GetWindowTextColor() );
aVersionText.SetControlForeground( aTextColor );
aCopyrightText.SetControlForeground( aTextColor );
rtl::OUStringBuffer sText(m_aVendorTextStr);
sal_uInt32 nCopyrightId =
utl::ConfigManager::getProductName().equalsAsciiL(
RTL_CONSTASCII_STRINGPARAM("LibreOffice"))
? ABOUT_STR_COPYRIGHT : ABOUT_STR_COPYRIGHT_DERIVED;
String aProductCopyrightTextStr(ResId(nCopyrightId, *rId.GetResMgr()));
sText.append(aProductCopyrightTextStr);
sText.appendAscii(RTL_CONSTASCII_STRINGPARAM("\n\n"));
sText.append(m_aOracleCopyrightTextStr);
sText.appendAscii(RTL_CONSTASCII_STRINGPARAM("\n\n"));
sText.append(m_aAcknowledgementTextStr);
aCopyrightText.SetText(sText.makeStringAndClear());
// determine size and position of the dialog & elements
Size aAppLogoSiz = aAppLogo.GetSizePixel();
// analyze size of the aVersionText widget
// character size
Size a6Size = aVersionText.LogicToPixel( Size( 6, 6 ), MAP_APPFONT );
// preferred Version widget size
long nY = aAppLogoSiz.Height() + ( a6Size.Height() * 2 );
long nDlgMargin = a6Size.Width() * 2;
long nCtrlMargin = a6Size.Height() * 2;
aVersionText.SetSizePixel(Size(800, 600));
Size aVersionTextSize = aVersionText.CalcMinimumSize();
aVersionTextSize.Width() += nDlgMargin;
Size aOutSiz = GetOutputSizePixel();
aOutSiz.Width() = aAppLogoSiz.Width();
if (aOutSiz.Width() < aVersionTextSize.Width())
aOutSiz.Width() = aVersionTextSize.Width();
if (aOutSiz.Width() < 300)
aOutSiz.Width() = 300;
//round up to nearest even
aOutSiz.Width() += aOutSiz.Width() & 1;
long nTextWidth = (aOutSiz.Width() - nDlgMargin);
// finally set the aVersionText widget position and size
Size aVTSize = aVersionText.GetSizePixel();
aVTSize.Width() = nTextWidth;
aVersionText.SetSizePixel(aVTSize);
aVTSize = aVersionText.CalcMinimumSize();
Point aVTPnt;
aVTPnt.X() = ( aOutSiz.Width() - aVTSize.Width() ) / 2;
aVTPnt.Y() = nY;
aVersionText.SetPosSizePixel( aVTPnt, aVTSize );
nY += aVTSize.Height() + nCtrlMargin;
// Multiline edit with Copyright-Text
// preferred Version widget size
aCopyrightText.SetSizePixel(Size(nTextWidth,600));
Size aCTSize = aCopyrightText.CalcMinimumSize();
aCTSize.Width()= nTextWidth;
Point aCTPnt;
aCTPnt.X() = ( aOutSiz.Width() - aCTSize.Width() ) / 2;
aCTPnt.Y() = nY;
aCopyrightText.SetPosSizePixel( aCTPnt, aCTSize );
nY += aCTSize.Height() + nCtrlMargin;
const int nLineSpace = 4;
// FixedHyperlink with more info link
Size aLTSize = aTdfLink.CalcMinimumSize();
Point aLTPnt;
aLTPnt.X() = ( aOutSiz.Width() - aLTSize.Width() ) / 2;
aLTPnt.Y() = nY;
aTdfLink.SetPosSizePixel( aLTPnt, aLTSize );
nY += aLTSize.Height();
aLTSize = aFeaturesLink.CalcMinimumSize();
aLTPnt.X() = ( aOutSiz.Width() - aLTSize.Width() ) / 2;
aLTPnt.Y() = aLTPnt.Y() + aLTSize.Height() + nLineSpace;
aFeaturesLink.SetPosSizePixel( aLTPnt, aLTSize );
nY += aLTSize.Height() + nLineSpace;
aLTSize = aInfoLink.CalcMinimumSize();
aLTPnt.X() = ( aOutSiz.Width() - aLTSize.Width() ) / 2;
aLTPnt.Y() = aLTPnt.Y() + aLTSize.Height() + nSpace;
aInfoLink.SetPosSizePixel( aLTPnt, aLTSize );
nY += aLTSize.Height() + nLineSpace;
nY += nCtrlMargin;
aOutSiz.Height() = nY;
// Change the size of the dialog
SetOutputSizePixel( aOutSiz );
FreeResource();
// explicit Help-Id
SetHelpId( CMD_SID_ABOUT );
}
// -----------------------------------------------------------------------
IMPL_LINK( AboutDialog, HandleHyperlink, svt::FixedHyperlink*, pHyperlink )
{
rtl::OUString sURL=pHyperlink->GetURL();
rtl::OUString sTitle=GetText();
if ( sURL.isEmpty() ) // Nothing to do, when the URL is empty
return 1;
try
{
uno::Reference< com::sun::star::system::XSystemShellExecute > xSystemShellExecute(
::comphelper::getProcessServiceFactory()->createInstance(
DEFINE_CONST_UNICODE("com.sun.star.system.SystemShellExecute") ), uno::UNO_QUERY_THROW );
xSystemShellExecute->execute( sURL, rtl::OUString(), com::sun::star::system::SystemShellExecuteFlags::DEFAULTS );
}
catch ( uno::Exception& )
{
uno::Any exc( ::cppu::getCaughtException() );
rtl::OUString msg( ::comphelper::anyToString( exc ) );
const SolarMutexGuard guard;
ErrorBox aErrorBox( NULL, WB_OK, msg );
aErrorBox.SetText( sTitle );
aErrorBox.Execute();
}
return 1;
}
void AboutDialog::Paint( const Rectangle& rRect )
{
SetClipRegion( rRect );
Point aPos( 0, 0 );
DrawImage( aPos, aAppLogo );
}
sal_Bool AboutDialog::Close()
{
EndDialog( RET_OK );
return sal_False;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>cui: about.cxx: nSpace was not declared in this scope<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// include ---------------------------------------------------------------
#include <vcl/svapp.hxx>
#include <vcl/msgbox.hxx>
#include <tools/stream.hxx>
#include <rtl/bootstrap.hxx>
#include <unotools/configmgr.hxx>
#include <unotools/bootstrap.hxx>
#include <com/sun/star/uno/Any.h>
#include <unotools/configmgr.hxx>
#include <vcl/svapp.hxx>
#include <vcl/graph.hxx>
#include <svtools/filter.hxx>
#include "com/sun/star/system/SystemShellExecuteFlags.hpp"
#include "com/sun/star/system/XSystemShellExecute.hpp"
#include <comphelper/processfactory.hxx>
#include "comphelper/anytostring.hxx"
#include "cppuhelper/exc_hlp.hxx"
#include "cppuhelper/bootstrap.hxx"
#include <sfx2/sfxuno.hxx>
#include <sfx2/sfxcommands.h>
#include "about.hxx"
#include "about.hrc"
#include <sfx2/sfxdefs.hxx>
#include <sfx2/app.hxx>
#include <rtl/ustrbuf.hxx>
using namespace ::com::sun::star;
// defines ---------------------------------------------------------------
#define SCROLL_OFFSET 1
#define SPACE_OFFSET 5
#define SCROLL_TIMER 30
/* get good version information */
static String
GetBuildId()
{
rtl::OUString sDefault;
rtl::OUString sBuildId( utl::Bootstrap::getBuildIdData( sDefault ) );
if (!sBuildId.isEmpty() && sBuildId.getLength() > 50)
{
rtl::OUStringBuffer aBuffer;
aBuffer.appendAscii(RTL_CONSTASCII_STRINGPARAM("\n\t"));
sal_Int32 nIndex = 0;
do
{
rtl::OUString aToken = sBuildId.getToken( 0, '-', nIndex );
if (!aToken.isEmpty())
{
aBuffer.append(aToken);
if (nIndex >= 0)
{
if (nIndex % 5)
aBuffer.append(static_cast<sal_Unicode>('-'));
else
aBuffer.appendAscii(RTL_CONSTASCII_STRINGPARAM("\n\t"));
}
}
}
while ( nIndex >= 0 );
sBuildId = aBuffer.makeStringAndClear();
}
OSL_ENSURE( !sBuildId.isEmpty(), "No BUILDID in bootstrap file" );
return sBuildId;
}
AboutDialog::AboutDialog( Window* pParent, const ResId& rId) :
SfxModalDialog ( pParent, rId ),
aVersionText ( this, ResId( ABOUT_FTXT_VERSION, *rId.GetResMgr() ) ),
aCopyrightText ( this, ResId( ABOUT_FTXT_COPYRIGHT, *rId.GetResMgr() ) ),
aInfoLink ( this, ResId( ABOUT_FTXT_LINK, *rId.GetResMgr() ) ),
aTdfLink ( this, ResId( ABOUT_TDFSTR_LINK, *rId.GetResMgr() ) ),
aFeaturesLink ( this, ResId( ABOUT_FEATURES_LINK, *rId.GetResMgr() ) ),
aVersionTextStr(ResId(ABOUT_STR_VERSION, *rId.GetResMgr())),
m_aVendorTextStr(ResId(ABOUT_STR_VENDOR, *rId.GetResMgr())),
m_aOracleCopyrightTextStr(ResId(ABOUT_STR_COPYRIGHT_ORACLE_DERIVED, *rId.GetResMgr())),
m_aAcknowledgementTextStr(ResId(ABOUT_STR_ACKNOWLEDGEMENT, *rId.GetResMgr())),
m_aLinkStr(ResId( ABOUT_STR_LINK, *rId.GetResMgr())),
m_aTdfLinkStr(ResId( ABOUT_TDF_LINK, *rId.GetResMgr())),
m_aFeaturesLinkStr(ResId( ABOUT_FEATURESSTR_LINK, *rId.GetResMgr())),
m_sBuildStr(ResId(ABOUT_STR_BUILD, *rId.GetResMgr()))
{
// load image from module path
aAppLogo = SfxApplication::GetApplicationLogo();
// Transparent Font
Font aFont = GetFont();
aFont.SetTransparent( sal_True );
SetFont( aFont );
// if necessary more info
String sVersion = aVersionTextStr;
sVersion.SearchAndReplaceAscii( "$(VER)", Application::GetDisplayName() );
sVersion += '\n';
sVersion += m_sBuildStr;
sVersion += ' ';
sVersion += GetBuildId();
#ifdef BUILD_VER_STRING
String aBuildString( DEFINE_CONST_UNICODE( BUILD_VER_STRING ) );
sVersion += '\n';
sVersion += aBuildString;
#endif
aVersionText.SetText( sVersion );
// set for background and text the correct system color
const StyleSettings& rSettings = GetSettings().GetStyleSettings();
Color aWhiteCol( rSettings.GetWindowColor() );
Wallpaper aWall( aWhiteCol );
SetBackground( aWall );
Font aNewFont( aCopyrightText.GetFont() );
aNewFont.SetTransparent( sal_True );
aVersionText.SetFont( aNewFont );
aCopyrightText.SetFont( aNewFont );
aVersionText.SetBackground();
aCopyrightText.SetBackground();
aInfoLink.SetURL(m_aLinkStr);
aInfoLink.SetBackground();
aInfoLink.SetClickHdl( LINK( this, AboutDialog, HandleHyperlink ) );
aTdfLink.SetURL(m_aTdfLinkStr);
aTdfLink.SetBackground();
aTdfLink.SetClickHdl( LINK( this, AboutDialog, HandleHyperlink ) );
aFeaturesLink.SetURL(m_aFeaturesLinkStr);
aFeaturesLink.SetBackground();
aFeaturesLink.SetClickHdl( LINK( this, AboutDialog, HandleHyperlink ) );
Color aTextColor( rSettings.GetWindowTextColor() );
aVersionText.SetControlForeground( aTextColor );
aCopyrightText.SetControlForeground( aTextColor );
rtl::OUStringBuffer sText(m_aVendorTextStr);
sal_uInt32 nCopyrightId =
utl::ConfigManager::getProductName().equalsAsciiL(
RTL_CONSTASCII_STRINGPARAM("LibreOffice"))
? ABOUT_STR_COPYRIGHT : ABOUT_STR_COPYRIGHT_DERIVED;
String aProductCopyrightTextStr(ResId(nCopyrightId, *rId.GetResMgr()));
sText.append(aProductCopyrightTextStr);
sText.appendAscii(RTL_CONSTASCII_STRINGPARAM("\n\n"));
sText.append(m_aOracleCopyrightTextStr);
sText.appendAscii(RTL_CONSTASCII_STRINGPARAM("\n\n"));
sText.append(m_aAcknowledgementTextStr);
aCopyrightText.SetText(sText.makeStringAndClear());
// determine size and position of the dialog & elements
Size aAppLogoSiz = aAppLogo.GetSizePixel();
// analyze size of the aVersionText widget
// character size
Size a6Size = aVersionText.LogicToPixel( Size( 6, 6 ), MAP_APPFONT );
// preferred Version widget size
long nY = aAppLogoSiz.Height() + ( a6Size.Height() * 2 );
long nDlgMargin = a6Size.Width() * 2;
long nCtrlMargin = a6Size.Height() * 2;
aVersionText.SetSizePixel(Size(800, 600));
Size aVersionTextSize = aVersionText.CalcMinimumSize();
aVersionTextSize.Width() += nDlgMargin;
Size aOutSiz = GetOutputSizePixel();
aOutSiz.Width() = aAppLogoSiz.Width();
if (aOutSiz.Width() < aVersionTextSize.Width())
aOutSiz.Width() = aVersionTextSize.Width();
if (aOutSiz.Width() < 300)
aOutSiz.Width() = 300;
//round up to nearest even
aOutSiz.Width() += aOutSiz.Width() & 1;
long nTextWidth = (aOutSiz.Width() - nDlgMargin);
// finally set the aVersionText widget position and size
Size aVTSize = aVersionText.GetSizePixel();
aVTSize.Width() = nTextWidth;
aVersionText.SetSizePixel(aVTSize);
aVTSize = aVersionText.CalcMinimumSize();
Point aVTPnt;
aVTPnt.X() = ( aOutSiz.Width() - aVTSize.Width() ) / 2;
aVTPnt.Y() = nY;
aVersionText.SetPosSizePixel( aVTPnt, aVTSize );
nY += aVTSize.Height() + nCtrlMargin;
// Multiline edit with Copyright-Text
// preferred Version widget size
aCopyrightText.SetSizePixel(Size(nTextWidth,600));
Size aCTSize = aCopyrightText.CalcMinimumSize();
aCTSize.Width()= nTextWidth;
Point aCTPnt;
aCTPnt.X() = ( aOutSiz.Width() - aCTSize.Width() ) / 2;
aCTPnt.Y() = nY;
aCopyrightText.SetPosSizePixel( aCTPnt, aCTSize );
nY += aCTSize.Height() + nCtrlMargin;
const int nLineSpace = 4;
// FixedHyperlink with more info link
Size aLTSize = aTdfLink.CalcMinimumSize();
Point aLTPnt;
aLTPnt.X() = ( aOutSiz.Width() - aLTSize.Width() ) / 2;
aLTPnt.Y() = nY;
aTdfLink.SetPosSizePixel( aLTPnt, aLTSize );
nY += aLTSize.Height();
aLTSize = aFeaturesLink.CalcMinimumSize();
aLTPnt.X() = ( aOutSiz.Width() - aLTSize.Width() ) / 2;
aLTPnt.Y() = aLTPnt.Y() + aLTSize.Height() + nLineSpace;
aFeaturesLink.SetPosSizePixel( aLTPnt, aLTSize );
nY += aLTSize.Height() + nLineSpace;
aLTSize = aInfoLink.CalcMinimumSize();
aLTPnt.X() = ( aOutSiz.Width() - aLTSize.Width() ) / 2;
aLTPnt.Y() = aLTPnt.Y() + aLTSize.Height() + nLineSpace;
aInfoLink.SetPosSizePixel( aLTPnt, aLTSize );
nY += aLTSize.Height() + nLineSpace;
nY += nCtrlMargin;
aOutSiz.Height() = nY;
// Change the size of the dialog
SetOutputSizePixel( aOutSiz );
FreeResource();
// explicit Help-Id
SetHelpId( CMD_SID_ABOUT );
}
// -----------------------------------------------------------------------
IMPL_LINK( AboutDialog, HandleHyperlink, svt::FixedHyperlink*, pHyperlink )
{
rtl::OUString sURL=pHyperlink->GetURL();
rtl::OUString sTitle=GetText();
if ( sURL.isEmpty() ) // Nothing to do, when the URL is empty
return 1;
try
{
uno::Reference< com::sun::star::system::XSystemShellExecute > xSystemShellExecute(
::comphelper::getProcessServiceFactory()->createInstance(
DEFINE_CONST_UNICODE("com.sun.star.system.SystemShellExecute") ), uno::UNO_QUERY_THROW );
xSystemShellExecute->execute( sURL, rtl::OUString(), com::sun::star::system::SystemShellExecuteFlags::DEFAULTS );
}
catch ( uno::Exception& )
{
uno::Any exc( ::cppu::getCaughtException() );
rtl::OUString msg( ::comphelper::anyToString( exc ) );
const SolarMutexGuard guard;
ErrorBox aErrorBox( NULL, WB_OK, msg );
aErrorBox.SetText( sTitle );
aErrorBox.Execute();
}
return 1;
}
void AboutDialog::Paint( const Rectangle& rRect )
{
SetClipRegion( rRect );
Point aPos( 0, 0 );
DrawImage( aPos, aAppLogo );
}
sal_Bool AboutDialog::Close()
{
EndDialog( RET_OK );
return sal_False;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: textconversion_zh.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: obo $ $Date: 2006-09-17 09:24:29 $
*
* 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_i18npool.hxx"
#include <assert.h>
#include <textconversion.hxx>
#include <com/sun/star/i18n/TextConversionType.hpp>
#include <com/sun/star/i18n/TextConversionOption.hpp>
#include <com/sun/star/linguistic2/ConversionDirection.hpp>
#include <com/sun/star/linguistic2/ConversionDictionaryType.hpp>
#include <i18nutil/x_rtl_ustring.h>
using namespace com::sun::star::lang;
using namespace com::sun::star::i18n;
using namespace com::sun::star::linguistic2;
using namespace com::sun::star::uno;
using namespace rtl;
namespace com { namespace sun { namespace star { namespace i18n {
TextConversion_zh::TextConversion_zh( const Reference < XMultiServiceFactory >& xMSF )
{
Reference < XInterface > xI;
xI = xMSF->createInstance(
OUString::createFromAscii( "com.sun.star.linguistic2.ConversionDictionaryList" ));
if ( xI.is() )
xI->queryInterface( getCppuType((const Reference< XConversionDictionaryList>*)0) ) >>= xCDL;
implementationName = "com.sun.star.i18n.TextConversion_zh";
}
sal_Unicode SAL_CALL getOneCharConversion(sal_Unicode ch, const sal_Unicode* Data, const sal_uInt16* Index)
{
if (Data && Index) {
sal_Unicode address = Index[ch>>8];
if (address != 0xFFFF)
address = Data[address + (ch & 0xFF)];
return (address != 0xFFFF) ? address : ch;
} else {
return ch;
}
}
OUString SAL_CALL
TextConversion_zh::getCharConversion(const OUString& aText, sal_Int32 nStartPos, sal_Int32 nLength, sal_Bool toSChinese, sal_Int32 nConversionOptions)
{
const sal_Unicode *Data;
const sal_uInt16 *Index;
if (toSChinese) {
Data = ((const sal_Unicode* (*)())getFunctionBySymbol("getSTC_CharData_T2S"))();
Index = ((const sal_uInt16* (*)())getFunctionBySymbol("getSTC_CharIndex_T2S"))();
} else if (nConversionOptions & TextConversionOption::USE_CHARACTER_VARIANTS) {
Data = ((const sal_Unicode* (*)())getFunctionBySymbol("getSTC_CharData_S2V"))();
Index = ((const sal_uInt16* (*)())getFunctionBySymbol("getSTC_CharIndex_S2V"))();
} else {
Data = ((const sal_Unicode* (*)())getFunctionBySymbol("getSTC_CharData_S2T"))();
Index = ((const sal_uInt16* (*)())getFunctionBySymbol("getSTC_CharIndex_S2T"))();
}
rtl_uString * newStr = x_rtl_uString_new_WithLength( nLength ); // defined in x_rtl_ustring.h
for (sal_Int32 i = 0; i < nLength; i++)
newStr->buffer[i] =
getOneCharConversion(aText[nStartPos+i], Data, Index);
return OUString( newStr->buffer, nLength);
}
OUString SAL_CALL
TextConversion_zh::getWordConversion(const OUString& aText, sal_Int32 nStartPos, sal_Int32 nLength, sal_Bool toSChinese, sal_Int32 nConversionOptions, Sequence<sal_Int32>& offset)
{
sal_Int32 dictLen = 0;
sal_Int32 maxLen = 0;
const sal_uInt16 *index;
const sal_uInt16 *entry;
const sal_Unicode *charData;
const sal_uInt16 *charIndex;
sal_Bool one2one=sal_True;
const sal_Unicode *wordData = ((const sal_Unicode* (*)(sal_Int32&)) getFunctionBySymbol("getSTC_WordData"))(dictLen);
if (toSChinese) {
index = ((const sal_uInt16* (*)(sal_Int32&)) getFunctionBySymbol("getSTC_WordIndex_T2S"))(maxLen);
entry = ((const sal_uInt16* (*)()) getFunctionBySymbol("getSTC_WordEntry_T2S"))();
charData = ((const sal_Unicode* (*)()) getFunctionBySymbol("getSTC_CharData_T2S"))();
charIndex = ((const sal_uInt16* (*)()) getFunctionBySymbol("getSTC_CharIndex_T2S"))();
} else {
index = ((const sal_uInt16* (*)(sal_Int32&)) getFunctionBySymbol("getSTC_WordIndex_S2T"))(maxLen);
entry = ((const sal_uInt16* (*)()) getFunctionBySymbol("getSTC_WordEntry_S2T"))();
if (nConversionOptions & TextConversionOption::USE_CHARACTER_VARIANTS) {
charData = ((const sal_Unicode* (*)()) getFunctionBySymbol("getSTC_CharData_S2V"))();
charIndex = ((const sal_uInt16* (*)()) getFunctionBySymbol("getSTC_CharIndex_S2V"))();
} else {
charData = ((const sal_Unicode* (*)()) getFunctionBySymbol("getSTC_CharData_S2T"))();
charIndex = ((const sal_uInt16* (*)()) getFunctionBySymbol("getSTC_CharIndex_S2T"))();
}
}
if ((!wordData || !index || !entry) && !xCDL.is()) // no word mapping defined, do char2char conversion.
return getCharConversion(aText, nStartPos, nLength, toSChinese, nConversionOptions);
rtl_uString * newStr = x_rtl_uString_new_WithLength( nLength * 2 ); // defined in x_rtl_ustring.h
sal_Int32 currPos = 0, count = 0;
while (currPos < nLength) {
sal_Int32 len = nLength - currPos;
sal_Bool found = sal_False;
if (len > maxLen)
len = maxLen;
for (; len > 0 && ! found; len--) {
OUString word = aText.copy(nStartPos + currPos, len);
sal_Int32 current = 0;
// user dictionary
if (xCDL.is()) {
Sequence < OUString > conversions;
try {
conversions = xCDL->queryConversions(word, 0, len,
aLocale, ConversionDictionaryType::SCHINESE_TCHINESE,
/*toSChinese ?*/ ConversionDirection_FROM_LEFT /*: ConversionDirection_FROM_RIGHT*/,
nConversionOptions);
}
catch ( NoSupportException & ) {
// clear reference (when there is no user dictionary) in order
// to not always have to catch this exception again
// in further calls. (save time)
xCDL = 0;
}
catch (...) {
// catch all other exceptions to allow
// querying the system dictionary in the next line
}
if (conversions.getLength() > 0) {
if (offset.getLength() > 0) {
if (word.getLength() != conversions[0].getLength())
one2one=sal_False;
while (current < conversions[0].getLength()) {
offset[count] = nStartPos + currPos + (current *
word.getLength() / conversions[0].getLength());
newStr->buffer[count++] = conversions[0][current++];
}
offset[count-1] = nStartPos + currPos + word.getLength() - 1;
} else {
while (current < conversions[0].getLength())
newStr->buffer[count++] = conversions[0][current++];
}
currPos += word.getLength();
found = sal_True;
}
}
if (!found && index[len+1] - index[len] > 0) {
sal_Int32 bottom = (sal_Int32) index[len];
sal_Int32 top = (sal_Int32) index[len+1] - 1;
while (bottom <= top && !found) {
current = (top + bottom) / 2;
const sal_Int32 result = word.compareTo(wordData + entry[current]);
if (result < 0)
top = current - 1;
else if (result > 0)
bottom = current + 1;
else {
if (toSChinese) // Traditionary/Simplified conversion,
for (current = entry[current]-1; current > 0 && wordData[current-1]; current--);
else // Simplified/Traditionary conversion, forwards search for next word
current = entry[current] + word.getLength() + 1;
sal_Int32 start=current;
if (offset.getLength() > 0) {
if (word.getLength() != OUString(&wordData[current]).getLength())
one2one=sal_False;
sal_Int32 convertedLength=OUString(&wordData[current]).getLength();
while (wordData[current]) {
offset[count]=nStartPos + currPos + ((current-start) *
word.getLength() / convertedLength);
newStr->buffer[count++] = wordData[current++];
}
offset[count-1]=nStartPos + currPos + word.getLength() - 1;
} else {
while (wordData[current])
newStr->buffer[count++] = wordData[current++];
}
currPos += word.getLength();
found = sal_True;
}
}
}
}
if (!found) {
if (offset.getLength() > 0)
offset[count]=nStartPos+currPos;
newStr->buffer[count++] =
getOneCharConversion(aText[nStartPos+currPos], charData, charIndex);
currPos++;
}
}
if (offset.getLength() > 0)
offset.realloc(one2one ? 0 : count);
return OUString( newStr->buffer, count);
}
TextConversionResult SAL_CALL
TextConversion_zh::getConversions( const OUString& aText, sal_Int32 nStartPos, sal_Int32 nLength,
const Locale& rLocale, sal_Int16 nConversionType, sal_Int32 nConversionOptions)
throw( RuntimeException, IllegalArgumentException, NoSupportException )
{
TextConversionResult result;
result.Candidates.realloc(1);
result.Candidates[0] = getConversion( aText, nStartPos, nLength, rLocale, nConversionType, nConversionOptions);
result.Boundary.startPos = nStartPos;
result.Boundary.endPos = nStartPos + nLength;
return result;
}
OUString SAL_CALL
TextConversion_zh::getConversion( const OUString& aText, sal_Int32 nStartPos, sal_Int32 nLength,
const Locale& rLocale, sal_Int16 nConversionType, sal_Int32 nConversionOptions)
throw( RuntimeException, IllegalArgumentException, NoSupportException )
{
if (rLocale.Language.equalsAscii("zh") &&
( nConversionType == TextConversionType::TO_SCHINESE ||
nConversionType == TextConversionType::TO_TCHINESE) ) {
aLocale=rLocale;
sal_Bool toSChinese = nConversionType == TextConversionType::TO_SCHINESE;
if (nConversionOptions & TextConversionOption::CHARACTER_BY_CHARACTER)
// char to char dictionary
return getCharConversion(aText, nStartPos, nLength, toSChinese, nConversionOptions);
else {
Sequence <sal_Int32> offset;
// word to word dictionary
return getWordConversion(aText, nStartPos, nLength, toSChinese, nConversionOptions, offset);
}
} else
throw NoSupportException(); // Conversion type is not supported in this service.
}
OUString SAL_CALL
TextConversion_zh::getConversionWithOffset( const OUString& aText, sal_Int32 nStartPos, sal_Int32 nLength,
const Locale& rLocale, sal_Int16 nConversionType, sal_Int32 nConversionOptions, Sequence<sal_Int32>& offset)
throw( RuntimeException, IllegalArgumentException, NoSupportException )
{
if (rLocale.Language.equalsAscii("zh") &&
( nConversionType == TextConversionType::TO_SCHINESE ||
nConversionType == TextConversionType::TO_TCHINESE) ) {
aLocale=rLocale;
sal_Bool toSChinese = nConversionType == TextConversionType::TO_SCHINESE;
if (nConversionOptions & TextConversionOption::CHARACTER_BY_CHARACTER) {
offset.realloc(0);
// char to char dictionary
return getCharConversion(aText, nStartPos, nLength, toSChinese, nConversionOptions);
} else {
if (offset.getLength() < 2*nLength)
offset.realloc(2*nLength);
// word to word dictionary
return getWordConversion(aText, nStartPos, nLength, toSChinese, nConversionOptions, offset);
}
} else
throw NoSupportException(); // Conversion type is not supported in this service.
}
sal_Bool SAL_CALL
TextConversion_zh::interactiveConversion( const Locale& /*rLocale*/, sal_Int16 /*nTextConversionType*/, sal_Int32 /*nTextConversionOptions*/ )
throw( RuntimeException, IllegalArgumentException, NoSupportException )
{
return sal_False;
}
} } } }
<commit_msg>INTEGRATION: CWS i18n27 (1.8.22); FILE MERGED 2006/10/11 00:17:11 khong 1.8.22.2: RESYNC: (1.8-1.9); FILE MERGED 2006/10/10 21:05:39 khong 1.8.22.1: #i63955# make offset point to beginning of converting position<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: textconversion_zh.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: kz $ $Date: 2006-11-06 14:41:02 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_i18npool.hxx"
#include <assert.h>
#include <textconversion.hxx>
#include <com/sun/star/i18n/TextConversionType.hpp>
#include <com/sun/star/i18n/TextConversionOption.hpp>
#include <com/sun/star/linguistic2/ConversionDirection.hpp>
#include <com/sun/star/linguistic2/ConversionDictionaryType.hpp>
#include <i18nutil/x_rtl_ustring.h>
using namespace com::sun::star::lang;
using namespace com::sun::star::i18n;
using namespace com::sun::star::linguistic2;
using namespace com::sun::star::uno;
using namespace rtl;
namespace com { namespace sun { namespace star { namespace i18n {
TextConversion_zh::TextConversion_zh( const Reference < XMultiServiceFactory >& xMSF )
{
Reference < XInterface > xI;
xI = xMSF->createInstance(
OUString::createFromAscii( "com.sun.star.linguistic2.ConversionDictionaryList" ));
if ( xI.is() )
xI->queryInterface( getCppuType((const Reference< XConversionDictionaryList>*)0) ) >>= xCDL;
implementationName = "com.sun.star.i18n.TextConversion_zh";
}
sal_Unicode SAL_CALL getOneCharConversion(sal_Unicode ch, const sal_Unicode* Data, const sal_uInt16* Index)
{
if (Data && Index) {
sal_Unicode address = Index[ch>>8];
if (address != 0xFFFF)
address = Data[address + (ch & 0xFF)];
return (address != 0xFFFF) ? address : ch;
} else {
return ch;
}
}
OUString SAL_CALL
TextConversion_zh::getCharConversion(const OUString& aText, sal_Int32 nStartPos, sal_Int32 nLength, sal_Bool toSChinese, sal_Int32 nConversionOptions)
{
const sal_Unicode *Data;
const sal_uInt16 *Index;
if (toSChinese) {
Data = ((const sal_Unicode* (*)())getFunctionBySymbol("getSTC_CharData_T2S"))();
Index = ((const sal_uInt16* (*)())getFunctionBySymbol("getSTC_CharIndex_T2S"))();
} else if (nConversionOptions & TextConversionOption::USE_CHARACTER_VARIANTS) {
Data = ((const sal_Unicode* (*)())getFunctionBySymbol("getSTC_CharData_S2V"))();
Index = ((const sal_uInt16* (*)())getFunctionBySymbol("getSTC_CharIndex_S2V"))();
} else {
Data = ((const sal_Unicode* (*)())getFunctionBySymbol("getSTC_CharData_S2T"))();
Index = ((const sal_uInt16* (*)())getFunctionBySymbol("getSTC_CharIndex_S2T"))();
}
rtl_uString * newStr = x_rtl_uString_new_WithLength( nLength ); // defined in x_rtl_ustring.h
for (sal_Int32 i = 0; i < nLength; i++)
newStr->buffer[i] =
getOneCharConversion(aText[nStartPos+i], Data, Index);
return OUString( newStr->buffer, nLength);
}
OUString SAL_CALL
TextConversion_zh::getWordConversion(const OUString& aText, sal_Int32 nStartPos, sal_Int32 nLength, sal_Bool toSChinese, sal_Int32 nConversionOptions, Sequence<sal_Int32>& offset)
{
sal_Int32 dictLen = 0;
sal_Int32 maxLen = 0;
const sal_uInt16 *index;
const sal_uInt16 *entry;
const sal_Unicode *charData;
const sal_uInt16 *charIndex;
sal_Bool one2one=sal_True;
const sal_Unicode *wordData = ((const sal_Unicode* (*)(sal_Int32&)) getFunctionBySymbol("getSTC_WordData"))(dictLen);
if (toSChinese) {
index = ((const sal_uInt16* (*)(sal_Int32&)) getFunctionBySymbol("getSTC_WordIndex_T2S"))(maxLen);
entry = ((const sal_uInt16* (*)()) getFunctionBySymbol("getSTC_WordEntry_T2S"))();
charData = ((const sal_Unicode* (*)()) getFunctionBySymbol("getSTC_CharData_T2S"))();
charIndex = ((const sal_uInt16* (*)()) getFunctionBySymbol("getSTC_CharIndex_T2S"))();
} else {
index = ((const sal_uInt16* (*)(sal_Int32&)) getFunctionBySymbol("getSTC_WordIndex_S2T"))(maxLen);
entry = ((const sal_uInt16* (*)()) getFunctionBySymbol("getSTC_WordEntry_S2T"))();
if (nConversionOptions & TextConversionOption::USE_CHARACTER_VARIANTS) {
charData = ((const sal_Unicode* (*)()) getFunctionBySymbol("getSTC_CharData_S2V"))();
charIndex = ((const sal_uInt16* (*)()) getFunctionBySymbol("getSTC_CharIndex_S2V"))();
} else {
charData = ((const sal_Unicode* (*)()) getFunctionBySymbol("getSTC_CharData_S2T"))();
charIndex = ((const sal_uInt16* (*)()) getFunctionBySymbol("getSTC_CharIndex_S2T"))();
}
}
if ((!wordData || !index || !entry) && !xCDL.is()) // no word mapping defined, do char2char conversion.
return getCharConversion(aText, nStartPos, nLength, toSChinese, nConversionOptions);
rtl_uString * newStr = x_rtl_uString_new_WithLength( nLength * 2 ); // defined in x_rtl_ustring.h
sal_Int32 currPos = 0, count = 0;
while (currPos < nLength) {
sal_Int32 len = nLength - currPos;
sal_Bool found = sal_False;
if (len > maxLen)
len = maxLen;
for (; len > 0 && ! found; len--) {
OUString word = aText.copy(nStartPos + currPos, len);
sal_Int32 current = 0;
// user dictionary
if (xCDL.is()) {
Sequence < OUString > conversions;
try {
conversions = xCDL->queryConversions(word, 0, len,
aLocale, ConversionDictionaryType::SCHINESE_TCHINESE,
/*toSChinese ?*/ ConversionDirection_FROM_LEFT /*: ConversionDirection_FROM_RIGHT*/,
nConversionOptions);
}
catch ( NoSupportException & ) {
// clear reference (when there is no user dictionary) in order
// to not always have to catch this exception again
// in further calls. (save time)
xCDL = 0;
}
catch (...) {
// catch all other exceptions to allow
// querying the system dictionary in the next line
}
if (conversions.getLength() > 0) {
if (offset.getLength() > 0) {
if (word.getLength() != conversions[0].getLength())
one2one=sal_False;
while (current < conversions[0].getLength()) {
offset[count] = nStartPos + currPos + (current *
word.getLength() / conversions[0].getLength());
newStr->buffer[count++] = conversions[0][current++];
}
// offset[count-1] = nStartPos + currPos + word.getLength() - 1;
} else {
while (current < conversions[0].getLength())
newStr->buffer[count++] = conversions[0][current++];
}
currPos += word.getLength();
found = sal_True;
}
}
if (!found && index[len+1] - index[len] > 0) {
sal_Int32 bottom = (sal_Int32) index[len];
sal_Int32 top = (sal_Int32) index[len+1] - 1;
while (bottom <= top && !found) {
current = (top + bottom) / 2;
const sal_Int32 result = word.compareTo(wordData + entry[current]);
if (result < 0)
top = current - 1;
else if (result > 0)
bottom = current + 1;
else {
if (toSChinese) // Traditionary/Simplified conversion,
for (current = entry[current]-1; current > 0 && wordData[current-1]; current--);
else // Simplified/Traditionary conversion, forwards search for next word
current = entry[current] + word.getLength() + 1;
sal_Int32 start=current;
if (offset.getLength() > 0) {
if (word.getLength() != OUString(&wordData[current]).getLength())
one2one=sal_False;
sal_Int32 convertedLength=OUString(&wordData[current]).getLength();
while (wordData[current]) {
offset[count]=nStartPos + currPos + ((current-start) *
word.getLength() / convertedLength);
newStr->buffer[count++] = wordData[current++];
}
// offset[count-1]=nStartPos + currPos + word.getLength() - 1;
} else {
while (wordData[current])
newStr->buffer[count++] = wordData[current++];
}
currPos += word.getLength();
found = sal_True;
}
}
}
}
if (!found) {
if (offset.getLength() > 0)
offset[count]=nStartPos+currPos;
newStr->buffer[count++] =
getOneCharConversion(aText[nStartPos+currPos], charData, charIndex);
currPos++;
}
}
if (offset.getLength() > 0)
offset.realloc(one2one ? 0 : count);
return OUString( newStr->buffer, count);
}
TextConversionResult SAL_CALL
TextConversion_zh::getConversions( const OUString& aText, sal_Int32 nStartPos, sal_Int32 nLength,
const Locale& rLocale, sal_Int16 nConversionType, sal_Int32 nConversionOptions)
throw( RuntimeException, IllegalArgumentException, NoSupportException )
{
TextConversionResult result;
result.Candidates.realloc(1);
result.Candidates[0] = getConversion( aText, nStartPos, nLength, rLocale, nConversionType, nConversionOptions);
result.Boundary.startPos = nStartPos;
result.Boundary.endPos = nStartPos + nLength;
return result;
}
OUString SAL_CALL
TextConversion_zh::getConversion( const OUString& aText, sal_Int32 nStartPos, sal_Int32 nLength,
const Locale& rLocale, sal_Int16 nConversionType, sal_Int32 nConversionOptions)
throw( RuntimeException, IllegalArgumentException, NoSupportException )
{
if (rLocale.Language.equalsAscii("zh") &&
( nConversionType == TextConversionType::TO_SCHINESE ||
nConversionType == TextConversionType::TO_TCHINESE) ) {
aLocale=rLocale;
sal_Bool toSChinese = nConversionType == TextConversionType::TO_SCHINESE;
if (nConversionOptions & TextConversionOption::CHARACTER_BY_CHARACTER)
// char to char dictionary
return getCharConversion(aText, nStartPos, nLength, toSChinese, nConversionOptions);
else {
Sequence <sal_Int32> offset;
// word to word dictionary
return getWordConversion(aText, nStartPos, nLength, toSChinese, nConversionOptions, offset);
}
} else
throw NoSupportException(); // Conversion type is not supported in this service.
}
OUString SAL_CALL
TextConversion_zh::getConversionWithOffset( const OUString& aText, sal_Int32 nStartPos, sal_Int32 nLength,
const Locale& rLocale, sal_Int16 nConversionType, sal_Int32 nConversionOptions, Sequence<sal_Int32>& offset)
throw( RuntimeException, IllegalArgumentException, NoSupportException )
{
if (rLocale.Language.equalsAscii("zh") &&
( nConversionType == TextConversionType::TO_SCHINESE ||
nConversionType == TextConversionType::TO_TCHINESE) ) {
aLocale=rLocale;
sal_Bool toSChinese = nConversionType == TextConversionType::TO_SCHINESE;
if (nConversionOptions & TextConversionOption::CHARACTER_BY_CHARACTER) {
offset.realloc(0);
// char to char dictionary
return getCharConversion(aText, nStartPos, nLength, toSChinese, nConversionOptions);
} else {
if (offset.getLength() < 2*nLength)
offset.realloc(2*nLength);
// word to word dictionary
return getWordConversion(aText, nStartPos, nLength, toSChinese, nConversionOptions, offset);
}
} else
throw NoSupportException(); // Conversion type is not supported in this service.
}
sal_Bool SAL_CALL
TextConversion_zh::interactiveConversion( const Locale& /*rLocale*/, sal_Int16 /*nTextConversionType*/, sal_Int32 /*nTextConversionOptions*/ )
throw( RuntimeException, IllegalArgumentException, NoSupportException )
{
return sal_False;
}
} } } }
<|endoftext|> |
<commit_before>/*
* Copyright 2008-2009 NVIDIA Corporation
*
* 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 <cusp/copy.h>
#include <cusp/format.h>
#include <cusp/array1d.h>
#include <thrust/fill.h>
#include <thrust/extrema.h>
#include <thrust/binary_search.h>
#include <thrust/transform.h>
#include <thrust/gather.h>
#include <thrust/scatter.h>
#include <thrust/sequence.h>
#include <thrust/sort.h>
namespace cusp
{
namespace detail
{
template <typename OffsetArray, typename IndexArray>
void offsets_to_indices(const OffsetArray& offsets, IndexArray& indices)
{
CUSP_PROFILE_SCOPED();
typedef typename OffsetArray::value_type OffsetType;
// convert compressed row offsets into uncompressed row indices
thrust::upper_bound(offsets.begin() + 1,
offsets.end(),
thrust::counting_iterator<OffsetType>(0),
thrust::counting_iterator<OffsetType>(indices.size()),
indices.begin());
}
template <typename IndexArray, typename OffsetArray>
void indices_to_offsets(const IndexArray& indices, OffsetArray& offsets)
{
CUSP_PROFILE_SCOPED();
typedef typename OffsetArray::value_type OffsetType;
// convert uncompressed row indices into compressed row offsets
thrust::lower_bound(indices.begin(),
indices.end(),
thrust::counting_iterator<OffsetType>(0),
thrust::counting_iterator<OffsetType>(offsets.size()),
offsets.begin());
}
template<typename T, typename IndexType>
struct row_operator : public std::unary_function<T,IndexType>
{
row_operator(int a_step)
: step(a_step)
{}
__host__ __device__
IndexType operator()(const T &value) const
{
return value % step;
}
private:
int step; // TODO replace with IndexType
};
// TODO fuse transform and scatter_if together
template <typename Matrix, typename Array>
void extract_diagonal(const Matrix& A, Array& output, cusp::coo_format)
{
CUSP_PROFILE_SCOPED();
typedef typename Matrix::index_type IndexType;
typedef typename Array::value_type ValueType;
typedef typename Array::memory_space MemorySpace; // TODO remove
// initialize output to zero
thrust::fill(output.begin(), output.end(), ValueType(0));
// determine which matrix entries correspond to the matrix diagonal
cusp::array1d<unsigned int,MemorySpace> is_diagonal(A.num_entries);
thrust::transform(A.row_indices.begin(), A.row_indices.end(), A.column_indices.begin(), is_diagonal.begin(), thrust::equal_to<IndexType>());
// scatter the diagonal values to output
thrust::scatter_if(A.values.begin(), A.values.end(),
A.row_indices.begin(),
is_diagonal.begin(),
output.begin());
}
template <typename Matrix, typename Array>
void extract_diagonal(const Matrix& A, Array& output, cusp::csr_format)
{
typedef typename Matrix::index_type IndexType;
typedef typename Array::value_type ValueType;
typedef typename Array::memory_space MemorySpace; // TODO remove
// initialize output to zero
thrust::fill(output.begin(), output.end(), ValueType(0));
// first expand the compressed row offsets into row indices
cusp::array1d<IndexType,MemorySpace> row_indices(A.num_entries);
offsets_to_indices(A.row_offsets, row_indices);
// determine which matrix entries correspond to the matrix diagonal
cusp::array1d<unsigned int,MemorySpace> is_diagonal(A.num_entries);
thrust::transform(row_indices.begin(), row_indices.end(), A.column_indices.begin(), is_diagonal.begin(), thrust::equal_to<IndexType>());
// scatter the diagonal values to output
thrust::scatter_if(A.values.begin(), A.values.end(),
row_indices.begin(),
is_diagonal.begin(),
output.begin());
}
template <typename Matrix, typename Array>
void extract_diagonal(const Matrix& A, Array& output, cusp::dia_format)
{
typedef typename Matrix::index_type IndexType;
typedef typename Array::value_type ValueType;
typedef typename Array::memory_space MemorySpace; // TODO remove
// copy diagonal_offsets to host (sometimes unnecessary)
cusp::array1d<IndexType,cusp::host_memory> diagonal_offsets(A.diagonal_offsets);
for(size_t i = 0; i < diagonal_offsets.size(); i++)
{
if(diagonal_offsets[i] == 0)
{
// diagonal found, copy to output and return
thrust::copy(A.values.values.begin() + A.values.pitch * i,
A.values.values.begin() + A.values.pitch * i + output.size(),
output.begin());
return;
}
}
// no diagonal found
thrust::fill(output.begin(), output.end(), ValueType(0));
}
template <typename Matrix, typename Array>
void extract_diagonal(const Matrix& A, Array& output, cusp::ell_format)
{
typedef typename Matrix::index_type IndexType;
typedef typename Array::value_type ValueType;
typedef typename Array::memory_space MemorySpace; // TODO remove
// initialize output to zero
thrust::fill(output.begin(), output.end(), ValueType(0));
// TODO completely ignore padded values either by remapping indices or zipping w/ predicate
// TODO fuse everything into the scatter_if
// compute ELL row indices
cusp::array1d<IndexType,MemorySpace> row_indices(A.column_indices.values.size());
thrust::transform(thrust::counting_iterator<int>(0), thrust::counting_iterator<int>(A.column_indices.values.size()),
row_indices.begin(), row_operator<int,IndexType>(A.column_indices.pitch));
// determine which matrix entries correspond to the matrix diagonal
cusp::array1d<unsigned int,MemorySpace> is_diagonal(A.column_indices.values.size());
thrust::transform(row_indices.begin(), row_indices.end(), A.column_indices.values.begin(), is_diagonal.begin(), thrust::equal_to<IndexType>());
// scatter the diagonal values to output
thrust::scatter_if(A.values.values.begin(), A.values.values.end(),
row_indices.begin(),
is_diagonal.begin(),
output.begin());
}
template <typename Matrix, typename Array>
void extract_diagonal(const Matrix& A, Array& output, cusp::hyb_format)
{
typedef typename Matrix::index_type IndexType;
typedef typename Array::value_type ValueType;
typedef typename Array::memory_space MemorySpace; // TODO remove
// initialize output to zero
thrust::fill(output.begin(), output.end(), ValueType(0));
// extract COO diagonal
{
// TODO fuse into single operation
// determine which matrix entries correspond to the matrix diagonal
cusp::array1d<unsigned int,MemorySpace> is_diagonal(A.coo.num_entries);
thrust::transform(A.coo.row_indices.begin(), A.coo.row_indices.end(),
A.coo.column_indices.begin(),
is_diagonal.begin(),
thrust::equal_to<IndexType>());
// scatter the diagonal values to output
thrust::scatter_if(A.coo.values.begin(), A.coo.values.end(),
A.coo.row_indices.begin(),
is_diagonal.begin(),
output.begin());
}
// extract ELL diagonal
{
// TODO fuse into single operation
// compute ELL row indices
cusp::array1d<IndexType,MemorySpace> row_indices(A.ell.column_indices.values.size());
thrust::transform(thrust::counting_iterator<int>(0), thrust::counting_iterator<int>(A.ell.column_indices.values.size()),
row_indices.begin(),
row_operator<int,IndexType>(A.ell.column_indices.num_rows));
// determine which matrix entries correspond to the matrix diagonal
cusp::array1d<unsigned int,MemorySpace> is_diagonal(A.ell.column_indices.values.size());
thrust::transform(row_indices.begin(), row_indices.end(),
A.ell.column_indices.values.begin(),
is_diagonal.begin(),
thrust::equal_to<IndexType>());
// scatter the diagonal values to output
thrust::scatter_if(A.ell.values.values.begin(), A.ell.values.values.end(),
row_indices.begin(),
is_diagonal.begin(),
output.begin());
}
}
template <typename Matrix, typename Array>
void extract_diagonal(const Matrix& A, Array& output)
{
CUSP_PROFILE_SCOPED();
output.resize(thrust::min(A.num_rows, A.num_cols));
// dispatch on matrix format
extract_diagonal(A, output, typename Matrix::format());
}
template <typename Array1, typename Array2, typename Array3>
void sort_by_row(Array1& rows, Array2& columns, Array3& values)
{
CUSP_PROFILE_SCOPED();
typedef typename Array1::value_type IndexType;
typedef typename Array3::value_type ValueType;
typedef typename Array1::memory_space MemorySpace;
size_t N = rows.size();
cusp::array1d<IndexType,MemorySpace> permutation(N);
thrust::sequence(permutation.begin(), permutation.end());
// compute permutation that sorts the rows
thrust::sort_by_key(rows.begin(), rows.end(), permutation.begin());
// copy columns and values to temporary buffers
cusp::array1d<IndexType,MemorySpace> temp1(columns);
cusp::array1d<ValueType,MemorySpace> temp2(values);
// use permutation to reorder the values
thrust::gather(permutation.begin(), permutation.end(),
thrust::make_zip_iterator(thrust::make_tuple(temp1.begin(), temp2.begin())),
thrust::make_zip_iterator(thrust::make_tuple(columns.begin(), values.begin())));
}
template <typename Array1, typename Array2, typename Array3>
void sort_by_row_and_column(Array1& rows, Array2& columns, Array3& values)
{
CUSP_PROFILE_SCOPED();
typedef typename Array1::value_type IndexType;
typedef typename Array3::value_type ValueType;
typedef typename Array1::memory_space MemorySpace;
size_t N = rows.size();
cusp::array1d<IndexType,MemorySpace> permutation(N);
thrust::sequence(permutation.begin(), permutation.end());
// compute permutation and sort by (I,J)
{
cusp::array1d<IndexType,MemorySpace> temp(columns);
thrust::stable_sort_by_key(temp.begin(), temp.end(), permutation.begin());
cusp::copy(rows, temp);
thrust::gather(permutation.begin(), permutation.end(), temp.begin(), rows.begin());
thrust::stable_sort_by_key(rows.begin(), rows.end(), permutation.begin());
cusp::copy(columns, temp);
thrust::gather(permutation.begin(), permutation.end(), temp.begin(), columns.begin());
}
// use permutation to reorder the values
{
cusp::array1d<ValueType,MemorySpace> temp(values);
thrust::gather(permutation.begin(), permutation.end(), temp.begin(), values.begin());
}
}
} // end namespace detail
} // end namespace cusp
<commit_msg>Improved offsets_to_indices performance<commit_after>/*
* Copyright 2008-2009 NVIDIA Corporation
*
* 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 <cusp/copy.h>
#include <cusp/format.h>
#include <cusp/array1d.h>
#include <thrust/fill.h>
#include <thrust/extrema.h>
#include <thrust/binary_search.h>
#include <thrust/transform.h>
#include <thrust/gather.h>
#include <thrust/scatter.h>
#include <thrust/sequence.h>
#include <thrust/scan.h>
#include <thrust/sort.h>
namespace cusp
{
namespace detail
{
template <typename IndexType>
struct empty_row_functor
{
typedef bool result_type;
template <typename Tuple>
__host__ __device__
bool operator()(const Tuple& t) const
{
const IndexType a = thrust::get<0>(t);
const IndexType b = thrust::get<1>(t);
return a != b;
}
};
template <typename OffsetArray, typename IndexArray>
void offsets_to_indices(const OffsetArray& offsets, IndexArray& indices)
{
CUSP_PROFILE_SCOPED();
typedef typename OffsetArray::value_type OffsetType;
// convert compressed row offsets into uncompressed row indices
thrust::fill(indices.begin(), indices.end(), OffsetType(0));
thrust::scatter_if( thrust::counting_iterator<OffsetType>(0),
thrust::counting_iterator<OffsetType>(offsets.size()-1),
offsets.begin(),
thrust::make_transform_iterator(
thrust::make_zip_iterator( thrust::make_tuple( offsets.begin(), offsets.begin()+1 ) ),
empty_row_functor<OffsetType>()),
indices.begin());
thrust::inclusive_scan(indices.begin(), indices.end(), indices.begin(), thrust::maximum<OffsetType>());
}
template <typename IndexArray, typename OffsetArray>
void indices_to_offsets(const IndexArray& indices, OffsetArray& offsets)
{
CUSP_PROFILE_SCOPED();
typedef typename OffsetArray::value_type OffsetType;
// convert uncompressed row indices into compressed row offsets
thrust::lower_bound(indices.begin(),
indices.end(),
thrust::counting_iterator<OffsetType>(0),
thrust::counting_iterator<OffsetType>(offsets.size()),
offsets.begin());
}
template<typename T, typename IndexType>
struct row_operator : public std::unary_function<T,IndexType>
{
row_operator(int a_step)
: step(a_step)
{}
__host__ __device__
IndexType operator()(const T &value) const
{
return value % step;
}
private:
int step; // TODO replace with IndexType
};
// TODO fuse transform and scatter_if together
template <typename Matrix, typename Array>
void extract_diagonal(const Matrix& A, Array& output, cusp::coo_format)
{
CUSP_PROFILE_SCOPED();
typedef typename Matrix::index_type IndexType;
typedef typename Array::value_type ValueType;
typedef typename Array::memory_space MemorySpace; // TODO remove
// initialize output to zero
thrust::fill(output.begin(), output.end(), ValueType(0));
// determine which matrix entries correspond to the matrix diagonal
cusp::array1d<unsigned int,MemorySpace> is_diagonal(A.num_entries);
thrust::transform(A.row_indices.begin(), A.row_indices.end(), A.column_indices.begin(), is_diagonal.begin(), thrust::equal_to<IndexType>());
// scatter the diagonal values to output
thrust::scatter_if(A.values.begin(), A.values.end(),
A.row_indices.begin(),
is_diagonal.begin(),
output.begin());
}
template <typename Matrix, typename Array>
void extract_diagonal(const Matrix& A, Array& output, cusp::csr_format)
{
typedef typename Matrix::index_type IndexType;
typedef typename Array::value_type ValueType;
typedef typename Array::memory_space MemorySpace; // TODO remove
// initialize output to zero
thrust::fill(output.begin(), output.end(), ValueType(0));
// first expand the compressed row offsets into row indices
cusp::array1d<IndexType,MemorySpace> row_indices(A.num_entries);
offsets_to_indices(A.row_offsets, row_indices);
// determine which matrix entries correspond to the matrix diagonal
cusp::array1d<unsigned int,MemorySpace> is_diagonal(A.num_entries);
thrust::transform(row_indices.begin(), row_indices.end(), A.column_indices.begin(), is_diagonal.begin(), thrust::equal_to<IndexType>());
// scatter the diagonal values to output
thrust::scatter_if(A.values.begin(), A.values.end(),
row_indices.begin(),
is_diagonal.begin(),
output.begin());
}
template <typename Matrix, typename Array>
void extract_diagonal(const Matrix& A, Array& output, cusp::dia_format)
{
typedef typename Matrix::index_type IndexType;
typedef typename Array::value_type ValueType;
typedef typename Array::memory_space MemorySpace; // TODO remove
// copy diagonal_offsets to host (sometimes unnecessary)
cusp::array1d<IndexType,cusp::host_memory> diagonal_offsets(A.diagonal_offsets);
for(size_t i = 0; i < diagonal_offsets.size(); i++)
{
if(diagonal_offsets[i] == 0)
{
// diagonal found, copy to output and return
thrust::copy(A.values.values.begin() + A.values.pitch * i,
A.values.values.begin() + A.values.pitch * i + output.size(),
output.begin());
return;
}
}
// no diagonal found
thrust::fill(output.begin(), output.end(), ValueType(0));
}
template <typename Matrix, typename Array>
void extract_diagonal(const Matrix& A, Array& output, cusp::ell_format)
{
typedef typename Matrix::index_type IndexType;
typedef typename Array::value_type ValueType;
typedef typename Array::memory_space MemorySpace; // TODO remove
// initialize output to zero
thrust::fill(output.begin(), output.end(), ValueType(0));
// TODO completely ignore padded values either by remapping indices or zipping w/ predicate
// TODO fuse everything into the scatter_if
// compute ELL row indices
cusp::array1d<IndexType,MemorySpace> row_indices(A.column_indices.values.size());
thrust::transform(thrust::counting_iterator<int>(0), thrust::counting_iterator<int>(A.column_indices.values.size()),
row_indices.begin(), row_operator<int,IndexType>(A.column_indices.pitch));
// determine which matrix entries correspond to the matrix diagonal
cusp::array1d<unsigned int,MemorySpace> is_diagonal(A.column_indices.values.size());
thrust::transform(row_indices.begin(), row_indices.end(), A.column_indices.values.begin(), is_diagonal.begin(), thrust::equal_to<IndexType>());
// scatter the diagonal values to output
thrust::scatter_if(A.values.values.begin(), A.values.values.end(),
row_indices.begin(),
is_diagonal.begin(),
output.begin());
}
template <typename Matrix, typename Array>
void extract_diagonal(const Matrix& A, Array& output, cusp::hyb_format)
{
typedef typename Matrix::index_type IndexType;
typedef typename Array::value_type ValueType;
typedef typename Array::memory_space MemorySpace; // TODO remove
// initialize output to zero
thrust::fill(output.begin(), output.end(), ValueType(0));
// extract COO diagonal
{
// TODO fuse into single operation
// determine which matrix entries correspond to the matrix diagonal
cusp::array1d<unsigned int,MemorySpace> is_diagonal(A.coo.num_entries);
thrust::transform(A.coo.row_indices.begin(), A.coo.row_indices.end(),
A.coo.column_indices.begin(),
is_diagonal.begin(),
thrust::equal_to<IndexType>());
// scatter the diagonal values to output
thrust::scatter_if(A.coo.values.begin(), A.coo.values.end(),
A.coo.row_indices.begin(),
is_diagonal.begin(),
output.begin());
}
// extract ELL diagonal
{
// TODO fuse into single operation
// compute ELL row indices
cusp::array1d<IndexType,MemorySpace> row_indices(A.ell.column_indices.values.size());
thrust::transform(thrust::counting_iterator<int>(0), thrust::counting_iterator<int>(A.ell.column_indices.values.size()),
row_indices.begin(),
row_operator<int,IndexType>(A.ell.column_indices.num_rows));
// determine which matrix entries correspond to the matrix diagonal
cusp::array1d<unsigned int,MemorySpace> is_diagonal(A.ell.column_indices.values.size());
thrust::transform(row_indices.begin(), row_indices.end(),
A.ell.column_indices.values.begin(),
is_diagonal.begin(),
thrust::equal_to<IndexType>());
// scatter the diagonal values to output
thrust::scatter_if(A.ell.values.values.begin(), A.ell.values.values.end(),
row_indices.begin(),
is_diagonal.begin(),
output.begin());
}
}
template <typename Matrix, typename Array>
void extract_diagonal(const Matrix& A, Array& output)
{
CUSP_PROFILE_SCOPED();
output.resize(thrust::min(A.num_rows, A.num_cols));
// dispatch on matrix format
extract_diagonal(A, output, typename Matrix::format());
}
template <typename Array1, typename Array2, typename Array3>
void sort_by_row(Array1& rows, Array2& columns, Array3& values)
{
CUSP_PROFILE_SCOPED();
typedef typename Array1::value_type IndexType;
typedef typename Array3::value_type ValueType;
typedef typename Array1::memory_space MemorySpace;
size_t N = rows.size();
cusp::array1d<IndexType,MemorySpace> permutation(N);
thrust::sequence(permutation.begin(), permutation.end());
// compute permutation that sorts the rows
thrust::sort_by_key(rows.begin(), rows.end(), permutation.begin());
// copy columns and values to temporary buffers
cusp::array1d<IndexType,MemorySpace> temp1(columns);
cusp::array1d<ValueType,MemorySpace> temp2(values);
// use permutation to reorder the values
thrust::gather(permutation.begin(), permutation.end(),
thrust::make_zip_iterator(thrust::make_tuple(temp1.begin(), temp2.begin())),
thrust::make_zip_iterator(thrust::make_tuple(columns.begin(), values.begin())));
}
template <typename Array1, typename Array2, typename Array3>
void sort_by_row_and_column(Array1& rows, Array2& columns, Array3& values)
{
CUSP_PROFILE_SCOPED();
typedef typename Array1::value_type IndexType;
typedef typename Array3::value_type ValueType;
typedef typename Array1::memory_space MemorySpace;
size_t N = rows.size();
cusp::array1d<IndexType,MemorySpace> permutation(N);
thrust::sequence(permutation.begin(), permutation.end());
// compute permutation and sort by (I,J)
{
cusp::array1d<IndexType,MemorySpace> temp(columns);
thrust::stable_sort_by_key(temp.begin(), temp.end(), permutation.begin());
cusp::copy(rows, temp);
thrust::gather(permutation.begin(), permutation.end(), temp.begin(), rows.begin());
thrust::stable_sort_by_key(rows.begin(), rows.end(), permutation.begin());
cusp::copy(columns, temp);
thrust::gather(permutation.begin(), permutation.end(), temp.begin(), columns.begin());
}
// use permutation to reorder the values
{
cusp::array1d<ValueType,MemorySpace> temp(values);
thrust::gather(permutation.begin(), permutation.end(), temp.begin(), values.begin());
}
}
} // end namespace detail
} // end namespace cusp
<|endoftext|> |
<commit_before>// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "vm/heap/freelist.h"
#include "platform/assert.h"
#include "vm/unit_test.h"
namespace dart {
static uword Allocate(FreeList* free_list, intptr_t size, bool is_protected) {
uword result = free_list->TryAllocate(size, is_protected);
if ((result != 0u) && is_protected) {
VirtualMemory::Protect(reinterpret_cast<void*>(result), size,
VirtualMemory::kReadExecute);
}
return result;
}
static void Free(FreeList* free_list,
uword address,
intptr_t size,
bool is_protected) {
if (is_protected) {
VirtualMemory::Protect(reinterpret_cast<void*>(address), size,
VirtualMemory::kReadWrite);
}
free_list->Free(address, size);
if (is_protected) {
VirtualMemory::Protect(reinterpret_cast<void*>(address), size,
VirtualMemory::kReadExecute);
}
}
static void TestFreeList(VirtualMemory* region,
FreeList* free_list,
bool is_protected) {
const intptr_t kSmallObjectSize = 4 * kWordSize;
const intptr_t kMediumObjectSize = 16 * kWordSize;
const intptr_t kLargeObjectSize = 8 * KB;
uword blob = region->start();
// Enqueue the large blob as one free block.
free_list->Free(blob, region->size());
if (is_protected) {
// Write protect the whole region.
region->Protect(VirtualMemory::kReadExecute);
}
// Allocate a small object. Expect it to be positioned as the first element.
uword small_object = Allocate(free_list, kSmallObjectSize, is_protected);
EXPECT_EQ(blob, small_object);
// Freeing and allocating should give us the same memory back.
Free(free_list, small_object, kSmallObjectSize, is_protected);
small_object = Allocate(free_list, kSmallObjectSize, is_protected);
EXPECT_EQ(blob, small_object);
// Splitting the remainder further with small and medium objects.
uword small_object2 = Allocate(free_list, kSmallObjectSize, is_protected);
EXPECT_EQ(blob + kSmallObjectSize, small_object2);
uword med_object = Allocate(free_list, kMediumObjectSize, is_protected);
EXPECT_EQ(small_object2 + kSmallObjectSize, med_object);
// Allocate a large object.
uword large_object = Allocate(free_list, kLargeObjectSize, is_protected);
EXPECT_EQ(med_object + kMediumObjectSize, large_object);
// Make sure that small objects can still split the remainder.
uword small_object3 = Allocate(free_list, kSmallObjectSize, is_protected);
EXPECT_EQ(large_object + kLargeObjectSize, small_object3);
// Split the large object.
Free(free_list, large_object, kLargeObjectSize, is_protected);
uword small_object4 = Allocate(free_list, kSmallObjectSize, is_protected);
EXPECT_EQ(large_object, small_object4);
// Get the full remainder of the large object.
large_object =
Allocate(free_list, kLargeObjectSize - kSmallObjectSize, is_protected);
EXPECT_EQ(small_object4 + kSmallObjectSize, large_object);
// Get another large object from the large unallocated remainder.
uword large_object2 = Allocate(free_list, kLargeObjectSize, is_protected);
EXPECT_EQ(small_object3 + kSmallObjectSize, large_object2);
}
TEST_CASE(FreeList) {
FreeList* free_list = new FreeList();
const intptr_t kBlobSize = 1 * MB;
VirtualMemory* region =
VirtualMemory::Allocate(kBlobSize, /* is_executable */ false, NULL);
TestFreeList(region, free_list, false);
// Delete the memory associated with the test.
delete region;
delete free_list;
}
TEST_CASE(FreeListProtected) {
FreeList* free_list = new FreeList();
const intptr_t kBlobSize = 1 * MB;
VirtualMemory* region =
VirtualMemory::Allocate(kBlobSize, /* is_executable */ false, NULL);
TestFreeList(region, free_list, true);
// Delete the memory associated with the test.
delete region;
delete free_list;
}
TEST_CASE(FreeListProtectedTinyObjects) {
FreeList* free_list = new FreeList();
const intptr_t kBlobSize = 1 * MB;
const intptr_t kObjectSize = 2 * kWordSize;
uword* objects = new uword[kBlobSize / kObjectSize];
VirtualMemory* blob =
VirtualMemory::Allocate(kBlobSize, /* is_executable = */ false, NULL);
ASSERT(Utils::IsAligned(blob->start(), 4096));
blob->Protect(VirtualMemory::kReadWrite);
// Enqueue the large blob as one free block.
free_list->Free(blob->start(), blob->size());
// Write protect the whole region.
blob->Protect(VirtualMemory::kReadExecute);
// Allocate small objects.
for (intptr_t i = 0; i < blob->size() / kObjectSize; i++) {
objects[i] = Allocate(free_list, kObjectSize, true); // is_protected
}
// All space is occupied. Expect failed allocation.
ASSERT(Allocate(free_list, kObjectSize, true) == 0);
// Free all objects again. Make the whole region writable for this.
blob->Protect(VirtualMemory::kReadWrite);
for (intptr_t i = 0; i < blob->size() / kObjectSize; i++) {
free_list->Free(objects[i], kObjectSize);
}
// Delete the memory associated with the test.
delete blob;
delete free_list;
delete[] objects;
}
TEST_CASE(FreeListProtectedVariableSizeObjects) {
FreeList* free_list = new FreeList();
const intptr_t kBlobSize = 8 * KB;
const intptr_t kMinSize = 2 * kWordSize;
uword* objects = new uword[kBlobSize / kMinSize];
for (intptr_t i = 0; i < kBlobSize / kMinSize; ++i) {
objects[i] = static_cast<uword>(NULL);
}
VirtualMemory* blob =
VirtualMemory::Allocate(kBlobSize, /* is_executable = */ false, NULL);
ASSERT(Utils::IsAligned(blob->start(), 4096));
blob->Protect(VirtualMemory::kReadWrite);
// Enqueue the large blob as one free block.
free_list->Free(blob->start(), blob->size());
// Write protect the whole region.
blob->Protect(VirtualMemory::kReadExecute);
// Allocate and free objects so that free list has > 1 elements.
uword e0 = Allocate(free_list, 1 * KB, true);
ASSERT(e0);
uword e1 = Allocate(free_list, 3 * KB, true);
ASSERT(e1);
uword e2 = Allocate(free_list, 2 * KB, true);
ASSERT(e2);
uword e3 = Allocate(free_list, 2 * KB, true);
ASSERT(e3);
Free(free_list, e1, 3 * KB, true);
Free(free_list, e2, 2 * KB, true);
e0 = Allocate(free_list, 3 * KB - 2 * kWordSize, true);
ASSERT(e0);
// Delete the memory associated with the test.
delete blob;
delete free_list;
delete[] objects;
}
} // namespace dart
<commit_msg>[vm] Regression test for free-list protection.<commit_after>// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include <memory>
#include "platform/assert.h"
#include "vm/heap/freelist.h"
#include "vm/pointer_tagging.h"
#include "vm/unit_test.h"
namespace dart {
static uword Allocate(FreeList* free_list, intptr_t size, bool is_protected) {
uword result = free_list->TryAllocate(size, is_protected);
if ((result != 0u) && is_protected) {
VirtualMemory::Protect(reinterpret_cast<void*>(result), size,
VirtualMemory::kReadExecute);
}
return result;
}
static void Free(FreeList* free_list,
uword address,
intptr_t size,
bool is_protected) {
if (is_protected) {
VirtualMemory::Protect(reinterpret_cast<void*>(address), size,
VirtualMemory::kReadWrite);
}
free_list->Free(address, size);
if (is_protected) {
VirtualMemory::Protect(reinterpret_cast<void*>(address), size,
VirtualMemory::kReadExecute);
}
}
static void TestFreeList(VirtualMemory* region,
FreeList* free_list,
bool is_protected) {
const intptr_t kSmallObjectSize = 4 * kWordSize;
const intptr_t kMediumObjectSize = 16 * kWordSize;
const intptr_t kLargeObjectSize = 8 * KB;
uword blob = region->start();
// Enqueue the large blob as one free block.
free_list->Free(blob, region->size());
if (is_protected) {
// Write protect the whole region.
region->Protect(VirtualMemory::kReadExecute);
}
// Allocate a small object. Expect it to be positioned as the first element.
uword small_object = Allocate(free_list, kSmallObjectSize, is_protected);
EXPECT_EQ(blob, small_object);
// Freeing and allocating should give us the same memory back.
Free(free_list, small_object, kSmallObjectSize, is_protected);
small_object = Allocate(free_list, kSmallObjectSize, is_protected);
EXPECT_EQ(blob, small_object);
// Splitting the remainder further with small and medium objects.
uword small_object2 = Allocate(free_list, kSmallObjectSize, is_protected);
EXPECT_EQ(blob + kSmallObjectSize, small_object2);
uword med_object = Allocate(free_list, kMediumObjectSize, is_protected);
EXPECT_EQ(small_object2 + kSmallObjectSize, med_object);
// Allocate a large object.
uword large_object = Allocate(free_list, kLargeObjectSize, is_protected);
EXPECT_EQ(med_object + kMediumObjectSize, large_object);
// Make sure that small objects can still split the remainder.
uword small_object3 = Allocate(free_list, kSmallObjectSize, is_protected);
EXPECT_EQ(large_object + kLargeObjectSize, small_object3);
// Split the large object.
Free(free_list, large_object, kLargeObjectSize, is_protected);
uword small_object4 = Allocate(free_list, kSmallObjectSize, is_protected);
EXPECT_EQ(large_object, small_object4);
// Get the full remainder of the large object.
large_object =
Allocate(free_list, kLargeObjectSize - kSmallObjectSize, is_protected);
EXPECT_EQ(small_object4 + kSmallObjectSize, large_object);
// Get another large object from the large unallocated remainder.
uword large_object2 = Allocate(free_list, kLargeObjectSize, is_protected);
EXPECT_EQ(small_object3 + kSmallObjectSize, large_object2);
}
TEST_CASE(FreeList) {
FreeList* free_list = new FreeList();
const intptr_t kBlobSize = 1 * MB;
VirtualMemory* region =
VirtualMemory::Allocate(kBlobSize, /* is_executable */ false, NULL);
TestFreeList(region, free_list, false);
// Delete the memory associated with the test.
delete region;
delete free_list;
}
TEST_CASE(FreeListProtected) {
FreeList* free_list = new FreeList();
const intptr_t kBlobSize = 1 * MB;
VirtualMemory* region =
VirtualMemory::Allocate(kBlobSize, /* is_executable */ false, NULL);
TestFreeList(region, free_list, true);
// Delete the memory associated with the test.
delete region;
delete free_list;
}
TEST_CASE(FreeListProtectedTinyObjects) {
FreeList* free_list = new FreeList();
const intptr_t kBlobSize = 1 * MB;
const intptr_t kObjectSize = 2 * kWordSize;
uword* objects = new uword[kBlobSize / kObjectSize];
VirtualMemory* blob =
VirtualMemory::Allocate(kBlobSize, /* is_executable = */ false, NULL);
ASSERT(Utils::IsAligned(blob->start(), 4096));
blob->Protect(VirtualMemory::kReadWrite);
// Enqueue the large blob as one free block.
free_list->Free(blob->start(), blob->size());
// Write protect the whole region.
blob->Protect(VirtualMemory::kReadExecute);
// Allocate small objects.
for (intptr_t i = 0; i < blob->size() / kObjectSize; i++) {
objects[i] = Allocate(free_list, kObjectSize, true); // is_protected
}
// All space is occupied. Expect failed allocation.
ASSERT(Allocate(free_list, kObjectSize, true) == 0);
// Free all objects again. Make the whole region writable for this.
blob->Protect(VirtualMemory::kReadWrite);
for (intptr_t i = 0; i < blob->size() / kObjectSize; i++) {
free_list->Free(objects[i], kObjectSize);
}
// Delete the memory associated with the test.
delete blob;
delete free_list;
delete[] objects;
}
TEST_CASE(FreeListProtectedVariableSizeObjects) {
FreeList* free_list = new FreeList();
const intptr_t kBlobSize = 8 * KB;
const intptr_t kMinSize = 2 * kWordSize;
uword* objects = new uword[kBlobSize / kMinSize];
for (intptr_t i = 0; i < kBlobSize / kMinSize; ++i) {
objects[i] = static_cast<uword>(NULL);
}
VirtualMemory* blob =
VirtualMemory::Allocate(kBlobSize, /* is_executable = */ false, NULL);
ASSERT(Utils::IsAligned(blob->start(), 4096));
blob->Protect(VirtualMemory::kReadWrite);
// Enqueue the large blob as one free block.
free_list->Free(blob->start(), blob->size());
// Write protect the whole region.
blob->Protect(VirtualMemory::kReadExecute);
// Allocate and free objects so that free list has > 1 elements.
uword e0 = Allocate(free_list, 1 * KB, true);
ASSERT(e0);
uword e1 = Allocate(free_list, 3 * KB, true);
ASSERT(e1);
uword e2 = Allocate(free_list, 2 * KB, true);
ASSERT(e2);
uword e3 = Allocate(free_list, 2 * KB, true);
ASSERT(e3);
Free(free_list, e1, 3 * KB, true);
Free(free_list, e2, 2 * KB, true);
e0 = Allocate(free_list, 3 * KB - 2 * kWordSize, true);
ASSERT(e0);
// Delete the memory associated with the test.
delete blob;
delete free_list;
delete[] objects;
}
static void TestRegress38528(intptr_t header_overlap) {
// Test the following scenario.
//
// | <------------ free list element -----------------> |
// | <allocated code> | <header> | <remainder - header> | <other code> |
// ^
// page boundary around here, depending on header_overlap
//
// It is important that after the allocation has been re-protected, the
// "<other code>" region is also still executable (and not writable).
std::unique_ptr<FreeList> free_list(new FreeList());
const uword page = VirtualMemory::PageSize();
std::unique_ptr<VirtualMemory> blob(
VirtualMemory::Allocate(2 * page,
/*is_executable=*/false, NULL));
const intptr_t remainder_size = page / 2;
const intptr_t alloc_size = page - header_overlap * kObjectAlignment;
void* const other_code =
reinterpret_cast<void*>(blob->start() + alloc_size + remainder_size);
// Load a simple function into the "other code" section which just returns.
// This is used to ensure that it's still executable.
#if defined(HOST_ARCH_X64) || defined(HOST_ARCH_IA32)
const uint8_t ret[1] = {0xC3}; // ret
#elif defined(HOST_ARCH_ARM)
const uint8_t ret[4] = {0x1e, 0xff, 0x2f, 0xe1}; // bx lr
#elif defined(HOST_ARCH_ARM64)
const uint8_t ret[4] = {0xc0, 0x03, 0x5f, 0xd6}; // ret
#else
#error "Unknown architecture."
#endif
memcpy(other_code, ret, sizeof(ret)); // NOLINT
free_list->Free(blob->start(), alloc_size + remainder_size);
blob->Protect(VirtualMemory::kReadExecute); // not writable
Allocate(free_list.get(), alloc_size, /*protected=*/true);
VirtualMemory::Protect(blob->address(), alloc_size,
VirtualMemory::kReadExecute);
reinterpret_cast<void (*)()>(other_code)();
}
TEST_CASE(Regress38528) {
for (const intptr_t i : {-2, -1, 0, 1, 2}) {
TestRegress38528(i);
}
}
} // namespace dart
<|endoftext|> |
<commit_before>// Copyright (c) 2009-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <core_io.h>
#include <consensus/consensus.h>
#include <consensus/validation.h>
#include <key_io.h>
#include <script/script.h>
#include <script/standard.h>
#include <serialize.h>
#include <streams.h>
#include <univalue.h>
#include <util/system.h>
#include <util/strencodings.h>
UniValue ValueFromAmount(const CAmount& amount)
{
bool sign = amount < 0;
int64_t n_abs = (sign ? -amount : amount);
int64_t quotient = n_abs / COIN;
int64_t remainder = n_abs % COIN;
return UniValue(UniValue::VNUM,
strprintf("%s%d.%08d", sign ? "-" : "", quotient, remainder));
}
std::string FormatScript(const CScript& script)
{
std::string ret;
CScript::const_iterator it = script.begin();
opcodetype op;
while (it != script.end()) {
CScript::const_iterator it2 = it;
std::vector<unsigned char> vch;
if (script.GetOp(it, op, vch)) {
if (op == OP_0) {
ret += "0 ";
continue;
} else if ((op >= OP_1 && op <= OP_16) || op == OP_1NEGATE) {
ret += strprintf("%i ", op - OP_1NEGATE - 1);
continue;
} else if (op >= OP_NOP && op <= OP_NOP10) {
std::string str(GetOpName(op));
if (str.substr(0, 3) == std::string("OP_")) {
ret += str.substr(3, std::string::npos) + " ";
continue;
}
}
if (vch.size() > 0) {
ret += strprintf("0x%x 0x%x ", HexStr(std::vector<uint8_t>(it2, it - vch.size())),
HexStr(std::vector<uint8_t>(it - vch.size(), it)));
} else {
ret += strprintf("0x%x ", HexStr(std::vector<uint8_t>(it2, it)));
}
continue;
}
ret += strprintf("0x%x ", HexStr(std::vector<uint8_t>(it2, script.end())));
break;
}
return ret.substr(0, ret.size() - 1);
}
const std::map<unsigned char, std::string> mapSigHashTypes = {
{static_cast<unsigned char>(SIGHASH_ALL), std::string("ALL")},
{static_cast<unsigned char>(SIGHASH_ALL|SIGHASH_ANYONECANPAY), std::string("ALL|ANYONECANPAY")},
{static_cast<unsigned char>(SIGHASH_NONE), std::string("NONE")},
{static_cast<unsigned char>(SIGHASH_NONE|SIGHASH_ANYONECANPAY), std::string("NONE|ANYONECANPAY")},
{static_cast<unsigned char>(SIGHASH_SINGLE), std::string("SINGLE")},
{static_cast<unsigned char>(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY), std::string("SINGLE|ANYONECANPAY")},
};
std::string SighashToStr(unsigned char sighash_type)
{
const auto& it = mapSigHashTypes.find(sighash_type);
if (it == mapSigHashTypes.end()) return "";
return it->second;
}
/**
* Create the assembly string representation of a CScript object.
* @param[in] script CScript object to convert into the asm string representation.
* @param[in] fAttemptSighashDecode Whether to attempt to decode sighash types on data within the script that matches the format
* of a signature. Only pass true for scripts you believe could contain signatures. For example,
* pass false, or omit the this argument (defaults to false), for scriptPubKeys.
*/
std::string ScriptToAsmStr(const CScript& script, const bool fAttemptSighashDecode)
{
std::string str;
opcodetype opcode;
std::vector<unsigned char> vch;
CScript::const_iterator pc = script.begin();
while (pc < script.end()) {
if (!str.empty()) {
str += " ";
}
if (!script.GetOp(pc, opcode, vch)) {
str += "[error]";
return str;
}
if (0 <= opcode && opcode <= OP_PUSHDATA4) {
if (vch.size() <= static_cast<std::vector<unsigned char>::size_type>(4)) {
str += strprintf("%d", CScriptNum(vch, false).getint());
} else {
// the IsUnspendable check makes sure not to try to decode OP_RETURN data that may match the format of a signature
if (fAttemptSighashDecode && !script.IsUnspendable()) {
std::string strSigHashDecode;
// goal: only attempt to decode a defined sighash type from data that looks like a signature within a scriptSig.
// this won't decode correctly formatted public keys in Pubkey or Multisig scripts due to
// the restrictions on the pubkey formats (see IsCompressedOrUncompressedPubKey) being incongruous with the
// checks in CheckSignatureEncoding.
if (CheckSignatureEncoding(vch, SCRIPT_VERIFY_STRICTENC, nullptr)) {
const unsigned char chSigHashType = vch.back();
const auto it = mapSigHashTypes.find(chSigHashType);
if (it != mapSigHashTypes.end()) {
strSigHashDecode = "[" + it->second + "]";
vch.pop_back(); // remove the sighash type byte. it will be replaced by the decode.
}
}
str += HexStr(vch) + strSigHashDecode;
} else {
str += HexStr(vch);
}
}
} else {
str += GetOpName(opcode);
}
}
return str;
}
std::string EncodeHexTx(const CTransaction& tx, const int serializeFlags)
{
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION | serializeFlags);
ssTx << tx;
return HexStr(ssTx);
}
void ScriptToUniv(const CScript& script, UniValue& out, bool include_address)
{
out.pushKV("asm", ScriptToAsmStr(script));
out.pushKV("hex", HexStr(script));
std::vector<std::vector<unsigned char>> solns;
TxoutType type = Solver(script, solns);
out.pushKV("type", GetTxnOutputType(type));
CTxDestination address;
if (include_address && ExtractDestination(script, address) && type != TxoutType::PUBKEY) {
out.pushKV("address", EncodeDestination(address));
}
}
void ScriptPubKeyToUniv(const CScript& scriptPubKey,
UniValue& out, bool fIncludeHex)
{
TxoutType type;
std::vector<CTxDestination> addresses;
int nRequired;
out.pushKV("asm", ScriptToAsmStr(scriptPubKey));
if (fIncludeHex)
out.pushKV("hex", HexStr(scriptPubKey));
if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired) || type == TxoutType::PUBKEY) {
out.pushKV("type", GetTxnOutputType(type));
return;
}
out.pushKV("reqSigs", nRequired);
out.pushKV("type", GetTxnOutputType(type));
UniValue a(UniValue::VARR);
for (const CTxDestination& addr : addresses) {
a.push_back(EncodeDestination(addr));
}
out.pushKV("addresses", a);
}
void TxToUniv(const CTransaction& tx, const uint256& hashBlock, UniValue& entry, bool include_hex, int serialize_flags)
{
entry.pushKV("txid", tx.GetHash().GetHex());
entry.pushKV("hash", tx.GetWitnessHash().GetHex());
// Transaction version is actually unsigned in consensus checks, just signed in memory,
// so cast to unsigned before giving it to the user.
entry.pushKV("version", static_cast<int64_t>(static_cast<uint32_t>(tx.nVersion)));
entry.pushKV("size", (int)::GetSerializeSize(tx, PROTOCOL_VERSION));
entry.pushKV("vsize", (GetTransactionWeight(tx) + WITNESS_SCALE_FACTOR - 1) / WITNESS_SCALE_FACTOR);
entry.pushKV("weight", GetTransactionWeight(tx));
entry.pushKV("locktime", (int64_t)tx.nLockTime);
UniValue vin(UniValue::VARR);
for (unsigned int i = 0; i < tx.vin.size(); i++) {
const CTxIn& txin = tx.vin[i];
UniValue in(UniValue::VOBJ);
if (tx.IsCoinBase())
in.pushKV("coinbase", HexStr(txin.scriptSig));
else {
in.pushKV("txid", txin.prevout.hash.GetHex());
in.pushKV("vout", (int64_t)txin.prevout.n);
UniValue o(UniValue::VOBJ);
o.pushKV("asm", ScriptToAsmStr(txin.scriptSig, true));
o.pushKV("hex", HexStr(txin.scriptSig));
in.pushKV("scriptSig", o);
}
if (!tx.vin[i].scriptWitness.IsNull()) {
UniValue txinwitness(UniValue::VARR);
for (const auto& item : tx.vin[i].scriptWitness.stack) {
txinwitness.push_back(HexStr(item));
}
in.pushKV("txinwitness", txinwitness);
}
in.pushKV("sequence", (int64_t)txin.nSequence);
vin.push_back(in);
}
entry.pushKV("vin", vin);
UniValue vout(UniValue::VARR);
for (unsigned int i = 0; i < tx.vout.size(); i++) {
const CTxOut& txout = tx.vout[i];
UniValue out(UniValue::VOBJ);
out.pushKV("value", ValueFromAmount(txout.nValue));
out.pushKV("n", (int64_t)i);
UniValue o(UniValue::VOBJ);
ScriptPubKeyToUniv(txout.scriptPubKey, o, true);
out.pushKV("scriptPubKey", o);
vout.push_back(out);
}
entry.pushKV("vout", vout);
if (!hashBlock.IsNull())
entry.pushKV("blockhash", hashBlock.GetHex());
if (include_hex) {
entry.pushKV("hex", EncodeHexTx(tx, serialize_flags)); // The hex-encoded transaction. Used the name "hex" to be consistent with the verbose output of "getrawtransaction".
}
}
<commit_msg>MWEB: TxToUniv updates<commit_after>// Copyright (c) 2009-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <core_io.h>
#include <consensus/consensus.h>
#include <consensus/validation.h>
#include <key_io.h>
#include <script/script.h>
#include <script/standard.h>
#include <serialize.h>
#include <streams.h>
#include <univalue.h>
#include <util/system.h>
#include <util/strencodings.h>
UniValue ValueFromAmount(const CAmount& amount)
{
bool sign = amount < 0;
int64_t n_abs = (sign ? -amount : amount);
int64_t quotient = n_abs / COIN;
int64_t remainder = n_abs % COIN;
return UniValue(UniValue::VNUM,
strprintf("%s%d.%08d", sign ? "-" : "", quotient, remainder));
}
std::string FormatScript(const CScript& script)
{
std::string ret;
CScript::const_iterator it = script.begin();
opcodetype op;
while (it != script.end()) {
CScript::const_iterator it2 = it;
std::vector<unsigned char> vch;
if (script.GetOp(it, op, vch)) {
if (op == OP_0) {
ret += "0 ";
continue;
} else if ((op >= OP_1 && op <= OP_16) || op == OP_1NEGATE) {
ret += strprintf("%i ", op - OP_1NEGATE - 1);
continue;
} else if (op >= OP_NOP && op <= OP_NOP10) {
std::string str(GetOpName(op));
if (str.substr(0, 3) == std::string("OP_")) {
ret += str.substr(3, std::string::npos) + " ";
continue;
}
}
if (vch.size() > 0) {
ret += strprintf("0x%x 0x%x ", HexStr(std::vector<uint8_t>(it2, it - vch.size())),
HexStr(std::vector<uint8_t>(it - vch.size(), it)));
} else {
ret += strprintf("0x%x ", HexStr(std::vector<uint8_t>(it2, it)));
}
continue;
}
ret += strprintf("0x%x ", HexStr(std::vector<uint8_t>(it2, script.end())));
break;
}
return ret.substr(0, ret.size() - 1);
}
const std::map<unsigned char, std::string> mapSigHashTypes = {
{static_cast<unsigned char>(SIGHASH_ALL), std::string("ALL")},
{static_cast<unsigned char>(SIGHASH_ALL|SIGHASH_ANYONECANPAY), std::string("ALL|ANYONECANPAY")},
{static_cast<unsigned char>(SIGHASH_NONE), std::string("NONE")},
{static_cast<unsigned char>(SIGHASH_NONE|SIGHASH_ANYONECANPAY), std::string("NONE|ANYONECANPAY")},
{static_cast<unsigned char>(SIGHASH_SINGLE), std::string("SINGLE")},
{static_cast<unsigned char>(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY), std::string("SINGLE|ANYONECANPAY")},
};
std::string SighashToStr(unsigned char sighash_type)
{
const auto& it = mapSigHashTypes.find(sighash_type);
if (it == mapSigHashTypes.end()) return "";
return it->second;
}
/**
* Create the assembly string representation of a CScript object.
* @param[in] script CScript object to convert into the asm string representation.
* @param[in] fAttemptSighashDecode Whether to attempt to decode sighash types on data within the script that matches the format
* of a signature. Only pass true for scripts you believe could contain signatures. For example,
* pass false, or omit the this argument (defaults to false), for scriptPubKeys.
*/
std::string ScriptToAsmStr(const CScript& script, const bool fAttemptSighashDecode)
{
std::string str;
opcodetype opcode;
std::vector<unsigned char> vch;
CScript::const_iterator pc = script.begin();
while (pc < script.end()) {
if (!str.empty()) {
str += " ";
}
if (!script.GetOp(pc, opcode, vch)) {
str += "[error]";
return str;
}
if (0 <= opcode && opcode <= OP_PUSHDATA4) {
if (vch.size() <= static_cast<std::vector<unsigned char>::size_type>(4)) {
str += strprintf("%d", CScriptNum(vch, false).getint());
} else {
// the IsUnspendable check makes sure not to try to decode OP_RETURN data that may match the format of a signature
if (fAttemptSighashDecode && !script.IsUnspendable()) {
std::string strSigHashDecode;
// goal: only attempt to decode a defined sighash type from data that looks like a signature within a scriptSig.
// this won't decode correctly formatted public keys in Pubkey or Multisig scripts due to
// the restrictions on the pubkey formats (see IsCompressedOrUncompressedPubKey) being incongruous with the
// checks in CheckSignatureEncoding.
if (CheckSignatureEncoding(vch, SCRIPT_VERIFY_STRICTENC, nullptr)) {
const unsigned char chSigHashType = vch.back();
const auto it = mapSigHashTypes.find(chSigHashType);
if (it != mapSigHashTypes.end()) {
strSigHashDecode = "[" + it->second + "]";
vch.pop_back(); // remove the sighash type byte. it will be replaced by the decode.
}
}
str += HexStr(vch) + strSigHashDecode;
} else {
str += HexStr(vch);
}
}
} else {
str += GetOpName(opcode);
}
}
return str;
}
std::string EncodeHexTx(const CTransaction& tx, const int serializeFlags)
{
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION | serializeFlags);
ssTx << tx;
return HexStr(ssTx);
}
void ScriptToUniv(const CScript& script, UniValue& out, bool include_address)
{
out.pushKV("asm", ScriptToAsmStr(script));
out.pushKV("hex", HexStr(script));
std::vector<std::vector<unsigned char>> solns;
TxoutType type = Solver(script, solns);
out.pushKV("type", GetTxnOutputType(type));
CTxDestination address;
if (include_address && ExtractDestination(script, address) && type != TxoutType::PUBKEY) {
out.pushKV("address", EncodeDestination(address));
}
}
void ScriptPubKeyToUniv(const CScript& scriptPubKey,
UniValue& out, bool fIncludeHex)
{
TxoutType type;
std::vector<CTxDestination> addresses;
int nRequired;
out.pushKV("asm", ScriptToAsmStr(scriptPubKey));
if (fIncludeHex)
out.pushKV("hex", HexStr(scriptPubKey));
if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired) || type == TxoutType::PUBKEY) {
out.pushKV("type", GetTxnOutputType(type));
return;
}
out.pushKV("reqSigs", nRequired);
out.pushKV("type", GetTxnOutputType(type));
UniValue a(UniValue::VARR);
for (const CTxDestination& addr : addresses) {
a.push_back(EncodeDestination(addr));
}
out.pushKV("addresses", a);
}
void TxToUniv(const CTransaction& tx, const uint256& hashBlock, UniValue& entry, bool include_hex, int serialize_flags)
{
entry.pushKV("txid", tx.GetHash().GetHex());
entry.pushKV("hash", tx.GetWitnessHash().GetHex());
// Transaction version is actually unsigned in consensus checks, just signed in memory,
// so cast to unsigned before giving it to the user.
entry.pushKV("version", static_cast<int64_t>(static_cast<uint32_t>(tx.nVersion)));
entry.pushKV("size", (int)::GetSerializeSize(tx, PROTOCOL_VERSION));
entry.pushKV("vsize", (GetTransactionWeight(tx) + WITNESS_SCALE_FACTOR - 1) / WITNESS_SCALE_FACTOR);
entry.pushKV("weight", GetTransactionWeight(tx));
entry.pushKV("locktime", (int64_t)tx.nLockTime);
UniValue vin(UniValue::VARR);
for (const CTxInput& input : tx.GetInputs()) {
UniValue in(UniValue::VOBJ);
in.pushKV("ismweb", input.IsMWEB());
if (input.IsMWEB()) {
in.pushKV("output_id", input.ToMWEB().ToHex());
} else {
const CTxIn& txin = input.GetTxIn();
if (tx.IsCoinBase())
in.pushKV("coinbase", HexStr(txin.scriptSig));
else {
in.pushKV("txid", txin.prevout.hash.GetHex());
in.pushKV("vout", (int64_t)txin.prevout.n);
UniValue o(UniValue::VOBJ);
o.pushKV("asm", ScriptToAsmStr(txin.scriptSig, true));
o.pushKV("hex", HexStr(txin.scriptSig));
in.pushKV("scriptSig", o);
}
if (!txin.scriptWitness.IsNull()) {
UniValue txinwitness(UniValue::VARR);
for (const auto& item : txin.scriptWitness.stack) {
txinwitness.push_back(HexStr(item));
}
in.pushKV("txinwitness", txinwitness);
}
in.pushKV("sequence", (int64_t)txin.nSequence);
}
vin.push_back(in);
}
entry.pushKV("vin", vin);
UniValue vout(UniValue::VARR);
int64_t n = 0;
for (const CTxOutput& output : tx.GetOutputs()) {
UniValue out(UniValue::VOBJ);
out.pushKV("ismweb", output.IsMWEB());
if (output.IsMWEB()) {
out.pushKV("output_id", output.ToMWEB().ToHex());
} else {
const CTxOut& txout = output.GetTxOut();
out.pushKV("value", ValueFromAmount(txout.nValue));
out.pushKV("n", n++);
UniValue o(UniValue::VOBJ);
ScriptPubKeyToUniv(txout.scriptPubKey, o, true);
out.pushKV("scriptPubKey", o);
}
vout.push_back(out);
}
entry.pushKV("vout", vout);
if (tx.HasMWEBTx()) {
UniValue vkern(UniValue::VARR);
for (const Kernel& kernel : tx.mweb_tx.m_transaction->GetKernels()) {
UniValue kern(UniValue::VOBJ);
kern.pushKV("kernel_id", kernel.GetKernelID().ToHex());
kern.pushKV("fee", kernel.GetFee());
kern.pushKV("pegin", kernel.GetPegIn());
UniValue pegouts(UniValue::VARR);
for (const PegOutCoin& pegout : kernel.GetPegOuts()) {
UniValue uni_pegout(UniValue::VOBJ);
uni_pegout.pushKV("value", pegout.GetAmount());
UniValue p(UniValue::VOBJ);
ScriptPubKeyToUniv(pegout.GetScriptPubKey(), p, true);
uni_pegout.pushKV("scriptPubKey", p);
pegouts.push_back(uni_pegout);
}
kern.pushKV("pegout", pegouts);
vkern.push_back(kern);
}
entry.pushKV("vkern", vkern);
}
if (!hashBlock.IsNull())
entry.pushKV("blockhash", hashBlock.GetHex());
if (include_hex) {
entry.pushKV("hex", EncodeHexTx(tx, serialize_flags)); // The hex-encoded transaction. Used the name "hex" to be consistent with the verbose output of "getrawtransaction".
}
}
<|endoftext|> |
<commit_before><commit_msg>Gui: add warning to DlgExpressionInput<commit_after><|endoftext|> |
<commit_before>/*
Copyright (c) 2012-2014 The SSDB Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <vector>
#include "log.h"
#include "sorted_set.h"
int main(int argc, char **argv){
SortedSet zset;
std::vector<std::string> keys;
for(int i='a'; i<='z'; i++){
char buf[10];
snprintf(buf, sizeof(buf), "%c", i);
keys.push_back(buf);
}
log_debug("");
srand(time(NULL));
for(int i=0; i<1000 * 1000; i++){
std::string &key = keys[rand() % keys.size()];
zset.add(key, rand()%30 - 15);
}
log_debug("");
std::string *key;
int64_t score;
int n = 0;
while(zset.front(key, &score)){
printf("%s : %4lld\n", key->c_str(), score);
zset.pop_front();
n ++;
}
log_debug("%d", n);
return 0;
}
<commit_msg>patch for resolve complite error<commit_after>/*
Copyright (c) 2012-2014 The SSDB Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <vector>
#include "log.h"
#include "sorted_set.h"
int main(int argc, char **argv){
SortedSet zset;
std::vector<std::string> keys;
for(int i='a'; i<='z'; i++){
char buf[10];
snprintf(buf, sizeof(buf), "%c", i);
keys.push_back(buf);
}
log_debug("");
srand(time(NULL));
for(int i=0; i<1000 * 1000; i++){
std::string &key = keys[rand() % keys.size()];
zset.add(key, rand()%30 - 15);
}
log_debug("");
std::string key;
int64_t score;
int n = 0;
while(zset.front(&key, &score)){
printf("%s : %4lld\n", key.c_str(), score);
zset.pop_front();
n ++;
}
log_debug("%d", n);
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/sys_info.h"
#include <sys/system_properties.h>
#include "base/logging.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
#include "base/strings/stringprintf.h"
namespace {
// Default version of Android to fall back to when actual version numbers
// cannot be acquired. This is an obviously invalid version number. Code
// doing version comparison should treat it as so and fail all comparisons.
const int kDefaultAndroidMajorVersion = 0;
const int kDefaultAndroidMinorVersion = 0;
const int kDefaultAndroidBugfixVersion = 0;
// Parse out the OS version numbers from the system properties.
void ParseOSVersionNumbers(const char* os_version_str,
int32 *major_version,
int32 *minor_version,
int32 *bugfix_version) {
if (os_version_str[0]) {
// Try to parse out the version numbers from the string.
int num_read = sscanf(os_version_str, "%d.%d.%d", major_version,
minor_version, bugfix_version);
if (num_read > 0) {
// If we don't have a full set of version numbers, make the extras 0.
if (num_read < 2) *minor_version = 0;
if (num_read < 3) *bugfix_version = 0;
return;
}
}
// For some reason, we couldn't parse the version number string.
*major_version = kDefaultAndroidMajorVersion;
*minor_version = kDefaultAndroidMinorVersion;
*bugfix_version = kDefaultAndroidBugfixVersion;
}
// Parses a system property (specified with unit 'k','m' or 'g').
// Returns a value in bytes.
// Returns -1 if the string could not be parsed.
int64 ParseSystemPropertyBytes(const base::StringPiece& str) {
const int64 KB = 1024;
const int64 MB = 1024 * KB;
const int64 GB = 1024 * MB;
if (str.size() == 0u)
return -1;
int64 unit_multiplier = 1;
size_t length = str.size();
if (str[length - 1] == 'k') {
unit_multiplier = KB;
length--;
} else if (str[length - 1] == 'm') {
unit_multiplier = MB;
length--;
} else if (str[length - 1] == 'g') {
unit_multiplier = GB;
length--;
}
int64 result = 0;
bool parsed = base::StringToInt64(str.substr(0, length), &result);
bool negative = result <= 0;
bool overflow = result >= std::numeric_limits<int64>::max() / unit_multiplier;
if (!parsed || negative || overflow)
return -1;
return result * unit_multiplier;
}
int GetDalvikHeapSizeMB() {
char heap_size_str[PROP_VALUE_MAX];
__system_property_get("dalvik.vm.heapsize", heap_size_str);
// dalvik.vm.heapsize property is writable by a root user.
// Clamp it to reasonable range as a sanity check,
// a typical android device will never have less than 48MB.
const int64 MB = 1024 * 1024;
int64 result = ParseSystemPropertyBytes(heap_size_str);
if (result == -1) {
// We should consider not exposing these values if they are not reliable.
LOG(ERROR) << "Can't parse dalvik.vm.heapsize: " << heap_size_str;
result = base::SysInfo::AmountOfPhysicalMemoryMB() / 3;
}
result = std::min<int64>(std::max<int64>(32 * MB, result), 1024 * MB) / MB;
return static_cast<int>(result);
}
int GetDalvikHeapGrowthLimitMB() {
char heap_size_str[PROP_VALUE_MAX];
__system_property_get("dalvik.vm.heapgrowthlimit", heap_size_str);
// dalvik.vm.heapgrowthlimit property is writable by a root user.
// Clamp it to reasonable range as a sanity check,
// a typical android device will never have less than 24MB.
const int64 MB = 1024 * 1024;
int64 result = ParseSystemPropertyBytes(heap_size_str);
if (result == -1) {
// We should consider not exposing these values if they are not reliable.
LOG(ERROR) << "Can't parse dalvik.vm.heapgrowthlimit: " << heap_size_str;
result = base::SysInfo::AmountOfPhysicalMemoryMB() / 6;
}
result = std::min<int64>(std::max<int64>(16 * MB, result), 512 * MB) / MB;
return static_cast<int>(result);
}
} // anonymous namespace
namespace base {
std::string SysInfo::OperatingSystemName() {
return "Android";
}
std::string SysInfo::GetAndroidBuildCodename() {
char os_version_codename_str[PROP_VALUE_MAX];
__system_property_get("ro.build.version.codename", os_version_codename_str);
return std::string(os_version_codename_str);
}
std::string SysInfo::GetAndroidBuildID() {
char os_build_id_str[PROP_VALUE_MAX];
__system_property_get("ro.build.id", os_build_id_str);
return std::string(os_build_id_str);
}
std::string SysInfo::GetDeviceName() {
char device_model_str[PROP_VALUE_MAX];
__system_property_get("ro.product.model", device_model_str);
return std::string(device_model_str);
}
std::string SysInfo::OperatingSystemVersion() {
int32 major, minor, bugfix;
OperatingSystemVersionNumbers(&major, &minor, &bugfix);
return StringPrintf("%d.%d.%d", major, minor, bugfix);
}
void SysInfo::OperatingSystemVersionNumbers(int32* major_version,
int32* minor_version,
int32* bugfix_version) {
// Read the version number string out from the properties.
char os_version_str[PROP_VALUE_MAX];
__system_property_get("ro.build.version.release", os_version_str);
// Parse out the numbers.
ParseOSVersionNumbers(os_version_str, major_version, minor_version,
bugfix_version);
}
int SysInfo::DalvikHeapSizeMB() {
static int heap_size = GetDalvikHeapSizeMB();
return heap_size;
}
int SysInfo::DalvikHeapGrowthLimitMB() {
static int heap_growth_limit = GetDalvikHeapGrowthLimitMB();
return heap_growth_limit;
}
} // namespace base
<commit_msg>Cherry-pick: base: Default android version to 4.4.99<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/sys_info.h"
#include <sys/system_properties.h>
#include "base/logging.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
#include "base/strings/stringprintf.h"
namespace {
// Default version of Android to fall back to when actual version numbers
// cannot be acquired. Use the latest Android release with a higher bug fix
// version to avoid unnecessarily comparison errors with the latest release.
// This should be manually kept up-to-date on each Android release.
const int kDefaultAndroidMajorVersion = 4;
const int kDefaultAndroidMinorVersion = 4;
const int kDefaultAndroidBugfixVersion = 99;
// Parse out the OS version numbers from the system properties.
void ParseOSVersionNumbers(const char* os_version_str,
int32 *major_version,
int32 *minor_version,
int32 *bugfix_version) {
if (os_version_str[0]) {
// Try to parse out the version numbers from the string.
int num_read = sscanf(os_version_str, "%d.%d.%d", major_version,
minor_version, bugfix_version);
if (num_read > 0) {
// If we don't have a full set of version numbers, make the extras 0.
if (num_read < 2) *minor_version = 0;
if (num_read < 3) *bugfix_version = 0;
return;
}
}
// For some reason, we couldn't parse the version number string.
*major_version = kDefaultAndroidMajorVersion;
*minor_version = kDefaultAndroidMinorVersion;
*bugfix_version = kDefaultAndroidBugfixVersion;
}
// Parses a system property (specified with unit 'k','m' or 'g').
// Returns a value in bytes.
// Returns -1 if the string could not be parsed.
int64 ParseSystemPropertyBytes(const base::StringPiece& str) {
const int64 KB = 1024;
const int64 MB = 1024 * KB;
const int64 GB = 1024 * MB;
if (str.size() == 0u)
return -1;
int64 unit_multiplier = 1;
size_t length = str.size();
if (str[length - 1] == 'k') {
unit_multiplier = KB;
length--;
} else if (str[length - 1] == 'm') {
unit_multiplier = MB;
length--;
} else if (str[length - 1] == 'g') {
unit_multiplier = GB;
length--;
}
int64 result = 0;
bool parsed = base::StringToInt64(str.substr(0, length), &result);
bool negative = result <= 0;
bool overflow = result >= std::numeric_limits<int64>::max() / unit_multiplier;
if (!parsed || negative || overflow)
return -1;
return result * unit_multiplier;
}
int GetDalvikHeapSizeMB() {
char heap_size_str[PROP_VALUE_MAX];
__system_property_get("dalvik.vm.heapsize", heap_size_str);
// dalvik.vm.heapsize property is writable by a root user.
// Clamp it to reasonable range as a sanity check,
// a typical android device will never have less than 48MB.
const int64 MB = 1024 * 1024;
int64 result = ParseSystemPropertyBytes(heap_size_str);
if (result == -1) {
// We should consider not exposing these values if they are not reliable.
LOG(ERROR) << "Can't parse dalvik.vm.heapsize: " << heap_size_str;
result = base::SysInfo::AmountOfPhysicalMemoryMB() / 3;
}
result = std::min<int64>(std::max<int64>(32 * MB, result), 1024 * MB) / MB;
return static_cast<int>(result);
}
int GetDalvikHeapGrowthLimitMB() {
char heap_size_str[PROP_VALUE_MAX];
__system_property_get("dalvik.vm.heapgrowthlimit", heap_size_str);
// dalvik.vm.heapgrowthlimit property is writable by a root user.
// Clamp it to reasonable range as a sanity check,
// a typical android device will never have less than 24MB.
const int64 MB = 1024 * 1024;
int64 result = ParseSystemPropertyBytes(heap_size_str);
if (result == -1) {
// We should consider not exposing these values if they are not reliable.
LOG(ERROR) << "Can't parse dalvik.vm.heapgrowthlimit: " << heap_size_str;
result = base::SysInfo::AmountOfPhysicalMemoryMB() / 6;
}
result = std::min<int64>(std::max<int64>(16 * MB, result), 512 * MB) / MB;
return static_cast<int>(result);
}
} // anonymous namespace
namespace base {
std::string SysInfo::OperatingSystemName() {
return "Android";
}
std::string SysInfo::GetAndroidBuildCodename() {
char os_version_codename_str[PROP_VALUE_MAX];
__system_property_get("ro.build.version.codename", os_version_codename_str);
return std::string(os_version_codename_str);
}
std::string SysInfo::GetAndroidBuildID() {
char os_build_id_str[PROP_VALUE_MAX];
__system_property_get("ro.build.id", os_build_id_str);
return std::string(os_build_id_str);
}
std::string SysInfo::GetDeviceName() {
char device_model_str[PROP_VALUE_MAX];
__system_property_get("ro.product.model", device_model_str);
return std::string(device_model_str);
}
std::string SysInfo::OperatingSystemVersion() {
int32 major, minor, bugfix;
OperatingSystemVersionNumbers(&major, &minor, &bugfix);
return StringPrintf("%d.%d.%d", major, minor, bugfix);
}
void SysInfo::OperatingSystemVersionNumbers(int32* major_version,
int32* minor_version,
int32* bugfix_version) {
// Read the version number string out from the properties.
char os_version_str[PROP_VALUE_MAX];
__system_property_get("ro.build.version.release", os_version_str);
// Parse out the numbers.
ParseOSVersionNumbers(os_version_str, major_version, minor_version,
bugfix_version);
}
int SysInfo::DalvikHeapSizeMB() {
static int heap_size = GetDalvikHeapSizeMB();
return heap_size;
}
int SysInfo::DalvikHeapGrowthLimitMB() {
static int heap_growth_limit = GetDalvikHeapGrowthLimitMB();
return heap_growth_limit;
}
} // namespace base
<|endoftext|> |
<commit_before>#ifndef INCLUDED_AQUAVCLEVENTS_HXX
#define INCLUDED_AQUAVCLEVENTS_HXX
#include <premac.h>
#include <Carbon/Carbon.h>
#include <postmac.h>
/* Definition of custom OpenOffice.org events.
Avoid conflict with Apple defined event class and type
definitions by using uppercase letters. Lowercase
letter definitions are reserved for Apple!
*/
enum {
cOOoSalUserEventClass = 'OOUE'
};
enum {
cOOoSalEventUser = 'UEVT',
cOOoSalEventTimer = 'EVTT',
cOOoSalEventData = 'EVTD',
cOOoSalEventParamTypePtr = 'EPPT'
};
/* Definition of all necessary EventTypeSpec's */
const EventTypeSpec cWindowBoundsChangedEvent = { kEventClassWindow, kEventWindowBoundsChanged };
const EventTypeSpec cWindowCloseEvent = { kEventClassWindow, kEventWindowClose };
const EventTypeSpec cOOoSalUserEvent = { cOOoSalUserEventClass, cOOoSalEventUser };
const EventTypeSpec cOOoSalTimerEvent = { cOOoSalUserEventClass, cOOoSalEventTimer };
const EventTypeSpec cWindowActivatedEvent[] = { { kEventClassWindow, kEventWindowActivated },
{ kEventClassWindow, kEventWindowDeactivated } };
const EventTypeSpec cWindowPaintEvent = { kEventClassWindow, kEventWindowPaint };
const EventTypeSpec cWindowDrawContentEvent = { kEventClassWindow, kEventWindowDrawContent };
const EventTypeSpec cWindowFocusEvent[] = { { kEventClassWindow, kEventWindowFocusAcquired },
{ kEventClassWindow, kEventWindowFocusRelinquish } };
const EventTypeSpec cMouseEnterExitEvent[] = { { kEventClassControl, kEventControlTrackingAreaEntered },
{ kEventClassControl, kEventControlTrackingAreaExited } };
const EventTypeSpec cMouseEvent[] = { { kEventClassMouse, kEventMouseDown },
{ kEventClassMouse, kEventMouseUp },
{ kEventClassMouse, kEventMouseMoved },
{ kEventClassMouse, kEventMouseDragged } };
const EventTypeSpec cMouseWheelMovedEvent = { kEventClassMouse, kEventMouseWheelMoved };
const EventTypeSpec cWindowResizeStarted = { kEventClassWindow, kEventWindowResizeStarted };
const EventTypeSpec cWindowResizeCompleted = { kEventClassWindow, kEventWindowResizeCompleted };
/* Events for native menus */
const EventTypeSpec cCommandProcessEvent = { kEventClassCommand, kEventCommandProcess };
const EventTypeSpec cMenuPopulateEvent = { kEventClassMenu, kEventMenuPopulate };
const EventTypeSpec cMenuClosedEvent = { kEventClassMenu, kEventMenuClosed };
const EventTypeSpec cMenuTargetItemEvent = { kEventClassMenu, kEventMenuTargetItem };
/* Events for keyboard */
const EventTypeSpec cKeyboardRawKeyEvents[] = { { kEventClassKeyboard, kEventRawKeyDown},
{ kEventClassKeyboard, kEventRawKeyUp},
{ kEventClassKeyboard, kEventRawKeyRepeat},
{ kEventClassKeyboard, kEventRawKeyModifiersChanged} };
const EventTypeSpec cTextInputEvents[] = { { kEventClassTextInput, kEventTextInputUpdateActiveInputArea},
{ kEventClassTextInput, kEventTextInputUnicodeForKeyEvent},
{ kEventClassTextInput, kEventTextInputOffsetToPos} };
/* Events for scrollbar */
const EventTypeSpec cAppearanceScrollbarVariantChangedEvent = { kEventClassAppearance, kEventAppearanceScrollBarVariantChanged };
#endif // INCLUDED_AQUAVCLEVENTS_HXX
<commit_msg>INTEGRATION: CWS aquavcl03 (1.2.4); FILE MERGED 2007/09/17 17:23:51 pl 1.2.4.2: RESYNC: (1.2-1.3); FILE MERGED 2007/08/08 09:27:49 pl 1.2.4.1: some header cleanup<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: aquavclevents.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: kz $ $Date: 2007-10-09 15:07:55 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef INCLUDED_AQUAVCLEVENTS_HXX
#define INCLUDED_AQUAVCLEVENTS_HXX
#include <premac.h>
#include <Carbon/Carbon.h>
#include <postmac.h>
/* Definition of custom OpenOffice.org events.
Avoid conflict with Apple defined event class and type
definitions by using uppercase letters. Lowercase
letter definitions are reserved for Apple!
*/
enum {
cOOoSalUserEventClass = 'OOUE'
};
enum {
cOOoSalEventUser = 'UEVT',
cOOoSalEventTimer = 'EVTT',
cOOoSalEventData = 'EVTD',
cOOoSalEventParamTypePtr = 'EPPT'
};
/* Definition of all necessary EventTypeSpec's */
const EventTypeSpec cWindowBoundsChangedEvent = { kEventClassWindow, kEventWindowBoundsChanged };
const EventTypeSpec cWindowCloseEvent = { kEventClassWindow, kEventWindowClose };
const EventTypeSpec cOOoSalUserEvent = { cOOoSalUserEventClass, cOOoSalEventUser };
const EventTypeSpec cOOoSalTimerEvent = { cOOoSalUserEventClass, cOOoSalEventTimer };
const EventTypeSpec cWindowActivatedEvent[] = { { kEventClassWindow, kEventWindowActivated },
{ kEventClassWindow, kEventWindowDeactivated } };
const EventTypeSpec cWindowPaintEvent = { kEventClassWindow, kEventWindowPaint };
const EventTypeSpec cWindowDrawContentEvent = { kEventClassWindow, kEventWindowDrawContent };
const EventTypeSpec cWindowFocusEvent[] = { { kEventClassWindow, kEventWindowFocusAcquired },
{ kEventClassWindow, kEventWindowFocusRelinquish } };
const EventTypeSpec cMouseEnterExitEvent[] = { { kEventClassControl, kEventControlTrackingAreaEntered },
{ kEventClassControl, kEventControlTrackingAreaExited } };
const EventTypeSpec cMouseEvent[] = { { kEventClassMouse, kEventMouseDown },
{ kEventClassMouse, kEventMouseUp },
{ kEventClassMouse, kEventMouseMoved },
{ kEventClassMouse, kEventMouseDragged } };
const EventTypeSpec cMouseWheelMovedEvent = { kEventClassMouse, kEventMouseWheelMoved };
const EventTypeSpec cWindowResizeStarted = { kEventClassWindow, kEventWindowResizeStarted };
const EventTypeSpec cWindowResizeCompleted = { kEventClassWindow, kEventWindowResizeCompleted };
/* Events for native menus */
const EventTypeSpec cCommandProcessEvent = { kEventClassCommand, kEventCommandProcess };
const EventTypeSpec cMenuPopulateEvent = { kEventClassMenu, kEventMenuPopulate };
const EventTypeSpec cMenuClosedEvent = { kEventClassMenu, kEventMenuClosed };
const EventTypeSpec cMenuTargetItemEvent = { kEventClassMenu, kEventMenuTargetItem };
/* Events for keyboard */
const EventTypeSpec cKeyboardRawKeyEvents[] = { { kEventClassKeyboard, kEventRawKeyDown},
{ kEventClassKeyboard, kEventRawKeyUp},
{ kEventClassKeyboard, kEventRawKeyRepeat},
{ kEventClassKeyboard, kEventRawKeyModifiersChanged} };
const EventTypeSpec cTextInputEvents[] = { { kEventClassTextInput, kEventTextInputUpdateActiveInputArea},
{ kEventClassTextInput, kEventTextInputUnicodeForKeyEvent},
{ kEventClassTextInput, kEventTextInputOffsetToPos} };
/* Events for scrollbar */
const EventTypeSpec cAppearanceScrollbarVariantChangedEvent = { kEventClassAppearance, kEventAppearanceScrollBarVariantChanged };
#endif // INCLUDED_AQUAVCLEVENTS_HXX
<|endoftext|> |
<commit_before>// Copyright 2012 Cloudera Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "util/webserver.h"
#include <stdio.h>
#include <signal.h>
#include <string>
#include <map>
#include <boost/lexical_cast.hpp>
#include <boost/foreach.hpp>
#include <boost/bind.hpp>
#include <boost/mem_fn.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include "common/logging.h"
#include "util/cpu-info.h"
#include "util/disk-info.h"
#include "util/mem-info.h"
#include "util/url-coding.h"
#include "util/logging.h"
#include "util/debug-util.h"
#include "util/thrift-util.h"
using namespace std;
using namespace boost;
using namespace boost::filesystem;
using namespace google;
const char* GetDefaultDocumentRoot();
DEFINE_int32(webserver_port, 25000, "Port to start debug webserver on");
DEFINE_string(webserver_interface, "",
"Interface to start debug webserver on. If blank, webserver binds to 0.0.0.0");
DEFINE_string(webserver_doc_root, GetDefaultDocumentRoot(),
"Files under <webserver_doc_root>/www are accessible via the debug webserver. "
"Defaults to $IMPALA_HOME, or if $IMPALA_HOME is not set, disables the document "
"root");
DEFINE_bool(enable_webserver_doc_root, true,
"If true, webserver may serve static files from the webserver_doc_root");
DEFINE_string(webserver_certificate_file, "",
"The location of the debug webserver's SSL certificate file, in .pem format. If "
"empty, webserver SSL support is not enabled");
DEFINE_string(webserver_authentication_domain, "",
"Domain used for debug webserver authentication");
DEFINE_string(webserver_password_file, "",
"(Optional) Location of .htpasswd file containing user names and hashed passwords for"
" debug webserver authentication");
// Mongoose requires a non-null return from the callback to signify successful processing
static void* PROCESSING_COMPLETE = reinterpret_cast<void*>(1);
static const char* DOC_FOLDER = "/www/";
static const int DOC_FOLDER_LEN = strlen(DOC_FOLDER);
// Returns $IMPALA_HOME if set, otherwise /tmp/impala_www
const char* GetDefaultDocumentRoot() {
stringstream ss;
char* impala_home = getenv("IMPALA_HOME");
if (impala_home == NULL) {
return ""; // Empty document root means don't serve static files
} else {
ss << impala_home;
}
// Deliberate memory leak, but this should be called exactly once.
string* str = new string(ss.str());
return str->c_str();
}
namespace impala {
Webserver::Webserver() : context_(NULL) {
http_address_ = MakeNetworkAddress(
FLAGS_webserver_interface.empty() ? "0.0.0.0" : FLAGS_webserver_interface,
FLAGS_webserver_port);
}
Webserver::Webserver(const int port) : context_(NULL) {
http_address_ = MakeNetworkAddress("0.0.0.0", port);
}
Webserver::~Webserver() {
Stop();
}
void Webserver::RootHandler(const Webserver::ArgumentMap& args, stringstream* output) {
// path_handler_lock_ already held by MongooseCallback
(*output) << "<h2>Version</h2>";
(*output) << "<pre>" << GetVersionString() << "</pre>" << endl;
(*output) << "<h2>Hardware Info</h2>";
(*output) << "<pre>";
(*output) << CpuInfo::DebugString();
(*output) << MemInfo::DebugString();
(*output) << DiskInfo::DebugString();
(*output) << "</pre>";
(*output) << "<h2>Status Pages</h2>";
BOOST_FOREACH(const PathHandlerMap::value_type& handler, path_handlers_) {
if (handler.second.is_on_nav_bar()) {
(*output) << "<a href=\"" << handler.first << "\">" << handler.first << "</a><br/>";
}
}
}
void Webserver::BuildArgumentMap(const string& args, ArgumentMap* output) {
vector<string> arg_pairs;
split(arg_pairs, args, is_any_of("&"));
BOOST_FOREACH(const string& arg_pair, arg_pairs) {
vector<string> key_value;
split(key_value, arg_pair, is_any_of("="));
if (key_value.empty()) continue;
string key;
if (!UrlDecode(key_value[0], &key)) continue;
string value;
if (!UrlDecode((key_value.size() >= 2 ? key_value[1] : ""), &value)) continue;
to_lower(key);
(*output)[key] = value;
}
}
bool Webserver::IsSecure() const {
return !FLAGS_webserver_certificate_file.empty();
}
Status Webserver::Start() {
LOG(INFO) << "Starting webserver on " << http_address_;
stringstream listening_spec;
if (IsWildcardAddress(http_address_.hostname)) {
listening_spec << http_address_;
} else {
string port_as_string = lexical_cast<string>(http_address_.port);
listening_spec << ":" << port_as_string;
}
if (IsSecure()) {
LOG(INFO) << "Webserver: Enabling HTTPS support";
// Mongoose makes sockets with 's' suffixes accept SSL traffic only
listening_spec << "s";
}
string listening_str = listening_spec.str();
vector<const char*> options;
if (!FLAGS_webserver_doc_root.empty() && FLAGS_enable_webserver_doc_root) {
LOG(INFO) << "Document root: " << FLAGS_webserver_doc_root;
options.push_back("document_root");
options.push_back(FLAGS_webserver_doc_root.c_str());
} else {
LOG(INFO)<< "Document root disabled";
}
if (IsSecure()) {
options.push_back("ssl_certificate");
options.push_back(FLAGS_webserver_certificate_file.c_str());
}
if (!FLAGS_webserver_authentication_domain.empty()) {
options.push_back("authentication_domain");
options.push_back(FLAGS_webserver_authentication_domain.c_str());
}
if (!FLAGS_webserver_password_file.empty()) {
// Mongoose doesn't log anything if it can't stat the password file (but will if it
// can't open it, which it tries to do during a request)
if (!exists(FLAGS_webserver_password_file)) {
stringstream ss;
ss << "Webserver: Password file does not exist: " << FLAGS_webserver_password_file;
return Status(ss.str());
}
LOG(INFO) << "Webserver: Password file is " << FLAGS_webserver_password_file;
options.push_back("global_passwords_file");
options.push_back(FLAGS_webserver_password_file.c_str());
}
options.push_back("listening_ports");
options.push_back(listening_str.c_str());
// Options must be a NULL-terminated list
options.push_back(NULL);
// mongoose ignores SIGCHLD and we need it to run kinit. This means that since
// mongoose does not reap its own children CGI programs must be avoided.
// Save the signal handler so we can restore it after mongoose sets it to be ignored.
sighandler_t sig_chld = signal(SIGCHLD, SIG_DFL);
// To work around not being able to pass member functions as C callbacks, we store a
// pointer to this server in the per-server state, and register a static method as the
// default callback. That method unpacks the pointer to this and calls the real
// callback.
context_ = mg_start(&Webserver::MongooseCallbackStatic, reinterpret_cast<void*>(this),
&options[0]);
// Restore the child signal handler so wait() works properly.
signal(SIGCHLD, sig_chld);
if (context_ == NULL) {
stringstream error_msg;
error_msg << "Webserver: Could not start on address " << http_address_;
return Status(error_msg.str());
}
PathHandlerCallback default_callback =
bind<void>(mem_fn(&Webserver::RootHandler), this, _1, _2);
RegisterPathHandler("/", default_callback);
LOG(INFO) << "Webserver started";
return Status::OK;
}
void Webserver::Stop() {
if (context_ != NULL) mg_stop(context_);
}
void* Webserver::MongooseCallbackStatic(enum mg_event event,
struct mg_connection* connection) {
const struct mg_request_info* request_info = mg_get_request_info(connection);
Webserver* instance =
reinterpret_cast<Webserver*>(mg_get_user_data(connection));
return instance->MongooseCallback(event, connection, request_info);
}
void* Webserver::MongooseCallback(enum mg_event event, struct mg_connection* connection,
const struct mg_request_info* request_info) {
if (event == MG_EVENT_LOG) {
const char* msg = mg_get_log_message(connection);
if (msg != NULL) {
LOG(INFO) << "Webserver: " << msg;
}
return PROCESSING_COMPLETE;
}
if (event == MG_NEW_REQUEST) {
if (!FLAGS_webserver_doc_root.empty() && FLAGS_enable_webserver_doc_root) {
if (strncmp(DOC_FOLDER, request_info->uri, DOC_FOLDER_LEN) == 0) {
VLOG(2) << "HTTP File access: " << request_info->uri;
// Let Mongoose deal with this request; returning NULL will fall through
// to the default handler which will serve files.
return NULL;
}
}
mutex::scoped_lock lock(path_handlers_lock_);
PathHandlerMap::const_iterator it = path_handlers_.find(request_info->uri);
if (it == path_handlers_.end()) {
mg_printf(connection, "HTTP/1.1 404 Not Found\r\n"
"Content-Type: text/plain\r\n\r\n");
mg_printf(connection, "No handler for URI %s\r\n\r\n", request_info->uri);
return PROCESSING_COMPLETE;
}
// Should we render with css styles?
bool use_style = true;
map<string, string> arguments;
if (request_info->query_string != NULL) {
BuildArgumentMap(request_info->query_string, &arguments);
}
if (!it->second.is_styled() || arguments.find("raw") != arguments.end()) {
use_style = false;
}
stringstream output;
if (use_style) BootstrapPageHeader(&output);
BOOST_FOREACH(const PathHandlerCallback& callback_, it->second.callbacks()) {
callback_(arguments, &output);
}
if (use_style) BootstrapPageFooter(&output);
string str = output.str();
// Without styling, render the page as plain text
if (arguments.find("raw") != arguments.end()) {
mg_printf(connection, "HTTP/1.1 200 OK\r\n"
"Content-Type: text/plain\r\n"
"Content-Length: %d\r\n"
"\r\n", (int)str.length());
} else {
mg_printf(connection, "HTTP/1.1 200 OK\r\n"
"Content-Type: text/html\r\n"
"Content-Length: %d\r\n"
"\r\n", (int)str.length());
}
// Make sure to use mg_write for printing the body; mg_printf truncates at 8kb
mg_write(connection, str.c_str(), str.length());
return PROCESSING_COMPLETE;
} else {
return NULL;
}
}
void Webserver::RegisterPathHandler(const string& path,
const PathHandlerCallback& callback, bool is_styled, bool is_on_nav_bar) {
mutex::scoped_lock lock(path_handlers_lock_);
PathHandlerMap::iterator it = path_handlers_.find(path);
if (it == path_handlers_.end()) {
it = path_handlers_.insert(
make_pair(path, PathHandler(is_styled, is_on_nav_bar))).first;
}
it->second.AddCallback(callback);
}
const string PAGE_HEADER = "<!DOCTYPE html>"
" <html>"
" <head><title>Cloudera Impala</title>"
" <link href='www/bootstrap/css/bootstrap.min.css' rel='stylesheet' media='screen'>"
" <style>"
" body {"
" padding-top: 60px; "
" }"
" </style>"
" </head>"
" <body>";
static const string PAGE_FOOTER = "</div></body></html>";
static const string NAVIGATION_BAR_PREFIX =
"<div class='navbar navbar-inverse navbar-fixed-top'>"
" <div class='navbar-inner'>"
" <div class='container'>"
" <a class='btn btn-navbar' data-toggle='collapse' data-target='.nav-collapse'>"
" <span class='icon-bar'></span>"
" <span class='icon-bar'></span>"
" <span class='icon-bar'></span>"
" </a>"
" <a class='brand' href='/'>Impala</a>"
" <div class='nav-collapse collapse'>"
" <ul class='nav'>";
static const string NAVIGATION_BAR_SUFFIX =
" </ul>"
" </div>"
" </div>"
" </div>"
" </div>"
" <div class='container'>";
void Webserver::BootstrapPageHeader(stringstream* output) {
(*output) << PAGE_HEADER;
(*output) << NAVIGATION_BAR_PREFIX;
BOOST_FOREACH(const PathHandlerMap::value_type& handler, path_handlers_) {
if (handler.second.is_on_nav_bar()) {
(*output) << "<li><a href=\"" << handler.first << "\">" << handler.first
<< "</a></li>";
}
}
(*output) << NAVIGATION_BAR_SUFFIX;
}
void Webserver::BootstrapPageFooter(stringstream* output) {
(*output) << PAGE_FOOTER;
}
}
<commit_msg>Fix logic for starting webserver on non-default interface<commit_after>// Copyright 2012 Cloudera Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "util/webserver.h"
#include <stdio.h>
#include <signal.h>
#include <string>
#include <map>
#include <boost/lexical_cast.hpp>
#include <boost/foreach.hpp>
#include <boost/bind.hpp>
#include <boost/mem_fn.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include "common/logging.h"
#include "util/cpu-info.h"
#include "util/disk-info.h"
#include "util/mem-info.h"
#include "util/url-coding.h"
#include "util/logging.h"
#include "util/debug-util.h"
#include "util/thrift-util.h"
using namespace std;
using namespace boost;
using namespace boost::filesystem;
using namespace google;
const char* GetDefaultDocumentRoot();
DEFINE_int32(webserver_port, 25000, "Port to start debug webserver on");
DEFINE_string(webserver_interface, "",
"Interface to start debug webserver on. If blank, webserver binds to 0.0.0.0");
DEFINE_string(webserver_doc_root, GetDefaultDocumentRoot(),
"Files under <webserver_doc_root>/www are accessible via the debug webserver. "
"Defaults to $IMPALA_HOME, or if $IMPALA_HOME is not set, disables the document "
"root");
DEFINE_bool(enable_webserver_doc_root, true,
"If true, webserver may serve static files from the webserver_doc_root");
DEFINE_string(webserver_certificate_file, "",
"The location of the debug webserver's SSL certificate file, in .pem format. If "
"empty, webserver SSL support is not enabled");
DEFINE_string(webserver_authentication_domain, "",
"Domain used for debug webserver authentication");
DEFINE_string(webserver_password_file, "",
"(Optional) Location of .htpasswd file containing user names and hashed passwords for"
" debug webserver authentication");
// Mongoose requires a non-null return from the callback to signify successful processing
static void* PROCESSING_COMPLETE = reinterpret_cast<void*>(1);
static const char* DOC_FOLDER = "/www/";
static const int DOC_FOLDER_LEN = strlen(DOC_FOLDER);
// Returns $IMPALA_HOME if set, otherwise /tmp/impala_www
const char* GetDefaultDocumentRoot() {
stringstream ss;
char* impala_home = getenv("IMPALA_HOME");
if (impala_home == NULL) {
return ""; // Empty document root means don't serve static files
} else {
ss << impala_home;
}
// Deliberate memory leak, but this should be called exactly once.
string* str = new string(ss.str());
return str->c_str();
}
namespace impala {
Webserver::Webserver() : context_(NULL) {
http_address_ = MakeNetworkAddress(
FLAGS_webserver_interface.empty() ? "0.0.0.0" : FLAGS_webserver_interface,
FLAGS_webserver_port);
}
Webserver::Webserver(const int port) : context_(NULL) {
http_address_ = MakeNetworkAddress("0.0.0.0", port);
}
Webserver::~Webserver() {
Stop();
}
void Webserver::RootHandler(const Webserver::ArgumentMap& args, stringstream* output) {
// path_handler_lock_ already held by MongooseCallback
(*output) << "<h2>Version</h2>";
(*output) << "<pre>" << GetVersionString() << "</pre>" << endl;
(*output) << "<h2>Hardware Info</h2>";
(*output) << "<pre>";
(*output) << CpuInfo::DebugString();
(*output) << MemInfo::DebugString();
(*output) << DiskInfo::DebugString();
(*output) << "</pre>";
(*output) << "<h2>Status Pages</h2>";
BOOST_FOREACH(const PathHandlerMap::value_type& handler, path_handlers_) {
if (handler.second.is_on_nav_bar()) {
(*output) << "<a href=\"" << handler.first << "\">" << handler.first << "</a><br/>";
}
}
}
void Webserver::BuildArgumentMap(const string& args, ArgumentMap* output) {
vector<string> arg_pairs;
split(arg_pairs, args, is_any_of("&"));
BOOST_FOREACH(const string& arg_pair, arg_pairs) {
vector<string> key_value;
split(key_value, arg_pair, is_any_of("="));
if (key_value.empty()) continue;
string key;
if (!UrlDecode(key_value[0], &key)) continue;
string value;
if (!UrlDecode((key_value.size() >= 2 ? key_value[1] : ""), &value)) continue;
to_lower(key);
(*output)[key] = value;
}
}
bool Webserver::IsSecure() const {
return !FLAGS_webserver_certificate_file.empty();
}
Status Webserver::Start() {
LOG(INFO) << "Starting webserver on " << http_address_;
stringstream listening_spec;
listening_spec << http_address_;
if (IsSecure()) {
LOG(INFO) << "Webserver: Enabling HTTPS support";
// Mongoose makes sockets with 's' suffixes accept SSL traffic only
listening_spec << "s";
}
string listening_str = listening_spec.str();
vector<const char*> options;
if (!FLAGS_webserver_doc_root.empty() && FLAGS_enable_webserver_doc_root) {
LOG(INFO) << "Document root: " << FLAGS_webserver_doc_root;
options.push_back("document_root");
options.push_back(FLAGS_webserver_doc_root.c_str());
} else {
LOG(INFO)<< "Document root disabled";
}
if (IsSecure()) {
options.push_back("ssl_certificate");
options.push_back(FLAGS_webserver_certificate_file.c_str());
}
if (!FLAGS_webserver_authentication_domain.empty()) {
options.push_back("authentication_domain");
options.push_back(FLAGS_webserver_authentication_domain.c_str());
}
if (!FLAGS_webserver_password_file.empty()) {
// Mongoose doesn't log anything if it can't stat the password file (but will if it
// can't open it, which it tries to do during a request)
if (!exists(FLAGS_webserver_password_file)) {
stringstream ss;
ss << "Webserver: Password file does not exist: " << FLAGS_webserver_password_file;
return Status(ss.str());
}
LOG(INFO) << "Webserver: Password file is " << FLAGS_webserver_password_file;
options.push_back("global_passwords_file");
options.push_back(FLAGS_webserver_password_file.c_str());
}
options.push_back("listening_ports");
options.push_back(listening_str.c_str());
// Options must be a NULL-terminated list
options.push_back(NULL);
// mongoose ignores SIGCHLD and we need it to run kinit. This means that since
// mongoose does not reap its own children CGI programs must be avoided.
// Save the signal handler so we can restore it after mongoose sets it to be ignored.
sighandler_t sig_chld = signal(SIGCHLD, SIG_DFL);
// To work around not being able to pass member functions as C callbacks, we store a
// pointer to this server in the per-server state, and register a static method as the
// default callback. That method unpacks the pointer to this and calls the real
// callback.
context_ = mg_start(&Webserver::MongooseCallbackStatic, reinterpret_cast<void*>(this),
&options[0]);
// Restore the child signal handler so wait() works properly.
signal(SIGCHLD, sig_chld);
if (context_ == NULL) {
stringstream error_msg;
error_msg << "Webserver: Could not start on address " << http_address_;
return Status(error_msg.str());
}
PathHandlerCallback default_callback =
bind<void>(mem_fn(&Webserver::RootHandler), this, _1, _2);
RegisterPathHandler("/", default_callback);
LOG(INFO) << "Webserver started";
return Status::OK;
}
void Webserver::Stop() {
if (context_ != NULL) mg_stop(context_);
}
void* Webserver::MongooseCallbackStatic(enum mg_event event,
struct mg_connection* connection) {
const struct mg_request_info* request_info = mg_get_request_info(connection);
Webserver* instance =
reinterpret_cast<Webserver*>(mg_get_user_data(connection));
return instance->MongooseCallback(event, connection, request_info);
}
void* Webserver::MongooseCallback(enum mg_event event, struct mg_connection* connection,
const struct mg_request_info* request_info) {
if (event == MG_EVENT_LOG) {
const char* msg = mg_get_log_message(connection);
if (msg != NULL) {
LOG(INFO) << "Webserver: " << msg;
}
return PROCESSING_COMPLETE;
}
if (event == MG_NEW_REQUEST) {
if (!FLAGS_webserver_doc_root.empty() && FLAGS_enable_webserver_doc_root) {
if (strncmp(DOC_FOLDER, request_info->uri, DOC_FOLDER_LEN) == 0) {
VLOG(2) << "HTTP File access: " << request_info->uri;
// Let Mongoose deal with this request; returning NULL will fall through
// to the default handler which will serve files.
return NULL;
}
}
mutex::scoped_lock lock(path_handlers_lock_);
PathHandlerMap::const_iterator it = path_handlers_.find(request_info->uri);
if (it == path_handlers_.end()) {
mg_printf(connection, "HTTP/1.1 404 Not Found\r\n"
"Content-Type: text/plain\r\n\r\n");
mg_printf(connection, "No handler for URI %s\r\n\r\n", request_info->uri);
return PROCESSING_COMPLETE;
}
// Should we render with css styles?
bool use_style = true;
map<string, string> arguments;
if (request_info->query_string != NULL) {
BuildArgumentMap(request_info->query_string, &arguments);
}
if (!it->second.is_styled() || arguments.find("raw") != arguments.end()) {
use_style = false;
}
stringstream output;
if (use_style) BootstrapPageHeader(&output);
BOOST_FOREACH(const PathHandlerCallback& callback_, it->second.callbacks()) {
callback_(arguments, &output);
}
if (use_style) BootstrapPageFooter(&output);
string str = output.str();
// Without styling, render the page as plain text
if (arguments.find("raw") != arguments.end()) {
mg_printf(connection, "HTTP/1.1 200 OK\r\n"
"Content-Type: text/plain\r\n"
"Content-Length: %d\r\n"
"\r\n", (int)str.length());
} else {
mg_printf(connection, "HTTP/1.1 200 OK\r\n"
"Content-Type: text/html\r\n"
"Content-Length: %d\r\n"
"\r\n", (int)str.length());
}
// Make sure to use mg_write for printing the body; mg_printf truncates at 8kb
mg_write(connection, str.c_str(), str.length());
return PROCESSING_COMPLETE;
} else {
return NULL;
}
}
void Webserver::RegisterPathHandler(const string& path,
const PathHandlerCallback& callback, bool is_styled, bool is_on_nav_bar) {
mutex::scoped_lock lock(path_handlers_lock_);
PathHandlerMap::iterator it = path_handlers_.find(path);
if (it == path_handlers_.end()) {
it = path_handlers_.insert(
make_pair(path, PathHandler(is_styled, is_on_nav_bar))).first;
}
it->second.AddCallback(callback);
}
const string PAGE_HEADER = "<!DOCTYPE html>"
" <html>"
" <head><title>Cloudera Impala</title>"
" <link href='www/bootstrap/css/bootstrap.min.css' rel='stylesheet' media='screen'>"
" <style>"
" body {"
" padding-top: 60px; "
" }"
" </style>"
" </head>"
" <body>";
static const string PAGE_FOOTER = "</div></body></html>";
static const string NAVIGATION_BAR_PREFIX =
"<div class='navbar navbar-inverse navbar-fixed-top'>"
" <div class='navbar-inner'>"
" <div class='container'>"
" <a class='btn btn-navbar' data-toggle='collapse' data-target='.nav-collapse'>"
" <span class='icon-bar'></span>"
" <span class='icon-bar'></span>"
" <span class='icon-bar'></span>"
" </a>"
" <a class='brand' href='/'>Impala</a>"
" <div class='nav-collapse collapse'>"
" <ul class='nav'>";
static const string NAVIGATION_BAR_SUFFIX =
" </ul>"
" </div>"
" </div>"
" </div>"
" </div>"
" <div class='container'>";
void Webserver::BootstrapPageHeader(stringstream* output) {
(*output) << PAGE_HEADER;
(*output) << NAVIGATION_BAR_PREFIX;
BOOST_FOREACH(const PathHandlerMap::value_type& handler, path_handlers_) {
if (handler.second.is_on_nav_bar()) {
(*output) << "<li><a href=\"" << handler.first << "\">" << handler.first
<< "</a></li>";
}
}
(*output) << NAVIGATION_BAR_SUFFIX;
}
void Webserver::BootstrapPageFooter(stringstream* output) {
(*output) << PAGE_FOOTER;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2012-2020 Daniele Bartolini and individual contributors.
* License: https://github.com/dbartolini/crown/blob/master/LICENSE
*/
#include "core/memory/temp_allocator.inl"
#include "core/os.h"
#include "core/platform.h"
#include "core/strings/string.inl"
#include "core/strings/string_stream.h"
#include "core/thread/scoped_mutex.inl"
#include "device/console_server.h"
#include "device/log.h"
namespace crown
{
namespace log_internal
{
static Mutex s_mutex;
static void stdout_log(LogSeverity::Enum sev, System system, const char* msg)
{
char buf[2048];
#if CROWN_PLATFORM_POSIX
#define ANSI_RESET "\x1b[0m"
#define ANSI_YELLOW "\x1b[33m"
#define ANSI_RED "\x1b[31m"
const char* stt[] = { ANSI_RESET, ANSI_YELLOW, ANSI_RED };
CE_STATIC_ASSERT(countof(stt) == LogSeverity::COUNT);
snprintf(buf, sizeof(buf), "%s%s: %s\n" ANSI_RESET, stt[sev], system.name, msg);
#else
snprintf(buf, sizeof(buf), "%s: %s\n", system.name, msg);
#endif
os::log(buf);
}
void vlogx(LogSeverity::Enum sev, System system, const char* msg, va_list args)
{
ScopedMutex sm(s_mutex);
char buf[2048];
int len = vsnprintf(buf, sizeof(buf), msg, args);
buf[len] = '\0';
stdout_log(sev, system, buf);
if (console_server())
console_server()->log(sev, system.name, buf);
}
void logx(LogSeverity::Enum sev, System system, const char* msg, ...)
{
va_list args;
va_start(args, msg);
vlogx(sev, system, msg, args);
va_end(args);
}
} // namespace log
} // namespace crown
<commit_msg>device: vsnprintf always NUL-terminates the output<commit_after>/*
* Copyright (c) 2012-2020 Daniele Bartolini and individual contributors.
* License: https://github.com/dbartolini/crown/blob/master/LICENSE
*/
#include "core/memory/temp_allocator.inl"
#include "core/os.h"
#include "core/platform.h"
#include "core/strings/string.inl"
#include "core/strings/string_stream.h"
#include "core/thread/scoped_mutex.inl"
#include "device/console_server.h"
#include "device/log.h"
namespace crown
{
namespace log_internal
{
static Mutex s_mutex;
static void stdout_log(LogSeverity::Enum sev, System system, const char* msg)
{
char buf[2048];
#if CROWN_PLATFORM_POSIX
#define ANSI_RESET "\x1b[0m"
#define ANSI_YELLOW "\x1b[33m"
#define ANSI_RED "\x1b[31m"
const char* stt[] = { ANSI_RESET, ANSI_YELLOW, ANSI_RED };
CE_STATIC_ASSERT(countof(stt) == LogSeverity::COUNT);
snprintf(buf, sizeof(buf), "%s%s: %s\n" ANSI_RESET, stt[sev], system.name, msg);
#else
snprintf(buf, sizeof(buf), "%s: %s\n", system.name, msg);
#endif
os::log(buf);
}
void vlogx(LogSeverity::Enum sev, System system, const char* msg, va_list args)
{
ScopedMutex sm(s_mutex);
char buf[2048];
vsnprintf(buf, sizeof(buf), msg, args);
stdout_log(sev, system, buf);
if (console_server())
console_server()->log(sev, system.name, buf);
}
void logx(LogSeverity::Enum sev, System system, const char* msg, ...)
{
va_list args;
va_start(args, msg);
vlogx(sev, system, msg, args);
va_end(args);
}
} // namespace log
} // namespace crown
<|endoftext|> |
<commit_before>//
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "config.h"
#include "core/inspector/InspectorTracingAgent.h"
#include "core/inspector/IdentifiersFactory.h"
#include "core/inspector/InspectorClient.h"
#include "core/inspector/InspectorState.h"
#include "core/inspector/InspectorWorkerAgent.h"
#include "platform/TraceEvent.h"
namespace blink {
namespace TracingAgentState {
const char sessionId[] = "sessionId";
const char tracingStarted[] = "tracingStarted";
}
namespace {
const char devtoolsMetadataEventCategory[] = TRACE_DISABLED_BY_DEFAULT("devtools.timeline");
}
InspectorTracingAgent::InspectorTracingAgent(InspectorClient* client, InspectorWorkerAgent* workerAgent)
: InspectorBaseAgent<InspectorTracingAgent>("Tracing")
, m_layerTreeId(0)
, m_client(client)
, m_frontend(0)
, m_workerAgent(workerAgent)
{
}
void InspectorTracingAgent::restore()
{
emitMetadataEvents();
}
void InspectorTracingAgent::start(ErrorString*, const String& categoryFilter, const String&, const double*, PassRefPtrWillBeRawPtr<StartCallback> callback)
{
if (m_state->getBoolean(TracingAgentState::tracingStarted)) {
callback->sendSuccess();
return;
}
m_state->setString(TracingAgentState::sessionId, IdentifiersFactory::createIdentifier());
m_state->setBoolean(TracingAgentState::tracingStarted, true);
m_client->enableTracing(categoryFilter);
emitMetadataEvents();
callback->sendSuccess();
}
void InspectorTracingAgent::end(ErrorString* errorString, PassRefPtrWillBeRawPtr<EndCallback> callback)
{
m_client->disableTracing();
m_state->setBoolean(TracingAgentState::tracingStarted, false);
m_workerAgent->setTracingSessionId(String());
callback->sendSuccess();
}
String InspectorTracingAgent::sessionId()
{
return m_state->getString(TracingAgentState::sessionId);
}
void InspectorTracingAgent::emitMetadataEvents()
{
if (!m_state->getBoolean(TracingAgentState::tracingStarted))
return;
TRACE_EVENT_INSTANT1(devtoolsMetadataEventCategory, "TracingStartedInPage", "sessionId", sessionId().utf8());
if (m_layerTreeId)
setLayerTreeId(m_layerTreeId);
m_workerAgent->setTracingSessionId(sessionId());
}
void InspectorTracingAgent::setLayerTreeId(int layerTreeId)
{
m_layerTreeId = layerTreeId;
TRACE_EVENT_INSTANT2(devtoolsMetadataEventCategory, "SetLayerTreeId", "sessionId", sessionId().utf8(), "layerTreeId", m_layerTreeId);
}
void InspectorTracingAgent::setFrontend(InspectorFrontend* frontend)
{
m_frontend = frontend->tracing();
}
}
<commit_msg>DevTools: tracing: remove state management from InspectorTracingAgent.<commit_after>//
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "config.h"
#include "core/inspector/InspectorTracingAgent.h"
#include "core/inspector/IdentifiersFactory.h"
#include "core/inspector/InspectorClient.h"
#include "core/inspector/InspectorState.h"
#include "core/inspector/InspectorWorkerAgent.h"
#include "platform/TraceEvent.h"
namespace blink {
namespace TracingAgentState {
const char sessionId[] = "sessionId";
}
namespace {
const char devtoolsMetadataEventCategory[] = TRACE_DISABLED_BY_DEFAULT("devtools.timeline");
}
InspectorTracingAgent::InspectorTracingAgent(InspectorClient* client, InspectorWorkerAgent* workerAgent)
: InspectorBaseAgent<InspectorTracingAgent>("Tracing")
, m_layerTreeId(0)
, m_client(client)
, m_frontend(0)
, m_workerAgent(workerAgent)
{
}
void InspectorTracingAgent::restore()
{
emitMetadataEvents();
}
void InspectorTracingAgent::start(ErrorString*, const String& categoryFilter, const String&, const double*, PassRefPtrWillBeRawPtr<StartCallback> callback)
{
m_state->setString(TracingAgentState::sessionId, IdentifiersFactory::createIdentifier());
m_client->enableTracing(categoryFilter);
emitMetadataEvents();
callback->sendSuccess();
}
void InspectorTracingAgent::end(ErrorString* errorString, PassRefPtrWillBeRawPtr<EndCallback> callback)
{
m_client->disableTracing();
m_workerAgent->setTracingSessionId(String());
callback->sendSuccess();
}
String InspectorTracingAgent::sessionId()
{
return m_state->getString(TracingAgentState::sessionId);
}
void InspectorTracingAgent::emitMetadataEvents()
{
TRACE_EVENT_INSTANT1(devtoolsMetadataEventCategory, "TracingStartedInPage", "sessionId", sessionId().utf8());
if (m_layerTreeId)
setLayerTreeId(m_layerTreeId);
m_workerAgent->setTracingSessionId(sessionId());
}
void InspectorTracingAgent::setLayerTreeId(int layerTreeId)
{
m_layerTreeId = layerTreeId;
TRACE_EVENT_INSTANT2(devtoolsMetadataEventCategory, "SetLayerTreeId", "sessionId", sessionId().utf8(), "layerTreeId", m_layerTreeId);
}
void InspectorTracingAgent::setFrontend(InspectorFrontend* frontend)
{
m_frontend = frontend->tracing();
}
}
<|endoftext|> |
<commit_before>#include <fstream>
#include <iostream>
#include <string>
#include <unordered_map>
#include <cctype>
#include <cstdlib>
#include <cstring>
#include "BibleReferenceParser.h"
#include "MapIO.h"
#include "StringUtil.h"
#include "util.h"
void SplitIntoBookAndChaptersAndVerses(const std::string &bib_ref_candidate, std::string * const book_candidate,
std::string * const chapters_and_verses_candidate)
{
book_candidate->clear();
chapters_and_verses_candidate->clear();
const size_t len(bib_ref_candidate.length());
if (len <= 3)
*book_candidate = bib_ref_candidate;
else if (isdigit(bib_ref_candidate[len - 1])
or (isalpha(bib_ref_candidate[len - 1]) and isdigit(bib_ref_candidate[len - 2])))
{
const size_t last_space_pos(bib_ref_candidate.rfind(' '));
if (last_space_pos == std::string::npos)
*book_candidate = bib_ref_candidate;
else {
*book_candidate = bib_ref_candidate.substr(0, last_space_pos);
*chapters_and_verses_candidate = bib_ref_candidate.substr(last_space_pos + 1);
}
} else
*book_candidate = bib_ref_candidate;
}
void Usage() {
std::cerr << "usage: " << progname << " [--debug] bible_reference_candidate books_of_the_bible_to_code_map\n";
std::cerr << " books_of_the_bible_to_canonical_form_map pericopes_to_codes_map\n";
std::exit(EXIT_FAILURE);
}
int main(int argc, char **argv) {
progname = argv[0];
bool verbose(false);
if (argc == 6) {
if (std::strcmp(argv[1], "--debug") != 0)
Usage();
verbose = true;
++argv, --argc;
}
if (argc != 5)
Usage();
//
// Deal with pericopes first...
//
std::unordered_multimap<std::string, std::string> pericopes_to_codes_map;
MapIO::DeserialiseMap(argv[4], &pericopes_to_codes_map);
std::string bib_ref_candidate(StringUtil::Trim(StringUtil::ToLower(argv[1])));
StringUtil::CollapseWhitespace(&bib_ref_candidate);
const auto begin_end(pericopes_to_codes_map.equal_range(bib_ref_candidate));
if (begin_end.first != begin_end.second) {
if (verbose)
std::cerr << "Found a pericope to codes mapping.\n";
for (auto pair(begin_end.first); pair != begin_end.second; ++pair)
std::cout << pair->second << '\n';
return EXIT_SUCCESS;
}
//
// ...now deal w/ ordinary references.
//
std::string book_candidate, chapters_and_verses_candidate;
SplitIntoBookAndChaptersAndVerses(bib_ref_candidate, &book_candidate, &chapters_and_verses_candidate);
if (verbose) {
std::cerr << "book_candidate = \"" << book_candidate << "\"\n";
std::cerr << "chapters_and_verses_candidate = \"" << chapters_and_verses_candidate << "\"\n";
}
// Map from noncanonical bible book forms to the canonical ones:
std::unordered_map<std::string, std::string> books_of_the_bible_to_canonical_form_map;
MapIO::DeserialiseMap(argv[3], &books_of_the_bible_to_canonical_form_map);
const auto non_canonical_form_and_canonical_form(books_of_the_bible_to_canonical_form_map.find(book_candidate));
if (non_canonical_form_and_canonical_form != books_of_the_bible_to_canonical_form_map.end()) {
if (verbose)
std::cerr << "Replacing \"" << book_candidate << "\" with \""
<< non_canonical_form_and_canonical_form->second << "\".\n";
book_candidate = non_canonical_form_and_canonical_form->second;
}
std::unordered_map<std::string, std::string> bible_books_to_codes_map;
MapIO::DeserialiseMap(argv[2], &bible_books_to_codes_map);
const auto bible_book_and_code(bible_books_to_codes_map.find(book_candidate));
if (bible_book_and_code == bible_books_to_codes_map.end()) {
if (verbose)
std::cerr << "No mapping from \"" << book_candidate << "\" to a book code was found!\n";
return EXIT_FAILURE; // Unknown bible book!
}
const std::string book_code(bible_book_and_code->second);
if (verbose)
std::cerr << "book code = \"" << book_code << "\"\n";
if (chapters_and_verses_candidate.empty()) {
std::cout << book_code << "00000:" << book_code << "99999" << '\n';
return EXIT_SUCCESS;
}
std::set<std::pair<std::string, std::string>> start_end;
if (not ParseBibleReference(chapters_and_verses_candidate, book_code, &start_end)) {
if (verbose)
std::cerr << "The parsing of \"" << chapters_and_verses_candidate
<< "\" as chapters and verses failed!\n";
return EXIT_FAILURE;
}
for (const auto &pair : start_end)
std::cout << pair.first << ':' << pair.second << '\n';
}
<commit_msg>Added the capability, using the new --query flag, to directly emit SOLR queries.<commit_after>#include <fstream>
#include <iostream>
#include <string>
#include <unordered_map>
#include <cctype>
#include <cstdlib>
#include <cstring>
#include "BibleReferenceParser.h"
#include "MapIO.h"
#include "StringUtil.h"
#include "util.h"
void SplitIntoBookAndChaptersAndVerses(const std::string &bib_ref_candidate, std::string * const book_candidate,
std::string * const chapters_and_verses_candidate)
{
book_candidate->clear();
chapters_and_verses_candidate->clear();
const size_t len(bib_ref_candidate.length());
if (len <= 3)
*book_candidate = bib_ref_candidate;
else if (isdigit(bib_ref_candidate[len - 1])
or (isalpha(bib_ref_candidate[len - 1]) and isdigit(bib_ref_candidate[len - 2])))
{
const size_t last_space_pos(bib_ref_candidate.rfind(' '));
if (last_space_pos == std::string::npos)
*book_candidate = bib_ref_candidate;
else {
*book_candidate = bib_ref_candidate.substr(0, last_space_pos);
*chapters_and_verses_candidate = bib_ref_candidate.substr(last_space_pos + 1);
}
} else
*book_candidate = bib_ref_candidate;
}
std::string GenerateQuery(const std::string &lower, const std::string &upper) {
std::string query;
for (unsigned index(1); index < 10; ++index) {
if (not query.empty())
query += " OR ";
const std::string start("bib_ref_start" + std::to_string(index));
const std::string end("bib_ref_end" + std::to_string(index));
query += "(" + start + ":[0000000 TO " + lower + "]" + " AND " + end + ":[" + upper + " TO 9999999])";
}
return query;
}
void Usage() {
std::cerr << "usage: " << progname << " [--debug|--query] bible_reference_candidate\n";
std::cerr << " books_of_the_bible_to_code_map\n";
std::cerr << " books_of_the_bible_to_canonical_form_map pericopes_to_codes_map\n";
std::cerr << '\n';
std::cerr << " When --debug has been specified additional tracing output will be generated.\n";
std::cerr << " When --query has been specified SOLR search queries will be output.\n";
std::exit(EXIT_FAILURE);
}
int main(int argc, char **argv) {
progname = argv[0];
bool verbose(false), generate_solr_query(false);
if (argc == 6) {
if (std::strcmp(argv[1], "--debug") == 0)
verbose = true;
else if (std::strcmp(argv[1], "--query") == 0)
generate_solr_query = true;
else
Usage();
++argv, --argc;
}
if (argc != 5)
Usage();
//
// Deal with pericopes first...
//
std::unordered_multimap<std::string, std::string> pericopes_to_codes_map;
MapIO::DeserialiseMap(argv[4], &pericopes_to_codes_map);
std::string bib_ref_candidate(StringUtil::Trim(StringUtil::ToLower(argv[1])));
StringUtil::CollapseWhitespace(&bib_ref_candidate);
const auto begin_end(pericopes_to_codes_map.equal_range(bib_ref_candidate));
if (begin_end.first != begin_end.second) {
if (verbose)
std::cerr << "Found a pericope to codes mapping.\n";
std::string query;
for (auto pair(begin_end.first); pair != begin_end.second; ++pair) {
if (generate_solr_query) {
if (not query.empty())
query += " OR ";
const size_t colon_pos(pair->second.find(':'));
query += GenerateQuery(pair->second.substr(0, colon_pos), pair->second.substr(colon_pos + 1));
} else
std::cout << pair->second << '\n';
}
if (generate_solr_query)
std::cout << query << '\n';
return EXIT_SUCCESS;
}
//
// ...now deal w/ ordinary references.
//
std::string book_candidate, chapters_and_verses_candidate;
SplitIntoBookAndChaptersAndVerses(bib_ref_candidate, &book_candidate, &chapters_and_verses_candidate);
if (verbose) {
std::cerr << "book_candidate = \"" << book_candidate << "\"\n";
std::cerr << "chapters_and_verses_candidate = \"" << chapters_and_verses_candidate << "\"\n";
}
// Map from noncanonical bible book forms to the canonical ones:
std::unordered_map<std::string, std::string> books_of_the_bible_to_canonical_form_map;
MapIO::DeserialiseMap(argv[3], &books_of_the_bible_to_canonical_form_map);
const auto non_canonical_form_and_canonical_form(books_of_the_bible_to_canonical_form_map.find(book_candidate));
if (non_canonical_form_and_canonical_form != books_of_the_bible_to_canonical_form_map.end()) {
if (verbose)
std::cerr << "Replacing \"" << book_candidate << "\" with \""
<< non_canonical_form_and_canonical_form->second << "\".\n";
book_candidate = non_canonical_form_and_canonical_form->second;
}
std::unordered_map<std::string, std::string> bible_books_to_codes_map;
MapIO::DeserialiseMap(argv[2], &bible_books_to_codes_map);
const auto bible_book_and_code(bible_books_to_codes_map.find(book_candidate));
if (bible_book_and_code == bible_books_to_codes_map.end()) {
if (verbose)
std::cerr << "No mapping from \"" << book_candidate << "\" to a book code was found!\n";
return EXIT_FAILURE; // Unknown bible book!
}
const std::string book_code(bible_book_and_code->second);
if (verbose)
std::cerr << "book code = \"" << book_code << "\"\n";
if (chapters_and_verses_candidate.empty()) {
if (generate_solr_query)
std::cout << GenerateQuery(book_code + "00000", book_code + "99999") << '\n';
else
std::cout << book_code << "00000:" << book_code << "99999" << '\n';
return EXIT_SUCCESS;
}
std::set<std::pair<std::string, std::string>> start_end;
if (not ParseBibleReference(chapters_and_verses_candidate, book_code, &start_end)) {
if (verbose)
std::cerr << "The parsing of \"" << chapters_and_verses_candidate
<< "\" as chapters and verses failed!\n";
return EXIT_FAILURE;
}
std::string query;
for (const auto &pair : start_end) {
if (generate_solr_query) {
if (not query.empty())
query += " OR ";
query += GenerateQuery(pair.first, pair.second);
} else
std::cout << pair.first << ':' << pair.second << '\n';
}
if (generate_solr_query)
std::cout << query << '\n';
}
<|endoftext|> |
<commit_before>
#include <gameplay/GameplayModule.hpp>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <malloc.h>
#include <assert.h>
#include <QApplication>
#include <QFile>
#include <QDir>
#include <QDateTime>
#include <QString>
#include <QMessageBox>
#include <boost/foreach.hpp>
#include "MainWindow.hpp"
#include "Configuration.hpp"
using namespace std;
////BEGIN memory debugging
//static void *(*old_malloc_hook)(size_t, const void *) = 0;
//static void *(*old_realloc_hook)(void *, size_t, const void *) = 0;
//static void (*old_free_hook)(void *, const void *) = 0;
//
//static void *md_malloc(size_t size, const void *caller);
//static void *md_realloc(void *ptr, size_t size, const void *caller);
//static void md_free(void *ptr, const void *caller);
//
//pthread_mutex_t md_mutex = PTHREAD_MUTEX_INITIALIZER;
//
//volatile bool barrier = false;
//
//static void *md_malloc(size_t size, const void *caller)
//{
// pthread_mutex_lock(&md_mutex);
// __malloc_hook = old_malloc_hook;
// __realloc_hook = old_realloc_hook;
// __free_hook = old_free_hook;
// assert(!barrier);
// barrier = true;
// void *result = malloc(size);
// old_malloc_hook = __malloc_hook;
// __malloc_hook = md_malloc;
// __realloc_hook = md_realloc;
// __free_hook = md_free;
// barrier = false;
// pthread_mutex_unlock(&md_mutex);
// return result;
//}
//
//static void *md_realloc(void *ptr, size_t size, const void *caller)
//{
// pthread_mutex_lock(&md_mutex);
// __malloc_hook = old_malloc_hook;
// __realloc_hook = old_realloc_hook;
// __free_hook = old_free_hook;
// assert(!barrier);
// barrier = true;
// assert(size < 1048576 * 100);
// void *result = realloc(ptr, size);
// __malloc_hook = md_malloc;a
// __realloc_hook = md_realloc;
// __free_hook = md_free;
// barrier = false;
// pthread_mutex_unlock(&md_mutex);
// return result;
//}
//
//static void md_free(void *ptr, const void *caller)
//{
// pthread_mutex_lock(&md_mutex);
// __malloc_hook = old_malloc_hook;
// __realloc_hook = old_realloc_hook;
// __free_hook = old_free_hook;
// assert(!barrier);
// barrier = true;
// if (!ptr)
// {
//// printf("Free zero from %p\n", caller);
// } else {
// free(ptr);
// }
// __malloc_hook = md_malloc;
// __realloc_hook = md_realloc;
// __free_hook = md_free;
// barrier = false;
// pthread_mutex_unlock(&md_mutex);
//}
//
//static void md_init_hook()
//{
// old_malloc_hook = __malloc_hook;
// old_realloc_hook = __realloc_hook;
// old_free_hook = __free_hook;
// __malloc_hook = md_malloc;
// __realloc_hook = md_realloc;
// __free_hook = md_free;
// fprintf(stderr, "Memory debugging initialized: %p %p %p\n", old_malloc_hook, old_realloc_hook, old_free_hook);
//}
//
//void (*__malloc_initialize_hook)(void) = md_init_hook;
////END memory debugging
void usage(const char* prog)
{
fprintf(stderr, "usage: %s [options...]\n", prog);
fprintf(stderr, "\t-y: run as the yellow team\n");
fprintf(stderr, "\t-b: run as the blue team\n");
fprintf(stderr, "\t-c <file>: specify the configuration file\n");
fprintf(stderr, "\t-s <seed>: set random seed (hexadecimal)\n");
fprintf(stderr, "\t-p <file>: load playbook\n");
fprintf(stderr, "\t-pp <play>: enable named play\n");
fprintf(stderr, "\t-ng: no goalie\n");
fprintf(stderr, "\t-sim: use simulator\n");
fprintf(stderr, "\t-freq: specify radio frequency (906 or 904)\n");
fprintf(stderr, "\t-nolog: don't write log files\n");
exit(1);
}
int main (int argc, char* argv[])
{
printf("Starting Soccer...\n");
// Seed the large random number generator
long int seed = 0;
int fd = open("/dev/random", O_RDONLY);
if (fd >= 0)
{
if (read(fd, &seed, sizeof(seed)) != sizeof(seed))
{
fprintf(stderr, "Can't read /dev/random, using zero seed: %m\n");
}
close(fd);
} else {
fprintf(stderr, "Can't open /dev/random, using zero seed: %m\n");
}
QApplication app(argc, argv);
bool blueTeam = false;
QString cfgFile;
QString playbook;
vector<const char *> playDirs;
vector<QString> extraPlays;
bool goalie = true;
bool sim = false;
bool log = true;
QString radioFreq;
for (int i=1 ; i<argc; ++i)
{
const char* var = argv[i];
if (strcmp(var, "--help") == 0)
{
usage(argv[0]);
} else if (strcmp(var, "-y") == 0)
{
blueTeam = false;
}
else if (strcmp(var, "-b") == 0)
{
blueTeam = true;
}
else if (strcmp(var, "-ng") == 0)
{
goalie = false;
}
else if (strcmp(var, "-sim") == 0)
{
sim = true;
}
else if (strcmp(var, "-nolog") == 0)
{
log = false;
}
else if(strcmp(var, "-freq") == 0)
{
if(i+1 >= argc)
{
printf("No radio frequency specified after -freq");
usage(argv[0]);
}
i++;
radioFreq = argv[i];
}
else if(strcmp(var, "-c") == 0)
{
if (i+1 >= argc)
{
printf("no config file specified after -c");
usage(argv[0]);
}
i++;
cfgFile = argv[i];
}
else if(strcmp(var, "-s") == 0)
{
if (i+1 >= argc)
{
printf("no seed specified after -s");
usage(argv[0]);
}
i++;
seed = strtol(argv[i], 0, 16);
}
else if(strcmp(var, "-pp") == 0)
{
if (i+1 >= argc)
{
printf("no play specified after -pp");
usage(argv[0]);
}
i++;
extraPlays.push_back(argv[i]);
}
else if(strcmp(var, "-p") == 0)
{
if (i+1 >= argc)
{
printf("no playbook file specified after -p");
usage(argv[0]);
}
i++;
playbook = argv[i];
}
else
{
printf("Not a valid flag: %s\n", argv[i]);
usage(argv[0]);
}
}
printf("Running on %s\n", sim ? "simulation" : "real hardware");
printf("seed %016lx\n", seed);
srand48(seed);
// Default config file name
if (cfgFile.isNull())
{
cfgFile = sim ? "soccer-sim.cfg" : "soccer-real.cfg";
}
Configuration config;
BOOST_FOREACH(Configurable *obj, Configurable::configurables())
{
obj->createConfiguration(&config);
}
Processor *processor = new Processor(sim);
processor->blueTeam(blueTeam);
// Load config file
QString error;
if (!config.load(cfgFile, error))
{
QMessageBox::critical(0, "Soccer",
QString("Can't read initial configuration %1:\n%2").arg(cfgFile, error));
}
MainWindow *win = new MainWindow;
win->configuration(&config);
win->processor(processor);
if (!QDir("logs").exists())
{
fprintf(stderr, "No logs/ directory - not writing log file\n");
} else if (!log)
{
fprintf(stderr, "Not writing log file\n");
} else {
QString logFile = QString("logs/") + QDateTime::currentDateTime().toString("yyyyMMdd-hhmmss.log");
if (!processor->openLog(logFile))
{
printf("Failed to open %s: %m\n", (const char *)logFile.toAscii());
}
}
if(!radioFreq.isEmpty())
{
if(radioFreq == "904")
win->setRadioChannel(RadioChannels::MHz_904);
else if(radioFreq == "906")
win->setRadioChannel(RadioChannels::MHz_906);
else
printf("Cannot recognize radio frequency : %s\n", radioFreq.toStdString().c_str());
}
win->logFileChanged();
processor->start();
win->showMaximized();
processor->gameplayModule()->setupUI();
int ret = app.exec();
processor->stop();
delete win;
delete processor;
return ret;
}
<commit_msg>dont maximize the soccer window<commit_after>
#include <gameplay/GameplayModule.hpp>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <malloc.h>
#include <assert.h>
#include <QApplication>
#include <QFile>
#include <QDir>
#include <QDateTime>
#include <QString>
#include <QMessageBox>
#include <boost/foreach.hpp>
#include "MainWindow.hpp"
#include "Configuration.hpp"
using namespace std;
////BEGIN memory debugging
//static void *(*old_malloc_hook)(size_t, const void *) = 0;
//static void *(*old_realloc_hook)(void *, size_t, const void *) = 0;
//static void (*old_free_hook)(void *, const void *) = 0;
//
//static void *md_malloc(size_t size, const void *caller);
//static void *md_realloc(void *ptr, size_t size, const void *caller);
//static void md_free(void *ptr, const void *caller);
//
//pthread_mutex_t md_mutex = PTHREAD_MUTEX_INITIALIZER;
//
//volatile bool barrier = false;
//
//static void *md_malloc(size_t size, const void *caller)
//{
// pthread_mutex_lock(&md_mutex);
// __malloc_hook = old_malloc_hook;
// __realloc_hook = old_realloc_hook;
// __free_hook = old_free_hook;
// assert(!barrier);
// barrier = true;
// void *result = malloc(size);
// old_malloc_hook = __malloc_hook;
// __malloc_hook = md_malloc;
// __realloc_hook = md_realloc;
// __free_hook = md_free;
// barrier = false;
// pthread_mutex_unlock(&md_mutex);
// return result;
//}
//
//static void *md_realloc(void *ptr, size_t size, const void *caller)
//{
// pthread_mutex_lock(&md_mutex);
// __malloc_hook = old_malloc_hook;
// __realloc_hook = old_realloc_hook;
// __free_hook = old_free_hook;
// assert(!barrier);
// barrier = true;
// assert(size < 1048576 * 100);
// void *result = realloc(ptr, size);
// __malloc_hook = md_malloc;a
// __realloc_hook = md_realloc;
// __free_hook = md_free;
// barrier = false;
// pthread_mutex_unlock(&md_mutex);
// return result;
//}
//
//static void md_free(void *ptr, const void *caller)
//{
// pthread_mutex_lock(&md_mutex);
// __malloc_hook = old_malloc_hook;
// __realloc_hook = old_realloc_hook;
// __free_hook = old_free_hook;
// assert(!barrier);
// barrier = true;
// if (!ptr)
// {
//// printf("Free zero from %p\n", caller);
// } else {
// free(ptr);
// }
// __malloc_hook = md_malloc;
// __realloc_hook = md_realloc;
// __free_hook = md_free;
// barrier = false;
// pthread_mutex_unlock(&md_mutex);
//}
//
//static void md_init_hook()
//{
// old_malloc_hook = __malloc_hook;
// old_realloc_hook = __realloc_hook;
// old_free_hook = __free_hook;
// __malloc_hook = md_malloc;
// __realloc_hook = md_realloc;
// __free_hook = md_free;
// fprintf(stderr, "Memory debugging initialized: %p %p %p\n", old_malloc_hook, old_realloc_hook, old_free_hook);
//}
//
//void (*__malloc_initialize_hook)(void) = md_init_hook;
////END memory debugging
void usage(const char* prog)
{
fprintf(stderr, "usage: %s [options...]\n", prog);
fprintf(stderr, "\t-y: run as the yellow team\n");
fprintf(stderr, "\t-b: run as the blue team\n");
fprintf(stderr, "\t-c <file>: specify the configuration file\n");
fprintf(stderr, "\t-s <seed>: set random seed (hexadecimal)\n");
fprintf(stderr, "\t-p <file>: load playbook\n");
fprintf(stderr, "\t-pp <play>: enable named play\n");
fprintf(stderr, "\t-ng: no goalie\n");
fprintf(stderr, "\t-sim: use simulator\n");
fprintf(stderr, "\t-freq: specify radio frequency (906 or 904)\n");
fprintf(stderr, "\t-nolog: don't write log files\n");
exit(1);
}
int main (int argc, char* argv[])
{
printf("Starting Soccer...\n");
// Seed the large random number generator
long int seed = 0;
int fd = open("/dev/random", O_RDONLY);
if (fd >= 0)
{
if (read(fd, &seed, sizeof(seed)) != sizeof(seed))
{
fprintf(stderr, "Can't read /dev/random, using zero seed: %m\n");
}
close(fd);
} else {
fprintf(stderr, "Can't open /dev/random, using zero seed: %m\n");
}
QApplication app(argc, argv);
bool blueTeam = false;
QString cfgFile;
QString playbook;
vector<const char *> playDirs;
vector<QString> extraPlays;
bool goalie = true;
bool sim = false;
bool log = true;
QString radioFreq;
for (int i=1 ; i<argc; ++i)
{
const char* var = argv[i];
if (strcmp(var, "--help") == 0)
{
usage(argv[0]);
} else if (strcmp(var, "-y") == 0)
{
blueTeam = false;
}
else if (strcmp(var, "-b") == 0)
{
blueTeam = true;
}
else if (strcmp(var, "-ng") == 0)
{
goalie = false;
}
else if (strcmp(var, "-sim") == 0)
{
sim = true;
}
else if (strcmp(var, "-nolog") == 0)
{
log = false;
}
else if(strcmp(var, "-freq") == 0)
{
if(i+1 >= argc)
{
printf("No radio frequency specified after -freq");
usage(argv[0]);
}
i++;
radioFreq = argv[i];
}
else if(strcmp(var, "-c") == 0)
{
if (i+1 >= argc)
{
printf("no config file specified after -c");
usage(argv[0]);
}
i++;
cfgFile = argv[i];
}
else if(strcmp(var, "-s") == 0)
{
if (i+1 >= argc)
{
printf("no seed specified after -s");
usage(argv[0]);
}
i++;
seed = strtol(argv[i], 0, 16);
}
else if(strcmp(var, "-pp") == 0)
{
if (i+1 >= argc)
{
printf("no play specified after -pp");
usage(argv[0]);
}
i++;
extraPlays.push_back(argv[i]);
}
else if(strcmp(var, "-p") == 0)
{
if (i+1 >= argc)
{
printf("no playbook file specified after -p");
usage(argv[0]);
}
i++;
playbook = argv[i];
}
else
{
printf("Not a valid flag: %s\n", argv[i]);
usage(argv[0]);
}
}
printf("Running on %s\n", sim ? "simulation" : "real hardware");
printf("seed %016lx\n", seed);
srand48(seed);
// Default config file name
if (cfgFile.isNull())
{
cfgFile = sim ? "soccer-sim.cfg" : "soccer-real.cfg";
}
Configuration config;
BOOST_FOREACH(Configurable *obj, Configurable::configurables())
{
obj->createConfiguration(&config);
}
Processor *processor = new Processor(sim);
processor->blueTeam(blueTeam);
// Load config file
QString error;
if (!config.load(cfgFile, error))
{
QMessageBox::critical(0, "Soccer",
QString("Can't read initial configuration %1:\n%2").arg(cfgFile, error));
}
MainWindow *win = new MainWindow;
win->configuration(&config);
win->processor(processor);
if (!QDir("logs").exists())
{
fprintf(stderr, "No logs/ directory - not writing log file\n");
} else if (!log)
{
fprintf(stderr, "Not writing log file\n");
} else {
QString logFile = QString("logs/") + QDateTime::currentDateTime().toString("yyyyMMdd-hhmmss.log");
if (!processor->openLog(logFile))
{
printf("Failed to open %s: %m\n", (const char *)logFile.toAscii());
}
}
if(!radioFreq.isEmpty())
{
if(radioFreq == "904")
win->setRadioChannel(RadioChannels::MHz_904);
else if(radioFreq == "906")
win->setRadioChannel(RadioChannels::MHz_906);
else
printf("Cannot recognize radio frequency : %s\n", radioFreq.toStdString().c_str());
}
win->logFileChanged();
processor->start();
win->show();
processor->gameplayModule()->setupUI();
int ret = app.exec();
processor->stop();
delete win;
delete processor;
return ret;
}
<|endoftext|> |
<commit_before>/*
* (C) 2010,2014,2015 Jack Lloyd
* (C) 2015 René Korthaus
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include "cli.h"
#if defined(BOTAN_HAS_PUBLIC_KEY_CRYPTO)
#include <botan/base64.h>
#include <botan/pk_keys.h>
#include <botan/pkcs8.h>
#include <botan/pubkey.h>
#if defined(BOTAN_HAS_DL_GROUP)
#include <botan/dl_group.h>
#endif
#if defined(BOTAN_HAS_RSA)
#include <botan/rsa.h>
#endif
#if defined(BOTAN_HAS_DSA)
#include <botan/dsa.h>
#endif
#if defined(BOTAN_HAS_ECDSA)
#include <botan/ecdsa.h>
#endif
#if defined(BOTAN_HAS_CURVE_25519)
#include <botan/curve25519.h>
#endif
#if defined(BOTAN_HAS_MCELIECE)
#include <botan/mceliece.h>
#endif
namespace Botan_CLI {
class PK_Keygen final : public Command
{
public:
PK_Keygen() : Command("keygen --algo=RSA --params= --passphrase= --pbe= --pbe-millis=300 --der-out") {}
static std::unique_ptr<Botan::Private_Key> do_keygen(const std::string& algo,
const std::string& params,
Botan::RandomNumberGenerator& rng)
{
typedef std::function<std::unique_ptr<Botan::Private_Key> (std::string)> gen_fn;
std::map<std::string, gen_fn> generators;
#if defined(BOTAN_HAS_RSA)
generators["RSA"] = [&rng](std::string param) -> std::unique_ptr<Botan::Private_Key> {
if(param.empty())
param = "2048";
return std::unique_ptr<Botan::Private_Key>(
new Botan::RSA_PrivateKey(rng, Botan::to_u32bit(param)));
};
#endif
#if defined(BOTAN_HAS_DSA)
generators["DSA"] = [&rng](std::string param) -> std::unique_ptr<Botan::Private_Key> {
if(param.empty())
param = "dsa/botan/2048";
return std::unique_ptr<Botan::Private_Key>(
new Botan::DSA_PrivateKey(rng, Botan::DL_Group(param)));
};
#endif
#if defined(BOTAN_HAS_ECDSA)
generators["ECDSA"] = [&rng](std::string param) {
if(param.empty())
param = "secp256r1";
Botan::EC_Group grp(param);
return std::unique_ptr<Botan::Private_Key>(
new Botan::ECDSA_PrivateKey(rng, grp));
};
#endif
#if defined(BOTAN_HAS_CURVE_25519)
generators["Curve25519"] = [&rng](std::string /*ignored*/) {
return std::unique_ptr<Botan::Private_Key>(
new Botan::Curve25519_PrivateKey(rng));
};
#endif
#if defined(BOTAN_HAS_MCELIECE)
generators["McEliece"] = [&rng](std::string param) {
if(param.empty())
param = "2280,45";
std::vector<std::string> param_parts = Botan::split_on(param, ',');
if(param_parts.size() != 2)
throw CLI_Usage_Error("Bad McEliece parameters " + param);
return std::unique_ptr<Botan::Private_Key>(
new Botan::McEliece_PrivateKey(rng,
Botan::to_u32bit(param_parts[0]),
Botan::to_u32bit(param_parts[1])));
};
#endif
auto gen = generators.find(algo);
if(gen == generators.end())
{
throw CLI_Error_Unsupported("keygen", algo);
}
return gen->second(params);
}
void go() override
{
std::unique_ptr<Botan::Private_Key> key(do_keygen(get_arg("algo"), get_arg("params"), rng()));
const std::string pass = get_arg("passphrase");
const bool der_out = flag_set("der-out");
const std::chrono::milliseconds pbe_millis(get_arg_sz("pbe-millis"));
const std::string pbe = get_arg("pbe");
if(der_out)
{
if(pass.empty())
{
write_output(Botan::PKCS8::BER_encode(*key));
}
else
{
write_output(Botan::PKCS8::BER_encode(*key, rng(), pass, pbe_millis, pbe));
}
}
else
{
if(pass.empty())
{
output() << Botan::PKCS8::PEM_encode(*key);
}
else
{
output() << Botan::PKCS8::PEM_encode(*key, rng(), pass, pbe_millis, pbe);
}
}
}
};
BOTAN_REGISTER_COMMAND("keygen", PK_Keygen);
namespace {
std::string algo_default_emsa(const std::string& key)
{
if(key == "RSA")
return "EMSA4"; // PSS
else if(key == "ECDSA" || key == "DSA")
return "EMSA1";
else
return "EMSA1";
}
}
class PK_Sign final : public Command
{
public:
PK_Sign() : Command("sign --passphrase= --hash=SHA-256 --emsa= key file") {}
void go() override
{
std::unique_ptr<Botan::Private_Key> key(Botan::PKCS8::load_key(get_arg("key"),
rng(),
get_arg("passphrase")));
if(!key)
throw CLI_Error("Unable to load private key");
const std::string sig_padding =
get_arg_or("emsa", algo_default_emsa(key->algo_name())) + "(" + get_arg("hash") + ")";
Botan::PK_Signer signer(*key, rng(), sig_padding);
this->read_file(get_arg("file"),
[&signer](const uint8_t b[], size_t l) { signer.update(b, l); });
output() << Botan::base64_encode(signer.signature(rng())) << "\n";
}
};
BOTAN_REGISTER_COMMAND("sign", PK_Sign);
class PK_Verify final : public Command
{
public:
PK_Verify() : Command("verify --hash=SHA-256 --emsa= pubkey file signature") {}
void go() override
{
std::unique_ptr<Botan::Public_Key> key(Botan::X509::load_key(get_arg("pubkey")));
if(!key)
throw CLI_Error("Unable to load public key");
const std::string sig_padding =
get_arg_or("emsa", algo_default_emsa(key->algo_name())) + "(" + get_arg("hash") + ")";
Botan::PK_Verifier verifier(*key, sig_padding);
this->read_file(get_arg("file"),
[&verifier](const uint8_t b[], size_t l) { verifier.update(b, l); });
const Botan::secure_vector<uint8_t> signature =
Botan::base64_decode(this->slurp_file_as_str(get_arg("signature")));
const bool valid = verifier.check_signature(signature);
output() << "Signature is " << (valid ? "valid" : "invalid") << "\n";
}
};
BOTAN_REGISTER_COMMAND("verify", PK_Verify);
#if defined(BOTAN_HAS_DL_GROUP)
class Gen_DL_Group final : public Command
{
public:
Gen_DL_Group() : Command("gen_dl_group --pbits=1024 --qbits=0 --type=subgroup") {}
void go() override
{
const size_t pbits = get_arg_sz("pbits");
const std::string type = get_arg("type");
if(type == "strong")
{
Botan::DL_Group grp(rng(), Botan::DL_Group::Strong, pbits);
output() << grp.PEM_encode(Botan::DL_Group::ANSI_X9_42);
}
else if(type == "subgroup")
{
Botan::DL_Group grp(rng(), Botan::DL_Group::Prime_Subgroup, pbits, get_arg_sz("qbits"));
output() << grp.PEM_encode(Botan::DL_Group::ANSI_X9_42);
}
else
throw CLI_Usage_Error("Invalid DL type '" + type + "'");
}
};
BOTAN_REGISTER_COMMAND("gen_dl_group", Gen_DL_Group);
#endif
class PKCS8_Tool final : public Command
{
public:
PKCS8_Tool() : Command("pkcs8 --pass-in= --pub-out --der-out --pass-out= --pbe= --pbe-millis=300 key") {}
void go() override
{
std::unique_ptr<Botan::Private_Key> key(
Botan::PKCS8::load_key(get_arg("key"),
rng(),
get_arg("pass-in")));
const std::chrono::milliseconds pbe_millis(get_arg_sz("pbe-millis"));
const std::string pbe = get_arg("pbe");
const bool der_out = flag_set("der-out");
if(flag_set("pub-out"))
{
if(der_out)
{
write_output(Botan::X509::BER_encode(*key));
}
else
{
output() << Botan::X509::PEM_encode(*key);
}
}
else
{
const std::string pass = get_arg("pass-out");
if(der_out)
{
if(pass.empty())
{
write_output(Botan::PKCS8::BER_encode(*key));
}
else
{
write_output(Botan::PKCS8::BER_encode(*key, rng(), pass, pbe_millis, pbe));
}
}
else
{
if(pass.empty())
{
output() << Botan::PKCS8::PEM_encode(*key);
}
else
{
output() << Botan::PKCS8::PEM_encode(*key, rng(), pass, pbe_millis, pbe);
}
}
}
}
};
BOTAN_REGISTER_COMMAND("pkcs8", PKCS8_Tool);
}
#endif
<commit_msg>cli: Add dl_group_info cmdlet<commit_after>/*
* (C) 2010,2014,2015 Jack Lloyd
* (C) 2015 René Korthaus
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include "cli.h"
#if defined(BOTAN_HAS_PUBLIC_KEY_CRYPTO)
#include <botan/base64.h>
#include <botan/pk_keys.h>
#include <botan/pkcs8.h>
#include <botan/pubkey.h>
#if defined(BOTAN_HAS_DL_GROUP)
#include <botan/dl_group.h>
#endif
#if defined(BOTAN_HAS_RSA)
#include <botan/rsa.h>
#endif
#if defined(BOTAN_HAS_DSA)
#include <botan/dsa.h>
#endif
#if defined(BOTAN_HAS_ECDSA)
#include <botan/ecdsa.h>
#endif
#if defined(BOTAN_HAS_CURVE_25519)
#include <botan/curve25519.h>
#endif
#if defined(BOTAN_HAS_MCELIECE)
#include <botan/mceliece.h>
#endif
namespace Botan_CLI {
class PK_Keygen final : public Command
{
public:
PK_Keygen() : Command("keygen --algo=RSA --params= --passphrase= --pbe= --pbe-millis=300 --der-out") {}
static std::unique_ptr<Botan::Private_Key> do_keygen(const std::string& algo,
const std::string& params,
Botan::RandomNumberGenerator& rng)
{
typedef std::function<std::unique_ptr<Botan::Private_Key> (std::string)> gen_fn;
std::map<std::string, gen_fn> generators;
#if defined(BOTAN_HAS_RSA)
generators["RSA"] = [&rng](std::string param) -> std::unique_ptr<Botan::Private_Key> {
if(param.empty())
param = "2048";
return std::unique_ptr<Botan::Private_Key>(
new Botan::RSA_PrivateKey(rng, Botan::to_u32bit(param)));
};
#endif
#if defined(BOTAN_HAS_DSA)
generators["DSA"] = [&rng](std::string param) -> std::unique_ptr<Botan::Private_Key> {
if(param.empty())
param = "dsa/botan/2048";
return std::unique_ptr<Botan::Private_Key>(
new Botan::DSA_PrivateKey(rng, Botan::DL_Group(param)));
};
#endif
#if defined(BOTAN_HAS_ECDSA)
generators["ECDSA"] = [&rng](std::string param) {
if(param.empty())
param = "secp256r1";
Botan::EC_Group grp(param);
return std::unique_ptr<Botan::Private_Key>(
new Botan::ECDSA_PrivateKey(rng, grp));
};
#endif
#if defined(BOTAN_HAS_CURVE_25519)
generators["Curve25519"] = [&rng](std::string /*ignored*/) {
return std::unique_ptr<Botan::Private_Key>(
new Botan::Curve25519_PrivateKey(rng));
};
#endif
#if defined(BOTAN_HAS_MCELIECE)
generators["McEliece"] = [&rng](std::string param) {
if(param.empty())
param = "2280,45";
std::vector<std::string> param_parts = Botan::split_on(param, ',');
if(param_parts.size() != 2)
throw CLI_Usage_Error("Bad McEliece parameters " + param);
return std::unique_ptr<Botan::Private_Key>(
new Botan::McEliece_PrivateKey(rng,
Botan::to_u32bit(param_parts[0]),
Botan::to_u32bit(param_parts[1])));
};
#endif
auto gen = generators.find(algo);
if(gen == generators.end())
{
throw CLI_Error_Unsupported("keygen", algo);
}
return gen->second(params);
}
void go() override
{
std::unique_ptr<Botan::Private_Key> key(do_keygen(get_arg("algo"), get_arg("params"), rng()));
const std::string pass = get_arg("passphrase");
const bool der_out = flag_set("der-out");
const std::chrono::milliseconds pbe_millis(get_arg_sz("pbe-millis"));
const std::string pbe = get_arg("pbe");
if(der_out)
{
if(pass.empty())
{
write_output(Botan::PKCS8::BER_encode(*key));
}
else
{
write_output(Botan::PKCS8::BER_encode(*key, rng(), pass, pbe_millis, pbe));
}
}
else
{
if(pass.empty())
{
output() << Botan::PKCS8::PEM_encode(*key);
}
else
{
output() << Botan::PKCS8::PEM_encode(*key, rng(), pass, pbe_millis, pbe);
}
}
}
};
BOTAN_REGISTER_COMMAND("keygen", PK_Keygen);
namespace {
std::string algo_default_emsa(const std::string& key)
{
if(key == "RSA")
return "EMSA4"; // PSS
else if(key == "ECDSA" || key == "DSA")
return "EMSA1";
else
return "EMSA1";
}
}
class PK_Sign final : public Command
{
public:
PK_Sign() : Command("sign --passphrase= --hash=SHA-256 --emsa= key file") {}
void go() override
{
std::unique_ptr<Botan::Private_Key> key(Botan::PKCS8::load_key(get_arg("key"),
rng(),
get_arg("passphrase")));
if(!key)
throw CLI_Error("Unable to load private key");
const std::string sig_padding =
get_arg_or("emsa", algo_default_emsa(key->algo_name())) + "(" + get_arg("hash") + ")";
Botan::PK_Signer signer(*key, rng(), sig_padding);
this->read_file(get_arg("file"),
[&signer](const uint8_t b[], size_t l) { signer.update(b, l); });
output() << Botan::base64_encode(signer.signature(rng())) << "\n";
}
};
BOTAN_REGISTER_COMMAND("sign", PK_Sign);
class PK_Verify final : public Command
{
public:
PK_Verify() : Command("verify --hash=SHA-256 --emsa= pubkey file signature") {}
void go() override
{
std::unique_ptr<Botan::Public_Key> key(Botan::X509::load_key(get_arg("pubkey")));
if(!key)
throw CLI_Error("Unable to load public key");
const std::string sig_padding =
get_arg_or("emsa", algo_default_emsa(key->algo_name())) + "(" + get_arg("hash") + ")";
Botan::PK_Verifier verifier(*key, sig_padding);
this->read_file(get_arg("file"),
[&verifier](const uint8_t b[], size_t l) { verifier.update(b, l); });
const Botan::secure_vector<uint8_t> signature =
Botan::base64_decode(this->slurp_file_as_str(get_arg("signature")));
const bool valid = verifier.check_signature(signature);
output() << "Signature is " << (valid ? "valid" : "invalid") << "\n";
}
};
BOTAN_REGISTER_COMMAND("verify", PK_Verify);
#if defined(BOTAN_HAS_DL_GROUP)
class DL_Group_Info final : public Command
{
public:
DL_Group_Info() : Command("dl_group_info --pem name") {}
void go() override
{
Botan::DL_Group group(get_arg("name"));
if(flag_set("pem"))
{
output() << group.PEM_encode(Botan::DL_Group::X942_DH_PARAMETERS);
}
else
{
output() << "P = " << std::hex << group.get_p() << "\n"
<< "G = " << group.get_g() << "\n";
}
}
};
BOTAN_REGISTER_COMMAND("dl_group_info", DL_Group_Info);
class Gen_DL_Group final : public Command
{
public:
Gen_DL_Group() : Command("gen_dl_group --pbits=1024 --qbits=0 --type=subgroup") {}
void go() override
{
const size_t pbits = get_arg_sz("pbits");
const std::string type = get_arg("type");
if(type == "strong")
{
Botan::DL_Group grp(rng(), Botan::DL_Group::Strong, pbits);
output() << grp.PEM_encode(Botan::DL_Group::ANSI_X9_42);
}
else if(type == "subgroup")
{
Botan::DL_Group grp(rng(), Botan::DL_Group::Prime_Subgroup, pbits, get_arg_sz("qbits"));
output() << grp.PEM_encode(Botan::DL_Group::ANSI_X9_42);
}
else
throw CLI_Usage_Error("Invalid DL type '" + type + "'");
}
};
BOTAN_REGISTER_COMMAND("gen_dl_group", Gen_DL_Group);
#endif
class PKCS8_Tool final : public Command
{
public:
PKCS8_Tool() : Command("pkcs8 --pass-in= --pub-out --der-out --pass-out= --pbe= --pbe-millis=300 key") {}
void go() override
{
std::unique_ptr<Botan::Private_Key> key(
Botan::PKCS8::load_key(get_arg("key"),
rng(),
get_arg("pass-in")));
const std::chrono::milliseconds pbe_millis(get_arg_sz("pbe-millis"));
const std::string pbe = get_arg("pbe");
const bool der_out = flag_set("der-out");
if(flag_set("pub-out"))
{
if(der_out)
{
write_output(Botan::X509::BER_encode(*key));
}
else
{
output() << Botan::X509::PEM_encode(*key);
}
}
else
{
const std::string pass = get_arg("pass-out");
if(der_out)
{
if(pass.empty())
{
write_output(Botan::PKCS8::BER_encode(*key));
}
else
{
write_output(Botan::PKCS8::BER_encode(*key, rng(), pass, pbe_millis, pbe));
}
}
else
{
if(pass.empty())
{
output() << Botan::PKCS8::PEM_encode(*key);
}
else
{
output() << Botan::PKCS8::PEM_encode(*key, rng(), pass, pbe_millis, pbe);
}
}
}
}
};
BOTAN_REGISTER_COMMAND("pkcs8", PKCS8_Tool);
}
#endif
<|endoftext|> |
<commit_before>#include "JSONParser.h"
#include "DiskFile.h"
#include "OS.h"
#include "StringUtils.h"
#include "Assert.h"
#include "Log.h"
namespace crown
{
//--------------------------------------------------------------------------
JSONParser::JSONParser(Allocator& allocator, const char* s) :
m_buffer(s),
m_nodes(allocator)
{
}
//--------------------------------------------------------------------------
JSONParser& JSONParser::root()
{
m_nodes.clear();
List<JSONPair> tmp(default_allocator());
JSON::parse_object(m_buffer, tmp);
JSONNode node;
for (int i = 0; i < tmp.size(); i++)
{
node.type = JSON::type(tmp[i].val);
node.key = tmp[i].key;
node.val = tmp[i].val;
m_nodes.push_back(node);
}
return *this;
}
//--------------------------------------------------------------------------
JSONParser& JSONParser::object(const char* key)
{
bool found = false;
for (int i = 0; i < m_nodes.size(); i++)
{
if (m_nodes[i].type == JT_OBJECT)
{
List<char> str(default_allocator());
JSON::parse_string(m_nodes[i].key, str);
if (string::strcmp(key, str.begin()) == 0)
{
List<JSONPair> obj(default_allocator());
JSON::parse_object(m_nodes[i].val, obj);
m_nodes.clear();
JSONNode node;
for (int j = 0; j < obj.size(); j++)
{
node.type = JSON::type(obj[j].val);
node.key = obj[j].key;
node.val = obj[j].val;
m_nodes.push_back(node);
}
found = true;
break;
}
}
}
CE_ASSERT(found, "Object called %s not found", key);
return *this;
}
//--------------------------------------------------------------------------
JSONParser& JSONParser::array(const char* key, uint32_t index)
{
bool found = false;
for (int i = 0; i < m_nodes.size(); i++)
{
if (m_nodes[i].type == JT_ARRAY)
{
List<char> str(default_allocator());
JSON::parse_string(m_nodes[i].key, str);
if (string::strcmp(key, str.begin()) == 0)
{
List<const char*> arr(default_allocator());
JSON::parse_array(m_nodes[i].val, arr);
m_nodes.clear();
JSONNode node;
node.type = JSON::type(arr[index]);
node.key = NULL;
node.val = arr[index];
m_nodes.push_back(node);
found = true;
break;
}
}
}
CE_ASSERT(found, "Array called %s not found", key);
return *this;
}
//--------------------------------------------------------------------------
const char* JSONParser::string(const char* key, List<char>& str)
{
bool found = false;
for (int i = 0; i < m_nodes.size(); i++)
{
if (JSON::type(m_nodes[i].val) == JT_STRING)
{
List<char> tmp(default_allocator());
JSON::parse_string(m_nodes[i].key, tmp);
if (string::strcmp(key, tmp.begin()) == 0)
{
JSON::parse_string(m_nodes[i].val, str);
found = true;
break;
}
}
}
CE_ASSERT(found, "String not found");
}
//--------------------------------------------------------------------------
double JSONParser::number(const char* key)
{
for (int i = 0; i < m_nodes.size(); i++)
{
if (JSON::type(m_nodes[i].val) == JT_NUMBER)
{
if (m_nodes[i].key == NULL)
{
return JSON::parse_number(m_nodes[i].val);
}
List<char> tmp(default_allocator());
JSON::parse_string(m_nodes[i].key, tmp);
if (string::strcmp(key, tmp.begin()) == 0)
{
return JSON::parse_number(m_nodes[i].val);
}
}
}
CE_ASSERT(found, "Number not found");
}
//--------------------------------------------------------------------------
bool JSONParser::boolean(const char* key)
{
for (int i = 0; i < m_nodes.size(); i++)
{
if (JSON::type(m_nodes[i].val) == JT_BOOL)
{
if (m_nodes[i].key == NULL)
{
return JSON::parse_bool(m_nodes[i].val);
}
List<char> tmp(default_allocator());
JSON::parse_string(m_nodes[i].key, tmp);
if (string::strcmp(key, tmp.begin()) == 0)
{
return JSON::parse_bool(m_nodes[i].val);
}
}
}
CE_ASSERT(found, "Boolean not found");
}
//--------------------------------------------------------------------------
void JSONParser::print_nodes()
{
for (int i = 0; i < m_nodes.size(); i++)
{
Log::i("Index: %d", i);
Log::i("Type : %d", m_nodes[i].type);
Log::i("Key : %s", m_nodes[i].key);
Log::i("Val : %s", m_nodes[i].val);
}
}
} //namespace crown<commit_msg>Make the engine build again<commit_after>#include "JSONParser.h"
#include "DiskFile.h"
#include "OS.h"
#include "StringUtils.h"
#include "Assert.h"
#include "Log.h"
namespace crown
{
//--------------------------------------------------------------------------
JSONParser::JSONParser(Allocator& allocator, const char* s) :
m_buffer(s),
m_nodes(allocator)
{
}
//--------------------------------------------------------------------------
JSONParser& JSONParser::root()
{
m_nodes.clear();
List<JSONPair> tmp(default_allocator());
JSON::parse_object(m_buffer, tmp);
JSONNode node;
for (int i = 0; i < tmp.size(); i++)
{
node.type = JSON::type(tmp[i].val);
node.key = tmp[i].key;
node.val = tmp[i].val;
m_nodes.push_back(node);
}
return *this;
}
//--------------------------------------------------------------------------
JSONParser& JSONParser::object(const char* key)
{
bool found = false;
for (int i = 0; i < m_nodes.size(); i++)
{
if (m_nodes[i].type == JT_OBJECT)
{
List<char> str(default_allocator());
JSON::parse_string(m_nodes[i].key, str);
if (string::strcmp(key, str.begin()) == 0)
{
List<JSONPair> obj(default_allocator());
JSON::parse_object(m_nodes[i].val, obj);
m_nodes.clear();
JSONNode node;
for (int j = 0; j < obj.size(); j++)
{
node.type = JSON::type(obj[j].val);
node.key = obj[j].key;
node.val = obj[j].val;
m_nodes.push_back(node);
}
found = true;
break;
}
}
}
CE_ASSERT(found, "Object called %s not found", key);
return *this;
}
//--------------------------------------------------------------------------
JSONParser& JSONParser::array(const char* key, uint32_t index)
{
bool found = false;
for (int i = 0; i < m_nodes.size(); i++)
{
if (m_nodes[i].type == JT_ARRAY)
{
List<char> str(default_allocator());
JSON::parse_string(m_nodes[i].key, str);
if (string::strcmp(key, str.begin()) == 0)
{
List<const char*> arr(default_allocator());
JSON::parse_array(m_nodes[i].val, arr);
m_nodes.clear();
JSONNode node;
node.type = JSON::type(arr[index]);
node.key = NULL;
node.val = arr[index];
m_nodes.push_back(node);
found = true;
break;
}
}
}
CE_ASSERT(found, "Array called %s not found", key);
return *this;
}
//--------------------------------------------------------------------------
const char* JSONParser::string(const char* key, List<char>& str)
{
bool found = false;
for (int i = 0; i < m_nodes.size(); i++)
{
if (JSON::type(m_nodes[i].val) == JT_STRING)
{
List<char> tmp(default_allocator());
JSON::parse_string(m_nodes[i].key, tmp);
if (string::strcmp(key, tmp.begin()) == 0)
{
JSON::parse_string(m_nodes[i].val, str);
found = true;
break;
}
}
}
CE_ASSERT(found, "String not found");
}
//--------------------------------------------------------------------------
double JSONParser::number(const char* key)
{
for (int i = 0; i < m_nodes.size(); i++)
{
if (JSON::type(m_nodes[i].val) == JT_NUMBER)
{
if (m_nodes[i].key == NULL)
{
return JSON::parse_number(m_nodes[i].val);
}
List<char> tmp(default_allocator());
JSON::parse_string(m_nodes[i].key, tmp);
if (string::strcmp(key, tmp.begin()) == 0)
{
return JSON::parse_number(m_nodes[i].val);
}
}
}
// CE_ASSERT(found, "Number not found");
}
//--------------------------------------------------------------------------
bool JSONParser::boolean(const char* key)
{
for (int i = 0; i < m_nodes.size(); i++)
{
if (JSON::type(m_nodes[i].val) == JT_BOOL)
{
if (m_nodes[i].key == NULL)
{
return JSON::parse_bool(m_nodes[i].val);
}
List<char> tmp(default_allocator());
JSON::parse_string(m_nodes[i].key, tmp);
if (string::strcmp(key, tmp.begin()) == 0)
{
return JSON::parse_bool(m_nodes[i].val);
}
}
}
// CE_ASSERT(found, "Boolean not found");
}
//--------------------------------------------------------------------------
void JSONParser::print_nodes()
{
for (int i = 0; i < m_nodes.size(); i++)
{
Log::i("Index: %d", i);
Log::i("Type : %d", m_nodes[i].type);
Log::i("Key : %s", m_nodes[i].key);
Log::i("Val : %s", m_nodes[i].val);
}
}
} //namespace crown<|endoftext|> |
<commit_before>#define WIN32_LEAN_AND_MEAN
#define STRICT
#define UNICODE
#include <winsock2.h>
#include <shellapi.h>
#include <stdio.h>
#include <time.h>
// int(md5.md5('ibb').hexdigest()[-4:], 16)
const int IBB_PORT = 26830;
int error(const char* msg) {
fprintf(stderr, "ibb *** error: %s\n", msg);
return 1;
}
bool openServerConnection(SOCKET* s) {
*s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (*s == INVALID_SOCKET) {
// TODO: print error code
error("Failed to create socket");
return false;
}
sockaddr_in address;
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr("127.0.0.1");
address.sin_port = htons(IBB_PORT);
int result = connect(*s, reinterpret_cast<sockaddr*>(&address), sizeof(address));
if (result) {
error("Failed to connect to IBB server");
return false;
}
return true;
}
bool startServer() {
WCHAR python_path[MAX_PATH + 1] = {0};
LONG size = sizeof(python_path);
LONG success = RegQueryValueW(
HKEY_LOCAL_MACHINE,
L"SOFTWARE\\Python\\PythonCore\\3.1\\InstallPath",
python_path,
&size);
if (success) {
// TODO: print error
fprintf(stderr, "ibb *** failed to locate Python 3.1\n");
return false;
}
wcsncat(python_path, L"\\python.exe", MAX_PATH);
// TODO: print error code
HINSTANCE result = ShellExecuteW(0, L"open", python_path, L"", NULL, SW_SHOW);
return result > reinterpret_cast<HINSTANCE>(32);
}
void sendString(SOCKET connection, const WCHAR* begin, const WCHAR* end = 0) {
if (!end) {
end = begin + wcslen(begin);
}
// UTF-16 over the wire
send(
connection,
reinterpret_cast<const char*>(begin),
(end - begin) * sizeof(WCHAR),
0);
// TODO: error checking
}
bool sendBuild(SOCKET connection, int argc, const wchar_t* argv[], clock_t start) {
sendString(connection, L"version: 1\n");
sendString(connection, L"cwd: ");
WCHAR current_directory[MAX_PATH] = {0};
GetCurrentDirectoryW(MAX_PATH, current_directory);
sendString(connection, current_directory);
sendString(connection, L"\n");
for (int i = 0; i < argc; ++i) {
sendString(connection, L"arg: ");
sendString(connection, argv[i]);
sendString(connection, L"\n");
}
sendString(connection, L"build\n");
//printf("Build sent in %g seconds\n", float(clock() - start) / CLOCKS_PER_SEC);
//fflush(stdout);
for (;;) {
WCHAR buffer[1024];
int bytes = recv(connection, reinterpret_cast<char*>(buffer), sizeof(buffer), 0);
if (0 == bytes) {
break;
}
if (SOCKET_ERROR == bytes) {
error("Broken connection");
break;
}
wprintf(L"%*s", bytes / sizeof(WCHAR), buffer);
}
//printf("Result recieved in %g seconds\n", float(clock() - start) / CLOCKS_PER_SEC);
//fflush(stdout);
return true;
}
int wmain(int argc, const wchar_t* argv[]) {
clock_t start = clock();
WSADATA wsadata;
if (0 != WSAStartup(2, &wsadata)) {
return error("Failed to initialize winsock");
}
struct cleanup_t {
cleanup_t() {}
~cleanup_t() { WSACleanup(); }
} cleanup;
//printf("Started winsock in %g seconds\n", float(clock() - start) / CLOCKS_PER_SEC);
//fflush(stdout);
SOCKET connection;
if (!openServerConnection(&connection)) {
if (!startServer()) {
return error("Failed to start server");
}
if (!openServerConnection(&connection)) {
return error("Failed to connect to server");
}
}
//printf("Opened connection in %g seconds\n", float(clock() - start) / CLOCKS_PER_SEC);
//fflush(stdout);
if (!sendBuild(connection, argc, argv, start)) {
return error("Failed to submit build");
}
closesocket(connection);
//printf("Socket closed in %g seconds\n", float(clock() - start) / CLOCKS_PER_SEC);
//fflush(stdout);
return 0;
}
// hack around mingw's lack of wmain support
int main() {
int argc;
WCHAR** argv = CommandLineToArgvW(
GetCommandLineW(),
&argc);
return wmain(argc, const_cast<const wchar_t**>(argv));
}
<commit_msg>Actually start the build server if ibb.exe detects that it's not running.<commit_after>#define WIN32_LEAN_AND_MEAN
#define STRICT
#define UNICODE
#include <winsock2.h>
#include <shellapi.h>
#include <stdio.h>
#include <time.h>
// int(md5.md5('ibb').hexdigest()[-4:], 16)
const int IBB_PORT = 26830;
int error(const char* msg) {
fprintf(stderr, "ibb *** error: %s\n", msg);
return 1;
}
bool openServerConnection(SOCKET* s) {
*s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (*s == INVALID_SOCKET) {
// TODO: print error code
error("Failed to create socket");
return false;
}
sockaddr_in address;
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr("127.0.0.1");
address.sin_port = htons(IBB_PORT);
int result = connect(*s, reinterpret_cast<sockaddr*>(&address), sizeof(address));
if (result) {
error("Failed to connect to IBB server");
return false;
}
return true;
}
bool startServer() {
WCHAR python_path[MAX_PATH + 1] = {0};
LONG size = sizeof(python_path);
LONG success = RegQueryValueW(
HKEY_LOCAL_MACHINE,
L"SOFTWARE\\Python\\PythonCore\\3.1\\InstallPath",
python_path,
&size);
if (success) {
// TODO: print error
fprintf(stderr, "ibb *** failed to locate Python 3.1\n");
return false;
}
// TODO: use safe strings
wcsncat(python_path, L"\\python.exe", MAX_PATH);
WCHAR executable_path[MAX_PATH * 2];
DWORD length = GetModuleFileNameW(GetModuleHandle(NULL), executable_path, MAX_PATH);
if (length == 0 || length == MAX_PATH) {
fprintf(stderr, "ibb *** failed to get executable path\n");
return false;
}
wchar_t* last_slash = wcsrchr(executable_path, '\\');
if (last_slash) {
*last_slash = 0;
}
wcsncat(executable_path, L"\\src\\ibb.py", MAX_PATH * 2);
// TODO: use CreateProcess instead of ShellExecute
// TODO: print error code
HINSTANCE result = ShellExecuteW(0, L"open", python_path, executable_path, NULL, SW_SHOW);
return result > reinterpret_cast<HINSTANCE>(32);
}
void sendString(SOCKET connection, const WCHAR* begin, const WCHAR* end = 0) {
if (!end) {
end = begin + wcslen(begin);
}
// UTF-16 over the wire
send(
connection,
reinterpret_cast<const char*>(begin),
(end - begin) * sizeof(WCHAR),
0);
// TODO: error checking
}
bool sendBuild(SOCKET connection, int argc, const wchar_t* argv[], clock_t start) {
sendString(connection, L"version: 1\n");
sendString(connection, L"cwd: ");
WCHAR current_directory[MAX_PATH] = {0};
GetCurrentDirectoryW(MAX_PATH, current_directory);
sendString(connection, current_directory);
sendString(connection, L"\n");
for (int i = 0; i < argc; ++i) {
sendString(connection, L"arg: ");
sendString(connection, argv[i]);
sendString(connection, L"\n");
}
sendString(connection, L"build\n");
//printf("Build sent in %g seconds\n", float(clock() - start) / CLOCKS_PER_SEC);
//fflush(stdout);
for (;;) {
WCHAR buffer[1024];
int bytes = recv(connection, reinterpret_cast<char*>(buffer), sizeof(buffer), 0);
if (0 == bytes) {
break;
}
if (SOCKET_ERROR == bytes) {
error("Broken connection");
break;
}
wprintf(L"%*s", bytes / sizeof(WCHAR), buffer);
}
//printf("Result recieved in %g seconds\n", float(clock() - start) / CLOCKS_PER_SEC);
//fflush(stdout);
return true;
}
int wmain(int argc, const wchar_t* argv[]) {
clock_t start = clock();
WSADATA wsadata;
if (0 != WSAStartup(2, &wsadata)) {
return error("Failed to initialize winsock");
}
struct cleanup_t {
cleanup_t() {}
~cleanup_t() { WSACleanup(); }
} cleanup;
//printf("Started winsock in %g seconds\n", float(clock() - start) / CLOCKS_PER_SEC);
//fflush(stdout);
SOCKET connection;
if (!openServerConnection(&connection)) {
if (!startServer()) {
return error("Failed to start server");
}
if (!openServerConnection(&connection)) {
return error("Failed to connect to server");
}
}
//printf("Opened connection in %g seconds\n", float(clock() - start) / CLOCKS_PER_SEC);
//fflush(stdout);
if (!sendBuild(connection, argc, argv, start)) {
return error("Failed to submit build");
}
closesocket(connection);
//printf("Socket closed in %g seconds\n", float(clock() - start) / CLOCKS_PER_SEC);
//fflush(stdout);
return 0;
}
// hack around mingw's lack of wmain support
int main() {
int argc;
WCHAR** argv = CommandLineToArgvW(
GetCommandLineW(),
&argc);
return wmain(argc, const_cast<const wchar_t**>(argv));
}
<|endoftext|> |
<commit_before>#include "partners_api/rutaxi_api.hpp"
#include "platform/http_client.hpp"
#include "platform/platform.hpp"
#include "geometry/latlon.hpp"
#include "geometry/mercator.hpp"
#include "coding/url_encode.hpp"
#include "base/logging.hpp"
#include "base/string_utils.hpp"
#include "std/target_os.hpp"
#include <iomanip>
#include <memory>
#include <sstream>
#include <utility>
#include "3party/jansson/myjansson.hpp"
#include "private.h"
namespace
{
std::string const kMappingFilepath = "taxi_places/osm_to_rutaxi.json";
std::string const kArrivalTimeSeconds = "300";
bool RunSimpleHttpRequest(std::string const & url, std::string const & data, std::string & result)
{
platform::HttpClient request(url);
request.SetTimeout(10.0);
if (!data.empty())
request.SetBodyData(data, "application/json");
request.SetRawHeader("Accept", "application/json");
request.SetRawHeader("X-Parse-Application-Id", std::string("App ") + RUTAXI_APP_TOKEN);
return request.RunHttpRequest(result);
}
} // namespace
namespace taxi
{
namespace rutaxi
{
std::string const kTaxiInfoUrl = "https://api.rutaxi.ru/api/1.0.0/";
// static
bool RawApi::GetNearObject(ms::LatLon const & pos, std::string const & city, std::string & result,
std::string const & baseUrl /* = kTaxiInfoUrl */)
{
std::ostringstream data;
data << R"({"latitude": )" << pos.lat << R"(, "longitude": )" << pos.lon << R"(, "city": ")"
<< city << R"("})";
return RunSimpleHttpRequest(baseUrl + "near/", data.str(), result);
}
// static
bool RawApi::GetCost(Object const & from, Object const & to, std::string const & city,
std::string & result, std::string const & baseUrl /* = kTaxiInfoUrl */)
{
std::ostringstream data;
data << R"({"city": ")" << city << R"(", "Order": {"points": [{"object_id": )" << from.m_id
<< R"(, "house": ")" << from.m_house << R"("}, {"object_id": )" << to.m_id
<< R"(, "house": ")" << to.m_house << R"("}]}})";
return RunSimpleHttpRequest(baseUrl + "cost/", data.str(), result);
}
Api::Api(std::string const & baseUrl /* = kTaxiInfoUrl */)
: ApiBase(baseUrl)
, m_cityMapping(LoadCityMapping())
{
}
void Api::SetDelegate(Delegate * delegate)
{
m_delegate = delegate;
}
void Api::GetAvailableProducts(ms::LatLon const & from, ms::LatLon const & to,
ProductsCallback const & successFn,
ErrorProviderCallback const & errorFn)
{
ASSERT(successFn, ());
ASSERT(errorFn, ());
ASSERT(m_delegate, ());
auto const fromCity = m_delegate->GetCityName(MercatorBounds::FromLatLon(from));
auto const toCity = m_delegate->GetCityName(MercatorBounds::FromLatLon(to));
auto const cityIdIt = m_cityMapping.find(toCity);
// TODO(a): Add ErrorCode::FarDistance and provide this error code.
if (fromCity != toCity || cityIdIt == m_cityMapping.cend() || !IsDistanceSupported(from, to))
{
errorFn(ErrorCode::NoProducts);
return;
}
auto const baseUrl = m_baseUrl;
auto const & city = cityIdIt->second;
GetPlatform().RunTask(Platform::Thread::Network, [from, to, city, baseUrl, successFn, errorFn]()
{
auto const getNearObject = [&city, &baseUrl, &errorFn](ms::LatLon const & pos, Object & dst)
{
std::string httpResult;
if (!RawApi::GetNearObject(pos, city.m_id, httpResult, baseUrl))
{
errorFn(ErrorCode::RemoteError);
return false;
}
try
{
MakeNearObject(httpResult, dst);
}
catch (base::Json::Exception const & e)
{
errorFn(ErrorCode::NoProducts);
LOG(LERROR, (e.what(), httpResult));
return false;
}
return true;
};
Object fromObj;
Object toObj;
if (!getNearObject(from, fromObj) || !getNearObject(to, toObj))
return;
std::string result;
if (!RawApi::GetCost(fromObj, toObj, city.m_id, result, baseUrl))
{
errorFn(ErrorCode::RemoteError);
return;
}
std::vector<Product> products;
try
{
MakeProducts(result, fromObj, toObj, city, products);
}
catch (base::Json::Exception const & e)
{
LOG(LERROR, (e.what(), result));
products.clear();
}
if (products.empty())
errorFn(ErrorCode::NoProducts);
else
successFn(products);
});
}
/// Returns link which allows you to launch the RuTaxi app.
RideRequestLinks Api::GetRideRequestLinks(std::string const & productId, ms::LatLon const & from,
ms::LatLon const & to) const
{
return {"rto://order.rutaxi.ru/a.php?" + productId, "https://go.onelink.me/757212956/mapsmevezet"};
}
void MakeNearObject(std::string const & src, Object & dst)
{
base::Json root(src.c_str());
auto const data = json_object_get(root.get(), "data");
auto const objects = json_object_get(data, "objects");
auto const item = json_array_get(objects, 0);
FromJSONObject(item, "id", dst.m_id);
FromJSONObject(item, "house", dst.m_house);
FromJSONObject(item, "name", dst.m_title);
}
void MakeProducts(std::string const & src, Object const & from, Object const & to,
City const & city, std::vector<taxi::Product> & products)
{
products.clear();
base::Json root(src.c_str());
std::ostringstream productStream;
productStream << "city=" << city.m_id << "&title1=" << UrlEncode(from.m_title)
<< "&ob1=" << from.m_id << "&h1=" << UrlEncode(from.m_house)
<< "&title2=" << UrlEncode(to.m_title) << "&ob2=" << to.m_id
<< "&h2=" << UrlEncode(to.m_house);
taxi::Product product;
product.m_productId = productStream.str();
product.m_currency = city.m_currency;
product.m_time = kArrivalTimeSeconds;
auto const data = json_object_get(root.get(), "data");
FromJSONObject(data, "cost", product.m_price);
products.emplace_back(std::move(product));
}
CityMapping LoadCityMapping()
{
std::string fileData;
try
{
auto const fileReader = GetPlatform().GetReader(kMappingFilepath);
fileReader->ReadAsString(fileData);
}
catch (FileAbsentException const & ex)
{
LOG(LERROR, ("Exception while get reader for file:", kMappingFilepath, "reason:", ex.what()));
return {};
}
catch (FileReader::Exception const & ex)
{
LOG(LERROR, ("Exception while reading file:", kMappingFilepath, "reason:", ex.what()));
return {};
}
ASSERT(!fileData.empty(), ());
CityMapping result;
try
{
base::Json root(fileData.c_str());
auto const count = json_array_size(root.get());
std::string osmName;
City city;
for (size_t i = 0; i < count; ++i)
{
auto const item = json_array_get(root.get(), i);
FromJSONObject(item, "osm", osmName);
FromJSONObject(item, "rutaxi", city.m_id);
FromJSONObject(item, "currency", city.m_currency);
result.emplace(osmName, city);
}
}
catch (base::Json::Exception const & ex)
{
LOG(LWARNING, ("Exception while parsing file:", kMappingFilepath, "reason:", ex.what(),
"json:", fileData));
return {};
}
return result;
}
} // namespace rutaxi
} // namespace taxi
<commit_msg>Fixed Taxi Vezet URL scheme<commit_after>#include "partners_api/rutaxi_api.hpp"
#include "platform/http_client.hpp"
#include "platform/platform.hpp"
#include "geometry/latlon.hpp"
#include "geometry/mercator.hpp"
#include "coding/url_encode.hpp"
#include "base/logging.hpp"
#include "base/string_utils.hpp"
#include "std/target_os.hpp"
#include <iomanip>
#include <memory>
#include <sstream>
#include <utility>
#include "3party/jansson/myjansson.hpp"
#include "private.h"
namespace
{
std::string const kMappingFilepath = "taxi_places/osm_to_rutaxi.json";
std::string const kArrivalTimeSeconds = "300";
bool RunSimpleHttpRequest(std::string const & url, std::string const & data, std::string & result)
{
platform::HttpClient request(url);
request.SetTimeout(10.0);
if (!data.empty())
request.SetBodyData(data, "application/json");
request.SetRawHeader("Accept", "application/json");
request.SetRawHeader("X-Parse-Application-Id", std::string("App ") + RUTAXI_APP_TOKEN);
return request.RunHttpRequest(result);
}
} // namespace
namespace taxi
{
namespace rutaxi
{
std::string const kTaxiInfoUrl = "https://api.rutaxi.ru/api/1.0.0/";
// static
bool RawApi::GetNearObject(ms::LatLon const & pos, std::string const & city, std::string & result,
std::string const & baseUrl /* = kTaxiInfoUrl */)
{
std::ostringstream data;
data << R"({"latitude": )" << pos.lat << R"(, "longitude": )" << pos.lon << R"(, "city": ")"
<< city << R"("})";
return RunSimpleHttpRequest(baseUrl + "near/", data.str(), result);
}
// static
bool RawApi::GetCost(Object const & from, Object const & to, std::string const & city,
std::string & result, std::string const & baseUrl /* = kTaxiInfoUrl */)
{
std::ostringstream data;
data << R"({"city": ")" << city << R"(", "Order": {"points": [{"object_id": )" << from.m_id
<< R"(, "house": ")" << from.m_house << R"("}, {"object_id": )" << to.m_id
<< R"(, "house": ")" << to.m_house << R"("}]}})";
return RunSimpleHttpRequest(baseUrl + "cost/", data.str(), result);
}
Api::Api(std::string const & baseUrl /* = kTaxiInfoUrl */)
: ApiBase(baseUrl)
, m_cityMapping(LoadCityMapping())
{
}
void Api::SetDelegate(Delegate * delegate)
{
m_delegate = delegate;
}
void Api::GetAvailableProducts(ms::LatLon const & from, ms::LatLon const & to,
ProductsCallback const & successFn,
ErrorProviderCallback const & errorFn)
{
ASSERT(successFn, ());
ASSERT(errorFn, ());
ASSERT(m_delegate, ());
auto const fromCity = m_delegate->GetCityName(MercatorBounds::FromLatLon(from));
auto const toCity = m_delegate->GetCityName(MercatorBounds::FromLatLon(to));
auto const cityIdIt = m_cityMapping.find(toCity);
// TODO(a): Add ErrorCode::FarDistance and provide this error code.
if (fromCity != toCity || cityIdIt == m_cityMapping.cend() || !IsDistanceSupported(from, to))
{
errorFn(ErrorCode::NoProducts);
return;
}
auto const baseUrl = m_baseUrl;
auto const & city = cityIdIt->second;
GetPlatform().RunTask(Platform::Thread::Network, [from, to, city, baseUrl, successFn, errorFn]()
{
auto const getNearObject = [&city, &baseUrl, &errorFn](ms::LatLon const & pos, Object & dst)
{
std::string httpResult;
if (!RawApi::GetNearObject(pos, city.m_id, httpResult, baseUrl))
{
errorFn(ErrorCode::RemoteError);
return false;
}
try
{
MakeNearObject(httpResult, dst);
}
catch (base::Json::Exception const & e)
{
errorFn(ErrorCode::NoProducts);
LOG(LERROR, (e.what(), httpResult));
return false;
}
return true;
};
Object fromObj;
Object toObj;
if (!getNearObject(from, fromObj) || !getNearObject(to, toObj))
return;
std::string result;
if (!RawApi::GetCost(fromObj, toObj, city.m_id, result, baseUrl))
{
errorFn(ErrorCode::RemoteError);
return;
}
std::vector<Product> products;
try
{
MakeProducts(result, fromObj, toObj, city, products);
}
catch (base::Json::Exception const & e)
{
LOG(LERROR, (e.what(), result));
products.clear();
}
if (products.empty())
errorFn(ErrorCode::NoProducts);
else
successFn(products);
});
}
/// Returns link which allows you to launch the RuTaxi app.
RideRequestLinks Api::GetRideRequestLinks(std::string const & productId, ms::LatLon const & from,
ms::LatLon const & to) const
{
return {"vzt://order.rutaxi.ru/a.php?" + productId, "https://go.onelink.me/757212956/mapsmevezet"};
}
void MakeNearObject(std::string const & src, Object & dst)
{
base::Json root(src.c_str());
auto const data = json_object_get(root.get(), "data");
auto const objects = json_object_get(data, "objects");
auto const item = json_array_get(objects, 0);
FromJSONObject(item, "id", dst.m_id);
FromJSONObject(item, "house", dst.m_house);
FromJSONObject(item, "name", dst.m_title);
}
void MakeProducts(std::string const & src, Object const & from, Object const & to,
City const & city, std::vector<taxi::Product> & products)
{
products.clear();
base::Json root(src.c_str());
std::ostringstream productStream;
productStream << "city=" << city.m_id << "&title1=" << UrlEncode(from.m_title)
<< "&ob1=" << from.m_id << "&h1=" << UrlEncode(from.m_house)
<< "&title2=" << UrlEncode(to.m_title) << "&ob2=" << to.m_id
<< "&h2=" << UrlEncode(to.m_house);
taxi::Product product;
product.m_productId = productStream.str();
product.m_currency = city.m_currency;
product.m_time = kArrivalTimeSeconds;
auto const data = json_object_get(root.get(), "data");
FromJSONObject(data, "cost", product.m_price);
products.emplace_back(std::move(product));
}
CityMapping LoadCityMapping()
{
std::string fileData;
try
{
auto const fileReader = GetPlatform().GetReader(kMappingFilepath);
fileReader->ReadAsString(fileData);
}
catch (FileAbsentException const & ex)
{
LOG(LERROR, ("Exception while get reader for file:", kMappingFilepath, "reason:", ex.what()));
return {};
}
catch (FileReader::Exception const & ex)
{
LOG(LERROR, ("Exception while reading file:", kMappingFilepath, "reason:", ex.what()));
return {};
}
ASSERT(!fileData.empty(), ());
CityMapping result;
try
{
base::Json root(fileData.c_str());
auto const count = json_array_size(root.get());
std::string osmName;
City city;
for (size_t i = 0; i < count; ++i)
{
auto const item = json_array_get(root.get(), i);
FromJSONObject(item, "osm", osmName);
FromJSONObject(item, "rutaxi", city.m_id);
FromJSONObject(item, "currency", city.m_currency);
result.emplace(osmName, city);
}
}
catch (base::Json::Exception const & ex)
{
LOG(LWARNING, ("Exception while parsing file:", kMappingFilepath, "reason:", ex.what(),
"json:", fileData));
return {};
}
return result;
}
} // namespace rutaxi
} // namespace taxi
<|endoftext|> |
<commit_before>
// Copyright **********************************************************
//
// IBM Confidential
// OCO Source Materials
// 9400 Licensed Internal Code
// (C) COPYRIGHT IBM CORP. 2003
//
// The source code for this program is not published or otherwise
// divested of its trade secrets, irrespective of what has been
// deposited with the U.S. Copyright Office.
//
// End Copyright ******************************************************
//--------------------------------------------------------------------
// Includes
//--------------------------------------------------------------------
#include <string.h>
#include <stdio.h>
#include <ecmdClientCapi.H>
#include <ecmdDataBuffer.H>
#include <ecmdReturnCodes.H>
#include <ecmdUtils.H>
#include <ecmdClientPerlapi.H>
#include <ecmdSharedUtils.H>
static int myErrorCode = ECMD_SUCCESS;
int ecmdPerlInterfaceErrorCheck (int errorCode) {
if (errorCode == -1) {
errorCode = myErrorCode;
myErrorCode = ECMD_SUCCESS;
if (errorCode != ECMD_SUCCESS) {
::ecmdOutputError( (::ecmdGetErrorMsg(errorCode) + "\n").c_str());
}
return errorCode;
}
else if (errorCode != ECMD_SUCCESS) {
myErrorCode = errorCode;
}
return ECMD_SUCCESS;
}
ecmdClientPerlapi::ecmdClientPerlapi () {
perlFormat = "b";
}
ecmdClientPerlapi::~ecmdClientPerlapi () {
this->cleanup();
}
void ecmdClientPerlapi::cleanup() {
ecmdUnloadDll();
}
int ecmdClientPerlapi::initDll (const char * i_dllName, const char * i_options) {
int rc = ECMD_SUCCESS;
std::string dllName = "";
if (i_dllName != NULL) {
dllName = i_dllName;
}
rc = ecmdLoadDll(dllName);
ecmdPerlInterfaceErrorCheck(rc);
return rc;
}
int ecmdClientPerlapi::getScom (const char* i_target, int i_address, char** o_data) {
/* char * ecmdClientPerlapi::getScom (const char * i_target, int i_address) { */
ecmdChipTarget myTarget;
std::string dataStr;
int rc = setupTarget(i_target, myTarget);
ecmdPerlInterfaceErrorCheck(rc);
if (rc) {
*o_data = NULL;
return rc;
}
ecmdDataBuffer buffer;
rc = ::getScom(myTarget, i_address, buffer);
ecmdPerlInterfaceErrorCheck(rc);
if (rc) {
o_data = NULL;
return rc;
}
dataStr = buffer.genBinStr();
char* tmp;
tmp = new char[dataStr.length()+1];
strcpy(tmp,dataStr.c_str());
*o_data = tmp;
/* o_data = dataStr; */
/* return (char*)(dataStr.c_str());*/
return rc;
}
int ecmdClientPerlapi::putScom (const char * i_target, int i_address, const char * i_data) {
ecmdChipTarget myTarget;
std::string dataStr;
std::string myFormat;
int rc = setupTarget(i_target, myTarget);
if (rc) return rc;
ecmdDataBuffer buffer;
myFormat = "b";
rc = ecmdReadDataFormatted(buffer, i_data, myFormat);
ecmdPerlInterfaceErrorCheck(rc);
if (rc) return rc;
rc = ::putScom(myTarget, i_address, buffer);
ecmdPerlInterfaceErrorCheck(rc);
return rc;
}
int ecmdClientPerlapi::getRing (const char * i_target, const char * i_ringName, char **o_data) {
int rc = 0;
ecmdDataBuffer buffer;
ecmdChipTarget myTarget;
rc = setupTarget(i_target, myTarget);
ecmdPerlInterfaceErrorCheck(rc);
if (rc) return rc;
rc = ::getRing(myTarget, i_ringName, buffer);
ecmdPerlInterfaceErrorCheck(rc);
if (rc) return rc;
*o_data = (char*)malloc(buffer.getBitLength()+1);
strcpy(*o_data,ecmdWriteDataFormatted(buffer, perlFormat).c_str());
return rc;
}
int ecmdClientPerlapi::putRing (const char * i_target, const char * i_ringName, const char * i_data) {
ecmdChipTarget myTarget;
std::string myFormat = "b";
int rc = setupTarget(i_target, myTarget);
ecmdPerlInterfaceErrorCheck(rc);
if (rc) return rc;
ecmdDataBuffer buffer;
rc = ecmdReadDataFormatted(buffer, i_data, myFormat);
ecmdPerlInterfaceErrorCheck(rc);
if (rc) return rc;
rc = ::putRing(myTarget, i_ringName, buffer);
ecmdPerlInterfaceErrorCheck(rc);
return rc;
}
/***
void ecmdClientPerlapi::add(char *retval) {
printf("Inside function: %c %c %c\n",retval[0],retval[1],retval[2]);
retval[0] = 'L'; retval[1] = 'p';
strcpy(retval,"Looky here - I made it");
}
void ecmdClientPerlapi::add2(char **retval) {
printf("Inside function: %s\n",*retval);
*retval = (char*)malloc(sizeof (char[100]));
strcpy(*retval,"Looky here - I made it");
}
***/
int ecmdClientPerlapi::setupTarget (const char * i_targetStr, ecmdChipTarget & o_target) {
int rc = ECMD_SUCCESS;
std::string printed;
if (i_targetStr == NULL) {
ecmdOutputError("ecmdClientPerlapi::setupTarget - It appears the target string is null\n");
return ECMD_INVALID_ARGS;
}
std::vector<std::string> tokens;
ecmdParseTokens(i_targetStr, " ,.", tokens);
/* Set our initial states */
o_target.cage = o_target.node = o_target.slot = o_target.pos = o_target.core = o_target.thread = 0;
o_target.cageState = o_target.nodeState = o_target.slotState = o_target.posState = o_target.coreState = o_target.threadState = ECMD_TARGET_FIELD_VALID;
o_target.chipTypeState = ECMD_TARGET_FIELD_UNUSED;
for (std::vector<std::string>::iterator tokit = tokens.begin(); tokit != tokens.end(); tokit ++) {
if ((*tokit)[0] == '-') {
switch((*tokit)[1]) {
case 'k': case 'K':
o_target.cage = atoi(tokit->substr(2,20).c_str());
break;
case 'n': case 'N':
o_target.node = atoi(tokit->substr(2,20).c_str());
break;
case 's': case 'S':
o_target.slot = atoi(tokit->substr(2,20).c_str());
break;
case 'p': case 'P':
o_target.pos = atoi(tokit->substr(2,20).c_str());
break;
case 'c': case 'C':
o_target.core = atoi(tokit->substr(2,20).c_str());
break;
case 't': case 'T':
o_target.thread = atoi(tokit->substr(2,20).c_str());
break;
default:
ecmdOutputError((((printed = "ecmdClientPerlapi::setupTarget - It appears the target string contained an invalid target parm : ") + i_targetStr) + "\n").c_str());
return ECMD_INVALID_ARGS;
}
} else {
/* If the first char is a digit then they must have specified a p1..3 or p1,4 and we tokenized it above, this is not good */
if (isdigit((*tokit)[0])) {
ecmdOutputError((((printed = "ecmdClientPerlapi::setupTarget - It appears the target string contained a range or multiple positions : ") + i_targetStr) + "\n").c_str());
return ECMD_INVALID_ARGS;
} else if (o_target.chipTypeState == ECMD_TARGET_FIELD_VALID) {
ecmdOutputError((((printed = "ecmdClientPerlapi::setupTarget - It appears the target string contained multiple chip names : ") + i_targetStr) + "\n").c_str());
return ECMD_INVALID_ARGS;
}
o_target.chipTypeState = ECMD_TARGET_FIELD_VALID;
o_target.chipType = *tokit;
}
}
return rc;
}
int ecmdClientPerlapi::ecmdCommandArgs(char** i_argv[]){
return 0;
}
/***
int ecmdClientPerlapi::ecmdCommandArgs(int* i_argc, char** i_argv[]) {
return 0;
}
***/
int ecmdClientPerlapi::sendCmd(const char* i_target, int i_instruction, int i_modifier, char** o_status) {
return 0;
}
int ecmdClientPerlapi::getCfamRegister (const char* i_target, int i_address, char** o_data){
return 0;
}
int ecmdClientPerlapi::putCfamRegister (const char* i_target, int i_address, const char* i_data){
return 0;
}
int ecmdClientPerlapi::getSpy (const char* i_target, const char * i_spyName, char** o_data){
return 0;
}
int ecmdClientPerlapi::getSpyEnum (const char* i_target, const char * i_spyName, char** o_enumValue){
return 0;
}
int ecmdClientPerlapi::getSpyEccGrouping (const char* i_target, const char * i_spyEccGroupName, char** o_groupData, char** o_eccData, char** o_eccErrorMask){
return 0;
}
int ecmdClientPerlapi::putSpy (const char* i_target, const char * i_spyName, const char* i_data){
return 0;
}
int ecmdClientPerlapi::putSpyEnum (const char* i_target, const char * i_spyName, const char* i_enumValue){
return 0;
}
void ecmdClientPerlapi::ecmdEnableRingCache(){
return ;
}
int ecmdClientPerlapi::ecmdDisableRingCache(){
return 0;
}
int ecmdClientPerlapi::ecmdFlushRingCache(){
return 0;
}
int ecmdClientPerlapi::getArray (const char* i_target, const char * i_arrayName, const char* i_address, char** o_data){
return 0;
}
int ecmdClientPerlapi::putArray (const char* i_target, const char * i_arrayName, const char* i_address, const char* i_data){
return 0;
}
int ecmdClientPerlapi::simaet(const char* i_function){
return 0;
}
int ecmdClientPerlapi::simcheckpoint(const char* i_checkpoint){
return 0;
}
int ecmdClientPerlapi::simclock(int i_cycles){
return 0;
}
int ecmdClientPerlapi::simecho(const char* i_message){
return 0;
}
int ecmdClientPerlapi::simexit(){
return 0;
}
int ecmdClientPerlapi::simEXPECTFAC(const char* i_facname, int i_bitlength, const char* i_expect, int i_row, int i_offset){
return 0;
}
int ecmdClientPerlapi::simexpecttcfac(const char* i_tcfacname, int i_bitlength, const char* i_expect, int i_row){
return 0;
}
int ecmdClientPerlapi::simgetcurrentcycle(char** o_cyclecount){
return 0;
}
int ecmdClientPerlapi::simGETFAC(const char* i_facname, int i_bitlength, char** o_data, int i_row, int i_offset){
return 0;
}
int ecmdClientPerlapi::simGETFACX(const char* i_facname, int i_bitlength, char** o_data, int i_row, int i_offset){
return 0;
}
int ecmdClientPerlapi::simgettcfac(const char* i_tcfacname, char** o_data, int i_row, int i_startbit, int i_bitlength){
return 0;
}
int ecmdClientPerlapi::siminit(const char* i_checkpoint){
return 0;
}
int ecmdClientPerlapi::simPUTFAC(const char* i_facname, int i_bitlength, const char* i_data, int i_row, int i_offset){
return 0;
}
int ecmdClientPerlapi::simPUTFACX(const char* i_facname, int i_bitlength, const char* i_data, int i_row, int i_offset){
return 0;
}
int ecmdClientPerlapi::simputtcfac(const char* i_tcfacname, int i_bitlength, const char* i_data, int i_row, int i_numrows){
return 0;
}
int ecmdClientPerlapi::simrestart(const char* i_checkpoint){
return 0;
}
int ecmdClientPerlapi::simSTKFAC(const char* i_facname, int i_bitlength, const char* i_data, int i_row, int i_offset){
return 0;
}
int ecmdClientPerlapi::simstktcfac(const char* i_tcfacname, int i_bitlength, const char* i_data, int i_row, int i_numrows){
return 0;
}
int ecmdClientPerlapi::simSUBCMD(const char* i_command){
return 0;
}
int ecmdClientPerlapi::simtckinterval(int i_tckinterval){
return 0;
}
int ecmdClientPerlapi::simUNSTICK(const char* i_facname, int i_bitlength, int i_row, int i_offset){
return 0;
}
int ecmdClientPerlapi::simunsticktcfac(const char* i_tcfacname, int i_bitlength, const char* i_data, int i_row, int i_numrows){
return 0;
}
char* ecmdClientPerlapi::ecmdGetErrorMsg(int i_errorCode){
return NULL;
}
void ecmdClientPerlapi::ecmdOutputError(const char* i_message){
::ecmdOutputError(i_message);
return ;
}
void ecmdClientPerlapi::ecmdOutputWarning(const char* i_message){
::ecmdOutputWarning(i_message);
return ;
}
void ecmdClientPerlapi::ecmdOutput(const char* i_message){
::ecmdOutput(i_message);
return ;
}
<commit_msg>added #include <ctype.h> for fixing isdigit declaration<commit_after>
// Copyright **********************************************************
//
// IBM Confidential
// OCO Source Materials
// 9400 Licensed Internal Code
// (C) COPYRIGHT IBM CORP. 2003
//
// The source code for this program is not published or otherwise
// divested of its trade secrets, irrespective of what has been
// deposited with the U.S. Copyright Office.
//
// End Copyright ******************************************************
//--------------------------------------------------------------------
// Includes
//--------------------------------------------------------------------
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <ecmdClientCapi.H>
#include <ecmdDataBuffer.H>
#include <ecmdReturnCodes.H>
#include <ecmdUtils.H>
#include <ecmdClientPerlapi.H>
#include <ecmdSharedUtils.H>
static int myErrorCode = ECMD_SUCCESS;
int ecmdPerlInterfaceErrorCheck (int errorCode) {
if (errorCode == -1) {
errorCode = myErrorCode;
myErrorCode = ECMD_SUCCESS;
if (errorCode != ECMD_SUCCESS) {
::ecmdOutputError( (::ecmdGetErrorMsg(errorCode) + "\n").c_str());
}
return errorCode;
}
else if (errorCode != ECMD_SUCCESS) {
myErrorCode = errorCode;
}
return ECMD_SUCCESS;
}
ecmdClientPerlapi::ecmdClientPerlapi () {
perlFormat = "b";
}
ecmdClientPerlapi::~ecmdClientPerlapi () {
this->cleanup();
}
void ecmdClientPerlapi::cleanup() {
ecmdUnloadDll();
}
int ecmdClientPerlapi::initDll (const char * i_dllName, const char * i_options) {
int rc = ECMD_SUCCESS;
std::string dllName = "";
if (i_dllName != NULL) {
dllName = i_dllName;
}
rc = ecmdLoadDll(dllName);
ecmdPerlInterfaceErrorCheck(rc);
return rc;
}
int ecmdClientPerlapi::getScom (const char* i_target, int i_address, char** o_data) {
/* char * ecmdClientPerlapi::getScom (const char * i_target, int i_address) { */
ecmdChipTarget myTarget;
std::string dataStr;
int rc = setupTarget(i_target, myTarget);
ecmdPerlInterfaceErrorCheck(rc);
if (rc) {
*o_data = NULL;
return rc;
}
ecmdDataBuffer buffer;
rc = ::getScom(myTarget, i_address, buffer);
ecmdPerlInterfaceErrorCheck(rc);
if (rc) {
o_data = NULL;
return rc;
}
dataStr = buffer.genBinStr();
char* tmp;
tmp = new char[dataStr.length()+1];
strcpy(tmp,dataStr.c_str());
*o_data = tmp;
/* o_data = dataStr; */
/* return (char*)(dataStr.c_str());*/
return rc;
}
int ecmdClientPerlapi::putScom (const char * i_target, int i_address, const char * i_data) {
ecmdChipTarget myTarget;
std::string dataStr;
std::string myFormat;
int rc = setupTarget(i_target, myTarget);
if (rc) return rc;
ecmdDataBuffer buffer;
myFormat = "b";
rc = ecmdReadDataFormatted(buffer, i_data, myFormat);
ecmdPerlInterfaceErrorCheck(rc);
if (rc) return rc;
rc = ::putScom(myTarget, i_address, buffer);
ecmdPerlInterfaceErrorCheck(rc);
return rc;
}
int ecmdClientPerlapi::getRing (const char * i_target, const char * i_ringName, char **o_data) {
int rc = 0;
ecmdDataBuffer buffer;
ecmdChipTarget myTarget;
rc = setupTarget(i_target, myTarget);
ecmdPerlInterfaceErrorCheck(rc);
if (rc) return rc;
rc = ::getRing(myTarget, i_ringName, buffer);
ecmdPerlInterfaceErrorCheck(rc);
if (rc) return rc;
*o_data = (char*)malloc(buffer.getBitLength()+1);
strcpy(*o_data,ecmdWriteDataFormatted(buffer, perlFormat).c_str());
return rc;
}
int ecmdClientPerlapi::putRing (const char * i_target, const char * i_ringName, const char * i_data) {
ecmdChipTarget myTarget;
std::string myFormat = "b";
int rc = setupTarget(i_target, myTarget);
ecmdPerlInterfaceErrorCheck(rc);
if (rc) return rc;
ecmdDataBuffer buffer;
rc = ecmdReadDataFormatted(buffer, i_data, myFormat);
ecmdPerlInterfaceErrorCheck(rc);
if (rc) return rc;
rc = ::putRing(myTarget, i_ringName, buffer);
ecmdPerlInterfaceErrorCheck(rc);
return rc;
}
/***
void ecmdClientPerlapi::add(char *retval) {
printf("Inside function: %c %c %c\n",retval[0],retval[1],retval[2]);
retval[0] = 'L'; retval[1] = 'p';
strcpy(retval,"Looky here - I made it");
}
void ecmdClientPerlapi::add2(char **retval) {
printf("Inside function: %s\n",*retval);
*retval = (char*)malloc(sizeof (char[100]));
strcpy(*retval,"Looky here - I made it");
}
***/
int ecmdClientPerlapi::setupTarget (const char * i_targetStr, ecmdChipTarget & o_target) {
int rc = ECMD_SUCCESS;
std::string printed;
if (i_targetStr == NULL) {
ecmdOutputError("ecmdClientPerlapi::setupTarget - It appears the target string is null\n");
return ECMD_INVALID_ARGS;
}
std::vector<std::string> tokens;
ecmdParseTokens(i_targetStr, " ,.", tokens);
/* Set our initial states */
o_target.cage = o_target.node = o_target.slot = o_target.pos = o_target.core = o_target.thread = 0;
o_target.cageState = o_target.nodeState = o_target.slotState = o_target.posState = o_target.coreState = o_target.threadState = ECMD_TARGET_FIELD_VALID;
o_target.chipTypeState = ECMD_TARGET_FIELD_UNUSED;
for (std::vector<std::string>::iterator tokit = tokens.begin(); tokit != tokens.end(); tokit ++) {
if ((*tokit)[0] == '-') {
switch((*tokit)[1]) {
case 'k': case 'K':
o_target.cage = atoi(tokit->substr(2,20).c_str());
break;
case 'n': case 'N':
o_target.node = atoi(tokit->substr(2,20).c_str());
break;
case 's': case 'S':
o_target.slot = atoi(tokit->substr(2,20).c_str());
break;
case 'p': case 'P':
o_target.pos = atoi(tokit->substr(2,20).c_str());
break;
case 'c': case 'C':
o_target.core = atoi(tokit->substr(2,20).c_str());
break;
case 't': case 'T':
o_target.thread = atoi(tokit->substr(2,20).c_str());
break;
default:
ecmdOutputError((((printed = "ecmdClientPerlapi::setupTarget - It appears the target string contained an invalid target parm : ") + i_targetStr) + "\n").c_str());
return ECMD_INVALID_ARGS;
}
} else {
/* If the first char is a digit then they must have specified a p1..3 or p1,4 and we tokenized it above, this is not good */
if (isdigit((*tokit)[0])) {
ecmdOutputError((((printed = "ecmdClientPerlapi::setupTarget - It appears the target string contained a range or multiple positions : ") + i_targetStr) + "\n").c_str());
return ECMD_INVALID_ARGS;
} else if (o_target.chipTypeState == ECMD_TARGET_FIELD_VALID) {
ecmdOutputError((((printed = "ecmdClientPerlapi::setupTarget - It appears the target string contained multiple chip names : ") + i_targetStr) + "\n").c_str());
return ECMD_INVALID_ARGS;
}
o_target.chipTypeState = ECMD_TARGET_FIELD_VALID;
o_target.chipType = *tokit;
}
}
return rc;
}
int ecmdClientPerlapi::ecmdCommandArgs(char** i_argv[]){
return 0;
}
/***
int ecmdClientPerlapi::ecmdCommandArgs(int* i_argc, char** i_argv[]) {
return 0;
}
***/
int ecmdClientPerlapi::sendCmd(const char* i_target, int i_instruction, int i_modifier, char** o_status) {
return 0;
}
int ecmdClientPerlapi::getCfamRegister (const char* i_target, int i_address, char** o_data){
return 0;
}
int ecmdClientPerlapi::putCfamRegister (const char* i_target, int i_address, const char* i_data){
return 0;
}
int ecmdClientPerlapi::getSpy (const char* i_target, const char * i_spyName, char** o_data){
return 0;
}
int ecmdClientPerlapi::getSpyEnum (const char* i_target, const char * i_spyName, char** o_enumValue){
return 0;
}
int ecmdClientPerlapi::getSpyEccGrouping (const char* i_target, const char * i_spyEccGroupName, char** o_groupData, char** o_eccData, char** o_eccErrorMask){
return 0;
}
int ecmdClientPerlapi::putSpy (const char* i_target, const char * i_spyName, const char* i_data){
return 0;
}
int ecmdClientPerlapi::putSpyEnum (const char* i_target, const char * i_spyName, const char* i_enumValue){
return 0;
}
void ecmdClientPerlapi::ecmdEnableRingCache(){
return ;
}
int ecmdClientPerlapi::ecmdDisableRingCache(){
return 0;
}
int ecmdClientPerlapi::ecmdFlushRingCache(){
return 0;
}
int ecmdClientPerlapi::getArray (const char* i_target, const char * i_arrayName, const char* i_address, char** o_data){
return 0;
}
int ecmdClientPerlapi::putArray (const char* i_target, const char * i_arrayName, const char* i_address, const char* i_data){
return 0;
}
int ecmdClientPerlapi::simaet(const char* i_function){
return 0;
}
int ecmdClientPerlapi::simcheckpoint(const char* i_checkpoint){
return 0;
}
int ecmdClientPerlapi::simclock(int i_cycles){
return 0;
}
int ecmdClientPerlapi::simecho(const char* i_message){
return 0;
}
int ecmdClientPerlapi::simexit(){
return 0;
}
int ecmdClientPerlapi::simEXPECTFAC(const char* i_facname, int i_bitlength, const char* i_expect, int i_row, int i_offset){
return 0;
}
int ecmdClientPerlapi::simexpecttcfac(const char* i_tcfacname, int i_bitlength, const char* i_expect, int i_row){
return 0;
}
int ecmdClientPerlapi::simgetcurrentcycle(char** o_cyclecount){
return 0;
}
int ecmdClientPerlapi::simGETFAC(const char* i_facname, int i_bitlength, char** o_data, int i_row, int i_offset){
return 0;
}
int ecmdClientPerlapi::simGETFACX(const char* i_facname, int i_bitlength, char** o_data, int i_row, int i_offset){
return 0;
}
int ecmdClientPerlapi::simgettcfac(const char* i_tcfacname, char** o_data, int i_row, int i_startbit, int i_bitlength){
return 0;
}
int ecmdClientPerlapi::siminit(const char* i_checkpoint){
return 0;
}
int ecmdClientPerlapi::simPUTFAC(const char* i_facname, int i_bitlength, const char* i_data, int i_row, int i_offset){
return 0;
}
int ecmdClientPerlapi::simPUTFACX(const char* i_facname, int i_bitlength, const char* i_data, int i_row, int i_offset){
return 0;
}
int ecmdClientPerlapi::simputtcfac(const char* i_tcfacname, int i_bitlength, const char* i_data, int i_row, int i_numrows){
return 0;
}
int ecmdClientPerlapi::simrestart(const char* i_checkpoint){
return 0;
}
int ecmdClientPerlapi::simSTKFAC(const char* i_facname, int i_bitlength, const char* i_data, int i_row, int i_offset){
return 0;
}
int ecmdClientPerlapi::simstktcfac(const char* i_tcfacname, int i_bitlength, const char* i_data, int i_row, int i_numrows){
return 0;
}
int ecmdClientPerlapi::simSUBCMD(const char* i_command){
return 0;
}
int ecmdClientPerlapi::simtckinterval(int i_tckinterval){
return 0;
}
int ecmdClientPerlapi::simUNSTICK(const char* i_facname, int i_bitlength, int i_row, int i_offset){
return 0;
}
int ecmdClientPerlapi::simunsticktcfac(const char* i_tcfacname, int i_bitlength, const char* i_data, int i_row, int i_numrows){
return 0;
}
char* ecmdClientPerlapi::ecmdGetErrorMsg(int i_errorCode){
return NULL;
}
void ecmdClientPerlapi::ecmdOutputError(const char* i_message){
::ecmdOutputError(i_message);
return ;
}
void ecmdClientPerlapi::ecmdOutputWarning(const char* i_message){
::ecmdOutputWarning(i_message);
return ;
}
void ecmdClientPerlapi::ecmdOutput(const char* i_message){
::ecmdOutput(i_message);
return ;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2015, Mario Flach. 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 <boost/lexical_cast.hpp>
#include <boost/algorithm/hex.hpp>
#include <ejdb/ejdb.h>
#include <ejdb/ejdb_private.h>
#include "../include/meteorpp/collection.hpp"
#include "../include/meteorpp/live_query.hpp"
std::weak_ptr<EJDB> db;
std::once_flag bson_oid_setup_flag;
namespace meteorpp {
ejdb_exception::ejdb_exception(std::string const& error_message, int error_code)
: std::runtime_error(error_message), _error_code(error_code)
{
}
ejdb_exception::ejdb_exception(int error_code)
: std::runtime_error(ejdberrmsg(error_code)), _error_code(error_code)
{
}
ejdb_exception::~ejdb_exception()
{
}
int ejdb_exception::error_code() const
{
return _error_code;
}
collection::collection(std::string const& name) throw(ejdb_exception)
{
if(name.empty()) {
throw ejdb_exception(JBEINVALIDCOLNAME);
}
std::call_once(bson_oid_setup_flag, std::bind(bson_set_oid_inc, []() -> int {
return 0xcafed00d;
}));
if(!(_db = db.lock())) {
_db = std::shared_ptr<EJDB>(ejdbnew(), ejdbdel);
if(!ejdbopen(_db.get(), "meteorpp.db", JBOWRITER | JBOCREAT | JBOTRUNC)) {
throw_last_ejdb_exception();
}
db = _db;
}
_coll.reset(ejdbcreatecoll(_db.get(), name.c_str(), nullptr), ejdbsyncoll);
}
collection::~collection()
{
}
std::shared_ptr<live_query> collection::track(nlohmann::json::object_t const& selector) throw(std::bad_weak_ptr)
{
return std::make_shared<live_query>(selector, shared_from_this());
}
std::vector<nlohmann::json::object_t> collection::find(nlohmann::json::object_t const& selector) throw(std::runtime_error)
{
return query(selector);
}
nlohmann::json::object_t collection::find_one(nlohmann::json::object_t const& selector) throw(std::runtime_error)
{
auto results = query(selector, nlohmann::json::object(), JBQRYFINDONE);
return results.size() ? results[0] : nlohmann::json::object();
}
std::string collection::insert(nlohmann::json::object_t const& document) throw(std::runtime_error)
{
bson_oid_t oid;
std::shared_ptr<bson> bson_doc = convert_to_bson(document);
if(document.find("_id") != document.end()) {
std::string const &id = document.find("_id")->second;
if(!ejdbisvalidoidstr(id.c_str())) {
throw ejdb_exception(JBEINVALIDBSONPK);
}
bson_oid_from_string(&oid, id.c_str());
std::shared_ptr<bson> bson_oid(bson_create(), bson_del);
bson_init(bson_oid.get());
bson_append_oid(bson_oid.get(), "_id", &oid);
bson_finish(bson_oid.get());
std::shared_ptr<bson> bson_doc_with_oid(bson_create(), bson_del);
bson_init(bson_doc_with_oid.get());
bson_merge(bson_oid.get(), bson_doc.get(), true, bson_doc_with_oid.get());
bson_finish(bson_doc_with_oid.get());
bson_doc.swap(bson_doc_with_oid);
}
if(!ejdbsavebson(_coll.get(), bson_doc.get(), &oid)) {
throw_last_ejdb_exception();
}
std::string id(24, '\0');
bson_oid_to_string(&oid, &id[0]);
document_added(id, document);
return id;
}
int collection::update(nlohmann::json::object_t const& selector, nlohmann::json::object_t const& modifier) throw(std::runtime_error)
{
return query(selector, modifier).size();
}
int collection::upsert(nlohmann::json::object_t const& selector, nlohmann::json::object_t const& modifier) throw(std::runtime_error)
{
return query(selector, {{ "$upsert", modifier }}).size();
}
int collection::remove(nlohmann::json::object_t const& selector) throw(std::runtime_error)
{
return query(selector, {{ "$dropall", true }}).size();
}
nlohmann::json collection::query(nlohmann::json::object_t const& selector, nlohmann::json::object_t const& modifier, int flags) throw(ejdb_exception)
{
nlohmann::json q1 = selector;
nlohmann::json q2 = modifier;
bool with_modifier = !q2.empty();
if(with_modifier) {
std::swap(q1, q2);
}
auto* ejdb_query = ejdbcreatequery(_db.get(), convert_to_bson(q1).get(), with_modifier ? convert_to_bson(q2).get() : nullptr, (int)with_modifier, nullptr);
if(!ejdb_query) {
throw_last_ejdb_exception();
}
uint32_t count;
std::shared_ptr<TCXSTR> log(tcxstrnew(), tcxstrdel);
auto cursor = ejdbqryexecute(_coll.get(), ejdb_query, &count, flags, log.get());
ejdbquerydel(ejdb_query);
nlohmann::json updates;
nlohmann::json upserts;
nlohmann::json dropall;
nlohmann::json const json_log = evaluate_log(std::string(log->ptr, log->size));
if(json_log["updating_mode"]) {
if(json_log.find("$update") != json_log.end()) {
updates = json_log["$update"];
if(updates.type() != nlohmann::json::value_t::array) {
updates = nlohmann::json::array_t({ updates });
}
}
if(json_log.find("$upsert") != json_log.end()) {
upserts = json_log["$upsert"];
if(upserts.type() != nlohmann::json::value_t::array) {
upserts = nlohmann::json::array_t({ upserts });
}
for(nlohmann::json::object_t doc: upserts) {
std::string const id = doc["_id"];
doc.erase("_id");
document_added(id, doc);
}
}
if(json_log.find("$dropall") != json_log.end()) {
for(std::string const& id: json_log["$dropall"]) {
dropall.push_back(id);
}
}
}
nlohmann::json return_val;
if(flags & JBQRYCOUNT) {
return_val = count;
} else {
std::vector<nlohmann::json::object_t> results;
results.reserve(count);
for(int i = 0; i < count; ++i) {
int data_size = 0;
auto const& result = convert_to_json(std::shared_ptr<bson>(bson_create_from_buffer(static_cast<char const*>(ejdbqresultbsondata(cursor, i, &data_size)), data_size), bson_destroy));
if(i < updates.size()) {
auto const& update = updates[i];
if(result != update) {
auto const diff = modified_fields(result, update);
document_pre_changed(result["_id"], result, update);
document_changed(result["_id"], diff["fields"], diff["cleared"]);
}
}
if(i < dropall.size()) {
std::string const& id = dropall[i];
if(result["_id"] == id) {
document_pre_removed(id, result);
document_removed(id);
}
}
results.push_back(result);
}
ejdbqresultdispose(cursor);
return_val = results;
}
return return_val;
}
nlohmann::json collection::evaluate_log(std::string const& log)
{
nlohmann::json json_log;
std::istringstream log_stream(log);
for(std::string line; std::getline(log_stream, line); ) {
auto const delimiter = line.find_first_of(':');
if(delimiter != std::string::npos) {
std::string key = line.substr(0, delimiter);
std::string val = line.substr(delimiter + 2);
std::replace(key.begin(), key.end(), ' ', '_');
std::transform(key.begin(), key.end(), key.begin(), ::tolower);
nlohmann::json json_val;
try {
json_val = boost::lexical_cast<long>(val);
} catch(boost::bad_lexical_cast const& e) {
if(val == "YES") {
json_val = true;
} else if(val == "NO") {
json_val = false;
} else if(val == "'NONE'") {
json_val = nullptr;
} else {
size_t const bson_hex_delimiter = val.find_first_of('/');
if(bson_hex_delimiter != std::string::npos) {
std::string const bson_hex_string = val.substr(0, bson_hex_delimiter);
std::string bson_decoded_data;
boost::algorithm::unhex(bson_hex_string.begin(), bson_hex_string.end(), back_inserter(bson_decoded_data));
json_val = convert_to_json(std::shared_ptr<bson>(bson_create_from_buffer(bson_decoded_data.data(), bson_decoded_data.size()), bson_del));
} else {
json_val = val;
}
}
}
if(json_log.find(key) != json_log.end()) {
if(json_log[key].type() != nlohmann::json::value_t::array) {
json_log[key] = nlohmann::json::array_t({ json_log[key] });
}
json_log[key].push_back(json_val);
} else {
json_log[key] = json_val;
}
}
}
return json_log;
}
void collection::throw_last_ejdb_exception() throw(ejdb_exception)
{
throw ejdb_exception(ejdbecode(_db.get()));
}
nlohmann::json collection::modified_fields(nlohmann::json::object_t const& a, nlohmann::json::object_t const& b)
{
nlohmann::json::object_t diff;
std::set_difference(b.begin(), b.end(), a.begin(), a.end(), std::inserter(diff, diff.begin()));
std::vector<std::string> cleared_fields;
for(auto const& field: a) {
if(b.find(field.first) == b.end()) {
cleared_fields.push_back(field.first);
}
}
return {{ "fields", diff }, { "cleared", cleared_fields }};
}
nlohmann::json collection::convert_to_json(std::shared_ptr<bson> const& value)
{
char* buffer;
int size = 0;
bson2json(bson_data(value.get()), &buffer, &size);
return nlohmann::json::parse(std::string(buffer, size));
}
std::shared_ptr<bson> collection::convert_to_bson(nlohmann::json const& value)
{
return std::shared_ptr<bson>(json2bson(value.dump().c_str()), bson_del);
}
}
<commit_msg>Fix compile error on Linux<commit_after>/*
* Copyright (c) 2015, Mario Flach. 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 <mutex>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/hex.hpp>
#include <ejdb/ejdb.h>
#include <ejdb/ejdb_private.h>
#include "../include/meteorpp/collection.hpp"
#include "../include/meteorpp/live_query.hpp"
std::weak_ptr<EJDB> db;
std::once_flag bson_oid_setup_flag;
namespace meteorpp {
ejdb_exception::ejdb_exception(std::string const& error_message, int error_code)
: std::runtime_error(error_message), _error_code(error_code)
{
}
ejdb_exception::ejdb_exception(int error_code)
: std::runtime_error(ejdberrmsg(error_code)), _error_code(error_code)
{
}
ejdb_exception::~ejdb_exception()
{
}
int ejdb_exception::error_code() const
{
return _error_code;
}
collection::collection(std::string const& name) throw(ejdb_exception)
{
if(name.empty()) {
throw ejdb_exception(JBEINVALIDCOLNAME);
}
std::call_once(bson_oid_setup_flag, std::bind(bson_set_oid_inc, []() -> int {
return 0xcafed00d;
}));
if(!(_db = db.lock())) {
_db = std::shared_ptr<EJDB>(ejdbnew(), ejdbdel);
if(!ejdbopen(_db.get(), "meteorpp.db", JBOWRITER | JBOCREAT | JBOTRUNC)) {
throw_last_ejdb_exception();
}
db = _db;
}
_coll.reset(ejdbcreatecoll(_db.get(), name.c_str(), nullptr), ejdbsyncoll);
}
collection::~collection()
{
}
std::shared_ptr<live_query> collection::track(nlohmann::json::object_t const& selector) throw(std::bad_weak_ptr)
{
return std::make_shared<live_query>(selector, shared_from_this());
}
std::vector<nlohmann::json::object_t> collection::find(nlohmann::json::object_t const& selector) throw(std::runtime_error)
{
return query(selector);
}
nlohmann::json::object_t collection::find_one(nlohmann::json::object_t const& selector) throw(std::runtime_error)
{
auto results = query(selector, nlohmann::json::object(), JBQRYFINDONE);
return results.size() ? results[0] : nlohmann::json::object();
}
std::string collection::insert(nlohmann::json::object_t const& document) throw(std::runtime_error)
{
bson_oid_t oid;
std::shared_ptr<bson> bson_doc = convert_to_bson(document);
if(document.find("_id") != document.end()) {
std::string const &id = document.find("_id")->second;
if(!ejdbisvalidoidstr(id.c_str())) {
throw ejdb_exception(JBEINVALIDBSONPK);
}
bson_oid_from_string(&oid, id.c_str());
std::shared_ptr<bson> bson_oid(bson_create(), bson_del);
bson_init(bson_oid.get());
bson_append_oid(bson_oid.get(), "_id", &oid);
bson_finish(bson_oid.get());
std::shared_ptr<bson> bson_doc_with_oid(bson_create(), bson_del);
bson_init(bson_doc_with_oid.get());
bson_merge(bson_oid.get(), bson_doc.get(), true, bson_doc_with_oid.get());
bson_finish(bson_doc_with_oid.get());
bson_doc.swap(bson_doc_with_oid);
}
if(!ejdbsavebson(_coll.get(), bson_doc.get(), &oid)) {
throw_last_ejdb_exception();
}
std::string id(24, '\0');
bson_oid_to_string(&oid, &id[0]);
document_added(id, document);
return id;
}
int collection::update(nlohmann::json::object_t const& selector, nlohmann::json::object_t const& modifier) throw(std::runtime_error)
{
return query(selector, modifier).size();
}
int collection::upsert(nlohmann::json::object_t const& selector, nlohmann::json::object_t const& modifier) throw(std::runtime_error)
{
return query(selector, {{ "$upsert", modifier }}).size();
}
int collection::remove(nlohmann::json::object_t const& selector) throw(std::runtime_error)
{
return query(selector, {{ "$dropall", true }}).size();
}
nlohmann::json collection::query(nlohmann::json::object_t const& selector, nlohmann::json::object_t const& modifier, int flags) throw(ejdb_exception)
{
nlohmann::json q1 = selector;
nlohmann::json q2 = modifier;
bool with_modifier = !q2.empty();
if(with_modifier) {
std::swap(q1, q2);
}
auto* ejdb_query = ejdbcreatequery(_db.get(), convert_to_bson(q1).get(), with_modifier ? convert_to_bson(q2).get() : nullptr, (int)with_modifier, nullptr);
if(!ejdb_query) {
throw_last_ejdb_exception();
}
uint32_t count;
std::shared_ptr<TCXSTR> log(tcxstrnew(), tcxstrdel);
auto cursor = ejdbqryexecute(_coll.get(), ejdb_query, &count, flags, log.get());
ejdbquerydel(ejdb_query);
nlohmann::json updates;
nlohmann::json upserts;
nlohmann::json dropall;
nlohmann::json const json_log = evaluate_log(std::string(log->ptr, log->size));
if(json_log["updating_mode"]) {
if(json_log.find("$update") != json_log.end()) {
updates = json_log["$update"];
if(updates.type() != nlohmann::json::value_t::array) {
updates = nlohmann::json::array_t({ updates });
}
}
if(json_log.find("$upsert") != json_log.end()) {
upserts = json_log["$upsert"];
if(upserts.type() != nlohmann::json::value_t::array) {
upserts = nlohmann::json::array_t({ upserts });
}
for(nlohmann::json::object_t doc: upserts) {
std::string const id = doc["_id"];
doc.erase("_id");
document_added(id, doc);
}
}
if(json_log.find("$dropall") != json_log.end()) {
for(std::string const& id: json_log["$dropall"]) {
dropall.push_back(id);
}
}
}
nlohmann::json return_val;
if(flags & JBQRYCOUNT) {
return_val = count;
} else {
std::vector<nlohmann::json::object_t> results;
results.reserve(count);
for(int i = 0; i < count; ++i) {
int data_size = 0;
auto const& result = convert_to_json(std::shared_ptr<bson>(bson_create_from_buffer(static_cast<char const*>(ejdbqresultbsondata(cursor, i, &data_size)), data_size), bson_destroy));
if(i < updates.size()) {
auto const& update = updates[i];
if(result != update) {
auto const diff = modified_fields(result, update);
document_pre_changed(result["_id"], result, update);
document_changed(result["_id"], diff["fields"], diff["cleared"]);
}
}
if(i < dropall.size()) {
std::string const& id = dropall[i];
if(result["_id"] == id) {
document_pre_removed(id, result);
document_removed(id);
}
}
results.push_back(result);
}
ejdbqresultdispose(cursor);
return_val = results;
}
return return_val;
}
nlohmann::json collection::evaluate_log(std::string const& log)
{
nlohmann::json json_log;
std::istringstream log_stream(log);
for(std::string line; std::getline(log_stream, line); ) {
auto const delimiter = line.find_first_of(':');
if(delimiter != std::string::npos) {
std::string key = line.substr(0, delimiter);
std::string val = line.substr(delimiter + 2);
std::replace(key.begin(), key.end(), ' ', '_');
std::transform(key.begin(), key.end(), key.begin(), ::tolower);
nlohmann::json json_val;
try {
json_val = boost::lexical_cast<long>(val);
} catch(boost::bad_lexical_cast const& e) {
if(val == "YES") {
json_val = true;
} else if(val == "NO") {
json_val = false;
} else if(val == "'NONE'") {
json_val = nullptr;
} else {
size_t const bson_hex_delimiter = val.find_first_of('/');
if(bson_hex_delimiter != std::string::npos) {
std::string const bson_hex_string = val.substr(0, bson_hex_delimiter);
std::string bson_decoded_data;
boost::algorithm::unhex(bson_hex_string.begin(), bson_hex_string.end(), back_inserter(bson_decoded_data));
json_val = convert_to_json(std::shared_ptr<bson>(bson_create_from_buffer(bson_decoded_data.data(), bson_decoded_data.size()), bson_del));
} else {
json_val = val;
}
}
}
if(json_log.find(key) != json_log.end()) {
if(json_log[key].type() != nlohmann::json::value_t::array) {
json_log[key] = nlohmann::json::array_t({ json_log[key] });
}
json_log[key].push_back(json_val);
} else {
json_log[key] = json_val;
}
}
}
return json_log;
}
void collection::throw_last_ejdb_exception() throw(ejdb_exception)
{
throw ejdb_exception(ejdbecode(_db.get()));
}
nlohmann::json collection::modified_fields(nlohmann::json::object_t const& a, nlohmann::json::object_t const& b)
{
nlohmann::json::object_t diff;
std::set_difference(b.begin(), b.end(), a.begin(), a.end(), std::inserter(diff, diff.begin()));
std::vector<std::string> cleared_fields;
for(auto const& field: a) {
if(b.find(field.first) == b.end()) {
cleared_fields.push_back(field.first);
}
}
return {{ "fields", diff }, { "cleared", cleared_fields }};
}
nlohmann::json collection::convert_to_json(std::shared_ptr<bson> const& value)
{
char* buffer;
int size = 0;
bson2json(bson_data(value.get()), &buffer, &size);
return nlohmann::json::parse(std::string(buffer, size));
}
std::shared_ptr<bson> collection::convert_to_bson(nlohmann::json const& value)
{
return std::shared_ptr<bson>(json2bson(value.dump().c_str()), bson_del);
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2015 - 2017 [email protected]
*
* 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/.
*/
#pragma once
#include "types.hpp"
namespace ox {
template<typename T>
class Vector {
private:
size_t m_size = 0;
T *m_items = nullptr;
public:
Vector() = default;
explicit Vector(size_t size);
Vector(Vector &other);
Vector(Vector &&other);
~Vector();
size_t size() const;
void resize(size_t size);
Vector &operator=(Vector &other);
Vector &operator=(Vector &&other);
T &operator[](size_t i);
const T &operator[](size_t i) const;
};
template<typename T>
Vector<T>::Vector(size_t size) {
m_size = size;
m_items = new T[m_size];
}
template<typename T>
Vector<T>::Vector(Vector<T> &other) {
m_size = size;
m_items = new T[m_size];
for (size_t i = 0; i < m_size; i++) {
m_items[i] = other.m_items[i];
}
}
template<typename T>
Vector<T>::Vector(Vector<T> &&other) {
m_size = other.m_size;
m_items = other.m_items;
other.m_size = 0;
other.m_items = nullptr;
}
template<typename T>
Vector<T>::~Vector() {
if (m_items) {
delete m_items;
m_items = nullptr;
}
}
template<typename T>
Vector<T> &Vector<T>::operator=(Vector<T> &other) {
~Vector<T>();
m_size = size;
m_items = new T[m_size];
for (size_t i = 0; i < m_size; i++) {
m_items[i] = other.m_items[i];
}
return *this;
}
template<typename T>
Vector<T> &Vector<T>::operator=(Vector<T> &&other) {
~Vector<T>();
m_size = other.m_size;
m_items = other.m_items;
other.m_size = 0;
other.m_items = nullptr;
return *this;
}
template<typename T>
size_t Vector<T>::size() const {
return m_size;
};
template<typename T>
void Vector<T>::resize(size_t size) {
auto oldItems = m_items;
m_items = new T[size];
const auto itRange = size > m_size ? m_size : size;
for (size_t i = 0; i < itRange; i++) {
m_items[i] = oldItems[i];
}
m_size = size;
}
template<typename T>
T &Vector<T>::operator[](size_t i) {
return *(m_items[i]);
}
template<typename T>
const T &Vector<T>::operator[](size_t i) const {
return *(m_items[i]);
}
}
<commit_msg>Fix ox::Vector::~Vector to use delete[] instead of delete<commit_after>/*
* Copyright 2015 - 2017 [email protected]
*
* 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/.
*/
#pragma once
#include "types.hpp"
namespace ox {
template<typename T>
class Vector {
private:
size_t m_size = 0;
T *m_items = nullptr;
public:
Vector() = default;
explicit Vector(size_t size);
Vector(Vector &other);
Vector(Vector &&other);
~Vector();
size_t size() const;
void resize(size_t size);
Vector &operator=(Vector &other);
Vector &operator=(Vector &&other);
T &operator[](size_t i);
const T &operator[](size_t i) const;
};
template<typename T>
Vector<T>::Vector(size_t size) {
m_size = size;
m_items = new T[m_size];
}
template<typename T>
Vector<T>::Vector(Vector<T> &other) {
m_size = size;
m_items = new T[m_size];
for (size_t i = 0; i < m_size; i++) {
m_items[i] = other.m_items[i];
}
}
template<typename T>
Vector<T>::Vector(Vector<T> &&other) {
m_size = other.m_size;
m_items = other.m_items;
other.m_size = 0;
other.m_items = nullptr;
}
template<typename T>
Vector<T>::~Vector() {
if (m_items) {
delete[] m_items;
m_items = nullptr;
}
}
template<typename T>
Vector<T> &Vector<T>::operator=(Vector<T> &other) {
~Vector<T>();
m_size = size;
m_items = new T[m_size];
for (size_t i = 0; i < m_size; i++) {
m_items[i] = other.m_items[i];
}
return *this;
}
template<typename T>
Vector<T> &Vector<T>::operator=(Vector<T> &&other) {
~Vector<T>();
m_size = other.m_size;
m_items = other.m_items;
other.m_size = 0;
other.m_items = nullptr;
return *this;
}
template<typename T>
size_t Vector<T>::size() const {
return m_size;
};
template<typename T>
void Vector<T>::resize(size_t size) {
auto oldItems = m_items;
m_items = new T[size];
const auto itRange = size > m_size ? m_size : size;
for (size_t i = 0; i < itRange; i++) {
m_items[i] = oldItems[i];
}
m_size = size;
}
template<typename T>
T &Vector<T>::operator[](size_t i) {
return *(m_items[i]);
}
template<typename T>
const T &Vector<T>::operator[](size_t i) const {
return *(m_items[i]);
}
}
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2012 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
*
*****************************************************************************/
#include <boost/version.hpp>
#if BOOST_VERSION >= 104700
// mapnik
#include <mapnik/json/geometry_grammar.hpp>
// boost
#include <boost/spirit/include/support_multi_pass.hpp>
#include <boost/spirit/include/phoenix_object.hpp>
#include <boost/spirit/include/phoenix_stl.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <iostream> // for clog, endl, etc
#include <string> // for string
namespace mapnik { namespace json {
template <typename Iterator>
geometry_grammar<Iterator>::geometry_grammar()
: geometry_grammar::base_type(geometry,"geometry")
{
using qi::lit;
using qi::int_;
using qi::double_;
using qi::_val;
using qi::_1;
using qi::_2;
using qi::_3;
using qi::_4;
using qi::_a;
using qi::_b;
using qi::_r1;
using qi::_r2;
using qi::eps;
using qi::_pass;
using qi::fail;
using qi::on_error;
using boost::phoenix::new_;
using boost::phoenix::push_back;
using boost::phoenix::construct;
// Nabialek trick - FIXME: how to bind argument to dispatch rule?
// geometry = lit("\"geometry\"")
// >> lit(':') >> lit('{')
// >> lit("\"type\"") >> lit(':') >> geometry_dispatch[_a = _1]
// >> lit(',') >> lit("\"coordinates\"") >> lit(':')
// >> qi::lazy(*_a)
// >> lit('}')
// ;
// geometry_dispatch.add
// ("\"Point\"",&point_coordinates)
// ("\"LineString\"",&linestring_coordinates)
// ("\"Polygon\"",&polygon_coordinates)
// ;
//////////////////////////////////////////////////////////////////
geometry = (lit('{')[_a = 0 ]
>> lit("\"type\"") >> lit(':') >> geometry_dispatch[_a = _1] // <---- should be Nabialek trick!
>> lit(',')
>> (lit("\"coordinates\"") > lit(':') > (lit("null") | coordinates(_r1,_a))
|
lit("\"geometries\"") > lit(':')
>> lit('[') >> geometry_collection(_r1) >> lit(']'))
>> lit('}'))
| lit("null")
;
geometry_dispatch.add
("\"Point\"",1)
("\"LineString\"",2)
("\"Polygon\"",3)
("\"MultiPoint\"",4)
("\"MultiLineString\"",5)
("\"MultiPolygon\"",6)
("\"GeometryCollection\"",7)
//
;
coordinates = (eps(_r2 == 1) > point_coordinates(_r1))
| (eps(_r2 == 2) > linestring_coordinates(_r1))
| (eps(_r2 == 3) > polygon_coordinates(_r1))
| (eps(_r2 == 4) > multipoint_coordinates(_r1))
| (eps(_r2 == 5) > multilinestring_coordinates(_r1))
| (eps(_r2 == 6) > multipolygon_coordinates(_r1))
;
point_coordinates = eps[ _a = new_<geometry_type>(geometry_type::types::Point) ]
> ( point(SEG_MOVETO,_a) [push_back(_r1,_a)] | eps[cleanup_(_a)][_pass = false] )
;
linestring_coordinates = eps[ _a = new_<geometry_type>(geometry_type::types::LineString)]
> -(points(_a) [push_back(_r1,_a)]
| eps[cleanup_(_a)][_pass = false])
;
polygon_coordinates = eps[ _a = new_<geometry_type>(geometry_type::types::Polygon) ]
> ((lit('[')
> -(points(_a)[close_path_(_a)] % lit(','))
> lit(']')) [push_back(_r1,_a)]
| eps[cleanup_(_a)][_pass = false])
;
multipoint_coordinates = lit('[')
> -(point_coordinates(_r1) % lit(','))
> lit(']')
;
multilinestring_coordinates = lit('[')
> -(linestring_coordinates(_r1) % lit(','))
> lit(']')
;
multipolygon_coordinates = lit('[')
> -(polygon_coordinates(_r1) % lit(','))
> lit(']')
;
geometry_collection = *geometry(_r1) >> *(lit(',') >> geometry(_r1))
;
// point
point = lit('[') > -((double_ > lit(',') > double_)[push_vertex_(_r1,_r2,_1,_2)]) > lit(']');
// points
points = lit('[')[_a = SEG_MOVETO] > -(point (_a,_r1) % lit(',')[_a = SEG_LINETO]) > lit(']');
// give some rules names
geometry.name("Geometry");
geometry_collection.name("GeometryCollection");
geometry_dispatch.name("Geometry dispatch");
coordinates.name("Coordinates");
// error handler
on_error<fail>
(
geometry
, std::clog
<< boost::phoenix::val("Error! Expecting ")
<< _4 // what failed?
<< boost::phoenix::val(" here: \"")
<< where_message_(_3, _2, 16) // max 16 chars
<< boost::phoenix::val("\"")
<< std::endl
);
}
template struct mapnik::json::geometry_grammar<std::string::const_iterator>;
template struct mapnik::json::geometry_grammar<boost::spirit::multi_pass<std::istreambuf_iterator<char> > >;
}}
#endif
<commit_msg>Revert "geojson parser : support 'null' as valid coordinates property (empty geometry)"<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2012 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
*
*****************************************************************************/
#include <boost/version.hpp>
#if BOOST_VERSION >= 104700
// mapnik
#include <mapnik/json/geometry_grammar.hpp>
// boost
#include <boost/spirit/include/support_multi_pass.hpp>
#include <boost/spirit/include/phoenix_object.hpp>
#include <boost/spirit/include/phoenix_stl.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <iostream> // for clog, endl, etc
#include <string> // for string
namespace mapnik { namespace json {
template <typename Iterator>
geometry_grammar<Iterator>::geometry_grammar()
: geometry_grammar::base_type(geometry,"geometry")
{
using qi::lit;
using qi::int_;
using qi::double_;
using qi::_val;
using qi::_1;
using qi::_2;
using qi::_3;
using qi::_4;
using qi::_a;
using qi::_b;
using qi::_r1;
using qi::_r2;
using qi::eps;
using qi::_pass;
using qi::fail;
using qi::on_error;
using boost::phoenix::new_;
using boost::phoenix::push_back;
using boost::phoenix::construct;
// Nabialek trick - FIXME: how to bind argument to dispatch rule?
// geometry = lit("\"geometry\"")
// >> lit(':') >> lit('{')
// >> lit("\"type\"") >> lit(':') >> geometry_dispatch[_a = _1]
// >> lit(',') >> lit("\"coordinates\"") >> lit(':')
// >> qi::lazy(*_a)
// >> lit('}')
// ;
// geometry_dispatch.add
// ("\"Point\"",&point_coordinates)
// ("\"LineString\"",&linestring_coordinates)
// ("\"Polygon\"",&polygon_coordinates)
// ;
//////////////////////////////////////////////////////////////////
geometry = (lit('{')[_a = 0 ]
>> lit("\"type\"") >> lit(':') >> geometry_dispatch[_a = _1] // <---- should be Nabialek trick!
>> lit(',')
>> (lit("\"coordinates\"") > lit(':') > coordinates(_r1,_a)
|
lit("\"geometries\"") > lit(':')
>> lit('[') >> geometry_collection(_r1) >> lit(']'))
>> lit('}'))
| lit("null")
;
geometry_dispatch.add
("\"Point\"",1)
("\"LineString\"",2)
("\"Polygon\"",3)
("\"MultiPoint\"",4)
("\"MultiLineString\"",5)
("\"MultiPolygon\"",6)
("\"GeometryCollection\"",7)
//
;
coordinates = (eps(_r2 == 1) > point_coordinates(_r1))
| (eps(_r2 == 2) > linestring_coordinates(_r1))
| (eps(_r2 == 3) > polygon_coordinates(_r1))
| (eps(_r2 == 4) > multipoint_coordinates(_r1))
| (eps(_r2 == 5) > multilinestring_coordinates(_r1))
| (eps(_r2 == 6) > multipolygon_coordinates(_r1))
;
point_coordinates = eps[ _a = new_<geometry_type>(geometry_type::types::Point) ]
> ( point(SEG_MOVETO,_a) [push_back(_r1,_a)] | eps[cleanup_(_a)][_pass = false] )
;
linestring_coordinates = eps[ _a = new_<geometry_type>(geometry_type::types::LineString)]
> -(points(_a) [push_back(_r1,_a)]
| eps[cleanup_(_a)][_pass = false])
;
polygon_coordinates = eps[ _a = new_<geometry_type>(geometry_type::types::Polygon) ]
> ((lit('[')
> -(points(_a)[close_path_(_a)] % lit(','))
> lit(']')) [push_back(_r1,_a)]
| eps[cleanup_(_a)][_pass = false])
;
multipoint_coordinates = lit('[')
> -(point_coordinates(_r1) % lit(','))
> lit(']')
;
multilinestring_coordinates = lit('[')
> -(linestring_coordinates(_r1) % lit(','))
> lit(']')
;
multipolygon_coordinates = lit('[')
> -(polygon_coordinates(_r1) % lit(','))
> lit(']')
;
geometry_collection = *geometry(_r1) >> *(lit(',') >> geometry(_r1))
;
// point
point = lit('[') > -((double_ > lit(',') > double_)[push_vertex_(_r1,_r2,_1,_2)]) > lit(']');
// points
points = lit('[')[_a = SEG_MOVETO] > -(point (_a,_r1) % lit(',')[_a = SEG_LINETO]) > lit(']');
// give some rules names
geometry.name("Geometry");
geometry_collection.name("GeometryCollection");
geometry_dispatch.name("Geometry dispatch");
coordinates.name("Coordinates");
// error handler
on_error<fail>
(
geometry
, std::clog
<< boost::phoenix::val("Error! Expecting ")
<< _4 // what failed?
<< boost::phoenix::val(" here: \"")
<< where_message_(_3, _2, 16) // max 16 chars
<< boost::phoenix::val("\"")
<< std::endl
);
}
template struct mapnik::json::geometry_grammar<std::string::const_iterator>;
template struct mapnik::json::geometry_grammar<boost::spirit::multi_pass<std::istreambuf_iterator<char> > >;
}}
#endif
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2014-2016, imec
* All rights reserved.
*/
#include "error.h"
#include "bpmf.h"
#include <random>
#include <memory>
#include <cstdio>
#include <iostream>
#include <climits>
#include <stdexcept>
#include "io.h"
static const bool measure_perf = false;
std::ostream *Sys::os;
int Sys::procid = -1;
int Sys::nprocs = -1;
int Sys::nsims;
int Sys::burnin;
int Sys::update_freq;
double Sys::alpha = 2.0;
std::string Sys::odirname = "";
bool Sys::permute = true;
bool Sys::verbose = false;
unsigned Sys::grain_size;
void calc_upper_part(MatrixNNd &m, VectorNd v); // function for calcutation of an upper part of a symmetric matrix: m = v * v.transpose();
void copy_lower_part(MatrixNNd &m); // function to copy an upper part of a symmetric matrix to a lower part
// verifies that A has the same non-zero structure as B
void assert_same_struct(SparseMatrixD &A, SparseMatrixD &B)
{
assert(A.cols() == B.cols());
assert(A.rows() == B.rows());
for(int i=0; i<A.cols(); ++i) assert(A.col(i).nonZeros() == B.col(i).nonZeros());
}
//
// Does predictions for prediction matrix T
// Computes RMSE (Root Means Square Error)
//
void Sys::predict(Sys& other, bool all)
{
int n = (iter < burnin) ? 0 : (iter - burnin);
double se(0.0); // squared err
double se_avg(0.0); // squared avg err
unsigned nump(0); // number of predictions
int lo = all ? 0 : from();
int hi = all ? num() : to();
#pragma omp parallel for reduction(+:se,se_avg,nump)
for(int k = lo; k<hi; k++) {
for (Eigen::SparseMatrix<double>::InnerIterator it(T,k); it; ++it)
{
auto m = items().col(it.col());
auto u = other.items().col(it.row());
assert(m.norm() > 0.0);
assert(u.norm() > 0.0);
const double pred = m.dot(u) + mean_rating;
se += sqr(it.value() - pred);
// update average prediction
double &avg = Pavg.coeffRef(it.row(), it.col());
double delta = pred - avg;
avg = (n == 0) ? pred : (avg + delta/n);
double &m2 = Pm2.coeffRef(it.row(), it.col());
m2 = (n == 0) ? 0 : m2 + delta * (pred - avg);
se_avg += sqr(it.value() - avg);
nump++;
}
}
rmse = sqrt( se / nump );
rmse_avg = sqrt( se_avg / nump );
}
//
// Prints sampling progress
//
void Sys::print(double items_per_sec, double ratings_per_sec, double norm_u, double norm_m) {
char buf[1024];
std::string phase = (iter < Sys::burnin) ? "Burnin" : "Sampling";
sprintf(buf, "%d: %s iteration %d:\t RMSE: %3.4f\tavg RMSE: %3.4f\tFU(%6.2f)\tFM(%6.2f)\titems/sec: %6.2f\tratings/sec: %6.2fM\n",
Sys::procid, phase.c_str(), iter, rmse, rmse_avg, norm_u, norm_m, items_per_sec, ratings_per_sec / 1e6);
Sys::cout() << buf;
}
//
// Constructor with that reads MTX files
//
Sys::Sys(std::string name, std::string fname, std::string probename)
: name(name), iter(-1), assigned(false), dom(nprocs+1)
{
read_matrix(fname, M);
read_matrix(probename, T);
auto rows = std::max(M.rows(), T.rows());
auto cols = std::max(M.cols(), T.cols());
M.conservativeResize(rows,cols);
T.conservativeResize(rows,cols);
Pm2 = Pavg = Torig = T; // reference ratings and predicted ratings
assert(M.rows() == Pavg.rows());
assert(M.cols() == Pavg.cols());
assert(Sys::nprocs <= (int)Sys::max_procs);
}
//
// Constructs Sys as transpose of existing Sys
//
Sys::Sys(std::string name, const SparseMatrixD &Mt, const SparseMatrixD &Pt) : name(name), iter(-1), assigned(false), dom(nprocs+1) {
M = Mt.transpose();
Pm2 = Pavg = T = Torig = Pt.transpose(); // reference ratings and predicted ratings
assert(M.rows() == Pavg.rows());
assert(M.cols() == Pavg.cols());
}
Sys::~Sys()
{
if (measure_perf) {
Sys::cout() << " --------------------\n";
Sys::cout() << name << ": sampling times on " << procid << "\n";
for(int i = from(); i<to(); ++i)
{
Sys::cout() << "\t" << nnz(i) << "\t" << sample_time.at(i) / nsims << "\n";
}
Sys::cout() << " --------------------\n\n";
}
}
bool Sys::has_prop_posterior() const
{
return propMu.nonZeros() > 0;
}
void Sys::add_prop_posterior(std::string fnames)
{
if (fnames.empty()) return;
std::size_t pos = fnames.find_first_of(",");
std::string mu_name = fnames.substr(0, pos);
std::string lambda_name = fnames.substr(pos+1);
read_matrix(mu_name, propMu);
read_matrix(lambda_name, propLambda);
assert(propMu.cols() == num());
assert(propLambda.cols() == num());
assert(propMu.rows() == num_latent);
assert(propLambda.rows() == num_latent * num_latent);
}
//
// Intializes internal Matrices and Vectors
//
void Sys::init()
{
//-- M
assert(M.rows() > 0 && M.cols() > 0);
mean_rating = M.sum() / M.nonZeros();
items().setZero();
sum_map().setZero();
cov_map().setZero();
norm_map().setZero();
col_permutation.setIdentity(num());
if (Sys::odirname.size())
{
aggrMu = Eigen::MatrixXd::Zero(num_latent, num());
aggrLambda = Eigen::MatrixXd::Zero(num_latent * num_latent, num());
}
int count_sum = 0;
for(int k = 0; k<M.cols(); k++) {
int count = M.col(k).nonZeros();
count_sum += count;
}
Sys::cout() << "mean rating: " << mean_rating << std::endl;
Sys::cout() << "total number of ratings in train: " << M.nonZeros() << std::endl;
Sys::cout() << "total number of ratings in test: " << T.nonZeros() << std::endl;
Sys::cout() << "average ratings per row: " << (double)count_sum / (double)M.cols() << std::endl;
Sys::cout() << "num " << name << ": " << num() << std::endl;
if (has_prop_posterior())
{
Sys::cout() << "with propagated posterior" << std::endl;
}
if (measure_perf) sample_time.resize(num(), .0);
}
class PrecomputedLLT : public Eigen::LLT<MatrixNNd>
{
public:
void operator=(const MatrixNNd &m) { m_matrix = m; m_isInitialized = true; m_info = Eigen::Success; }
};
//
// Update ONE movie or one user
//
VectorNd Sys::sample(long idx, const MapNXd in)
{
auto start = tick();
VectorNd hp_mu;
MatrixNNd hp_LambdaF;
MatrixNNd hp_LambdaL;
if (has_prop_posterior())
{
hp_mu = propMu.col(idx);
hp_LambdaF = Eigen::Map<MatrixNNd>(propLambda.col(idx).data());
hp_LambdaL = hp_LambdaF.llt().matrixL();
}
else
{
hp_mu = hp.mu;
hp_LambdaF = hp.LambdaF;
hp_LambdaL = hp.LambdaL;
}
VectorNd rr = hp_LambdaF * hp.mu; // vector num_latent x 1, we will use it in formula (14) from the paper
PrecomputedLLT chol; // matrix num_latent x num_latent, chol="lambda_i with *" from formula (14)
MatrixNNd MM(MatrixNNd::Zero());
for (SparseMatrixD::InnerIterator it(M, idx); it; ++it)
{
auto col = in.col(it.row());
MM.triangularView<Eigen::Upper>() = col * col.transpose();
rr.noalias() += col * ((it.value() - mean_rating) * alpha);
}
// Here, we copy a triangular upper part to a triangular lower part, because the matrix is symmetric.
MM.triangularView<Eigen::Lower>() = MM.transpose();
chol.compute(hp_LambdaF + alpha * MM);
if(chol.info() != Eigen::Success) THROWERROR("Cholesky failed");
// now we should calculate formula (14) from the paper
// u_i for k-th iteration = Gaussian distribution N(u_i | mu_i with *, [lambda_i with *]^-1) =
// = mu_i with * + s * [U]^-1,
// where
// s is a random vector with N(0, I),
// mu_i with * is a vector num_latent x 1,
// mu_i with * = [lambda_i with *]^-1 * rr,
// lambda_i with * = L * U
// Expression u_i = U \ (s + (L \ rr)) in Matlab looks for Eigen library like:
chol.matrixL().solveInPlace(rr); // L*Y=rr => Y=L\rr, we store Y result again in rr vector
rr += nrandn(); // rr=s+(L\rr), we store result again in rr vector
chol.matrixU().solveInPlace(rr); // u_i=U\rr
items().col(idx) = rr; // we save rr vector in items matrix (it is user features matrix)
auto stop = tick();
register_time(idx, 1e6 * (stop - start));
//Sys::cout() << " " << count << ": " << 1e6*(stop - start) << std::endl;
assert(rr.norm() > .0);
return rr;
}
//
// update ALL movies / users in parallel
//
void Sys::sample(Sys &in)
{
iter++;
thread_vector<VectorNd> sums(VectorNd::Zero()); // sum
thread_vector<double> norms(0.0); // squared norm
thread_vector<MatrixNNd> prods(MatrixNNd::Zero()); // outer prod
#pragma omp parallel for schedule(guided)
for (int i = from(); i < to(); ++i)
{
#pragma omp task
{
auto r = sample(i, in.items());
MatrixNNd cov = (r * r.transpose());
prods.local() += cov;
sums.local() += r;
norms.local() += r.squaredNorm();
if (iter >= burnin && Sys::odirname.size())
{
aggrMu.col(i) += r;
aggrLambda.col(i) += Eigen::Map<Eigen::VectorXd>(cov.data(), num_latent * num_latent);
}
send_item(i);
}
}
#pragma omp taskwait
VectorNd sum = sums.combine();
MatrixNNd prod = prods.combine();
double norm = norms.combine();
const int N = num();
local_sum() = sum;
local_cov() = (prod - (sum * sum.transpose() / N)) / (N-1);
local_norm() = norm;
}
void Sys::register_time(int i, double t)
{
if (measure_perf) sample_time.at(i) += t;
}<commit_msg>ENH: remove dead code<commit_after>/*
* Copyright (c) 2014-2016, imec
* All rights reserved.
*/
#include "error.h"
#include "bpmf.h"
#include <random>
#include <memory>
#include <cstdio>
#include <iostream>
#include <climits>
#include <stdexcept>
#include "io.h"
static const bool measure_perf = false;
std::ostream *Sys::os;
int Sys::procid = -1;
int Sys::nprocs = -1;
int Sys::nsims;
int Sys::burnin;
int Sys::update_freq;
double Sys::alpha = 2.0;
std::string Sys::odirname = "";
bool Sys::permute = true;
bool Sys::verbose = false;
unsigned Sys::grain_size;
// verifies that A has the same non-zero structure as B
void assert_same_struct(SparseMatrixD &A, SparseMatrixD &B)
{
assert(A.cols() == B.cols());
assert(A.rows() == B.rows());
for(int i=0; i<A.cols(); ++i) assert(A.col(i).nonZeros() == B.col(i).nonZeros());
}
//
// Does predictions for prediction matrix T
// Computes RMSE (Root Means Square Error)
//
void Sys::predict(Sys& other, bool all)
{
int n = (iter < burnin) ? 0 : (iter - burnin);
double se(0.0); // squared err
double se_avg(0.0); // squared avg err
unsigned nump(0); // number of predictions
int lo = all ? 0 : from();
int hi = all ? num() : to();
#pragma omp parallel for reduction(+:se,se_avg,nump)
for(int k = lo; k<hi; k++) {
for (Eigen::SparseMatrix<double>::InnerIterator it(T,k); it; ++it)
{
auto m = items().col(it.col());
auto u = other.items().col(it.row());
assert(m.norm() > 0.0);
assert(u.norm() > 0.0);
const double pred = m.dot(u) + mean_rating;
se += sqr(it.value() - pred);
// update average prediction
double &avg = Pavg.coeffRef(it.row(), it.col());
double delta = pred - avg;
avg = (n == 0) ? pred : (avg + delta/n);
double &m2 = Pm2.coeffRef(it.row(), it.col());
m2 = (n == 0) ? 0 : m2 + delta * (pred - avg);
se_avg += sqr(it.value() - avg);
nump++;
}
}
rmse = sqrt( se / nump );
rmse_avg = sqrt( se_avg / nump );
}
//
// Prints sampling progress
//
void Sys::print(double items_per_sec, double ratings_per_sec, double norm_u, double norm_m) {
char buf[1024];
std::string phase = (iter < Sys::burnin) ? "Burnin" : "Sampling";
sprintf(buf, "%d: %s iteration %d:\t RMSE: %3.4f\tavg RMSE: %3.4f\tFU(%6.2f)\tFM(%6.2f)\titems/sec: %6.2f\tratings/sec: %6.2fM\n",
Sys::procid, phase.c_str(), iter, rmse, rmse_avg, norm_u, norm_m, items_per_sec, ratings_per_sec / 1e6);
Sys::cout() << buf;
}
//
// Constructor with that reads MTX files
//
Sys::Sys(std::string name, std::string fname, std::string probename)
: name(name), iter(-1), assigned(false), dom(nprocs+1)
{
read_matrix(fname, M);
read_matrix(probename, T);
auto rows = std::max(M.rows(), T.rows());
auto cols = std::max(M.cols(), T.cols());
M.conservativeResize(rows,cols);
T.conservativeResize(rows,cols);
Pm2 = Pavg = Torig = T; // reference ratings and predicted ratings
assert(M.rows() == Pavg.rows());
assert(M.cols() == Pavg.cols());
assert(Sys::nprocs <= (int)Sys::max_procs);
}
//
// Constructs Sys as transpose of existing Sys
//
Sys::Sys(std::string name, const SparseMatrixD &Mt, const SparseMatrixD &Pt) : name(name), iter(-1), assigned(false), dom(nprocs+1) {
M = Mt.transpose();
Pm2 = Pavg = T = Torig = Pt.transpose(); // reference ratings and predicted ratings
assert(M.rows() == Pavg.rows());
assert(M.cols() == Pavg.cols());
}
Sys::~Sys()
{
if (measure_perf) {
Sys::cout() << " --------------------\n";
Sys::cout() << name << ": sampling times on " << procid << "\n";
for(int i = from(); i<to(); ++i)
{
Sys::cout() << "\t" << nnz(i) << "\t" << sample_time.at(i) / nsims << "\n";
}
Sys::cout() << " --------------------\n\n";
}
}
bool Sys::has_prop_posterior() const
{
return propMu.nonZeros() > 0;
}
void Sys::add_prop_posterior(std::string fnames)
{
if (fnames.empty()) return;
std::size_t pos = fnames.find_first_of(",");
std::string mu_name = fnames.substr(0, pos);
std::string lambda_name = fnames.substr(pos+1);
read_matrix(mu_name, propMu);
read_matrix(lambda_name, propLambda);
assert(propMu.cols() == num());
assert(propLambda.cols() == num());
assert(propMu.rows() == num_latent);
assert(propLambda.rows() == num_latent * num_latent);
}
//
// Intializes internal Matrices and Vectors
//
void Sys::init()
{
//-- M
assert(M.rows() > 0 && M.cols() > 0);
mean_rating = M.sum() / M.nonZeros();
items().setZero();
sum_map().setZero();
cov_map().setZero();
norm_map().setZero();
col_permutation.setIdentity(num());
if (Sys::odirname.size())
{
aggrMu = Eigen::MatrixXd::Zero(num_latent, num());
aggrLambda = Eigen::MatrixXd::Zero(num_latent * num_latent, num());
}
int count_sum = 0;
for(int k = 0; k<M.cols(); k++) {
int count = M.col(k).nonZeros();
count_sum += count;
}
Sys::cout() << "mean rating: " << mean_rating << std::endl;
Sys::cout() << "total number of ratings in train: " << M.nonZeros() << std::endl;
Sys::cout() << "total number of ratings in test: " << T.nonZeros() << std::endl;
Sys::cout() << "average ratings per row: " << (double)count_sum / (double)M.cols() << std::endl;
Sys::cout() << "num " << name << ": " << num() << std::endl;
if (has_prop_posterior())
{
Sys::cout() << "with propagated posterior" << std::endl;
}
if (measure_perf) sample_time.resize(num(), .0);
}
class PrecomputedLLT : public Eigen::LLT<MatrixNNd>
{
public:
void operator=(const MatrixNNd &m) { m_matrix = m; m_isInitialized = true; m_info = Eigen::Success; }
};
//
// Update ONE movie or one user
//
VectorNd Sys::sample(long idx, const MapNXd in)
{
auto start = tick();
VectorNd hp_mu;
MatrixNNd hp_LambdaF;
MatrixNNd hp_LambdaL;
if (has_prop_posterior())
{
hp_mu = propMu.col(idx);
hp_LambdaF = Eigen::Map<MatrixNNd>(propLambda.col(idx).data());
hp_LambdaL = hp_LambdaF.llt().matrixL();
}
else
{
hp_mu = hp.mu;
hp_LambdaF = hp.LambdaF;
hp_LambdaL = hp.LambdaL;
}
VectorNd rr = hp_LambdaF * hp.mu; // vector num_latent x 1, we will use it in formula (14) from the paper
PrecomputedLLT chol; // matrix num_latent x num_latent, chol="lambda_i with *" from formula (14)
MatrixNNd MM(MatrixNNd::Zero());
for (SparseMatrixD::InnerIterator it(M, idx); it; ++it)
{
auto col = in.col(it.row());
MM.triangularView<Eigen::Upper>() += col * col.transpose();
rr.noalias() += col * ((it.value() - mean_rating) * alpha);
}
// copy upper -> lower part, matrix is symmetric.
MM.triangularView<Eigen::Lower>() = MM.transpose();
chol.compute(hp_LambdaF + alpha * MM);
if(chol.info() != Eigen::Success) THROWERROR("Cholesky failed");
// now we should calculate formula (14) from the paper
// u_i for k-th iteration = Gaussian distribution N(u_i | mu_i with *, [lambda_i with *]^-1) =
// = mu_i with * + s * [U]^-1,
// where
// s is a random vector with N(0, I),
// mu_i with * is a vector num_latent x 1,
// mu_i with * = [lambda_i with *]^-1 * rr,
// lambda_i with * = L * U
// Expression u_i = U \ (s + (L \ rr)) in Matlab looks for Eigen library like:
chol.matrixL().solveInPlace(rr); // L*Y=rr => Y=L\rr, we store Y result again in rr vector
rr += nrandn(); // rr=s+(L\rr), we store result again in rr vector
chol.matrixU().solveInPlace(rr); // u_i=U\rr
items().col(idx) = rr; // we save rr vector in items matrix (it is user features matrix)
auto stop = tick();
register_time(idx, 1e6 * (stop - start));
//Sys::cout() << " " << count << ": " << 1e6*(stop - start) << std::endl;
assert(rr.norm() > .0);
return rr;
}
//
// update ALL movies / users in parallel
//
void Sys::sample(Sys &in)
{
iter++;
thread_vector<VectorNd> sums(VectorNd::Zero()); // sum
thread_vector<double> norms(0.0); // squared norm
thread_vector<MatrixNNd> prods(MatrixNNd::Zero()); // outer prod
#pragma omp parallel for schedule(guided)
for (int i = from(); i < to(); ++i)
{
#pragma omp task
{
auto r = sample(i, in.items());
MatrixNNd cov = (r * r.transpose());
prods.local() += cov;
sums.local() += r;
norms.local() += r.squaredNorm();
if (iter >= burnin && Sys::odirname.size())
{
aggrMu.col(i) += r;
aggrLambda.col(i) += Eigen::Map<Eigen::VectorXd>(cov.data(), num_latent * num_latent);
}
send_item(i);
}
}
#pragma omp taskwait
VectorNd sum = sums.combine();
MatrixNNd prod = prods.combine();
double norm = norms.combine();
const int N = num();
local_sum() = sum;
local_cov() = (prod - (sum * sum.transpose() / N)) / (N-1);
local_norm() = norm;
}
void Sys::register_time(int i, double t)
{
if (measure_perf) sample_time.at(i) += t;
}<|endoftext|> |
<commit_before>#include "FileReaderMPACK.hpp"
#include "InputResource.hpp"
namespace MVFS
{
FileReaderMPACK::FileReaderMPACK(const char *pPath)
{
m_pInputResource = MPACK::Core::GetInputResource(pPath);
m_pInputResource->Open();
}
FileReaderMPACK::~FileReaderMPACK()
{
delete m_pInputResource;
}
int FileReaderMPACK::Size()
{
return m_pInputResource->GetLength();
}
void FileReaderMPACK::Reset()
{
m_pInputResource->SetOffset(0);
}
void FileReaderMPACK::Read(char *pBuffer, int size)
{
m_pInputResource->Read(pBuffer,size);
}
void FileReaderMPACK::ReadFrom(int offset, char *pBuffer, int size)
{
m_pInputResource->ReadFrom(offset,pBuffer,size);
}
void FileReaderMPACK::Skip(int size)
{
m_pInputResource->Skip(size);
}
int FileReaderMPACK::GetOffset()
{
return m_pInputResource->GetOffset();
}
void FileReaderMPACK::SetOffset(int offset)
{
m_pInputResource->SetOffset(offset);
}
FileReaderMPACK* FileReaderMPACK::Open(const char *pPath)
{
return new FileReaderMPACK(pPath);
}
}
<commit_msg>Resources: add sanity check for FileReaderMPACK::Open<commit_after>#include "FileReaderMPACK.hpp"
#include "InputResource.hpp"
namespace MVFS
{
FileReaderMPACK::FileReaderMPACK(const char *pPath)
{
m_pInputResource = MPACK::Core::GetInputResource(pPath);
m_pInputResource->Open();
}
FileReaderMPACK::~FileReaderMPACK()
{
delete m_pInputResource;
}
int FileReaderMPACK::Size()
{
return m_pInputResource->GetLength();
}
void FileReaderMPACK::Reset()
{
m_pInputResource->SetOffset(0);
}
void FileReaderMPACK::Read(char *pBuffer, int size)
{
m_pInputResource->Read(pBuffer,size);
}
void FileReaderMPACK::ReadFrom(int offset, char *pBuffer, int size)
{
m_pInputResource->ReadFrom(offset,pBuffer,size);
}
void FileReaderMPACK::Skip(int size)
{
m_pInputResource->Skip(size);
}
int FileReaderMPACK::GetOffset()
{
return m_pInputResource->GetOffset();
}
void FileReaderMPACK::SetOffset(int offset)
{
m_pInputResource->SetOffset(offset);
}
FileReaderMPACK* FileReaderMPACK::Open(const char *pPath)
{
FileReaderMPACK *fileReaderMPACK = new FileReaderMPACK(pPath);
if(fileReaderMPACK)
{
return fileReaderMPACK;
}
LOGE("FileReaderMPACK::Open fileReaderMPACK is NULL");
return NULL;
}
}
<|endoftext|> |
<commit_before>/*****************************************************************************
YASK: Yet Another Stencil Kernel
Copyright (c) 2014-2019, Intel Corporation
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice 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.
*****************************************************************************/
// This file contains implementations of AutoTuner methods and
// use of the tuner from StencilContext.
#include "yask_stencil.hpp"
using namespace std;
namespace yask {
// Ctor.
AutoTuner::AutoTuner(StencilContext* context,
KernelSettings* settings,
const std::string& name) :
ContextLinker(context),
_settings(settings),
_name("auto-tuner") {
assert(settings);
if (name.length())
_name += "(" + name + ")";
clear(settings->_do_auto_tune);
}
// Eval auto-tuner for given number of steps.
void StencilContext::eval_auto_tuner(idx_t num_steps) {
STATE_VARS(this);
_at.steps_done += num_steps;
_at.timer.stop();
if (state->_use_pack_tuners) {
for (auto& sp : stPacks)
sp->getAT().eval();
}
else
_at.eval();
}
// Reset auto-tuners.
void StencilContext::reset_auto_tuner(bool enable, bool verbose) {
for (auto& sp : stPacks)
sp->getAT().clear(!enable, verbose);
_at.clear(!enable, verbose);
}
// Determine if any auto tuners are running.
bool StencilContext::is_auto_tuner_enabled() const {
STATE_VARS(this);
bool done = true;
if (state->_use_pack_tuners) {
for (auto& sp : stPacks)
if (!sp->getAT().is_done())
done = false;
} else
done = _at.is_done();
return !done;
}
// Apply auto-tuning immediately, i.e., not as part of normal processing.
// Will alter data in grids.
void StencilContext::run_auto_tuner_now(bool verbose) {
STATE_VARS(this);
if (!rank_bb.bb_valid)
THROW_YASK_EXCEPTION("Error: run_auto_tuner_now() called without calling prepare_solution() first");
os << "Auto-tuning...\n" << flush;
YaskTimer at_timer;
at_timer.start();
// Temporarily disable halo exchange to tune intra-rank.
enable_halo_exchange = false;
// Temporarily ignore step conditions to force eval of conditional
// bundles. NB: may affect perf, e.g., if packs A and B run in
// AAABAAAB sequence, perf may be [very] different if run as
// ABABAB..., esp. w/temporal tiling. TODO: work around this.
check_step_conds = false;
// Init tuners.
reset_auto_tuner(true, verbose);
// Reset stats.
clear_timers();
// Determine number of steps to run.
// If wave-fronts are enabled, run a max number of these steps.
idx_t step_dir = dims->_step_dir; // +/- 1.
idx_t step_t = min(max(wf_steps, idx_t(1)), +AutoTuner::max_step_t) * step_dir;
// Run time-steps until AT converges.
for (idx_t t = 0; ; t += step_t) {
// Run step_t time-step(s).
run_solution(t, t + step_t - step_dir);
// AT done on this rank?
if (!is_auto_tuner_enabled())
break;
}
// Wait for all ranks to finish.
os << "Waiting for auto-tuner to converge on all ranks...\n";
env->global_barrier();
// reenable normal operation.
#ifndef NO_HALO_EXCHANGE
enable_halo_exchange = true;
#endif
check_step_conds = true;
// Report results.
at_timer.stop();
os << "Auto-tuner done after " << steps_done << " step(s) in " <<
makeNumStr(at_timer.get_elapsed_secs()) << " secs.\n";
if (state->_use_pack_tuners) {
for (auto& sp : stPacks)
sp->getAT().print_settings(os);
} else
_at.print_settings(os);
print_temporal_tiling_info();
// Reset stats.
clear_timers();
}
// Print the best settings.
void AutoTuner::print_settings(ostream& os) const {
if (tune_mini_blks())
os << _name << ": best-mini-block-size: " <<
target_sizes().makeDimValStr(" * ") << endl;
else
os << _name << ": best-block-size: " <<
target_sizes().makeDimValStr(" * ") << endl <<
_name << ": mini-block-size: " <<
_settings->_mini_block_sizes.makeDimValStr(" * ") << endl;
os << _name << ": sub-block-size: " <<
_settings->_sub_block_sizes.makeDimValStr(" * ") << endl <<
flush;
}
// Access settings.
bool AutoTuner::tune_mini_blks() const {
return _context->get_settings()->_tune_mini_blks;
}
// Reset the auto-tuner.
void AutoTuner::clear(bool mark_done, bool verbose) {
STATE_VARS(this);
#ifdef TRACE
this->verbose = true;
#else
this->verbose = verbose;
#endif
// Apply the best known settings from existing data, if any.
if (best_rate > 0.) {
target_sizes() = best_sizes;
apply();
os << _name << ": applying size " <<
best_sizes.makeDimValStr(" * ") << endl;
}
// Reset all vars.
results.clear();
n2big = n2small = n2far = 0;
best_sizes = target_sizes();
best_rate = 0.;
center_sizes = best_sizes;
radius = max_radius;
done = mark_done;
neigh_idx = 0;
better_neigh_found = false;
ctime = 0.;
csteps = 0;
in_warmup = true;
timer.clear();
steps_done = 0;
// Set min blocks to number of region threads.
int rt=0, bt=0;
get_num_comp_threads(rt, bt);
min_blks = rt;
// Adjust starting block if needed.
for (auto dim : center_sizes.getDims()) {
auto& dname = dim.getName();
auto& dval = dim.getVal();
if (dname == step_dim) {
target_steps = target_sizes()[dname]; // save value.
center_sizes[dname] = target_steps;
} else {
auto dmax = max(idx_t(1), outer_sizes()[dname] / 2);
if (dval > dmax || dval < 1)
center_sizes[dname] = dmax;
}
}
if (!done) {
TRACE_MSG(_name << ": starting size: " <<
center_sizes.makeDimValStr(" * "));
TRACE_MSG(_name << ": starting search radius: " << radius);
}
} // clear.
// Evaluate the previous run and take next auto-tuner step.
void AutoTuner::eval() {
STATE_VARS(this);
// Get elapsed time and reset.
double etime = timer.get_elapsed_secs();
timer.clear();
idx_t steps = steps_done;
steps_done = 0;
// Leave if done.
if (done)
return;
// Setup not done?
if (!nullop)
return;
// Cumulative stats.
csteps += steps;
ctime += etime;
// Still in warmup?
if (in_warmup) {
// Warmup not done?
if (ctime < warmup_secs && csteps < warmup_steps)
return;
// Done.
os << _name << ": finished warmup for " <<
csteps << " steps(s) in " <<
makeNumStr(ctime) << " secs\n" <<
_name << ": tuning " << (tune_mini_blks() ? "mini-" : "") <<
"block sizes...\n";
in_warmup = false;
// Restart for first measurement.
csteps = 0;
ctime = 0;
// Fix settings for next step.
apply();
TRACE_MSG(_name << ": first size " <<
target_sizes().makeDimValStr(" * "));
return;
}
// Need more steps to get a good measurement?
if (ctime < min_secs && csteps < min_steps)
return;
// Calc perf and reset vars for next time.
double rate = (ctime > 0.) ? (double(csteps) / ctime) : 0.;
os << _name << ": search-radius=" << radius << ": " <<
csteps << " steps(s) in " <<
makeNumStr(ctime) << " secs (" <<
makeNumStr(rate) << " steps/sec) with size " <<
target_sizes().makeDimValStr(" * ") << endl;
csteps = 0;
ctime = 0.;
// Save result.
results[target_sizes()] = rate;
bool is_better = rate > best_rate;
if (is_better) {
best_sizes = target_sizes();
best_rate = rate;
better_neigh_found = true;
}
// At this point, we have gathered perf info on the current settings.
// Now, we need to determine next unevaluated point in search space.
while (true) {
// Gradient-descent(GD) search:
// Use the neighborhood info from MPI to track neighbors.
// TODO: move to a more general place.
// Valid neighbor index?
if (neigh_idx < mpiInfo->neighborhood_size) {
// Convert index to offsets in each domain dim.
auto ofs = mpiInfo->neighborhood_sizes.unlayout(neigh_idx);
// Next neighbor of center point.
neigh_idx++;
// Determine new size.
IdxTuple bsize(center_sizes);
bool ok = true;
int mdist = 0; // manhattan dist from center.
for (auto odim : ofs.getDims()) {
auto& dname = odim.getName(); // a domain-dim name.
auto& dofs = odim.getVal(); // always [0..2].
// Min and max sizes of this dim.
auto dmin = dims->_cluster_pts[dname];
auto dmax = outer_sizes()[dname];
// Determine distance of GD neighbors.
auto dist = dmin; // step by cluster size.
dist = max(dist, min_dist);
dist *= radius;
auto sz = center_sizes[dname];
switch (dofs) {
case 0: // reduce size in 'odim'.
sz -= dist;
mdist++;
break;
case 1: // keep size in 'odim'.
break;
case 2: // increase size in 'odim'.
sz += dist;
mdist++;
break;
default:
assert(false && "internal error in tune_settings()");
}
// Don't look in far corners.
if (mdist > 2) {
n2far++;
ok = false;
break; // out of dim-loop.
}
// Too small?
if (sz < dmin) {
n2small++;
ok = false;
break; // out of dim-loop.
}
// Adjustments.
sz = min(sz, dmax);
sz = ROUND_UP(sz, dmin);
// Save.
bsize[dname] = sz;
} // domain dims.
TRACE_MSG(_name << ": checking size " <<
bsize.makeDimValStr(" * "));
// Too small?
if (ok && get_num_domain_points(bsize) < min_pts) {
n2small++;
ok = false;
}
// Too few?
else if (ok) {
idx_t nblks = get_num_domain_points(outer_sizes()) /
get_num_domain_points(bsize);
if (nblks < min_blks) {
ok = false;
n2big++;
}
}
// Valid size and not already checked?
if (ok && !results.count(bsize)) {
// Run next step with this size.
target_sizes() = bsize;
break; // out of block-search loop.
}
} // valid neighbor index.
// Beyond last neighbor of current center?
else {
// Should GD continue?
bool stop_gd = !better_neigh_found;
// Make new center at best size so far.
center_sizes = best_sizes;
// Reset search vars.
neigh_idx = 0;
better_neigh_found = false;
// No new best point, so this is the end of this
// GD search.
if (stop_gd) {
// Move to next radius.
radius /= 2;
// Done?
if (radius < 1) {
// Reset AT and disable.
clear(true);
os << _name << ": done" << endl;
return;
}
TRACE_MSG(_name << ": new search radius=" << radius);
}
else {
TRACE_MSG(_name << ": continuing search from " <<
center_sizes.makeDimValStr(" * "));
}
} // beyond next neighbor of center.
} // search for new setting to try.
// Fix settings for next step.
apply();
TRACE_MSG(_name << ": next size " <<
target_sizes().makeDimValStr(" * "));
} // eval.
// Apply auto-tuner settings to prepare for a run.
// Does *not* set the settings being tuned.
void AutoTuner::apply() {
STATE_VARS(this);
// Restore step-dim value for block.
target_sizes()[step_posn] = target_steps;
// Change derived sizes to 0 so adjustSettings()
// will set them to the default.
if (!tune_mini_blks()) {
_settings->_block_group_sizes.setValsSame(0);
_settings->_mini_block_sizes.setValsSame(0);
}
_settings->_mini_block_group_sizes.setValsSame(0);
_settings->_sub_block_sizes.setValsSame(0);
_settings->_sub_block_group_sizes.setValsSame(0);
// Save debug output and set to null.
auto saved_op = get_debug_output();
set_debug_output(nullop);
// Make sure everything is resized based on block size.
_settings->adjustSettings();
// Update temporal blocking info.
_context->update_tb_info();
// Reallocate scratch data based on new mini-block size.
// TODO: only do this when blocks have increased or
// decreased by a certain percentage.
_context->allocScratchData();
// Restore debug output.
set_debug_output(saved_op);
}
} // namespace yask.
<commit_msg>Improve auto-tuner status msg.<commit_after>/*****************************************************************************
YASK: Yet Another Stencil Kernel
Copyright (c) 2014-2019, Intel Corporation
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice 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.
*****************************************************************************/
// This file contains implementations of AutoTuner methods and
// use of the tuner from StencilContext.
#include "yask_stencil.hpp"
using namespace std;
namespace yask {
// Ctor.
AutoTuner::AutoTuner(StencilContext* context,
KernelSettings* settings,
const std::string& name) :
ContextLinker(context),
_settings(settings),
_name("auto-tuner") {
assert(settings);
if (name.length())
_name += "(" + name + ")";
clear(settings->_do_auto_tune);
}
// Eval auto-tuner for given number of steps.
void StencilContext::eval_auto_tuner(idx_t num_steps) {
STATE_VARS(this);
_at.steps_done += num_steps;
_at.timer.stop();
if (state->_use_pack_tuners) {
for (auto& sp : stPacks)
sp->getAT().eval();
}
else
_at.eval();
}
// Reset auto-tuners.
void StencilContext::reset_auto_tuner(bool enable, bool verbose) {
for (auto& sp : stPacks)
sp->getAT().clear(!enable, verbose);
_at.clear(!enable, verbose);
}
// Determine if any auto tuners are running.
bool StencilContext::is_auto_tuner_enabled() const {
STATE_VARS(this);
bool done = true;
if (state->_use_pack_tuners) {
for (auto& sp : stPacks)
if (!sp->getAT().is_done())
done = false;
} else
done = _at.is_done();
return !done;
}
// Apply auto-tuning immediately, i.e., not as part of normal processing.
// Will alter data in grids.
void StencilContext::run_auto_tuner_now(bool verbose) {
STATE_VARS(this);
if (!rank_bb.bb_valid)
THROW_YASK_EXCEPTION("Error: run_auto_tuner_now() called without calling prepare_solution() first");
os << "Auto-tuning...\n" << flush;
YaskTimer at_timer;
at_timer.start();
// Temporarily disable halo exchange to tune intra-rank.
enable_halo_exchange = false;
// Temporarily ignore step conditions to force eval of conditional
// bundles. NB: may affect perf, e.g., if packs A and B run in
// AAABAAAB sequence, perf may be [very] different if run as
// ABABAB..., esp. w/temporal tiling. TODO: work around this.
check_step_conds = false;
// Init tuners.
reset_auto_tuner(true, verbose);
// Reset stats.
clear_timers();
// Determine number of steps to run.
// If wave-fronts are enabled, run a max number of these steps.
idx_t step_dir = dims->_step_dir; // +/- 1.
idx_t step_t = min(max(wf_steps, idx_t(1)), +AutoTuner::max_step_t) * step_dir;
// Run time-steps until AT converges.
for (idx_t t = 0; ; t += step_t) {
// Run step_t time-step(s).
run_solution(t, t + step_t - step_dir);
// AT done on this rank?
if (!is_auto_tuner_enabled())
break;
}
// Wait for all ranks to finish.
os << "Waiting for auto-tuner to converge on all ranks...\n";
env->global_barrier();
// reenable normal operation.
#ifndef NO_HALO_EXCHANGE
enable_halo_exchange = true;
#endif
check_step_conds = true;
// Report results.
at_timer.stop();
os << "Auto-tuner done after " << steps_done << " step(s) in " <<
makeNumStr(at_timer.get_elapsed_secs()) << " secs.\n";
if (state->_use_pack_tuners) {
for (auto& sp : stPacks)
sp->getAT().print_settings(os);
} else
_at.print_settings(os);
print_temporal_tiling_info();
// Reset stats.
clear_timers();
}
// Print the best settings.
void AutoTuner::print_settings(ostream& os) const {
if (tune_mini_blks())
os << _name << ": best-mini-block-size: " <<
target_sizes().makeDimValStr(" * ") << endl;
else
os << _name << ": best-block-size: " <<
target_sizes().makeDimValStr(" * ") << endl <<
_name << ": mini-block-size: " <<
_settings->_mini_block_sizes.makeDimValStr(" * ") << endl;
os << _name << ": sub-block-size: " <<
_settings->_sub_block_sizes.makeDimValStr(" * ") << endl <<
flush;
}
// Access settings.
bool AutoTuner::tune_mini_blks() const {
return _context->get_settings()->_tune_mini_blks;
}
// Reset the auto-tuner.
void AutoTuner::clear(bool mark_done, bool verbose) {
STATE_VARS(this);
#ifdef TRACE
this->verbose = true;
#else
this->verbose = verbose;
#endif
// Apply the best known settings from existing data, if any.
if (best_rate > 0.) {
target_sizes() = best_sizes;
apply();
os << _name << ": applying size " <<
best_sizes.makeDimValStr(" * ") << endl;
}
// Reset all vars.
results.clear();
n2big = n2small = n2far = 0;
best_sizes = target_sizes();
best_rate = 0.;
center_sizes = best_sizes;
radius = max_radius;
done = mark_done;
neigh_idx = 0;
better_neigh_found = false;
ctime = 0.;
csteps = 0;
in_warmup = true;
timer.clear();
steps_done = 0;
// Set min blocks to number of region threads.
int rt=0, bt=0;
get_num_comp_threads(rt, bt);
min_blks = rt;
// Adjust starting block if needed.
for (auto dim : center_sizes.getDims()) {
auto& dname = dim.getName();
auto& dval = dim.getVal();
if (dname == step_dim) {
target_steps = target_sizes()[dname]; // save value.
center_sizes[dname] = target_steps;
} else {
auto dmax = max(idx_t(1), outer_sizes()[dname] / 2);
if (dval > dmax || dval < 1)
center_sizes[dname] = dmax;
}
}
if (!done) {
TRACE_MSG(_name << ": starting size: " <<
center_sizes.makeDimValStr(" * "));
TRACE_MSG(_name << ": starting search radius: " << radius);
}
} // clear.
// Evaluate the previous run and take next auto-tuner step.
void AutoTuner::eval() {
STATE_VARS(this);
// Get elapsed time and reset.
double etime = timer.get_elapsed_secs();
timer.clear();
idx_t steps = steps_done;
steps_done = 0;
// Leave if done.
if (done)
return;
// Setup not done?
if (!nullop)
return;
// Cumulative stats.
csteps += steps;
ctime += etime;
// Still in warmup?
if (in_warmup) {
// Warmup not done?
if (ctime < warmup_secs && csteps < warmup_steps)
return;
// Done.
os << _name << ": finished warmup for " <<
csteps << " steps(s) in " <<
makeNumStr(ctime) << " secs\n" <<
_name << ": tuning " << (tune_mini_blks() ? "mini-" : "") <<
"block sizes...\n";
in_warmup = false;
// Restart for first measurement.
csteps = 0;
ctime = 0;
// Fix settings for next step.
apply();
TRACE_MSG(_name << ": first size " <<
target_sizes().makeDimValStr(" * "));
return;
}
// Need more steps to get a good measurement?
if (ctime < min_secs && csteps < min_steps)
return;
// Calc perf and reset vars for next time.
double rate = (ctime > 0.) ? (double(csteps) / ctime) : 0.;
os << _name << ": search-dist=" << radius << ": " <<
csteps << " steps(s) in " <<
makeNumStr(ctime) << " secs (" <<
makeNumStr(rate) << " steps/sec) with size " <<
target_sizes().makeDimValStr(" * ") << endl;
csteps = 0;
ctime = 0.;
// Save result.
results[target_sizes()] = rate;
bool is_better = rate > best_rate;
if (is_better) {
best_sizes = target_sizes();
best_rate = rate;
better_neigh_found = true;
}
// At this point, we have gathered perf info on the current settings.
// Now, we need to determine next unevaluated point in search space.
while (true) {
// Gradient-descent(GD) search:
// Use the neighborhood info from MPI to track neighbors.
// TODO: move to a more general place.
// Valid neighbor index?
if (neigh_idx < mpiInfo->neighborhood_size) {
// Convert index to offsets in each domain dim.
auto ofs = mpiInfo->neighborhood_sizes.unlayout(neigh_idx);
// Next neighbor of center point.
neigh_idx++;
// Determine new size.
IdxTuple bsize(center_sizes);
bool ok = true;
int mdist = 0; // manhattan dist from center.
for (auto odim : ofs.getDims()) {
auto& dname = odim.getName(); // a domain-dim name.
auto& dofs = odim.getVal(); // always [0..2].
// Min and max sizes of this dim.
auto dmin = dims->_cluster_pts[dname];
auto dmax = outer_sizes()[dname];
// Determine distance of GD neighbors.
auto dist = dmin; // step by cluster size.
dist = max(dist, min_dist);
dist *= radius;
auto sz = center_sizes[dname];
switch (dofs) {
case 0: // reduce size in 'odim'.
sz -= dist;
mdist++;
break;
case 1: // keep size in 'odim'.
break;
case 2: // increase size in 'odim'.
sz += dist;
mdist++;
break;
default:
assert(false && "internal error in tune_settings()");
}
// Don't look in far corners.
if (mdist > 2) {
n2far++;
ok = false;
break; // out of dim-loop.
}
// Too small?
if (sz < dmin) {
n2small++;
ok = false;
break; // out of dim-loop.
}
// Adjustments.
sz = min(sz, dmax);
sz = ROUND_UP(sz, dmin);
// Save.
bsize[dname] = sz;
} // domain dims.
TRACE_MSG(_name << ": checking size " <<
bsize.makeDimValStr(" * "));
// Too small?
if (ok && get_num_domain_points(bsize) < min_pts) {
n2small++;
ok = false;
}
// Too few?
else if (ok) {
idx_t nblks = get_num_domain_points(outer_sizes()) /
get_num_domain_points(bsize);
if (nblks < min_blks) {
ok = false;
n2big++;
}
}
// Valid size and not already checked?
if (ok && !results.count(bsize)) {
// Run next step with this size.
target_sizes() = bsize;
break; // out of block-search loop.
}
} // valid neighbor index.
// Beyond last neighbor of current center?
else {
// Should GD continue?
bool stop_gd = !better_neigh_found;
// Make new center at best size so far.
center_sizes = best_sizes;
// Reset search vars.
neigh_idx = 0;
better_neigh_found = false;
// No new best point, so this is the end of this
// GD search.
if (stop_gd) {
// Move to next radius.
radius /= 2;
// Done?
if (radius < 1) {
// Reset AT and disable.
clear(true);
os << _name << ": done" << endl;
return;
}
TRACE_MSG(_name << ": new search radius=" << radius);
}
else {
TRACE_MSG(_name << ": continuing search from " <<
center_sizes.makeDimValStr(" * "));
}
} // beyond next neighbor of center.
} // search for new setting to try.
// Fix settings for next step.
apply();
TRACE_MSG(_name << ": next size " <<
target_sizes().makeDimValStr(" * "));
} // eval.
// Apply auto-tuner settings to prepare for a run.
// Does *not* set the settings being tuned.
void AutoTuner::apply() {
STATE_VARS(this);
// Restore step-dim value for block.
target_sizes()[step_posn] = target_steps;
// Change derived sizes to 0 so adjustSettings()
// will set them to the default.
if (!tune_mini_blks()) {
_settings->_block_group_sizes.setValsSame(0);
_settings->_mini_block_sizes.setValsSame(0);
}
_settings->_mini_block_group_sizes.setValsSame(0);
_settings->_sub_block_sizes.setValsSame(0);
_settings->_sub_block_group_sizes.setValsSame(0);
// Save debug output and set to null.
auto saved_op = get_debug_output();
set_debug_output(nullop);
// Make sure everything is resized based on block size.
_settings->adjustSettings();
// Update temporal blocking info.
_context->update_tb_info();
// Reallocate scratch data based on new mini-block size.
// TODO: only do this when blocks have increased or
// decreased by a certain percentage.
_context->allocScratchData();
// Restore debug output.
set_debug_output(saved_op);
}
} // namespace yask.
<|endoftext|> |
<commit_before>/* This file is part of the Pangolin Project.
* http://github.com/stevenlovegrove/Pangolin
*
* Copyright (c) 2014 Steven Lovegrove
*
* 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 <pangolin/video/drivers/unpack.h>
#include <pangolin/video/video_factory.h>
#include <pangolin/video/iostream_operators.h>
#ifdef DEBUGUNPACK
#include <pangolin/utils/timer.h>
#define TSTART() pangolin::basetime start,last,now; start = pangolin::TimeNow(); last = start;
#define TGRABANDPRINT(...) now = pangolin::TimeNow(); fprintf(stderr,"UNPACK: "); fprintf(stderr, __VA_ARGS__); fprintf(stderr, " %fms.\n",1000*pangolin::TimeDiff_s(last, now)); last = now;
#define DBGPRINT(...) fprintf(stderr,"UNPACK: "); fprintf(stderr, __VA_ARGS__); fprintf(stderr,"\n");
#else
#define TSTART()
#define TGRABANDPRINT(...)
#define DBGPRINT(...)
#endif
namespace pangolin
{
UnpackVideo::UnpackVideo(std::unique_ptr<VideoInterface> &src_, VideoPixelFormat out_fmt)
: src(std::move(src_)), size_bytes(0), buffer(0)
{
if( !src || out_fmt.channels != 1) {
throw VideoException("UnpackVideo: Only supports single channel output.");
}
videoin.push_back(src.get());
for(size_t s=0; s< src->Streams().size(); ++s) {
const size_t w = src->Streams()[s].Width();
const size_t h = src->Streams()[s].Height();
// Check compatibility of formats
const VideoPixelFormat in_fmt = src->Streams()[s].PixFormat();
if(in_fmt.channels > 1 || in_fmt.bpp > 16) {
throw VideoException("UnpackVideo: Only supports one channel input.");
}
const size_t pitch = (w*out_fmt.bpp)/ 8;
streams.push_back(pangolin::StreamInfo( out_fmt, w, h, pitch, (unsigned char*)0 + size_bytes ));
size_bytes += h*pitch;
}
buffer = new unsigned char[src->SizeBytes()];
}
UnpackVideo::~UnpackVideo()
{
delete[] buffer;
}
//! Implement VideoInput::Start()
void UnpackVideo::Start()
{
videoin[0]->Start();
}
//! Implement VideoInput::Stop()
void UnpackVideo::Stop()
{
videoin[0]->Stop();
}
//! Implement VideoInput::SizeBytes()
size_t UnpackVideo::SizeBytes() const
{
return size_bytes;
}
//! Implement VideoInput::Streams()
const std::vector<StreamInfo>& UnpackVideo::Streams() const
{
return streams;
}
template<typename T>
void ConvertFrom8bit(
Image<unsigned char>& out,
const Image<unsigned char>& in
) {
for(size_t r=0; r<out.h; ++r) {
T* pout = (T*)(out.ptr + r*out.pitch);
uint8_t* pin = in.ptr + r*in.pitch;
const uint8_t* pin_end = in.ptr + (r+1)*in.pitch;
while(pin != pin_end) {
*(pout++) = *(pin++);
}
}
}
template<typename T>
void ConvertFrom10bit(
Image<unsigned char>& out,
const Image<unsigned char>& in
) {
for(size_t r=0; r<out.h; ++r) {
T* pout = (T*)(out.ptr + r*out.pitch);
uint8_t* pin = in.ptr + r*in.pitch;
const uint8_t* pin_end = in.ptr + (r+1)*in.pitch;
while(pin != pin_end) {
uint64_t val = *(pin++);
val |= uint64_t(*(pin++)) << 8;
val |= uint64_t(*(pin++)) << 16;
val |= uint64_t(*(pin++)) << 24;
val |= uint64_t(*(pin++)) << 32;
*(pout++) = T( val & 0x00000003FF);
*(pout++) = T((val & 0x00000FFC00) >> 10);
*(pout++) = T((val & 0x003FF00000) >> 20);
*(pout++) = T((val & 0xFFC0000000) >> 30);
}
}
}
template<typename T>
void ConvertFrom12bit(
Image<unsigned char>& out,
const Image<unsigned char>& in
) {
for(size_t r=0; r<out.h; ++r) {
T* pout = (T*)(out.ptr + r*out.pitch);
uint8_t* pin = in.ptr + r*in.pitch;
const uint8_t* pin_end = in.ptr + (r+1)*in.pitch;
while(pin != pin_end) {
uint32_t val = *(pin++);
val |= uint32_t(*(pin++)) << 8;
val |= uint32_t(*(pin++)) << 16;
*(pout++) = T( val & 0x000FFF);
*(pout++) = T((val & 0xFFF000) >> 12);
}
}
}
void UnpackVideo::Process(unsigned char* image, const unsigned char* buffer)
{
TSTART()
for(size_t s=0; s<streams.size(); ++s) {
const Image<unsigned char> img_in = videoin[0]->Streams()[s].StreamImage(buffer);
Image<unsigned char> img_out = Streams()[s].StreamImage(image);
const int bits_in = videoin[0]->Streams()[s].PixFormat().bpp;
if(Streams()[s].PixFormat().format == "GRAY32F") {
if( bits_in == 8) {
ConvertFrom8bit<float>(img_out, img_in);
}else if( bits_in == 10) {
ConvertFrom10bit<float>(img_out, img_in);
}else if( bits_in == 12){
ConvertFrom12bit<float>(img_out, img_in);
}else{
throw pangolin::VideoException("Unsupported bitdepths.");
}
}else if(Streams()[s].PixFormat().format == "GRAY16LE") {
if( bits_in == 8) {
ConvertFrom8bit<uint16_t>(img_out, img_in);
}else if( bits_in == 10) {
ConvertFrom10bit<uint16_t>(img_out, img_in);
}else if( bits_in == 12){
ConvertFrom12bit<uint16_t>(img_out, img_in);
}else{
throw pangolin::VideoException("Unsupported bitdepths.");
}
}else{
}
}
TGRABANDPRINT("Unpacking took ")
}
//! Implement VideoInput::GrabNext()
bool UnpackVideo::GrabNext( unsigned char* image, bool wait )
{
if(videoin[0]->GrabNext(buffer,wait)) {
Process(image,buffer);
return true;
}else{
return false;
}
}
//! Implement VideoInput::GrabNewest()
bool UnpackVideo::GrabNewest( unsigned char* image, bool wait )
{
if(videoin[0]->GrabNewest(buffer,wait)) {
Process(image,buffer);
return true;
}else{
return false;
}
}
std::vector<VideoInterface*>& UnpackVideo::InputStreams()
{
return videoin;
}
unsigned int UnpackVideo::AvailableFrames() const
{
BufferAwareVideoInterface* vpi = dynamic_cast<BufferAwareVideoInterface*>(videoin[0]);
if(!vpi)
{
pango_print_warn("Unpack: child interface is not buffer aware.");
return 0;
}
else
{
return vpi->AvailableFrames();
}
}
bool UnpackVideo::DropNFrames(uint32_t n)
{
BufferAwareVideoInterface* vpi = dynamic_cast<BufferAwareVideoInterface*>(videoin[0]);
if(!vpi)
{
pango_print_warn("Unpack: child interface is not buffer aware.");
return false;
}
else
{
return vpi->DropNFrames(n);
}
}
PANGOLIN_REGISTER_FACTORY(UnpackVideo)
{
struct UnpackVideoFactory : public VideoFactoryInterface {
std::unique_ptr<VideoInterface> OpenVideo(const Uri& uri) override {
std::unique_ptr<VideoInterface> subvid = pangolin::OpenVideo(uri.url);
const bool make_float = uri.Contains("float");
return std::unique_ptr<VideoInterface>(
new UnpackVideo(subvid, VideoFormatFromString(make_float ? "GRAY32F" : "GRAY16LE"))
);
}
};
VideoFactoryRegistry::I().RegisterFactory(std::make_shared<UnpackVideoFactory>(), 10, "unpack");
}
}
#undef TSTART
#undef TGRABANDPRINT
#undef DBGPRINT
<commit_msg>UnpackVideo: Allow to overload output format.<commit_after>/* This file is part of the Pangolin Project.
* http://github.com/stevenlovegrove/Pangolin
*
* Copyright (c) 2014 Steven Lovegrove
*
* 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 <pangolin/video/drivers/unpack.h>
#include <pangolin/video/video_factory.h>
#include <pangolin/video/iostream_operators.h>
#ifdef DEBUGUNPACK
#include <pangolin/utils/timer.h>
#define TSTART() pangolin::basetime start,last,now; start = pangolin::TimeNow(); last = start;
#define TGRABANDPRINT(...) now = pangolin::TimeNow(); fprintf(stderr,"UNPACK: "); fprintf(stderr, __VA_ARGS__); fprintf(stderr, " %fms.\n",1000*pangolin::TimeDiff_s(last, now)); last = now;
#define DBGPRINT(...) fprintf(stderr,"UNPACK: "); fprintf(stderr, __VA_ARGS__); fprintf(stderr,"\n");
#else
#define TSTART()
#define TGRABANDPRINT(...)
#define DBGPRINT(...)
#endif
namespace pangolin
{
UnpackVideo::UnpackVideo(std::unique_ptr<VideoInterface> &src_, VideoPixelFormat out_fmt)
: src(std::move(src_)), size_bytes(0), buffer(0)
{
if( !src || out_fmt.channels != 1) {
throw VideoException("UnpackVideo: Only supports single channel output.");
}
videoin.push_back(src.get());
for(size_t s=0; s< src->Streams().size(); ++s) {
const size_t w = src->Streams()[s].Width();
const size_t h = src->Streams()[s].Height();
// Check compatibility of formats
const VideoPixelFormat in_fmt = src->Streams()[s].PixFormat();
if(in_fmt.channels > 1 || in_fmt.bpp > 16) {
throw VideoException("UnpackVideo: Only supports one channel input.");
}
const size_t pitch = (w*out_fmt.bpp)/ 8;
streams.push_back(pangolin::StreamInfo( out_fmt, w, h, pitch, (unsigned char*)0 + size_bytes ));
size_bytes += h*pitch;
}
buffer = new unsigned char[src->SizeBytes()];
}
UnpackVideo::~UnpackVideo()
{
delete[] buffer;
}
//! Implement VideoInput::Start()
void UnpackVideo::Start()
{
videoin[0]->Start();
}
//! Implement VideoInput::Stop()
void UnpackVideo::Stop()
{
videoin[0]->Stop();
}
//! Implement VideoInput::SizeBytes()
size_t UnpackVideo::SizeBytes() const
{
return size_bytes;
}
//! Implement VideoInput::Streams()
const std::vector<StreamInfo>& UnpackVideo::Streams() const
{
return streams;
}
template<typename T>
void ConvertFrom8bit(
Image<unsigned char>& out,
const Image<unsigned char>& in
) {
for(size_t r=0; r<out.h; ++r) {
T* pout = (T*)(out.ptr + r*out.pitch);
uint8_t* pin = in.ptr + r*in.pitch;
const uint8_t* pin_end = in.ptr + (r+1)*in.pitch;
while(pin != pin_end) {
*(pout++) = *(pin++);
}
}
}
template<typename T>
void ConvertFrom10bit(
Image<unsigned char>& out,
const Image<unsigned char>& in
) {
for(size_t r=0; r<out.h; ++r) {
T* pout = (T*)(out.ptr + r*out.pitch);
uint8_t* pin = in.ptr + r*in.pitch;
const uint8_t* pin_end = in.ptr + (r+1)*in.pitch;
while(pin != pin_end) {
uint64_t val = *(pin++);
val |= uint64_t(*(pin++)) << 8;
val |= uint64_t(*(pin++)) << 16;
val |= uint64_t(*(pin++)) << 24;
val |= uint64_t(*(pin++)) << 32;
*(pout++) = T( val & 0x00000003FF);
*(pout++) = T((val & 0x00000FFC00) >> 10);
*(pout++) = T((val & 0x003FF00000) >> 20);
*(pout++) = T((val & 0xFFC0000000) >> 30);
}
}
}
template<typename T>
void ConvertFrom12bit(
Image<unsigned char>& out,
const Image<unsigned char>& in
) {
for(size_t r=0; r<out.h; ++r) {
T* pout = (T*)(out.ptr + r*out.pitch);
uint8_t* pin = in.ptr + r*in.pitch;
const uint8_t* pin_end = in.ptr + (r+1)*in.pitch;
while(pin != pin_end) {
uint32_t val = *(pin++);
val |= uint32_t(*(pin++)) << 8;
val |= uint32_t(*(pin++)) << 16;
*(pout++) = T( val & 0x000FFF);
*(pout++) = T((val & 0xFFF000) >> 12);
}
}
}
void UnpackVideo::Process(unsigned char* image, const unsigned char* buffer)
{
TSTART()
for(size_t s=0; s<streams.size(); ++s) {
const Image<unsigned char> img_in = videoin[0]->Streams()[s].StreamImage(buffer);
Image<unsigned char> img_out = Streams()[s].StreamImage(image);
const int bits_in = videoin[0]->Streams()[s].PixFormat().bpp;
if(Streams()[s].PixFormat().format == "GRAY32F") {
if( bits_in == 8) {
ConvertFrom8bit<float>(img_out, img_in);
}else if( bits_in == 10) {
ConvertFrom10bit<float>(img_out, img_in);
}else if( bits_in == 12){
ConvertFrom12bit<float>(img_out, img_in);
}else{
throw pangolin::VideoException("Unsupported bitdepths.");
}
}else if(Streams()[s].PixFormat().format == "GRAY16LE") {
if( bits_in == 8) {
ConvertFrom8bit<uint16_t>(img_out, img_in);
}else if( bits_in == 10) {
ConvertFrom10bit<uint16_t>(img_out, img_in);
}else if( bits_in == 12){
ConvertFrom12bit<uint16_t>(img_out, img_in);
}else{
throw pangolin::VideoException("Unsupported bitdepths.");
}
}else{
}
}
TGRABANDPRINT("Unpacking took ")
}
//! Implement VideoInput::GrabNext()
bool UnpackVideo::GrabNext( unsigned char* image, bool wait )
{
if(videoin[0]->GrabNext(buffer,wait)) {
Process(image,buffer);
return true;
}else{
return false;
}
}
//! Implement VideoInput::GrabNewest()
bool UnpackVideo::GrabNewest( unsigned char* image, bool wait )
{
if(videoin[0]->GrabNewest(buffer,wait)) {
Process(image,buffer);
return true;
}else{
return false;
}
}
std::vector<VideoInterface*>& UnpackVideo::InputStreams()
{
return videoin;
}
unsigned int UnpackVideo::AvailableFrames() const
{
BufferAwareVideoInterface* vpi = dynamic_cast<BufferAwareVideoInterface*>(videoin[0]);
if(!vpi)
{
pango_print_warn("Unpack: child interface is not buffer aware.");
return 0;
}
else
{
return vpi->AvailableFrames();
}
}
bool UnpackVideo::DropNFrames(uint32_t n)
{
BufferAwareVideoInterface* vpi = dynamic_cast<BufferAwareVideoInterface*>(videoin[0]);
if(!vpi)
{
pango_print_warn("Unpack: child interface is not buffer aware.");
return false;
}
else
{
return vpi->DropNFrames(n);
}
}
PANGOLIN_REGISTER_FACTORY(UnpackVideo)
{
struct UnpackVideoFactory : public VideoFactoryInterface {
std::unique_ptr<VideoInterface> OpenVideo(const Uri& uri) override {
std::unique_ptr<VideoInterface> subvid = pangolin::OpenVideo(uri.url);
const std::string fmt = uri.Get("fmt", std::string("GRAY16LE") );
return std::unique_ptr<VideoInterface>(
new UnpackVideo(subvid, VideoFormatFromString(fmt) )
);
}
};
VideoFactoryRegistry::I().RegisterFactory(std::make_shared<UnpackVideoFactory>(), 10, "unpack");
}
}
#undef TSTART
#undef TGRABANDPRINT
#undef DBGPRINT
<|endoftext|> |
<commit_before>#if _WIN32
#pragma warning(disable : 4267 4996)
#endif
#include "./labelling_coordinator.h"
#include <QtOpenGLExtensions>
#include <QLoggingCategory>
#include <map>
#include <vector>
#include <memory>
#include "./labelling/clustering.h"
#include "./labelling/labels.h"
#include "./placement/occlusion_calculator.h"
#include "./placement/constraint_updater.h"
#include "./placement/persistent_constraint_updater.h"
#include "./placement/cuda_texture_mapper.h"
#include "./placement/integral_costs_calculator.h"
#include "./placement/saliency.h"
#include "./placement/labels_arranger.h"
#include "./placement/insertion_order_labels_arranger.h"
#include "./placement/randomized_labels_arranger.h"
#include "./placement/apollonius_labels_arranger.h"
#include "./placement/anchor_constraint_drawer.h"
#include "./placement/shadow_constraint_drawer.h"
#include "./graphics/buffer_drawer.h"
#include "./nodes.h"
#include "./math/eigen.h"
#include "./label_node.h"
#include "./texture_mapper_manager.h"
#include "./utils/profiler.h"
#include "./utils/profiling_statistics.h"
#include "./graphics/managers.h"
QLoggingCategory lcChan("LabellingCoordinator");
LabellingCoordinator::LabellingCoordinator(
int layerCount, std::shared_ptr<Forces::Labeller> forcesLabeller,
std::shared_ptr<Labels> labels, std::shared_ptr<Nodes> nodes)
: layerCount(layerCount), forcesLabeller(forcesLabeller), labels(labels),
nodes(nodes), clustering(labels, layerCount - 1),
profilingStatistics("LabellingCoordinator", lcChan)
{
occlusionCalculator =
std::make_shared<Placement::OcclusionCalculator>(layerCount);
}
void LabellingCoordinator::initialize(
Graphics::Gl *gl, int bufferSize,
std::shared_ptr<Graphics::BufferDrawer> drawer,
std::shared_ptr<Graphics::Managers> managers,
std::shared_ptr<TextureMapperManager> textureMapperManager, int width,
int height)
{
qCInfo(lcChan) << "Initialize";
saliency = std::make_shared<Placement::Saliency>(
textureMapperManager->getAccumulatedLayersTextureMapper(),
textureMapperManager->getSaliencyTextureMapper());
occlusionCalculator->initialize(textureMapperManager);
integralCostsCalculator =
std::make_shared<Placement::IntegralCostsCalculator>(
textureMapperManager->getOcclusionTextureMapper(),
textureMapperManager->getSaliencyTextureMapper(),
textureMapperManager->getIntegralCostsTextureMapper());
auto shaderManager = managers->getShaderManager();
auto anchorConstraintDrawer =
std::make_shared<AnchorConstraintDrawer>(width, height);
anchorConstraintDrawer->initialize(gl, shaderManager);
auto connectorShadowDrawer = std::make_shared<ShadowConstraintDrawer>(
width, height);
connectorShadowDrawer->initialize(gl, shaderManager);
auto shadowConstraintDrawer = std::make_shared<ShadowConstraintDrawer>(
width, height);
shadowConstraintDrawer->initialize(gl, shaderManager);
auto constraintUpdater = std::make_shared<ConstraintUpdater>(
bufferSize, bufferSize, anchorConstraintDrawer, connectorShadowDrawer,
shadowConstraintDrawer);
persistentConstraintUpdater =
std::make_shared<PersistentConstraintUpdater>(constraintUpdater);
insertionOrderLabelsArranger =
std::make_shared<Placement::InsertionOrderLabelsArranger>();
randomizedLabelsArranger =
std::make_shared<Placement::RandomizedLabelsArranger>();
for (int layerIndex = 0; layerIndex < layerCount; ++layerIndex)
{
auto labelsContainer = std::make_shared<LabelsContainer>();
labelsInLayer.push_back(labelsContainer);
auto labeller = std::make_shared<Placement::Labeller>(labelsContainer);
labeller->resize(width, height);
labeller->initialize(textureMapperManager->getIntegralCostsTextureMapper(),
textureMapperManager->getConstraintTextureMapper(),
persistentConstraintUpdater);
auto apolloniusLabelsArranger =
std::make_shared<Placement::ApolloniusLabelsArranger>();
apolloniusLabelsArranger->initialize(
textureMapperManager->getDistanceTransformTextureMapper(layerIndex),
textureMapperManager->getOcclusionTextureMapper(),
textureMapperManager->getApolloniusTextureMapper(layerIndex));
apolloniusLabelsArrangers.push_back(apolloniusLabelsArranger);
labeller->setLabelsArranger(useApollonius ? apolloniusLabelsArranger
: insertionOrderLabelsArranger);
placementLabellers.push_back(labeller);
}
}
void LabellingCoordinator::cleanup()
{
occlusionCalculator.reset();
saliency.reset();
integralCostsCalculator.reset();
for (auto apolloniusLabelsArranger : apolloniusLabelsArrangers)
apolloniusLabelsArranger->cleanup();
for (auto placementLabeller : placementLabellers)
placementLabeller->cleanup();
}
void LabellingCoordinator::setEnabled(bool enabled)
{
labellingEnabled = enabled;
for (auto &labelNode : nodes->getLabelNodes())
{
labelNode->setIsVisible(!enabled);
}
}
bool LabellingCoordinator::update(double frameTime, bool isIdle,
Eigen::Matrix4f projection,
Eigen::Matrix4f view, int activeLayerNumber)
{
Profiler profiler("update", lcChan, &profilingStatistics);
if (!labellingEnabled)
return false;
this->isIdle = isIdle;
labellerFrameData = LabellerFrameData(frameTime, projection, view);
saliency->runKernel();
auto positionsNDC2d = getPlacementPositions(activeLayerNumber);
auto positionsNDC = addDepthValueNDC(positionsNDC2d);
LabelPositions labelPositions(positionsNDC, ndcPositionsTo3d(positionsNDC));
if (forcesEnabled)
labelPositions = getForcesPositions(labelPositions);
distributeLabelsToLayers();
updateLabelPositionsInLabelNodes(labelPositions);
return hasChanges;
}
void LabellingCoordinator::updatePlacement()
{
Profiler profiler("updatePlacement", lcChan, &profilingStatistics);
if (!labellingEnabled)
return;
bool optimize = isIdle && optimizeOnIdle;
bool ignoreOldPosition = !isIdle;
float newSumOfCosts = 0.0f;
persistentConstraintUpdater->clear();
for (int layerIndex = 0; layerIndex < layerCount; ++layerIndex)
{
occlusionCalculator->calculateFor(layerIndex);
integralCostsCalculator->runKernel();
auto labeller = placementLabellers[layerIndex];
auto defaultArranger = useApollonius ? apolloniusLabelsArrangers[layerIndex]
: insertionOrderLabelsArranger;
labeller->setLabelsArranger(optimize ? randomizedLabelsArranger
: defaultArranger);
labeller->update(labellerFrameData, ignoreOldPosition);
newSumOfCosts += labeller->getLastSumOfCosts();
}
if (optimize)
{
std::cout << "Old costs: " << sumOfCosts << "\tnew costs:" << newSumOfCosts
<< std::endl;
}
if (optimize && newSumOfCosts > sumOfCosts)
{
preserveLastResult = true;
}
else
{
preserveLastResult = false;
sumOfCosts = newSumOfCosts;
}
}
std::vector<float> LabellingCoordinator::updateClusters()
{
if (!labellingEnabled)
return std::vector<float>{ 1.0f };
clustering.update(labellerFrameData.viewProjection);
return clustering.getMedianClusterMembers();
}
bool LabellingCoordinator::haveLabelPositionsChanged()
{
return hasChanges;
}
void LabellingCoordinator::resize(int width, int height)
{
for (auto placementLabeller : placementLabellers)
placementLabeller->resize(width, height);
forcesLabeller->resize(width, height);
}
void LabellingCoordinator::saveOcclusion()
{
occlusionCalculator->saveOcclusion();
}
void LabellingCoordinator::setCostFunctionWeights(
Placement::CostFunctionWeights weights)
{
for (auto placementLabeller : placementLabellers)
placementLabeller->setCostFunctionWeights(weights);
}
std::map<int, Eigen::Vector2f>
LabellingCoordinator::getPlacementPositions(int activeLayerNumber)
{
if (preserveLastResult)
return lastPlacementResult;
std::map<int, Eigen::Vector2f> placementPositions;
int layerIndex = 0;
for (auto placementLabeller : placementLabellers)
{
if (activeLayerNumber == 0 || activeLayerNumber - 1 == layerIndex)
{
auto newPositionsForLayer = placementLabeller->getLastPlacementResult();
placementPositions.insert(newPositionsForLayer.begin(),
newPositionsForLayer.end());
}
layerIndex++;
}
lastPlacementResult = placementPositions;
return placementPositions;
}
LabelPositions
LabellingCoordinator::getForcesPositions(LabelPositions placementPositions)
{
if (placementPositions.size() == 0)
return LabelPositions();
if (firstFramesWithoutPlacement && placementPositions.size())
{
firstFramesWithoutPlacement = false;
forcesLabeller->overallForceFactor = isIdle ? 6.0f : 3.0f;
forcesLabeller->setPositions(labellerFrameData, placementPositions);
}
return forcesLabeller->update(labellerFrameData, placementPositions);
}
void LabellingCoordinator::distributeLabelsToLayers()
{
auto centerWithLabelIds = clustering.getMedianClusterMembersWithLabelIds();
int layerIndex = 0;
for (auto &pair : centerWithLabelIds)
{
auto &container = labelsInLayer[layerIndex];
container->clear();
for (int labelId : pair.second)
{
container->add(labels->getById(labelId));
labelIdToLayerIndex[labelId] = layerIndex;
labelIdToZValue[labelId] = pair.first;
}
layerIndex++;
}
}
void LabellingCoordinator::updateLabelPositionsInLabelNodes(
LabelPositions labelPositions)
{
hasChanges = false;
for (auto &labelNode : nodes->getLabelNodes())
{
int labelId = labelNode->label.id;
if (labelPositions.count(labelId))
{
auto newPosition = labelPositions.get3dFor(labelId);
if (!hasChanges && (labelNode->labelPosition - newPosition).norm() > 1e-7)
{
hasChanges = true;
}
labelNode->setIsVisible(true);
labelNode->labelPosition = labelPositions.get3dFor(labelId);
labelNode->labelPositionNDC = labelPositions.getNDCFor(labelId);
labelNode->layerIndex = labelIdToLayerIndex[labelId];
}
else
{
labelNode->setIsVisible(false);
}
}
}
std::map<int, Eigen::Vector3f> LabellingCoordinator::addDepthValueNDC(
std::map<int, Eigen::Vector2f> positionsNDC)
{
std::map<int, Eigen::Vector3f> positions;
for (auto positionNDCPair : positionsNDC)
{
int labelId = positionNDCPair.first;
auto position2d = positionNDCPair.second;
positions[labelId] = Eigen::Vector3f(position2d.x(), position2d.y(),
labelIdToZValue[labelId]);
}
return positions;
}
std::map<int, Eigen::Vector3f> LabellingCoordinator::ndcPositionsTo3d(
std::map<int, Eigen::Vector3f> positionsNDC)
{
Eigen::Matrix4f inverseViewProjection =
labellerFrameData.viewProjection.inverse();
std::map<int, Eigen::Vector3f> positions;
for (auto positionNDCPair : positionsNDC)
{
int labelId = positionNDCPair.first;
positions[labelId] = project(inverseViewProjection, positionNDCPair.second);
}
return positions;
}
<commit_msg>Fix width and height passed to drawers in LabellingCoordinator::initialize.<commit_after>#if _WIN32
#pragma warning(disable : 4267 4996)
#endif
#include "./labelling_coordinator.h"
#include <QtOpenGLExtensions>
#include <QLoggingCategory>
#include <map>
#include <vector>
#include <memory>
#include "./labelling/clustering.h"
#include "./labelling/labels.h"
#include "./placement/occlusion_calculator.h"
#include "./placement/constraint_updater.h"
#include "./placement/persistent_constraint_updater.h"
#include "./placement/cuda_texture_mapper.h"
#include "./placement/integral_costs_calculator.h"
#include "./placement/saliency.h"
#include "./placement/labels_arranger.h"
#include "./placement/insertion_order_labels_arranger.h"
#include "./placement/randomized_labels_arranger.h"
#include "./placement/apollonius_labels_arranger.h"
#include "./placement/anchor_constraint_drawer.h"
#include "./placement/shadow_constraint_drawer.h"
#include "./graphics/buffer_drawer.h"
#include "./nodes.h"
#include "./math/eigen.h"
#include "./label_node.h"
#include "./texture_mapper_manager.h"
#include "./utils/profiler.h"
#include "./utils/profiling_statistics.h"
#include "./graphics/managers.h"
QLoggingCategory lcChan("LabellingCoordinator");
LabellingCoordinator::LabellingCoordinator(
int layerCount, std::shared_ptr<Forces::Labeller> forcesLabeller,
std::shared_ptr<Labels> labels, std::shared_ptr<Nodes> nodes)
: layerCount(layerCount), forcesLabeller(forcesLabeller), labels(labels),
nodes(nodes), clustering(labels, layerCount - 1),
profilingStatistics("LabellingCoordinator", lcChan)
{
occlusionCalculator =
std::make_shared<Placement::OcclusionCalculator>(layerCount);
}
void LabellingCoordinator::initialize(
Graphics::Gl *gl, int bufferSize,
std::shared_ptr<Graphics::BufferDrawer> drawer,
std::shared_ptr<Graphics::Managers> managers,
std::shared_ptr<TextureMapperManager> textureMapperManager, int width,
int height)
{
qCInfo(lcChan) << "Initialize";
saliency = std::make_shared<Placement::Saliency>(
textureMapperManager->getAccumulatedLayersTextureMapper(),
textureMapperManager->getSaliencyTextureMapper());
occlusionCalculator->initialize(textureMapperManager);
integralCostsCalculator =
std::make_shared<Placement::IntegralCostsCalculator>(
textureMapperManager->getOcclusionTextureMapper(),
textureMapperManager->getSaliencyTextureMapper(),
textureMapperManager->getIntegralCostsTextureMapper());
auto shaderManager = managers->getShaderManager();
auto anchorConstraintDrawer =
std::make_shared<AnchorConstraintDrawer>(bufferSize, bufferSize);
anchorConstraintDrawer->initialize(gl, shaderManager);
auto connectorShadowDrawer = std::make_shared<ShadowConstraintDrawer>(
bufferSize, bufferSize);
connectorShadowDrawer->initialize(gl, shaderManager);
auto shadowConstraintDrawer = std::make_shared<ShadowConstraintDrawer>(
bufferSize, bufferSize);
shadowConstraintDrawer->initialize(gl, shaderManager);
auto constraintUpdater = std::make_shared<ConstraintUpdater>(
bufferSize, bufferSize, anchorConstraintDrawer, connectorShadowDrawer,
shadowConstraintDrawer);
persistentConstraintUpdater =
std::make_shared<PersistentConstraintUpdater>(constraintUpdater);
insertionOrderLabelsArranger =
std::make_shared<Placement::InsertionOrderLabelsArranger>();
randomizedLabelsArranger =
std::make_shared<Placement::RandomizedLabelsArranger>();
for (int layerIndex = 0; layerIndex < layerCount; ++layerIndex)
{
auto labelsContainer = std::make_shared<LabelsContainer>();
labelsInLayer.push_back(labelsContainer);
auto labeller = std::make_shared<Placement::Labeller>(labelsContainer);
labeller->resize(width, height);
labeller->initialize(textureMapperManager->getIntegralCostsTextureMapper(),
textureMapperManager->getConstraintTextureMapper(),
persistentConstraintUpdater);
auto apolloniusLabelsArranger =
std::make_shared<Placement::ApolloniusLabelsArranger>();
apolloniusLabelsArranger->initialize(
textureMapperManager->getDistanceTransformTextureMapper(layerIndex),
textureMapperManager->getOcclusionTextureMapper(),
textureMapperManager->getApolloniusTextureMapper(layerIndex));
apolloniusLabelsArrangers.push_back(apolloniusLabelsArranger);
labeller->setLabelsArranger(useApollonius ? apolloniusLabelsArranger
: insertionOrderLabelsArranger);
placementLabellers.push_back(labeller);
}
}
void LabellingCoordinator::cleanup()
{
occlusionCalculator.reset();
saliency.reset();
integralCostsCalculator.reset();
for (auto apolloniusLabelsArranger : apolloniusLabelsArrangers)
apolloniusLabelsArranger->cleanup();
for (auto placementLabeller : placementLabellers)
placementLabeller->cleanup();
}
void LabellingCoordinator::setEnabled(bool enabled)
{
labellingEnabled = enabled;
for (auto &labelNode : nodes->getLabelNodes())
{
labelNode->setIsVisible(!enabled);
}
}
bool LabellingCoordinator::update(double frameTime, bool isIdle,
Eigen::Matrix4f projection,
Eigen::Matrix4f view, int activeLayerNumber)
{
Profiler profiler("update", lcChan, &profilingStatistics);
if (!labellingEnabled)
return false;
this->isIdle = isIdle;
labellerFrameData = LabellerFrameData(frameTime, projection, view);
saliency->runKernel();
auto positionsNDC2d = getPlacementPositions(activeLayerNumber);
auto positionsNDC = addDepthValueNDC(positionsNDC2d);
LabelPositions labelPositions(positionsNDC, ndcPositionsTo3d(positionsNDC));
if (forcesEnabled)
labelPositions = getForcesPositions(labelPositions);
distributeLabelsToLayers();
updateLabelPositionsInLabelNodes(labelPositions);
return hasChanges;
}
void LabellingCoordinator::updatePlacement()
{
Profiler profiler("updatePlacement", lcChan, &profilingStatistics);
if (!labellingEnabled)
return;
bool optimize = isIdle && optimizeOnIdle;
bool ignoreOldPosition = !isIdle;
float newSumOfCosts = 0.0f;
persistentConstraintUpdater->clear();
for (int layerIndex = 0; layerIndex < layerCount; ++layerIndex)
{
occlusionCalculator->calculateFor(layerIndex);
integralCostsCalculator->runKernel();
auto labeller = placementLabellers[layerIndex];
auto defaultArranger = useApollonius ? apolloniusLabelsArrangers[layerIndex]
: insertionOrderLabelsArranger;
labeller->setLabelsArranger(optimize ? randomizedLabelsArranger
: defaultArranger);
labeller->update(labellerFrameData, ignoreOldPosition);
newSumOfCosts += labeller->getLastSumOfCosts();
}
if (optimize)
{
std::cout << "Old costs: " << sumOfCosts << "\tnew costs:" << newSumOfCosts
<< std::endl;
}
if (optimize && newSumOfCosts > sumOfCosts)
{
preserveLastResult = true;
}
else
{
preserveLastResult = false;
sumOfCosts = newSumOfCosts;
}
}
std::vector<float> LabellingCoordinator::updateClusters()
{
if (!labellingEnabled)
return std::vector<float>{ 1.0f };
clustering.update(labellerFrameData.viewProjection);
return clustering.getMedianClusterMembers();
}
bool LabellingCoordinator::haveLabelPositionsChanged()
{
return hasChanges;
}
void LabellingCoordinator::resize(int width, int height)
{
for (auto placementLabeller : placementLabellers)
placementLabeller->resize(width, height);
forcesLabeller->resize(width, height);
}
void LabellingCoordinator::saveOcclusion()
{
occlusionCalculator->saveOcclusion();
}
void LabellingCoordinator::setCostFunctionWeights(
Placement::CostFunctionWeights weights)
{
for (auto placementLabeller : placementLabellers)
placementLabeller->setCostFunctionWeights(weights);
}
std::map<int, Eigen::Vector2f>
LabellingCoordinator::getPlacementPositions(int activeLayerNumber)
{
if (preserveLastResult)
return lastPlacementResult;
std::map<int, Eigen::Vector2f> placementPositions;
int layerIndex = 0;
for (auto placementLabeller : placementLabellers)
{
if (activeLayerNumber == 0 || activeLayerNumber - 1 == layerIndex)
{
auto newPositionsForLayer = placementLabeller->getLastPlacementResult();
placementPositions.insert(newPositionsForLayer.begin(),
newPositionsForLayer.end());
}
layerIndex++;
}
lastPlacementResult = placementPositions;
return placementPositions;
}
LabelPositions
LabellingCoordinator::getForcesPositions(LabelPositions placementPositions)
{
if (placementPositions.size() == 0)
return LabelPositions();
if (firstFramesWithoutPlacement && placementPositions.size())
{
firstFramesWithoutPlacement = false;
forcesLabeller->overallForceFactor = isIdle ? 6.0f : 3.0f;
forcesLabeller->setPositions(labellerFrameData, placementPositions);
}
return forcesLabeller->update(labellerFrameData, placementPositions);
}
void LabellingCoordinator::distributeLabelsToLayers()
{
auto centerWithLabelIds = clustering.getMedianClusterMembersWithLabelIds();
int layerIndex = 0;
for (auto &pair : centerWithLabelIds)
{
auto &container = labelsInLayer[layerIndex];
container->clear();
for (int labelId : pair.second)
{
container->add(labels->getById(labelId));
labelIdToLayerIndex[labelId] = layerIndex;
labelIdToZValue[labelId] = pair.first;
}
layerIndex++;
}
}
void LabellingCoordinator::updateLabelPositionsInLabelNodes(
LabelPositions labelPositions)
{
hasChanges = false;
for (auto &labelNode : nodes->getLabelNodes())
{
int labelId = labelNode->label.id;
if (labelPositions.count(labelId))
{
auto newPosition = labelPositions.get3dFor(labelId);
if (!hasChanges && (labelNode->labelPosition - newPosition).norm() > 1e-7)
{
hasChanges = true;
}
labelNode->setIsVisible(true);
labelNode->labelPosition = labelPositions.get3dFor(labelId);
labelNode->labelPositionNDC = labelPositions.getNDCFor(labelId);
labelNode->layerIndex = labelIdToLayerIndex[labelId];
}
else
{
labelNode->setIsVisible(false);
}
}
}
std::map<int, Eigen::Vector3f> LabellingCoordinator::addDepthValueNDC(
std::map<int, Eigen::Vector2f> positionsNDC)
{
std::map<int, Eigen::Vector3f> positions;
for (auto positionNDCPair : positionsNDC)
{
int labelId = positionNDCPair.first;
auto position2d = positionNDCPair.second;
positions[labelId] = Eigen::Vector3f(position2d.x(), position2d.y(),
labelIdToZValue[labelId]);
}
return positions;
}
std::map<int, Eigen::Vector3f> LabellingCoordinator::ndcPositionsTo3d(
std::map<int, Eigen::Vector3f> positionsNDC)
{
Eigen::Matrix4f inverseViewProjection =
labellerFrameData.viewProjection.inverse();
std::map<int, Eigen::Vector3f> positions;
for (auto positionNDCPair : positionsNDC)
{
int labelId = positionNDCPair.first;
positions[labelId] = project(inverseViewProjection, positionNDCPair.second);
}
return positions;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2014-2016, imec
* All rights reserved.
*/
#include <random>
#include <memory>
#include <cstdio>
#include <iostream>
#include <climits>
#include <stdexcept>
#include "error.h"
#include "bpmf.h"
#include "io.h"
static const bool measure_perf = false;
std::ostream *Sys::os;
int Sys::procid = -1;
int Sys::nprocs = -1;
int Sys::nsims;
int Sys::burnin;
int Sys::update_freq;
double Sys::alpha = 2.0;
std::string Sys::odirname = "";
bool Sys::permute = true;
bool Sys::verbose = false;
// verifies that A has the same non-zero structure as B
void assert_same_struct(SparseMatrixD &A, SparseMatrixD &B)
{
assert(A.cols() == B.cols());
assert(A.rows() == B.rows());
for(int i=0; i<A.cols(); ++i) assert(A.col(i).nonZeros() == B.col(i).nonZeros());
}
//
// Does predictions for prediction matrix T
// Computes RMSE (Root Means Square Error)
//
void Sys::predict(Sys& other, bool all)
{
int n = (iter < burnin) ? 0 : (iter - burnin);
double se(0.0); // squared err
double se_avg(0.0); // squared avg err
unsigned nump(0); // number of predictions
int lo = all ? 0 : from();
int hi = all ? num() : to();
#pragma omp parallel for reduction(+:se,se_avg,nump)
for(int k = lo; k<hi; k++) {
for (Eigen::SparseMatrix<double>::InnerIterator it(T,k); it; ++it)
{
#ifdef BPMF_REDUCE
if (it.row() >= other.to() || it.row() < other.from())
continue;
#endif
auto m = items().col(it.col());
auto u = other.items().col(it.row());
assert(m.norm() > 0.0);
assert(u.norm() > 0.0);
const double pred = m.dot(u) + mean_rating;
se += sqr(it.value() - pred);
// update average prediction
double &avg = Pavg.coeffRef(it.row(), it.col());
double delta = pred - avg;
avg = (n == 0) ? pred : (avg + delta/n);
double &m2 = Pm2.coeffRef(it.row(), it.col());
m2 = (n == 0) ? 0 : m2 + delta * (pred - avg);
se_avg += sqr(it.value() - avg);
nump++;
}
}
rmse = sqrt( se / nump );
rmse_avg = sqrt( se_avg / nump );
}
//
// Prints sampling progress
//
void Sys::print(double items_per_sec, double ratings_per_sec, double norm_u, double norm_m) {
char buf[1024];
std::string phase = (iter < Sys::burnin) ? "Burnin" : "Sampling";
sprintf(buf, "%d: %s iteration %d:\t RMSE: %3.4f\tavg RMSE: %3.4f\tFU(%6.2f)\tFM(%6.2f)\titems/sec: %6.2f\tratings/sec: %6.2fM\n",
Sys::procid, phase.c_str(), iter, rmse, rmse_avg, norm_u, norm_m, items_per_sec, ratings_per_sec / 1e6);
Sys::cout() << buf;
}
//
// Constructor with that reads MTX files
//
Sys::Sys(std::string name, std::string fname, std::string probename)
: name(name), iter(-1), assigned(false), dom(nprocs+1)
{
read_matrix(fname, M);
read_matrix(probename, T);
auto rows = std::max(M.rows(), T.rows());
auto cols = std::max(M.cols(), T.cols());
M.conservativeResize(rows,cols);
T.conservativeResize(rows,cols);
Pm2 = Pavg = Torig = T; // reference ratings and predicted ratings
assert(M.rows() == Pavg.rows());
assert(M.cols() == Pavg.cols());
assert(Sys::nprocs <= (int)Sys::max_procs);
}
//
// Constructs Sys as transpose of existing Sys
//
Sys::Sys(std::string name, const SparseMatrixD &Mt, const SparseMatrixD &Pt) : name(name), iter(-1), assigned(false), dom(nprocs+1) {
M = Mt.transpose();
Pm2 = Pavg = T = Torig = Pt.transpose(); // reference ratings and predicted ratings
assert(M.rows() == Pavg.rows());
assert(M.cols() == Pavg.cols());
}
Sys::~Sys()
{
if (measure_perf) {
Sys::cout() << " --------------------\n";
Sys::cout() << name << ": sampling times on " << procid << "\n";
for(int i = from(); i<to(); ++i)
{
Sys::cout() << "\t" << nnz(i) << "\t" << sample_time.at(i) / nsims << "\n";
}
Sys::cout() << " --------------------\n\n";
}
}
bool Sys::has_prop_posterior() const
{
return propMu.nonZeros() > 0;
}
void Sys::add_prop_posterior(std::string fnames)
{
if (fnames.empty()) return;
std::size_t pos = fnames.find_first_of(",");
std::string mu_name = fnames.substr(0, pos);
std::string lambda_name = fnames.substr(pos+1);
read_matrix(mu_name, propMu);
read_matrix(lambda_name, propLambda);
assert(propMu.cols() == num());
assert(propLambda.cols() == num());
assert(propMu.rows() == num_latent);
assert(propLambda.rows() == num_latent * num_latent);
}
//
// Intializes internal Matrices and Vectors
//
void Sys::init()
{
//-- M
assert(M.rows() > 0 && M.cols() > 0);
mean_rating = M.sum() / M.nonZeros();
items().setZero();
sum_map().setZero();
cov_map().setZero();
norm_map().setZero();
col_permutation.setIdentity(num());
#ifdef BPMF_REDUCE
precMu = MatrixNXd::Zero(num_latent, num());
precLambda = Eigen::MatrixXd::Zero(num_latent * num_latent, num());
#endif
if (Sys::odirname.size())
{
aggrMu = Eigen::MatrixXd::Zero(num_latent, num());
aggrLambda = Eigen::MatrixXd::Zero(num_latent * num_latent, num());
}
int count_sum = 0;
for(int k = 0; k<M.cols(); k++) {
int count = M.col(k).nonZeros();
count_sum += count;
}
Sys::cout() << "mean rating: " << mean_rating << std::endl;
Sys::cout() << "total number of ratings in train: " << M.nonZeros() << std::endl;
Sys::cout() << "total number of ratings in test: " << T.nonZeros() << std::endl;
Sys::cout() << "average ratings per row: " << (double)M.nonZeros() / (double)M.cols() << std::endl;
Sys::cout() << "num " << name << ": " << num() << std::endl;
if (has_prop_posterior())
{
Sys::cout() << "with propagated posterior" << std::endl;
}
if (measure_perf) sample_time.resize(num(), .0);
}
class PrecomputedLLT : public Eigen::LLT<MatrixNNd>
{
public:
void operator=(const MatrixNNd &m) { m_matrix = m; m_isInitialized = true; m_info = Eigen::Success; }
};
void Sys::computeMuLambda(long idx, const Sys &other, VectorNd &rr, MatrixNNd &MM) const
{
for (SparseMatrixD::InnerIterator it(M, idx); it; ++it)
{
auto col = other.items().col(it.row());
MM.triangularView<Eigen::Upper>() += col * col.transpose();
rr.noalias() += col * ((it.value() - mean_rating) * alpha);
}
}
//
// Update ONE movie or one user
//
VectorNd Sys::sample(long idx, Sys &other)
{
auto start = tick();
VectorNd hp_mu;
MatrixNNd hp_LambdaF;
MatrixNNd hp_LambdaL;
if (has_prop_posterior())
{
hp_mu = propMu.col(idx);
hp_LambdaF = Eigen::Map<MatrixNNd>(propLambda.col(idx).data());
hp_LambdaL = hp_LambdaF.llt().matrixL();
}
else
{
hp_mu = hp.mu;
hp_LambdaF = hp.LambdaF;
hp_LambdaL = hp.LambdaL;
}
VectorNd rr = hp_LambdaF * hp.mu; // vector num_latent x 1, we will use it in formula (14) from the paper
MatrixNNd MM(MatrixNNd::Zero());
PrecomputedLLT chol; // matrix num_latent x num_latent, chol="lambda_i with *" from formula (14)
#ifdef BPMF_REDUCE
rr += precMu.col(idx);
MM += precLambdaMatrix(idx);
#else
computeMuLambda(idx, other, rr, MM);
#endif
// copy upper -> lower part, matrix is symmetric.
MM.triangularView<Eigen::Lower>() = MM.transpose();
chol.compute(hp_LambdaF + alpha * MM);
if(chol.info() != Eigen::Success) THROWERROR("Cholesky failed");
// now we should calculate formula (14) from the paper
// u_i for k-th iteration = Gaussian distribution N(u_i | mu_i with *, [lambda_i with *]^-1) =
// = mu_i with * + s * [U]^-1,
// where
// s is a random vector with N(0, I),
// mu_i with * is a vector num_latent x 1,
// mu_i with * = [lambda_i with *]^-1 * rr,
// lambda_i with * = L * U
// Expression u_i = U \ (s + (L \ rr)) in Matlab looks for Eigen library like:
chol.matrixL().solveInPlace(rr); // L*Y=rr => Y=L\rr, we store Y result again in rr vector
rr += nrandn(); // rr=s+(L\rr), we store result again in rr vector
chol.matrixU().solveInPlace(rr); // u_i=U\rr
items().col(idx) = rr; // we save rr vector in items matrix (it is user features matrix)
#ifdef BPMF_REDUCE
#pragma omp critical
for (SparseMatrixD::InnerIterator it(M, idx); it; ++it)
{
other.precLambdaMatrix(it.row()).triangularView<Eigen::Upper>() += rr * rr.transpose();
other.precMu.col(it.row()).noalias() += rr * (it.value() - mean_rating) * alpha;
}
#endif
auto stop = tick();
register_time(idx, 1e6 * (stop - start));
//Sys::cout() << " " << count << ": " << 1e6*(stop - start) << std::endl;
assert(rr.norm() > .0);
return rr;
}
//
// update ALL movies / users in parallel
//
void Sys::sample(Sys &other)
{
iter++;
thread_vector<VectorNd> sums(VectorNd::Zero()); // sum
thread_vector<double> norms(0.0); // squared norm
thread_vector<MatrixNNd> prods(MatrixNNd::Zero()); // outer prod
#ifdef BPMF_REDUCE
other.precMu.setZero();
other.precLambda.setZero();
#endif
#pragma omp parallel for schedule(guided)
for (int i = from(); i < to(); ++i)
{
#pragma omp task
{
auto r = sample(i, other);
MatrixNNd cov = (r * r.transpose());
prods.local() += cov;
sums.local() += r;
norms.local() += r.squaredNorm();
if (iter >= burnin && Sys::odirname.size())
{
aggrMu.col(i) += r;
aggrLambda.col(i) += Eigen::Map<Eigen::VectorXd>(cov.data(), num_latent * num_latent);
}
send_item(i);
}
}
#pragma omp taskwait
VectorNd sum = sums.combine();
MatrixNNd prod = prods.combine();
double norm = norms.combine();
const int N = num();
local_sum() = sum;
local_cov() = (prod - (sum * sum.transpose() / N)) / (N-1);
local_norm() = norm;
}
void Sys::register_time(int i, double t)
{
if (measure_perf) sample_time.at(i) += t;
}<commit_msg>Optimize calcMuLambda using OpenMP<commit_after>/*
* Copyright (c) 2014-2016, imec
* All rights reserved.
*/
#include <random>
#include <memory>
#include <cstdio>
#include <iostream>
#include <climits>
#include <stdexcept>
#include "error.h"
#include "bpmf.h"
#include "io.h"
static const bool measure_perf = false;
std::ostream *Sys::os;
int Sys::procid = -1;
int Sys::nprocs = -1;
int Sys::nsims;
int Sys::burnin;
int Sys::update_freq;
double Sys::alpha = 2.0;
std::string Sys::odirname = "";
bool Sys::permute = true;
bool Sys::verbose = false;
// verifies that A has the same non-zero structure as B
void assert_same_struct(SparseMatrixD &A, SparseMatrixD &B)
{
assert(A.cols() == B.cols());
assert(A.rows() == B.rows());
for(int i=0; i<A.cols(); ++i) assert(A.col(i).nonZeros() == B.col(i).nonZeros());
}
//
// Does predictions for prediction matrix T
// Computes RMSE (Root Means Square Error)
//
void Sys::predict(Sys& other, bool all)
{
int n = (iter < burnin) ? 0 : (iter - burnin);
double se(0.0); // squared err
double se_avg(0.0); // squared avg err
unsigned nump(0); // number of predictions
int lo = all ? 0 : from();
int hi = all ? num() : to();
#pragma omp parallel for reduction(+:se,se_avg,nump)
for(int k = lo; k<hi; k++) {
for (Eigen::SparseMatrix<double>::InnerIterator it(T,k); it; ++it)
{
#ifdef BPMF_REDUCE
if (it.row() >= other.to() || it.row() < other.from())
continue;
#endif
auto m = items().col(it.col());
auto u = other.items().col(it.row());
assert(m.norm() > 0.0);
assert(u.norm() > 0.0);
const double pred = m.dot(u) + mean_rating;
se += sqr(it.value() - pred);
// update average prediction
double &avg = Pavg.coeffRef(it.row(), it.col());
double delta = pred - avg;
avg = (n == 0) ? pred : (avg + delta/n);
double &m2 = Pm2.coeffRef(it.row(), it.col());
m2 = (n == 0) ? 0 : m2 + delta * (pred - avg);
se_avg += sqr(it.value() - avg);
nump++;
}
}
rmse = sqrt( se / nump );
rmse_avg = sqrt( se_avg / nump );
}
//
// Prints sampling progress
//
void Sys::print(double items_per_sec, double ratings_per_sec, double norm_u, double norm_m) {
char buf[1024];
std::string phase = (iter < Sys::burnin) ? "Burnin" : "Sampling";
sprintf(buf, "%d: %s iteration %d:\t RMSE: %3.4f\tavg RMSE: %3.4f\tFU(%6.2f)\tFM(%6.2f)\titems/sec: %6.2f\tratings/sec: %6.2fM\n",
Sys::procid, phase.c_str(), iter, rmse, rmse_avg, norm_u, norm_m, items_per_sec, ratings_per_sec / 1e6);
Sys::cout() << buf;
}
//
// Constructor with that reads MTX files
//
Sys::Sys(std::string name, std::string fname, std::string probename)
: name(name), iter(-1), assigned(false), dom(nprocs+1)
{
read_matrix(fname, M);
read_matrix(probename, T);
auto rows = std::max(M.rows(), T.rows());
auto cols = std::max(M.cols(), T.cols());
M.conservativeResize(rows,cols);
T.conservativeResize(rows,cols);
Pm2 = Pavg = Torig = T; // reference ratings and predicted ratings
assert(M.rows() == Pavg.rows());
assert(M.cols() == Pavg.cols());
assert(Sys::nprocs <= (int)Sys::max_procs);
}
//
// Constructs Sys as transpose of existing Sys
//
Sys::Sys(std::string name, const SparseMatrixD &Mt, const SparseMatrixD &Pt) : name(name), iter(-1), assigned(false), dom(nprocs+1) {
M = Mt.transpose();
Pm2 = Pavg = T = Torig = Pt.transpose(); // reference ratings and predicted ratings
assert(M.rows() == Pavg.rows());
assert(M.cols() == Pavg.cols());
}
Sys::~Sys()
{
if (measure_perf) {
Sys::cout() << " --------------------\n";
Sys::cout() << name << ": sampling times on " << procid << "\n";
for(int i = from(); i<to(); ++i)
{
Sys::cout() << "\t" << nnz(i) << "\t" << sample_time.at(i) / nsims << "\n";
}
Sys::cout() << " --------------------\n\n";
}
}
bool Sys::has_prop_posterior() const
{
return propMu.nonZeros() > 0;
}
void Sys::add_prop_posterior(std::string fnames)
{
if (fnames.empty()) return;
std::size_t pos = fnames.find_first_of(",");
std::string mu_name = fnames.substr(0, pos);
std::string lambda_name = fnames.substr(pos+1);
read_matrix(mu_name, propMu);
read_matrix(lambda_name, propLambda);
assert(propMu.cols() == num());
assert(propLambda.cols() == num());
assert(propMu.rows() == num_latent);
assert(propLambda.rows() == num_latent * num_latent);
}
//
// Intializes internal Matrices and Vectors
//
void Sys::init()
{
//-- M
assert(M.rows() > 0 && M.cols() > 0);
mean_rating = M.sum() / M.nonZeros();
items().setZero();
sum_map().setZero();
cov_map().setZero();
norm_map().setZero();
col_permutation.setIdentity(num());
#ifdef BPMF_REDUCE
precMu = MatrixNXd::Zero(num_latent, num());
precLambda = Eigen::MatrixXd::Zero(num_latent * num_latent, num());
#endif
if (Sys::odirname.size())
{
aggrMu = Eigen::MatrixXd::Zero(num_latent, num());
aggrLambda = Eigen::MatrixXd::Zero(num_latent * num_latent, num());
}
int count_larger_bp1 = 0;
int count_larger_bp2 = 0;
int count_sum = 0;
for(int k = 0; k<M.cols(); k++) {
int count = M.col(k).nonZeros();
count_sum += count;
if (count > breakpoint1) count_larger_bp1++;
if (count > breakpoint2) count_larger_bp2++;
}
Sys::cout() << "mean rating: " << mean_rating << std::endl;
Sys::cout() << "total number of ratings in train: " << M.nonZeros() << std::endl;
Sys::cout() << "total number of ratings in test: " << T.nonZeros() << std::endl;
Sys::cout() << "average ratings per row: " << (double)count_sum / (double)M.cols() << std::endl;
Sys::cout() << "rows > break_point1: " << 100. * (double)count_larger_bp1 / (double)M.cols() << std::endl;
Sys::cout() << "rows > break_point2: " << 100. * (double)count_larger_bp2 / (double)M.cols() << std::endl;
Sys::cout() << "num " << name << ": " << num() << std::endl;
if (has_prop_posterior())
{
Sys::cout() << "with propagated posterior" << std::endl;
}
if (measure_perf) sample_time.resize(num(), .0);
}
class PrecomputedLLT : public Eigen::LLT<MatrixNNd>
{
public:
void operator=(const MatrixNNd &m) { m_matrix = m; m_isInitialized = true; m_info = Eigen::Success; }
};
void Sys::computeMuLambda(long idx, const Sys &other, VectorNd &rr, MatrixNNd &MM) const
{
const int count = M.innerVector(idx).nonZeros(); // count of nonzeros elements in idx-th row of M matrix
// (how many movies watched idx-th user?).
if (count < breakpoint2)
{
for (SparseMatrixD::InnerIterator it(M, idx); it; ++it)
{
auto col = other.items().col(it.row());
MM.triangularView<Eigen::Upper>() += col * col.transpose();
rr.noalias() += col * ((it.value() - mean_rating) * alpha);
}
}
else
{
const int task_size = count / 100;
auto from = M.outerIndexPtr()[idx]; // "from" belongs to [1..m], m - number of movies in M matrix
auto to = M.outerIndexPtr()[idx + 1]; // "to" belongs to [1..m], m - number of movies in M matrix
thread_vector<VectorNd> rrs(VectorNd::Zero());
thread_vector<MatrixNNd> MMs(MatrixNNd::Zero());
for (int i = from; i < to; i += task_size)
{
#pragma omp task shared(rrs, MMs, other)
for (int j = i; j < std::min(i + task_size, to); j++)
{
// for each nonzeros elemen in the i-th row of M matrix
auto val = M.valuePtr()[j]; // value of the j-th nonzeros element from idx-th row of M matrix
auto idx = M.innerIndexPtr()[j]; // index "j" of the element [i,j] from M matrix in compressed M matrix
auto col = other.items().col(idx); // vector num_latent x 1 from V matrix: M[i,j] = U[i,:] x V[idx,:]
MMs.local().triangularView<Eigen::Upper>() += col * col.transpose(); // outer product
rrs.local().noalias() += col * ((val - mean_rating) * alpha); // vector num_latent x 1
}
}
#pragma omp taskwait
// accumulate
MM += MMs.combine();
rr += rrs.combine();
}
}
//
// Update ONE movie or one user
//
VectorNd Sys::sample(long idx, Sys &other)
{
auto start = tick();
VectorNd hp_mu;
MatrixNNd hp_LambdaF;
MatrixNNd hp_LambdaL;
if (has_prop_posterior())
{
hp_mu = propMu.col(idx);
hp_LambdaF = Eigen::Map<MatrixNNd>(propLambda.col(idx).data());
hp_LambdaL = hp_LambdaF.llt().matrixL();
}
else
{
hp_mu = hp.mu;
hp_LambdaF = hp.LambdaF;
hp_LambdaL = hp.LambdaL;
}
VectorNd rr = hp_LambdaF * hp.mu; // vector num_latent x 1, we will use it in formula (14) from the paper
MatrixNNd MM(MatrixNNd::Zero());
PrecomputedLLT chol; // matrix num_latent x num_latent, chol="lambda_i with *" from formula (14)
#ifdef BPMF_REDUCE
rr += precMu.col(idx);
MM += precLambdaMatrix(idx);
#else
computeMuLambda(idx, other, rr, MM);
#endif
// copy upper -> lower part, matrix is symmetric.
MM.triangularView<Eigen::Lower>() = MM.transpose();
chol.compute(hp_LambdaF + alpha * MM);
if(chol.info() != Eigen::Success) THROWERROR("Cholesky failed");
// now we should calculate formula (14) from the paper
// u_i for k-th iteration = Gaussian distribution N(u_i | mu_i with *, [lambda_i with *]^-1) =
// = mu_i with * + s * [U]^-1,
// where
// s is a random vector with N(0, I),
// mu_i with * is a vector num_latent x 1,
// mu_i with * = [lambda_i with *]^-1 * rr,
// lambda_i with * = L * U
// Expression u_i = U \ (s + (L \ rr)) in Matlab looks for Eigen library like:
chol.matrixL().solveInPlace(rr); // L*Y=rr => Y=L\rr, we store Y result again in rr vector
rr += nrandn(); // rr=s+(L\rr), we store result again in rr vector
chol.matrixU().solveInPlace(rr); // u_i=U\rr
items().col(idx) = rr; // we save rr vector in items matrix (it is user features matrix)
#ifdef BPMF_REDUCE
#pragma omp critical
for (SparseMatrixD::InnerIterator it(M, idx); it; ++it)
{
other.precLambdaMatrix(it.row()).triangularView<Eigen::Upper>() += rr * rr.transpose();
other.precMu.col(it.row()).noalias() += rr * (it.value() - mean_rating) * alpha;
}
#endif
auto stop = tick();
register_time(idx, 1e6 * (stop - start));
//Sys::cout() << " " << count << ": " << 1e6*(stop - start) << std::endl;
assert(rr.norm() > .0);
return rr;
}
//
// update ALL movies / users in parallel
//
void Sys::sample(Sys &other)
{
iter++;
thread_vector<VectorNd> sums(VectorNd::Zero()); // sum
thread_vector<double> norms(0.0); // squared norm
thread_vector<MatrixNNd> prods(MatrixNNd::Zero()); // outer prod
#ifdef BPMF_REDUCE
other.precMu.setZero();
other.precLambda.setZero();
#endif
#pragma omp parallel for schedule(guided)
for (int i = from(); i < to(); ++i)
{
#pragma omp task
{
auto r = sample(i, other);
MatrixNNd cov = (r * r.transpose());
prods.local() += cov;
sums.local() += r;
norms.local() += r.squaredNorm();
if (iter >= burnin && Sys::odirname.size())
{
aggrMu.col(i) += r;
aggrLambda.col(i) += Eigen::Map<Eigen::VectorXd>(cov.data(), num_latent * num_latent);
}
send_item(i);
}
}
#pragma omp taskwait
VectorNd sum = sums.combine();
MatrixNNd prod = prods.combine();
double norm = norms.combine();
const int N = num();
local_sum() = sum;
local_cov() = (prod - (sum * sum.transpose() / N)) / (N-1);
local_norm() = norm;
}
void Sys::register_time(int i, double t)
{
if (measure_perf) sample_time.at(i) += t;
}<|endoftext|> |
<commit_before>/*
* Copyright (c) 2013 - 2015, Roland Bock
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <ciso646>
#include <iostream>
#ifdef _LIBCPP_VERSION
#include <boost/thread/tss.hpp> // libc++ does not have thread_local yet.
#endif
#include <sqlpp11/exception.h>
#include <sqlpp11/mysql/connection.h>
#include "detail/prepared_statement_handle.h"
#include "detail/result_handle.h"
#include "detail/connection_handle.h"
namespace sqlpp
{
namespace mysql
{
namespace
{
struct MySqlThreadInitializer
{
MySqlThreadInitializer()
{
if (!mysql_thread_safe())
{
throw sqlpp::exception("MySQL error: Operating on a non-threadsafe client");
}
mysql_thread_init();
}
~MySqlThreadInitializer()
{
mysql_thread_end();
}
};
#ifdef _LIBCPP_VERSION
boost::thread_specific_ptr<MySqlThreadInitializer> mysqlThreadInit;
#endif
void thread_init()
{
#ifdef _LIBCPP_VERSION
if (!mysqlThreadInit.get())
{
mysqlThreadInit.reset(new MySqlThreadInitializer);
}
#else
thread_local MySqlThreadInitializer threadInitializer;
#endif
}
void execute_statement(detail::connection_handle_t& handle, const std::string& statement)
{
thread_init();
if (handle.config->debug)
std::cerr << "MySQL debug: Executing: '" << statement << "'" << std::endl;
if (mysql_query(handle.mysql.get(), statement.c_str()))
{
throw sqlpp::exception("MySQL error: Could not execute MySQL-statement: " +
std::string(mysql_error(handle.mysql.get())) + " (statement was >>" + statement +
"<<\n");
}
}
void execute_prepared_statement(detail::prepared_statement_handle_t& prepared_statement)
{
thread_init();
if (prepared_statement.debug)
std::cerr << "MySQL debug: Executing prepared_statement" << std::endl;
if (mysql_stmt_bind_param(prepared_statement.mysql_stmt, prepared_statement.stmt_params.data()))
{
throw sqlpp::exception(std::string("MySQL error: Could not bind parameters to statement") +
mysql_stmt_error(prepared_statement.mysql_stmt));
}
if (mysql_stmt_execute(prepared_statement.mysql_stmt))
{
throw sqlpp::exception(std::string("MySQL error: Could not execute prepared statement: ") +
mysql_stmt_error(prepared_statement.mysql_stmt));
}
}
std::shared_ptr<detail::prepared_statement_handle_t> prepare_statement(detail::connection_handle_t& handle,
const std::string& statement,
size_t no_of_parameters,
size_t no_of_columns)
{
thread_init();
if (handle.config->debug)
std::cerr << "MySQL debug: Preparing: '" << statement << "'" << std::endl;
auto prepared_statement = std::make_shared<detail::prepared_statement_handle_t>(
mysql_stmt_init(handle.mysql.get()), no_of_parameters, no_of_columns, handle.config->debug);
if (not prepared_statement)
{
throw sqlpp::exception("MySQL error: Could not allocate prepared statement\n");
}
if (mysql_stmt_prepare(prepared_statement->mysql_stmt, statement.data(), statement.size()))
{
throw sqlpp::exception("MySQL error: Could not prepare statement: " +
std::string(mysql_error(handle.mysql.get())) + " (statement was >>" + statement +
"<<\n");
}
return prepared_statement;
}
}
connection::connection(const std::shared_ptr<connection_config>& config)
: _handle(new detail::connection_handle_t(config))
{
if (mysql_set_character_set(_handle->mysql.get(), _handle->config->charset.c_str()))
{
throw sqlpp::exception("MySQL error: can't set character set " + _handle->config->charset);
}
if (mysql_select_db(_handle->mysql.get(), _handle->config->database.c_str()))
{
throw sqlpp::exception("MySQL error: can't select database '" + _handle->config->database + "'");
}
}
connection::~connection()
{
}
connection::connection(connection&& other)
{
this->_transaction_active = other._transaction_active;
this->_handle = std::move(other._handle);
}
const std::shared_ptr<connection_config> connection::get_config()
{
return _handle->config;
}
char_result_t connection::select_impl(const std::string& statement)
{
execute_statement(*_handle, statement);
std::unique_ptr<detail::result_handle> result_handle(
new detail::result_handle(mysql_store_result(_handle->mysql.get()), _handle->config->debug));
if (!result_handle)
{
throw sqlpp::exception("MySQL error: Could not store result set: " +
std::string(mysql_error(_handle->mysql.get())));
}
return {std::move(result_handle)};
}
bind_result_t connection::run_prepared_select_impl(prepared_statement_t& prepared_statement)
{
execute_prepared_statement(*prepared_statement._handle);
return prepared_statement._handle;
}
size_t connection::run_prepared_insert_impl(prepared_statement_t& prepared_statement)
{
execute_prepared_statement(*prepared_statement._handle);
return mysql_stmt_insert_id(prepared_statement._handle->mysql_stmt);
}
size_t connection::run_prepared_update_impl(prepared_statement_t& prepared_statement)
{
execute_prepared_statement(*prepared_statement._handle);
return mysql_stmt_affected_rows(prepared_statement._handle->mysql_stmt);
}
size_t connection::run_prepared_remove_impl(prepared_statement_t& prepared_statement)
{
execute_prepared_statement(*prepared_statement._handle);
return mysql_stmt_affected_rows(prepared_statement._handle->mysql_stmt);
}
prepared_statement_t connection::prepare_impl(const std::string& statement,
size_t no_of_parameters,
size_t no_of_columns)
{
return prepare_statement(*_handle, statement, no_of_parameters, no_of_columns);
}
size_t connection::insert_impl(const std::string& statement)
{
execute_statement(*_handle, statement);
return mysql_insert_id(_handle->mysql.get());
}
void connection::execute(const std::string& command)
{
execute_statement(*_handle, command);
}
size_t connection::update_impl(const std::string& statement)
{
execute_statement(*_handle, statement);
return mysql_affected_rows(_handle->mysql.get());
}
size_t connection::remove_impl(const std::string& statement)
{
execute_statement(*_handle, statement);
return mysql_affected_rows(_handle->mysql.get());
}
std::string connection::escape(const std::string& s) const
{
std::unique_ptr<char[]> dest(new char[s.size() * 2 + 1]);
mysql_real_escape_string(_handle->mysql.get(), dest.get(), s.c_str(), s.size());
return dest.get();
}
void connection::start_transaction()
{
if (_transaction_active)
{
throw sqlpp::exception("MySQL: Cannot have more than one open transaction per connection");
}
execute_statement(*_handle, "START TRANSACTION");
_transaction_active = true;
}
void connection::commit_transaction()
{
if (not _transaction_active)
{
throw sqlpp::exception("MySQL: Cannot commit a finished or failed transaction");
}
_transaction_active = false;
execute_statement(*_handle, "COMMIT");
}
void connection::rollback_transaction(bool report)
{
if (not _transaction_active)
{
throw sqlpp::exception("MySQL: Cannot rollback a finished or failed transaction");
}
if (report)
{
std::cerr << "MySQL warning: Rolling back unfinished transaction" << std::endl;
}
_transaction_active = false;
execute_statement(*_handle, "ROLLBACK");
}
void connection::report_rollback_failure(const std::string message) noexcept
{
std::cerr << "MySQL message:" << message << std::endl;
}
}
}
<commit_msg>fix spacing<commit_after>/*
* Copyright (c) 2013 - 2015, Roland Bock
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <ciso646>
#include <iostream>
#ifdef _LIBCPP_VERSION
#include <boost/thread/tss.hpp> // libc++ does not have thread_local yet.
#endif
#include <sqlpp11/exception.h>
#include <sqlpp11/mysql/connection.h>
#include "detail/prepared_statement_handle.h"
#include "detail/result_handle.h"
#include "detail/connection_handle.h"
namespace sqlpp
{
namespace mysql
{
namespace
{
struct MySqlThreadInitializer
{
MySqlThreadInitializer()
{
if (!mysql_thread_safe())
{
throw sqlpp::exception("MySQL error: Operating on a non-threadsafe client");
}
mysql_thread_init();
}
~MySqlThreadInitializer()
{
mysql_thread_end();
}
};
#ifdef _LIBCPP_VERSION
boost::thread_specific_ptr<MySqlThreadInitializer> mysqlThreadInit;
#endif
void thread_init()
{
#ifdef _LIBCPP_VERSION
if (!mysqlThreadInit.get())
{
mysqlThreadInit.reset(new MySqlThreadInitializer);
}
#else
thread_local MySqlThreadInitializer threadInitializer;
#endif
}
void execute_statement(detail::connection_handle_t& handle, const std::string& statement)
{
thread_init();
if (handle.config->debug)
std::cerr << "MySQL debug: Executing: '" << statement << "'" << std::endl;
if (mysql_query(handle.mysql.get(), statement.c_str()))
{
throw sqlpp::exception("MySQL error: Could not execute MySQL-statement: " +
std::string(mysql_error(handle.mysql.get())) + " (statement was >>" + statement +
"<<\n");
}
}
void execute_prepared_statement(detail::prepared_statement_handle_t& prepared_statement)
{
thread_init();
if (prepared_statement.debug)
std::cerr << "MySQL debug: Executing prepared_statement" << std::endl;
if (mysql_stmt_bind_param(prepared_statement.mysql_stmt, prepared_statement.stmt_params.data()))
{
throw sqlpp::exception(std::string("MySQL error: Could not bind parameters to statement") +
mysql_stmt_error(prepared_statement.mysql_stmt));
}
if (mysql_stmt_execute(prepared_statement.mysql_stmt))
{
throw sqlpp::exception(std::string("MySQL error: Could not execute prepared statement: ") +
mysql_stmt_error(prepared_statement.mysql_stmt));
}
}
std::shared_ptr<detail::prepared_statement_handle_t> prepare_statement(detail::connection_handle_t& handle,
const std::string& statement,
size_t no_of_parameters,
size_t no_of_columns)
{
thread_init();
if (handle.config->debug)
std::cerr << "MySQL debug: Preparing: '" << statement << "'" << std::endl;
auto prepared_statement = std::make_shared<detail::prepared_statement_handle_t>(
mysql_stmt_init(handle.mysql.get()), no_of_parameters, no_of_columns, handle.config->debug);
if (not prepared_statement)
{
throw sqlpp::exception("MySQL error: Could not allocate prepared statement\n");
}
if (mysql_stmt_prepare(prepared_statement->mysql_stmt, statement.data(), statement.size()))
{
throw sqlpp::exception("MySQL error: Could not prepare statement: " +
std::string(mysql_error(handle.mysql.get())) + " (statement was >>" + statement +
"<<\n");
}
return prepared_statement;
}
}
connection::connection(const std::shared_ptr<connection_config>& config)
: _handle(new detail::connection_handle_t(config))
{
if (mysql_set_character_set(_handle->mysql.get(), _handle->config->charset.c_str()))
{
throw sqlpp::exception("MySQL error: can't set character set " + _handle->config->charset);
}
if (mysql_select_db(_handle->mysql.get(), _handle->config->database.c_str()))
{
throw sqlpp::exception("MySQL error: can't select database '" + _handle->config->database + "'");
}
}
connection::~connection()
{
}
connection::connection(connection&& other)
{
this->_transaction_active = other._transaction_active;
this->_handle = std::move(other._handle);
}
const std::shared_ptr<connection_config> connection::get_config()
{
return _handle->config;
}
char_result_t connection::select_impl(const std::string& statement)
{
execute_statement(*_handle, statement);
std::unique_ptr<detail::result_handle> result_handle(
new detail::result_handle(mysql_store_result(_handle->mysql.get()), _handle->config->debug));
if (!result_handle)
{
throw sqlpp::exception("MySQL error: Could not store result set: " +
std::string(mysql_error(_handle->mysql.get())));
}
return {std::move(result_handle)};
}
bind_result_t connection::run_prepared_select_impl(prepared_statement_t& prepared_statement)
{
execute_prepared_statement(*prepared_statement._handle);
return prepared_statement._handle;
}
size_t connection::run_prepared_insert_impl(prepared_statement_t& prepared_statement)
{
execute_prepared_statement(*prepared_statement._handle);
return mysql_stmt_insert_id(prepared_statement._handle->mysql_stmt);
}
size_t connection::run_prepared_update_impl(prepared_statement_t& prepared_statement)
{
execute_prepared_statement(*prepared_statement._handle);
return mysql_stmt_affected_rows(prepared_statement._handle->mysql_stmt);
}
size_t connection::run_prepared_remove_impl(prepared_statement_t& prepared_statement)
{
execute_prepared_statement(*prepared_statement._handle);
return mysql_stmt_affected_rows(prepared_statement._handle->mysql_stmt);
}
prepared_statement_t connection::prepare_impl(const std::string& statement,
size_t no_of_parameters,
size_t no_of_columns)
{
return prepare_statement(*_handle, statement, no_of_parameters, no_of_columns);
}
size_t connection::insert_impl(const std::string& statement)
{
execute_statement(*_handle, statement);
return mysql_insert_id(_handle->mysql.get());
}
void connection::execute(const std::string& command)
{
execute_statement(*_handle, command);
}
size_t connection::update_impl(const std::string& statement)
{
execute_statement(*_handle, statement);
return mysql_affected_rows(_handle->mysql.get());
}
size_t connection::remove_impl(const std::string& statement)
{
execute_statement(*_handle, statement);
return mysql_affected_rows(_handle->mysql.get());
}
std::string connection::escape(const std::string& s) const
{
std::unique_ptr<char[]> dest(new char[s.size() * 2 + 1]);
mysql_real_escape_string(_handle->mysql.get(), dest.get(), s.c_str(), s.size());
return dest.get();
}
void connection::start_transaction()
{
if (_transaction_active)
{
throw sqlpp::exception("MySQL: Cannot have more than one open transaction per connection");
}
execute_statement(*_handle, "START TRANSACTION");
_transaction_active = true;
}
void connection::commit_transaction()
{
if (not _transaction_active)
{
throw sqlpp::exception("MySQL: Cannot commit a finished or failed transaction");
}
_transaction_active = false;
execute_statement(*_handle, "COMMIT");
}
void connection::rollback_transaction(bool report)
{
if (not _transaction_active)
{
throw sqlpp::exception("MySQL: Cannot rollback a finished or failed transaction");
}
if (report)
{
std::cerr << "MySQL warning: Rolling back unfinished transaction" << std::endl;
}
_transaction_active = false;
execute_statement(*_handle, "ROLLBACK");
}
void connection::report_rollback_failure(const std::string message) noexcept
{
std::cerr << "MySQL message:" << message << std::endl;
}
}
}
<|endoftext|> |
<commit_before>/*
* This file is part of Poedit (http://www.poedit.net)
*
* Copyright (C) 1999-2007 Vaclav Slavik
* Copyright (C) 2005 Olivier Sannier
*
* 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.
*
* $Id$
*
* List view control
*
*/
#include <wx/wx.h>
#include <wx/imaglist.h>
#include <wx/artprov.h>
#include <wx/dcmemory.h>
#include <wx/image.h>
#include "edlistctrl.h"
#include "digits.h"
// I don't like this global flag, but all PoeditFrame instances should share it :(
bool gs_shadedList = false;
// colours used in the list:
#define g_darkColourFactor 0.95
#define DARKEN_COLOUR(r,g,b) (wxColour(int((r)*g_darkColourFactor),\
int((g)*g_darkColourFactor),\
int((b)*g_darkColourFactor)))
#define LIST_COLOURS(r,g,b) { wxColour(r,g,b), DARKEN_COLOUR(r,g,b) }
static const wxColour
g_ItemColourNormal[2] = LIST_COLOURS(0xFF,0xFF,0xFF), // white
g_ItemColourUntranslated[2] = LIST_COLOURS(0xA5,0xEA,0xEF), // blue
g_ItemColourFuzzy[2] = LIST_COLOURS(0xF4,0xF1,0xC1), // yellow
g_ItemColourInvalid[2] = LIST_COLOURS(0xFF,0x20,0x20); // red
static const wxColour g_TranspColour(254, 0, 253);
enum
{
IMG_NOTHING = 0x00,
IMG_AUTOMATIC = 0x01,
IMG_COMMENT = 0x02,
IMG_MODIFIED = 0x04,
IMG_BK0 = 1 << 3,
IMG_BK1 = 2 << 3,
IMG_BK2 = 3 << 3,
IMG_BK3 = 4 << 3,
IMG_BK4 = 5 << 3,
IMG_BK5 = 6 << 3,
IMG_BK6 = 7 << 3,
IMG_BK7 = 8 << 3,
IMG_BK8 = 9 << 3,
IMG_BK9 = 10 << 3
};
BEGIN_EVENT_TABLE(PoeditListCtrl, wxListCtrl)
EVT_SIZE(PoeditListCtrl::OnSize)
END_EVENT_TABLE()
static wxBitmap AddDigit(int digit, int x, int y, const wxBitmap& bmp)
{
wxMemoryDC dc;
int width = bmp.GetWidth();
int height = bmp.GetHeight();
wxBitmap tmpBmp(width, height);
dc.SelectObject(tmpBmp);
dc.SetPen(*wxTRANSPARENT_PEN);
dc.SetBrush(wxBrush(g_TranspColour, wxSOLID));
dc.DrawRectangle(0, 0, width, height);
dc.DrawBitmap(bmp, 0,0,true);
dc.SetPen(*wxBLACK_PEN);
for(int i = 0; i < 5; i++)
{
for(int j = 0; j < 3; j++)
{
if (g_digits[digit][i][j] == 1)
dc.DrawPoint(x+j, y+i);
}
}
dc.SelectObject(wxNullBitmap);
tmpBmp.SetMask(new wxMask(tmpBmp, g_TranspColour));
return tmpBmp;
}
wxBitmap MergeBitmaps(const wxBitmap& bmp1, const wxBitmap& bmp2)
{
wxMemoryDC dc;
wxBitmap tmpBmp(bmp1.GetWidth(), bmp1.GetHeight());
dc.SelectObject(tmpBmp);
dc.SetPen(*wxTRANSPARENT_PEN);
dc.SetBrush(wxBrush(g_TranspColour, wxSOLID));
dc.DrawRectangle(0, 0, bmp1.GetWidth(), bmp1.GetHeight());
dc.DrawBitmap(bmp1, 0, 0, true);
dc.DrawBitmap(bmp2, 0, 0, true);
dc.SelectObject(wxNullBitmap);
tmpBmp.SetMask(new wxMask(tmpBmp, g_TranspColour));
return tmpBmp;
}
wxBitmap BitmapFromList(wxImageList* list, int index)
{
int width, height;
list->GetSize(index, width, height);
wxMemoryDC dc;
wxBitmap bmp(width, height);
dc.SelectObject(bmp);
dc.SetPen(*wxTRANSPARENT_PEN);
dc.SetBrush(wxBrush(g_TranspColour, wxSOLID));
dc.DrawRectangle(0, 0, width, height);
list->Draw(index, dc, 0, 0, wxIMAGELIST_DRAW_TRANSPARENT);
dc.SelectObject(wxNullBitmap);
bmp.SetMask(new wxMask(bmp, g_TranspColour));
return bmp;
}
PoeditListCtrl::PoeditListCtrl(wxWindow *parent,
wxWindowID id,
const wxPoint &pos,
const wxSize &size,
long style,
bool dispLines,
const wxValidator& validator,
const wxString &name)
: wxListView(parent, id, pos, size, style | wxLC_VIRTUAL, validator, name)
{
m_catalog = NULL;
m_displayLines = dispLines;
CreateColumns();
int i;
wxImageList *list = new wxImageList(16, 16);
// IMG_NOTHING:
list->Add(wxArtProvider::GetBitmap(_T("poedit-status-nothing")));
// IMG_AUTOMATIC:
list->Add(wxArtProvider::GetBitmap(_T("poedit-status-automatic")));
// IMG_COMMENT:
list->Add(wxArtProvider::GetBitmap(_T("poedit-status-comment")));
// IMG_AUTOMATIC | IMG_COMMENT:
list->Add(MergeBitmaps(wxArtProvider::GetBitmap(_T("poedit-status-automatic")),
wxArtProvider::GetBitmap(_T("poedit-status-comment"))));
// IMG_MODIFIED
list->Add(wxArtProvider::GetBitmap(_T("poedit-status-modified")));
// IMG_MODIFIED variations:
for (i = 1; i < IMG_MODIFIED; i++)
{
list->Add(MergeBitmaps(BitmapFromList(list, i),
wxArtProvider::GetBitmap(_T("poedit-status-modified"))));
}
// BK_XX variations:
for (int bk = 0; bk < 10; bk++)
{
for(i = 0; i <= (IMG_AUTOMATIC|IMG_COMMENT|IMG_MODIFIED); i++)
{
wxBitmap bmp = BitmapFromList(list, i);
list->Add(AddDigit(bk, 0, 0, bmp));
}
}
AssignImageList(list, wxIMAGE_LIST_SMALL);
// configure items colors:
m_attrNormal[0].SetBackgroundColour(g_ItemColourNormal[0]);
m_attrNormal[1].SetBackgroundColour(g_ItemColourNormal[1]);
m_attrUntranslated[0].SetBackgroundColour(g_ItemColourUntranslated[0]);
m_attrUntranslated[1].SetBackgroundColour(g_ItemColourUntranslated[1]);
m_attrFuzzy[0].SetBackgroundColour(g_ItemColourFuzzy[0]);
m_attrFuzzy[1].SetBackgroundColour(g_ItemColourFuzzy[1]);
m_attrInvalid[0].SetBackgroundColour(g_ItemColourInvalid[0]);
m_attrInvalid[1].SetBackgroundColour(g_ItemColourInvalid[1]);
}
PoeditListCtrl::~PoeditListCtrl()
{
}
void PoeditListCtrl::CreateColumns()
{
ClearAll();
InsertColumn(0, _("Original string"));
InsertColumn(1, _("Translation"));
if (m_displayLines)
InsertColumn(2, _("Line"), wxLIST_FORMAT_RIGHT);
ReadCatalog();
SizeColumns();
}
void PoeditListCtrl::SizeColumns()
{
const int LINE_COL_SIZE = m_displayLines ? 50 : 0;
int w = GetSize().x
- wxSystemSettings::GetMetric(wxSYS_VSCROLL_X) - 10
- LINE_COL_SIZE;
SetColumnWidth(0, w / 2);
SetColumnWidth(1, w - w / 2);
if (m_displayLines)
SetColumnWidth(2, LINE_COL_SIZE);
m_colWidth = (w/2) / GetCharWidth();
}
void PoeditListCtrl::CatalogChanged(Catalog* catalog)
{
m_catalog = catalog;
ReadCatalog();
}
void PoeditListCtrl::ReadCatalog()
{
if (m_catalog == NULL)
{
SetItemCount(0);
return;
}
// set the item count
SetItemCount(m_catalog->GetCount());
// create the lookup arrays of Ids by first splitting it upon
// four categories of items:
// unstranslated, invalid, fuzzy and the rest
m_itemIndexToCatalogIndexArray.clear();
std::vector<int> untranslatedIds;
std::vector<int> invalidIds;
std::vector<int> fuzzyIds;
std::vector<int> restIds;
for (size_t i = 0; i < m_catalog->GetCount(); i++)
{
CatalogData& d = (*m_catalog)[i];
if (!d.IsTranslated())
untranslatedIds.push_back(i);
else if (d.GetValidity() == CatalogData::Val_Invalid)
invalidIds.push_back(i);
else if (d.IsFuzzy())
fuzzyIds.push_back(i);
else
restIds.push_back(i);
}
// Now fill the lookup array, not forgetting to set the appropriate
// property in the catalog entry to be able to go back and forth
// from one numbering system to the other
m_catalogIndexToItemIndexArray.resize(m_catalog->GetCount());
int listItemId = 0;
for (size_t i = 0; i < untranslatedIds.size(); i++)
{
m_itemIndexToCatalogIndexArray.push_back(untranslatedIds[i]);
m_catalogIndexToItemIndexArray[untranslatedIds[i]] = listItemId++;
}
for (size_t i = 0; i < invalidIds.size(); i++)
{
m_itemIndexToCatalogIndexArray.push_back(invalidIds[i]);
m_catalogIndexToItemIndexArray[invalidIds[i]] = listItemId++;
}
for (size_t i = 0; i < fuzzyIds.size(); i++)
{
m_itemIndexToCatalogIndexArray.push_back(fuzzyIds[i]);
m_catalogIndexToItemIndexArray[fuzzyIds[i]] = listItemId++;
}
for (size_t i = 0; i < restIds.size(); i++)
{
m_itemIndexToCatalogIndexArray.push_back(restIds[i]);
m_catalogIndexToItemIndexArray[restIds[i]] = listItemId++;
}
}
wxString PoeditListCtrl::OnGetItemText(long item, long column) const
{
if (m_catalog == NULL)
return wxEmptyString;
CatalogData& d = (*m_catalog)[m_itemIndexToCatalogIndexArray[item]];
switch (column)
{
case 0:
{
wxString orig = d.GetString();
return orig.substr(0,GetMaxColChars());
}
case 1:
{
wxString trans = d.GetTranslation();
return trans;
}
case 2:
return wxString() << d.GetLineNumber();
default:
return wxEmptyString;
}
}
wxListItemAttr *PoeditListCtrl::OnGetItemAttr(long item) const
{
size_t idx = gs_shadedList ? size_t(item % 2) : 0;
if (m_catalog == NULL)
return (wxListItemAttr*)&m_attrNormal[idx];
CatalogData& d = (*m_catalog)[m_itemIndexToCatalogIndexArray[item]];
if (!d.IsTranslated())
return (wxListItemAttr*)&m_attrUntranslated[idx];
else if (d.IsFuzzy())
return (wxListItemAttr*)&m_attrFuzzy[idx];
else if (d.GetValidity() == CatalogData::Val_Invalid)
return (wxListItemAttr*)&m_attrInvalid[idx];
else
return (wxListItemAttr*)&m_attrNormal[idx];
}
int PoeditListCtrl::OnGetItemImage(long item) const
{
if (m_catalog == NULL)
return IMG_NOTHING;
CatalogData& d = (*m_catalog)[m_itemIndexToCatalogIndexArray[item]];
int index = IMG_NOTHING;
if (d.IsAutomatic())
index |= IMG_AUTOMATIC;
if (d.HasComment())
index |= IMG_COMMENT;
if (d.IsModified())
index |= IMG_MODIFIED;
index |= (static_cast<int>(d.GetBookmark())+1) << 3;
return index;
}
void PoeditListCtrl::OnSize(wxSizeEvent& event)
{
SizeColumns();
event.Skip();
}
long PoeditListCtrl::GetIndexInCatalog(long item) const
{
if (item < (long)m_itemIndexToCatalogIndexArray.size())
return m_itemIndexToCatalogIndexArray[item];
else
return -1;
}
int PoeditListCtrl::GetItemIndex(int catalogIndex) const
{
if (catalogIndex < (int)m_catalogIndexToItemIndexArray.size())
return m_catalogIndexToItemIndexArray[catalogIndex];
else
return -1;
}
<commit_msg>fixed crash in list control code on OSX<commit_after>/*
* This file is part of Poedit (http://www.poedit.net)
*
* Copyright (C) 1999-2007 Vaclav Slavik
* Copyright (C) 2005 Olivier Sannier
*
* 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.
*
* $Id$
*
* List view control
*
*/
#include <wx/wx.h>
#include <wx/imaglist.h>
#include <wx/artprov.h>
#include <wx/dcmemory.h>
#include <wx/image.h>
#include "edlistctrl.h"
#include "digits.h"
// I don't like this global flag, but all PoeditFrame instances should share it :(
bool gs_shadedList = false;
// colours used in the list:
#define g_darkColourFactor 0.95
#define DARKEN_COLOUR(r,g,b) (wxColour(int((r)*g_darkColourFactor),\
int((g)*g_darkColourFactor),\
int((b)*g_darkColourFactor)))
#define LIST_COLOURS(r,g,b) { wxColour(r,g,b), DARKEN_COLOUR(r,g,b) }
static const wxColour
g_ItemColourNormal[2] = LIST_COLOURS(0xFF,0xFF,0xFF), // white
g_ItemColourUntranslated[2] = LIST_COLOURS(0xA5,0xEA,0xEF), // blue
g_ItemColourFuzzy[2] = LIST_COLOURS(0xF4,0xF1,0xC1), // yellow
g_ItemColourInvalid[2] = LIST_COLOURS(0xFF,0x20,0x20); // red
static const wxColour g_TranspColour(254, 0, 253);
enum
{
IMG_NOTHING = 0x00,
IMG_AUTOMATIC = 0x01,
IMG_COMMENT = 0x02,
IMG_MODIFIED = 0x04,
IMG_BK0 = 1 << 3,
IMG_BK1 = 2 << 3,
IMG_BK2 = 3 << 3,
IMG_BK3 = 4 << 3,
IMG_BK4 = 5 << 3,
IMG_BK5 = 6 << 3,
IMG_BK6 = 7 << 3,
IMG_BK7 = 8 << 3,
IMG_BK8 = 9 << 3,
IMG_BK9 = 10 << 3
};
BEGIN_EVENT_TABLE(PoeditListCtrl, wxListCtrl)
EVT_SIZE(PoeditListCtrl::OnSize)
END_EVENT_TABLE()
static wxBitmap AddDigit(int digit, int x, int y, const wxBitmap& bmp)
{
wxMemoryDC dc;
int width = bmp.GetWidth();
int height = bmp.GetHeight();
wxBitmap tmpBmp(width, height);
dc.SelectObject(tmpBmp);
dc.SetPen(*wxTRANSPARENT_PEN);
dc.SetBrush(wxBrush(g_TranspColour, wxSOLID));
dc.DrawRectangle(0, 0, width, height);
dc.DrawBitmap(bmp, 0,0,true);
dc.SetPen(*wxBLACK_PEN);
for(int i = 0; i < 5; i++)
{
for(int j = 0; j < 3; j++)
{
if (g_digits[digit][i][j] == 1)
dc.DrawPoint(x+j, y+i);
}
}
dc.SelectObject(wxNullBitmap);
tmpBmp.SetMask(new wxMask(tmpBmp, g_TranspColour));
return tmpBmp;
}
wxBitmap MergeBitmaps(const wxBitmap& bmp1, const wxBitmap& bmp2)
{
wxMemoryDC dc;
wxBitmap tmpBmp(bmp1.GetWidth(), bmp1.GetHeight());
dc.SelectObject(tmpBmp);
dc.SetPen(*wxTRANSPARENT_PEN);
dc.SetBrush(wxBrush(g_TranspColour, wxSOLID));
dc.DrawRectangle(0, 0, bmp1.GetWidth(), bmp1.GetHeight());
dc.DrawBitmap(bmp1, 0, 0, true);
dc.DrawBitmap(bmp2, 0, 0, true);
dc.SelectObject(wxNullBitmap);
tmpBmp.SetMask(new wxMask(tmpBmp, g_TranspColour));
return tmpBmp;
}
wxBitmap BitmapFromList(wxImageList* list, int index)
{
int width, height;
list->GetSize(index, width, height);
wxMemoryDC dc;
wxBitmap bmp(width, height);
dc.SelectObject(bmp);
dc.SetPen(*wxTRANSPARENT_PEN);
dc.SetBrush(wxBrush(g_TranspColour, wxSOLID));
dc.DrawRectangle(0, 0, width, height);
list->Draw(index, dc, 0, 0, wxIMAGELIST_DRAW_TRANSPARENT);
dc.SelectObject(wxNullBitmap);
bmp.SetMask(new wxMask(bmp, g_TranspColour));
return bmp;
}
PoeditListCtrl::PoeditListCtrl(wxWindow *parent,
wxWindowID id,
const wxPoint &pos,
const wxSize &size,
long style,
bool dispLines,
const wxValidator& validator,
const wxString &name)
: wxListView(parent, id, pos, size, style | wxLC_VIRTUAL, validator, name)
{
m_catalog = NULL;
m_displayLines = dispLines;
CreateColumns();
int i;
wxImageList *list = new wxImageList(16, 16);
// IMG_NOTHING:
list->Add(wxArtProvider::GetBitmap(_T("poedit-status-nothing")));
// IMG_AUTOMATIC:
list->Add(wxArtProvider::GetBitmap(_T("poedit-status-automatic")));
// IMG_COMMENT:
list->Add(wxArtProvider::GetBitmap(_T("poedit-status-comment")));
// IMG_AUTOMATIC | IMG_COMMENT:
list->Add(MergeBitmaps(wxArtProvider::GetBitmap(_T("poedit-status-automatic")),
wxArtProvider::GetBitmap(_T("poedit-status-comment"))));
// IMG_MODIFIED
list->Add(wxArtProvider::GetBitmap(_T("poedit-status-modified")));
// IMG_MODIFIED variations:
for (i = 1; i < IMG_MODIFIED; i++)
{
list->Add(MergeBitmaps(BitmapFromList(list, i),
wxArtProvider::GetBitmap(_T("poedit-status-modified"))));
}
// BK_XX variations:
for (int bk = 0; bk < 10; bk++)
{
for(i = 0; i <= (IMG_AUTOMATIC|IMG_COMMENT|IMG_MODIFIED); i++)
{
wxBitmap bmp = BitmapFromList(list, i);
list->Add(AddDigit(bk, 0, 0, bmp));
}
}
AssignImageList(list, wxIMAGE_LIST_SMALL);
// configure items colors:
m_attrNormal[0].SetBackgroundColour(g_ItemColourNormal[0]);
m_attrNormal[1].SetBackgroundColour(g_ItemColourNormal[1]);
m_attrUntranslated[0].SetBackgroundColour(g_ItemColourUntranslated[0]);
m_attrUntranslated[1].SetBackgroundColour(g_ItemColourUntranslated[1]);
m_attrFuzzy[0].SetBackgroundColour(g_ItemColourFuzzy[0]);
m_attrFuzzy[1].SetBackgroundColour(g_ItemColourFuzzy[1]);
m_attrInvalid[0].SetBackgroundColour(g_ItemColourInvalid[0]);
m_attrInvalid[1].SetBackgroundColour(g_ItemColourInvalid[1]);
}
PoeditListCtrl::~PoeditListCtrl()
{
}
void PoeditListCtrl::CreateColumns()
{
ClearAll();
InsertColumn(0, _("Original string"));
InsertColumn(1, _("Translation"));
if (m_displayLines)
InsertColumn(2, _("Line"), wxLIST_FORMAT_RIGHT);
ReadCatalog();
SizeColumns();
}
void PoeditListCtrl::SizeColumns()
{
const int LINE_COL_SIZE = m_displayLines ? 50 : 0;
int w = GetSize().x
- wxSystemSettings::GetMetric(wxSYS_VSCROLL_X) - 10
- LINE_COL_SIZE;
SetColumnWidth(0, w / 2);
SetColumnWidth(1, w - w / 2);
if (m_displayLines)
SetColumnWidth(2, LINE_COL_SIZE);
m_colWidth = (w/2) / GetCharWidth();
}
void PoeditListCtrl::CatalogChanged(Catalog* catalog)
{
Freeze();
// this is to prevent crashes (wxMac at least) when shortening virtual
// listctrl when its scrolled to the bottom:
m_catalog = NULL;
SetItemCount(0);
// now read the new catalog:
m_catalog = catalog;
ReadCatalog();
Thaw();
}
void PoeditListCtrl::ReadCatalog()
{
if (m_catalog == NULL)
{
SetItemCount(0);
return;
}
// create the lookup arrays of Ids by first splitting it upon
// four categories of items:
// unstranslated, invalid, fuzzy and the rest
m_itemIndexToCatalogIndexArray.clear();
std::vector<int> untranslatedIds;
std::vector<int> invalidIds;
std::vector<int> fuzzyIds;
std::vector<int> restIds;
for (size_t i = 0; i < m_catalog->GetCount(); i++)
{
CatalogData& d = (*m_catalog)[i];
if (!d.IsTranslated())
untranslatedIds.push_back(i);
else if (d.GetValidity() == CatalogData::Val_Invalid)
invalidIds.push_back(i);
else if (d.IsFuzzy())
fuzzyIds.push_back(i);
else
restIds.push_back(i);
}
// Now fill the lookup array, not forgetting to set the appropriate
// property in the catalog entry to be able to go back and forth
// from one numbering system to the other
m_catalogIndexToItemIndexArray.resize(m_catalog->GetCount());
int listItemId = 0;
for (size_t i = 0; i < untranslatedIds.size(); i++)
{
m_itemIndexToCatalogIndexArray.push_back(untranslatedIds[i]);
m_catalogIndexToItemIndexArray[untranslatedIds[i]] = listItemId++;
}
for (size_t i = 0; i < invalidIds.size(); i++)
{
m_itemIndexToCatalogIndexArray.push_back(invalidIds[i]);
m_catalogIndexToItemIndexArray[invalidIds[i]] = listItemId++;
}
for (size_t i = 0; i < fuzzyIds.size(); i++)
{
m_itemIndexToCatalogIndexArray.push_back(fuzzyIds[i]);
m_catalogIndexToItemIndexArray[fuzzyIds[i]] = listItemId++;
}
for (size_t i = 0; i < restIds.size(); i++)
{
m_itemIndexToCatalogIndexArray.push_back(restIds[i]);
m_catalogIndexToItemIndexArray[restIds[i]] = listItemId++;
}
// now that everything is prepared, we may set the item count
SetItemCount(m_catalog->GetCount());
// scroll to the top and refresh everything:
Select(0);
RefreshItems(0, m_catalog->GetCount());
}
wxString PoeditListCtrl::OnGetItemText(long item, long column) const
{
if (m_catalog == NULL)
return wxEmptyString;
CatalogData& d = (*m_catalog)[m_itemIndexToCatalogIndexArray[item]];
switch (column)
{
case 0:
{
wxString orig = d.GetString();
return orig.substr(0,GetMaxColChars());
}
case 1:
{
wxString trans = d.GetTranslation();
return trans;
}
case 2:
return wxString() << d.GetLineNumber();
default:
return wxEmptyString;
}
}
wxListItemAttr *PoeditListCtrl::OnGetItemAttr(long item) const
{
size_t idx = gs_shadedList ? size_t(item % 2) : 0;
if (m_catalog == NULL)
return (wxListItemAttr*)&m_attrNormal[idx];
CatalogData& d = (*m_catalog)[m_itemIndexToCatalogIndexArray[item]];
if (!d.IsTranslated())
return (wxListItemAttr*)&m_attrUntranslated[idx];
else if (d.IsFuzzy())
return (wxListItemAttr*)&m_attrFuzzy[idx];
else if (d.GetValidity() == CatalogData::Val_Invalid)
return (wxListItemAttr*)&m_attrInvalid[idx];
else
return (wxListItemAttr*)&m_attrNormal[idx];
}
int PoeditListCtrl::OnGetItemImage(long item) const
{
if (m_catalog == NULL)
return IMG_NOTHING;
CatalogData& d = (*m_catalog)[m_itemIndexToCatalogIndexArray[item]];
int index = IMG_NOTHING;
if (d.IsAutomatic())
index |= IMG_AUTOMATIC;
if (d.HasComment())
index |= IMG_COMMENT;
if (d.IsModified())
index |= IMG_MODIFIED;
index |= (static_cast<int>(d.GetBookmark())+1) << 3;
return index;
}
void PoeditListCtrl::OnSize(wxSizeEvent& event)
{
SizeColumns();
event.Skip();
}
long PoeditListCtrl::GetIndexInCatalog(long item) const
{
if (item < (long)m_itemIndexToCatalogIndexArray.size())
return m_itemIndexToCatalogIndexArray[item];
else
return -1;
}
int PoeditListCtrl::GetItemIndex(int catalogIndex) const
{
if (catalogIndex < (int)m_catalogIndexToItemIndexArray.size())
return m_catalogIndexToItemIndexArray[catalogIndex];
else
return -1;
}
<|endoftext|> |
<commit_before>// Copyright (C) 2005-2009 by Jukka Korpela
// Copyright (C) 2009-2013 by David Hoerl
// Copyright (C) 2013 by Martin Moene
//
// 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 "eng_format.hpp"
#include <iomanip>
#include <limits>
#include <sstream>
#include <ctype.h>
#include <float.h>
#include <math.h>
#include <stdlib.h>
/*
* Note: using fabs() and other math functions in global namespace for
* best compiler coverage.
*/
/*
* Note: micro, , may not work everywhere, so you can define a glyph yourself:
*/
#ifndef ENG_FORMAT_MICRO_GLYPH
# define ENG_FORMAT_MICRO_GLYPH ""
#endif
/*
* Note: if not using signed at the computation of prefix_end below,
* VC2010 -Wall issues a warning about unsigned and addition overflow.
* Hence the cast to signed int here.
*/
#define ENG_FORMAT_DIMENSION_OF(a) ( static_cast<int>( sizeof(a) / sizeof(0[a]) ) )
eng_prefixed_t eng_prefixed;
eng_exponential_t eng_exponential;
namespace
{
char const * const prefixes[/*exp*/][2][9] =
{
{
{ "", "m", ENG_FORMAT_MICRO_GLYPH
, "n", "p", "f", "a", "z", "y", },
{ "", "k", "M", "G", "T", "P", "E", "Z", "Y", },
},
{
{ "e0", "e-3", "e-6", "e-9", "e-12", "e-15", "e-18", "e-21", "e-24", },
{ "e0", "e3", "e6", "e9", "e12", "e15", "e18", "e21", "e24", },
},
};
const int prefix_count = ENG_FORMAT_DIMENSION_OF( prefixes[false][false] );
#if defined( _MSC_VER )
template <typename T>
long lrint( T const x )
{
return static_cast<long>( x );
}
#endif
int sign( int const value )
{
return value == 0 ? +1 : value / abs( value );
}
bool is_zero( double const value )
{
#if __cplusplus >= 201103L
return FP_ZERO == fpclassify( value );
#else
// deliberately compare literally:
return 0.0 == value;
#endif
}
bool is_nan( double const value )
{
#if __cplusplus >= 201103L
return isnan( value );
#else
// deliberately return false for now:
return false;
#endif
}
bool is_inf( double const value )
{
#if __cplusplus >= 201103L
return isinf( value );
#else
// deliberately return false for now:
return false;
#endif
}
long degree_of( double const value )
{
return is_zero( value ) ? 0 : lrint( floor( log10( fabs( value ) ) / 3) );
}
int precision( double const scaled, int const digits )
{
// MSVC6 requires -2 * DBL_EPSILON;
// g++ 4.8.1: ok with -1 * DBL_EPSILON
return is_zero( scaled ) ? digits - 1 : digits - log10( fabs( scaled ) ) - 2 * DBL_EPSILON;
}
std::string prefix_or_exponent( bool const exponential, int const degree, std::string separator )
{
return std::string( exponential || 0 == degree ? "" : separator ) + prefixes[ exponential ][ sign(degree) > 0 ][ abs( degree ) ];
}
std::string exponent( int const degree )
{
std::ostringstream os;
os << "e" << 3 * degree;
return os.str();
}
bool starts_with( std::string const text, std::string const start )
{
return 0 == text.find( start );
}
/*
* "k" => 3
*/
int prefix_to_exponent( std::string const pfx )
{
for ( int i = 0; i < 2; ++i )
{
// skip prefixes[0][i][0], it matches everything
for( int k = 1; k < prefix_count; ++k )
{
if ( starts_with( pfx, prefixes[0][i][k] ) )
{
return ( i ? 1 : -1 ) * k * 3;
}
}
}
return 0;
}
} // anonymous namespace
/**
* convert real number to prefixed or exponential notation, optionally followed by a unit.
*/
std::string
to_engineering_string( double const value, int const digits, bool exponential, std::string const unit /*= ""*/, std::string separator /*= " "*/ )
{
if ( is_nan( value ) ) return "NaN";
else if ( is_inf( value ) ) return "INFINITE";
const int degree = degree_of( value );
std::string factor;
if ( abs( degree ) < prefix_count )
{
factor = prefix_or_exponent( exponential, degree, separator );
}
else
{
exponential = true;
factor = exponent( degree );
}
std::ostringstream os;
const double scaled = value * pow( 1000.0, -degree );
const std::string space = ( 0 == degree || exponential ) && unit.length() ? separator : "";
os << std::fixed << std::setprecision( precision( scaled, digits ) ) << scaled << factor << space << unit;
return os.str();
}
/**
* convert the output of to_engineering_string() into a double.
*
* The engineering presentation should not contain a unit, as the first letter
* is interpreted as an SI prefix, e.g. "1 T" is 1e12, not 1 (Tesla).
*
* "1.23 M" => 1.23e+6
* "1.23 kPa" => 1.23e+3 (ok, but not recommended)
* "1.23 Pa" => 1.23e+12 (not what's intended!)
*/
double from_engineering_string( std::string const text )
{
char * tail;
double magnitude = strtod( text.c_str(), &tail );
// skip any whitespace between magnitude and SI prefix
while ( *tail && isspace( *tail ) )
{
++tail;
}
return magnitude * pow( 10.0, prefix_to_exponent( tail ) );
}
/**
* step a value by the smallest possible increment.
*/
std::string step_engineering_string( std::string const text, int digits, bool const exponential, bool const positive )
{
const double value = from_engineering_string( text );
if ( digits < 3 )
{
digits = 3;
}
// correctly round to desired precision
const int expof10 = is_zero(value) ? 0 : lrint( floor( log10( value ) ) );
const int power = expof10 + 1 - digits;
const double inc = pow( 10.0, power ) * ( positive ? +1 : -1 );
const double ret = value + inc;
return to_engineering_string( ret, digits, exponential );
}
// end of file
<commit_msg>Extract first_non_space()<commit_after>// Copyright (C) 2005-2009 by Jukka Korpela
// Copyright (C) 2009-2013 by David Hoerl
// Copyright (C) 2013 by Martin Moene
//
// 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 "eng_format.hpp"
#include <iomanip>
#include <limits>
#include <sstream>
#include <ctype.h>
#include <float.h>
#include <math.h>
#include <stdlib.h>
/*
* Note: using fabs() and other math functions in global namespace for
* best compiler coverage.
*/
/*
* Note: micro, , may not work everywhere, so you can define a glyph yourself:
*/
#ifndef ENG_FORMAT_MICRO_GLYPH
# define ENG_FORMAT_MICRO_GLYPH ""
#endif
/*
* Note: if not using signed at the computation of prefix_end below,
* VC2010 -Wall issues a warning about unsigned and addition overflow.
* Hence the cast to signed int here.
*/
#define ENG_FORMAT_DIMENSION_OF(a) ( static_cast<int>( sizeof(a) / sizeof(0[a]) ) )
eng_prefixed_t eng_prefixed;
eng_exponential_t eng_exponential;
namespace
{
char const * const prefixes[/*exp*/][2][9] =
{
{
{ "", "m", ENG_FORMAT_MICRO_GLYPH
, "n", "p", "f", "a", "z", "y", },
{ "", "k", "M", "G", "T", "P", "E", "Z", "Y", },
},
{
{ "e0", "e-3", "e-6", "e-9", "e-12", "e-15", "e-18", "e-21", "e-24", },
{ "e0", "e3", "e6", "e9", "e12", "e15", "e18", "e21", "e24", },
},
};
const int prefix_count = ENG_FORMAT_DIMENSION_OF( prefixes[false][false] );
#if defined( _MSC_VER )
template <typename T>
long lrint( T const x )
{
return static_cast<long>( x );
}
#endif
int sign( int const value )
{
return value == 0 ? +1 : value / abs( value );
}
bool is_zero( double const value )
{
#if __cplusplus >= 201103L
return FP_ZERO == fpclassify( value );
#else
// deliberately compare literally:
return 0.0 == value;
#endif
}
bool is_nan( double const value )
{
#if __cplusplus >= 201103L
return isnan( value );
#else
// deliberately return false for now:
return false;
#endif
}
bool is_inf( double const value )
{
#if __cplusplus >= 201103L
return isinf( value );
#else
// deliberately return false for now:
return false;
#endif
}
long degree_of( double const value )
{
return is_zero( value ) ? 0 : lrint( floor( log10( fabs( value ) ) / 3) );
}
int precision( double const scaled, int const digits )
{
// MSVC6 requires -2 * DBL_EPSILON;
// g++ 4.8.1: ok with -1 * DBL_EPSILON
return is_zero( scaled ) ? digits - 1 : digits - log10( fabs( scaled ) ) - 2 * DBL_EPSILON;
}
std::string prefix_or_exponent( bool const exponential, int const degree, std::string separator )
{
return std::string( exponential || 0 == degree ? "" : separator ) + prefixes[ exponential ][ sign(degree) > 0 ][ abs( degree ) ];
}
std::string exponent( int const degree )
{
std::ostringstream os;
os << "e" << 3 * degree;
return os.str();
}
char const * first_non_space( char const * text )
{
while ( *text && isspace( *text ) )
{
++text;
}
return text;
}
bool starts_with( std::string const text, std::string const start )
{
return 0 == text.find( start );
}
/*
* "k" => 3
*/
int prefix_to_exponent( std::string const pfx )
{
for ( int i = 0; i < 2; ++i )
{
// skip prefixes[0][i][0], it matches everything
for( int k = 1; k < prefix_count; ++k )
{
if ( starts_with( pfx, prefixes[0][i][k] ) )
{
return ( i ? 1 : -1 ) * k * 3;
}
}
}
return 0;
}
} // anonymous namespace
/**
* convert real number to prefixed or exponential notation, optionally followed by a unit.
*/
std::string
to_engineering_string( double const value, int const digits, bool exponential, std::string const unit /*= ""*/, std::string separator /*= " "*/ )
{
if ( is_nan( value ) ) return "NaN";
else if ( is_inf( value ) ) return "INFINITE";
const int degree = degree_of( value );
std::string factor;
if ( abs( degree ) < prefix_count )
{
factor = prefix_or_exponent( exponential, degree, separator );
}
else
{
exponential = true;
factor = exponent( degree );
}
std::ostringstream os;
const double scaled = value * pow( 1000.0, -degree );
const std::string space = ( 0 == degree || exponential ) && unit.length() ? separator : "";
os << std::fixed << std::setprecision( precision( scaled, digits ) ) << scaled << factor << space << unit;
return os.str();
}
/**
* convert the output of to_engineering_string() into a double.
*
* The engineering presentation should not contain a unit, as the first letter
* is interpreted as an SI prefix, e.g. "1 T" is 1e12, not 1 (Tesla).
*
* "1.23 M" => 1.23e+6
* "1.23 kPa" => 1.23e+3 (ok, but not recommended)
* "1.23 Pa" => 1.23e+12 (not what's intended!)
*/
double from_engineering_string( std::string const text )
{
char * tail;
const double magnitude = strtod( text.c_str(), &tail );
return magnitude * pow( 10.0, prefix_to_exponent( first_non_space( tail ) ) );
}
/**
* step a value by the smallest possible increment.
*/
std::string step_engineering_string( std::string const text, int digits, bool const exponential, bool const positive )
{
const double value = from_engineering_string( text );
if ( digits < 3 )
{
digits = 3;
}
// correctly round to desired precision
const int expof10 = is_zero(value) ? 0 : lrint( floor( log10( value ) ) );
const int power = expof10 + 1 - digits;
const double inc = pow( 10.0, power ) * ( positive ? +1 : -1 );
const double ret = value + inc;
return to_engineering_string( ret, digits, exponential );
}
// end of file
<|endoftext|> |
<commit_before>#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-parameter"
#ifndef CALLBACK
# if defined(_ARM_)
# define CALLBACK
# else
# define CALLBACK __stdcall
# endif
#endif
#include <cstdint>
#include <cstdlib>
#include "SDL_gpu/SDL_gpu.h"
#include "misc/consts.h"
#include "misc/luaIncludes.h"
#include "riko.h"
#include "core/shader.h"
#include "gpu.h"
namespace riko::gfx {
bool shaderOn = false;
int pixelScale = DEFAULT_SCALE;
int setPixelScale = DEFAULT_SCALE;
GPU_Image *buffer;
GPU_Target *renderer;
GPU_Target *bufferTarget;
Uint8 palette[COLOR_LIMIT][3] = INIT_COLORS;
int paletteNum = 0;
int drawOffX = 0;
int drawOffY = 0;
int windowWidth;
int windowHeight;
int drawX = 0;
int drawY = 0;
int lastWindowX = 0;
int lastWindowY = 0;
void assessWindow() {
int winW = 0;
int winH = 0;
SDL_GetWindowSize(riko::window, &winW, &winH);
int candidateOne = winH / SCRN_HEIGHT;
int candidateTwo = winW / SCRN_WIDTH;
if (winW != 0 && winH != 0) {
pixelScale = (candidateOne > candidateTwo) ? candidateTwo : candidateOne;
windowWidth = winW;
windowHeight = winH;
drawX = (windowWidth - pixelScale*SCRN_WIDTH) / 2;
drawY = (windowHeight - pixelScale*SCRN_HEIGHT) / 2;
GPU_SetWindowResolution(winW, winH);
}
}
}
#define off(o, t) (float)((o) - riko::gfx::drawOffX), (float)((t) - riko::gfx::drawOffY)
namespace riko::gpu {
static int getColor(lua_State *L, int arg) {
int color = luaL_checkint(L, arg) - 1;
return color < 0 ? 0 : (color > (COLOR_LIMIT - 1) ? (COLOR_LIMIT - 1) : color);
}
static int gpu_draw_pixel(lua_State *L) {
int x = luaL_checkint(L, 1);
int y = luaL_checkint(L, 2);
int color = getColor(L, 3);
SDL_Color colorS = {riko::gfx::palette[color][0], riko::gfx::palette[color][1], riko::gfx::palette[color][2],
255};
GPU_RectangleFilled(riko::gfx::bufferTarget, off(x, y), off(x + 1, y + 1), colorS);
return 0;
}
static int gpu_draw_rectangle(lua_State *L) {
int color = getColor(L, 5);
int x = luaL_checkint(L, 1);
int y = luaL_checkint(L, 2);
GPU_Rect rect = {
off(x, y),
(float) luaL_checkint(L, 3),
(float) luaL_checkint(L, 4)
};
SDL_Color colorS = {riko::gfx::palette[color][0], riko::gfx::palette[color][1], riko::gfx::palette[color][2],
255};
GPU_RectangleFilled2(riko::gfx::bufferTarget, rect, colorS);
return 0;
}
static int gpu_blit_pixels(lua_State *L) {
int x = luaL_checkint(L, 1);
int y = luaL_checkint(L, 2);
int w = luaL_checkint(L, 3);
int h = luaL_checkint(L, 4);
unsigned long long amt = lua_objlen(L, -1);
int len = w * h;
if (amt < len) {
luaL_error(L, "blitPixels expected %d pixels, got %d", len, amt);
return 0;
}
for (int i = 1; i <= len; i++) {
lua_pushnumber(L, i);
lua_gettable(L, -2);
if (!lua_isnumber(L, -1)) {
luaL_error(L, "Index %d is non-numeric", i);
}
int color = (int) lua_tointeger(L, -1) - 1;
if (color == -1) {
lua_pop(L, 1);
continue;
}
color = color < 0 ? 0 : (color > (COLOR_LIMIT - 1) ? (COLOR_LIMIT - 1) : color);
int xp = (i - 1) % w;
int yp = (i - 1) / w;
GPU_Rect rect = {
off(x + xp,
y + yp),
1, 1
};
SDL_Color colorS = {riko::gfx::palette[color][0], riko::gfx::palette[color][1],
riko::gfx::palette[color][2], 255};
GPU_RectangleFilled2(riko::gfx::bufferTarget, rect, colorS);
lua_pop(L, 1);
}
return 0;
}
static int gpu_set_clipping(lua_State *L) {
if (lua_gettop(L) == 0) {
GPU_SetClip(riko::gfx::buffer->target, 0, 0, riko::gfx::buffer->w, riko::gfx::buffer->h);
return 0;
}
auto x = static_cast<Sint16>luaL_checkint(L, 1);
auto y = static_cast<Sint16>luaL_checkint(L, 2);
auto w = static_cast<Uint16>luaL_checkint(L, 3);
auto h = static_cast<Uint16>luaL_checkint(L, 4);
GPU_SetClip(riko::gfx::buffer->target, x, y, w, h);
return 0;
}
static int gpu_set_palette_color(lua_State *L) {
int slot = getColor(L, 1);
auto r = static_cast<Uint8>luaL_checkint(L, 2);
auto g = static_cast<Uint8>luaL_checkint(L, 3);
auto b = static_cast<Uint8>luaL_checkint(L, 4);
riko::gfx::palette[slot][0] = r;
riko::gfx::palette[slot][1] = g;
riko::gfx::palette[slot][2] = b;
riko::gfx::paletteNum++;
return 0;
}
static int gpu_blit_palette(lua_State *L) {
auto amt = (char) lua_objlen(L, -1);
if (amt < 1) {
return 0;
}
amt = static_cast<char>(amt > COLOR_LIMIT ? COLOR_LIMIT : amt);
for (int i = 1; i <= amt; i++) {
lua_pushnumber(L, i);
lua_gettable(L, -2);
if (lua_type(L, -1) == LUA_TNUMBER) {
lua_pop(L, 1);
continue;
}
lua_pushnumber(L, 1);
lua_gettable(L, -2);
riko::gfx::palette[i - 1][0] = static_cast<Uint8>luaL_checkint(L, -1);
lua_pushnumber(L, 2);
lua_gettable(L, -3);
riko::gfx::palette[i - 1][1] = static_cast<Uint8>luaL_checkint(L, -1);
lua_pushnumber(L, 3);
lua_gettable(L, -4);
riko::gfx::palette[i - 1][2] = static_cast<Uint8>luaL_checkint(L, -1);
lua_pop(L, 4);
}
riko::gfx::paletteNum++;
return 0;
}
static int gpu_get_palette(lua_State *L) {
lua_newtable(L);
for (int i = 0; i < COLOR_LIMIT; i++) {
lua_pushinteger(L, i + 1);
lua_newtable(L);
for (int j = 0; j < 3; j++) {
lua_pushinteger(L, j + 1);
lua_pushinteger(L, riko::gfx::palette[i][j]);
lua_rawset(L, -3);
}
lua_rawset(L, -3);
}
return 1;
}
static int gpu_get_pixel(lua_State *L) {
auto x = static_cast<Sint16>luaL_checkint(L, 1);
auto y = static_cast<Sint16>luaL_checkint(L, 2);
SDL_Color col = GPU_GetPixel(riko::gfx::buffer->target, x, y);
for (int i = 0; i < COLOR_LIMIT; i++) {
Uint8 *pCol = riko::gfx::palette[i];
if (col.r == pCol[0] && col.g == pCol[1] && col.b == pCol[2]) {
lua_pushinteger(L, i + 1);
return 1;
}
}
lua_pushinteger(L, 1); // Should never happen
return 1;
}
static int gpu_clear(lua_State *L) {
if (lua_gettop(L) > 0) {
int color = getColor(L, 1);
SDL_Color colorS = {riko::gfx::palette[color][0], riko::gfx::palette[color][1],
riko::gfx::palette[color][2], 255};
GPU_ClearColor(riko::gfx::bufferTarget, colorS);
} else {
SDL_Color colorS = {riko::gfx::palette[0][0], riko::gfx::palette[0][1], riko::gfx::palette[0][2], 255};
GPU_ClearColor(riko::gfx::bufferTarget, colorS);
}
return 0;
}
int *translateStack;
int tStackUsed = 0;
int tStackSize = 32;
static int gpu_translate(lua_State *L) {
riko::gfx::drawOffX -= luaL_checkint(L, -2);
riko::gfx::drawOffY -= luaL_checkint(L, -1);
return 0;
}
static int gpu_push(lua_State *L) {
if (tStackUsed == tStackSize) {
tStackSize *= 2;
translateStack = (int *) realloc(translateStack, tStackSize * sizeof(int));
}
translateStack[tStackUsed] = riko::gfx::drawOffX;
translateStack[tStackUsed + 1] = riko::gfx::drawOffY;
tStackUsed += 2;
return 0;
}
static int gpu_pop(lua_State *L) {
if (tStackUsed > 0) {
tStackUsed -= 2;
riko::gfx::drawOffX = translateStack[tStackUsed];
riko::gfx::drawOffY = translateStack[tStackUsed + 1];
lua_pushboolean(L, true);
lua_pushinteger(L, tStackUsed / 2);
return 2;
} else {
lua_pushboolean(L, false);
return 1;
}
}
static int gpu_set_fullscreen(lua_State *L) {
auto fsc = static_cast<bool>(lua_toboolean(L, 1));
if (!GPU_SetFullscreen(fsc, true)) {
riko::gfx::pixelScale = riko::gfx::setPixelScale;
GPU_SetWindowResolution(
riko::gfx::pixelScale * SCRN_WIDTH,
riko::gfx::pixelScale * SCRN_HEIGHT);
SDL_SetWindowPosition(riko::window, riko::gfx::lastWindowX, riko::gfx::lastWindowY);
}
riko::gfx::assessWindow();
return 0;
}
static int gpu_swap(lua_State *L) {
SDL_Color colorS = {riko::gfx::palette[0][0], riko::gfx::palette[0][1], riko::gfx::palette[0][2], 255};
GPU_ClearColor(riko::gfx::renderer, colorS);
riko::shader::updateShader();
GPU_BlitScale(riko::gfx::buffer, nullptr, riko::gfx::renderer,
riko::gfx::windowWidth / 2, riko::gfx::windowHeight / 2,
riko::gfx::pixelScale, riko::gfx::pixelScale);
GPU_Flip(riko::gfx::renderer);
GPU_DeactivateShaderProgram();
return 0;
}
static const luaL_Reg gpuLib[] = {
{"setPaletteColor", gpu_set_palette_color},
{"blitPalette", gpu_blit_palette},
{"getPalette", gpu_get_palette},
{"drawPixel", gpu_draw_pixel},
{"drawRectangle", gpu_draw_rectangle},
{"blitPixels", gpu_blit_pixels},
{"translate", gpu_translate},
{"push", gpu_push},
{"pop", gpu_pop},
{"setFullscreen", gpu_set_fullscreen},
{"getPixel", gpu_get_pixel},
{"clear", gpu_clear},
{"swap", gpu_swap},
{"clip", gpu_set_clipping},
{nullptr, nullptr}
};
LUALIB_API int openLua(lua_State *L) {
translateStack = new int[32];
luaL_openlib(L, RIKO_GPU_NAME, gpuLib, 0);
lua_pushnumber(L, SCRN_WIDTH);
lua_setfield(L, -2, "width");
lua_pushnumber(L, SCRN_HEIGHT);
lua_setfield(L, -2, "height");
return 1;
}
}
#pragma clang diagnostic pop
<commit_msg>Fix setPaletteColor<commit_after>#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-parameter"
#ifndef CALLBACK
# if defined(_ARM_)
# define CALLBACK
# else
# define CALLBACK __stdcall
# endif
#endif
#include <cstdint>
#include <cstdlib>
#include "SDL_gpu/SDL_gpu.h"
#include "misc/consts.h"
#include "misc/luaIncludes.h"
#include "riko.h"
#include "core/shader.h"
#include "gpu.h"
namespace riko::gfx {
bool shaderOn = false;
int pixelScale = DEFAULT_SCALE;
int setPixelScale = DEFAULT_SCALE;
GPU_Image *buffer;
GPU_Target *renderer;
GPU_Target *bufferTarget;
Uint8 palette[COLOR_LIMIT][3] = INIT_COLORS;
int paletteNum = 0;
int drawOffX = 0;
int drawOffY = 0;
int windowWidth;
int windowHeight;
int drawX = 0;
int drawY = 0;
int lastWindowX = 0;
int lastWindowY = 0;
void assessWindow() {
int winW = 0;
int winH = 0;
SDL_GetWindowSize(riko::window, &winW, &winH);
int candidateOne = winH / SCRN_HEIGHT;
int candidateTwo = winW / SCRN_WIDTH;
if (winW != 0 && winH != 0) {
pixelScale = (candidateOne > candidateTwo) ? candidateTwo : candidateOne;
windowWidth = winW;
windowHeight = winH;
drawX = (windowWidth - pixelScale*SCRN_WIDTH) / 2;
drawY = (windowHeight - pixelScale*SCRN_HEIGHT) / 2;
GPU_SetWindowResolution(winW, winH);
}
}
}
#define off(o, t) (float)((o) - riko::gfx::drawOffX), (float)((t) - riko::gfx::drawOffY)
namespace riko::gpu {
static int getColor(lua_State *L, int arg) {
int color = luaL_checkint(L, arg) - 1;
return color < 0 ? 0 : (color > (COLOR_LIMIT - 1) ? (COLOR_LIMIT - 1) : color);
}
static int gpu_draw_pixel(lua_State *L) {
int x = luaL_checkint(L, 1);
int y = luaL_checkint(L, 2);
int color = getColor(L, 3);
SDL_Color colorS = {riko::gfx::palette[color][0], riko::gfx::palette[color][1], riko::gfx::palette[color][2],
255};
GPU_RectangleFilled(riko::gfx::bufferTarget, off(x, y), off(x + 1, y + 1), colorS);
return 0;
}
static int gpu_draw_rectangle(lua_State *L) {
int color = getColor(L, 5);
int x = luaL_checkint(L, 1);
int y = luaL_checkint(L, 2);
GPU_Rect rect = {
off(x, y),
(float) luaL_checkint(L, 3),
(float) luaL_checkint(L, 4)
};
SDL_Color colorS = {riko::gfx::palette[color][0], riko::gfx::palette[color][1], riko::gfx::palette[color][2],
255};
GPU_RectangleFilled2(riko::gfx::bufferTarget, rect, colorS);
return 0;
}
static int gpu_blit_pixels(lua_State *L) {
int x = luaL_checkint(L, 1);
int y = luaL_checkint(L, 2);
int w = luaL_checkint(L, 3);
int h = luaL_checkint(L, 4);
unsigned long long amt = lua_objlen(L, -1);
int len = w * h;
if (amt < len) {
luaL_error(L, "blitPixels expected %d pixels, got %d", len, amt);
return 0;
}
for (int i = 1; i <= len; i++) {
lua_pushnumber(L, i);
lua_gettable(L, -2);
if (!lua_isnumber(L, -1)) {
luaL_error(L, "Index %d is non-numeric", i);
}
int color = (int) lua_tointeger(L, -1) - 1;
if (color == -1) {
lua_pop(L, 1);
continue;
}
color = color < 0 ? 0 : (color > (COLOR_LIMIT - 1) ? (COLOR_LIMIT - 1) : color);
int xp = (i - 1) % w;
int yp = (i - 1) / w;
GPU_Rect rect = {
off(x + xp,
y + yp),
1, 1
};
SDL_Color colorS = {riko::gfx::palette[color][0], riko::gfx::palette[color][1],
riko::gfx::palette[color][2], 255};
GPU_RectangleFilled2(riko::gfx::bufferTarget, rect, colorS);
lua_pop(L, 1);
}
return 0;
}
static int gpu_set_clipping(lua_State *L) {
if (lua_gettop(L) == 0) {
GPU_SetClip(riko::gfx::buffer->target, 0, 0, riko::gfx::buffer->w, riko::gfx::buffer->h);
return 0;
}
auto x = static_cast<Sint16>luaL_checkint(L, 1);
auto y = static_cast<Sint16>luaL_checkint(L, 2);
auto w = static_cast<Uint16>luaL_checkint(L, 3);
auto h = static_cast<Uint16>luaL_checkint(L, 4);
GPU_SetClip(riko::gfx::buffer->target, x, y, w, h);
return 0;
}
static int gpu_set_palette_color(lua_State *L) {
int slot = getColor(L, 1) - 1;
if (slot < 0 || slot >= COLOR_LIMIT) return 0;
auto r = static_cast<Uint8>luaL_checkint(L, 2);
auto g = static_cast<Uint8>luaL_checkint(L, 3);
auto b = static_cast<Uint8>luaL_checkint(L, 4);
riko::gfx::palette[slot][0] = r;
riko::gfx::palette[slot][1] = g;
riko::gfx::palette[slot][2] = b;
riko::gfx::paletteNum++;
return 0;
}
static int gpu_blit_palette(lua_State *L) {
auto amt = (char) lua_objlen(L, -1);
if (amt < 1) {
return 0;
}
amt = static_cast<char>(amt > COLOR_LIMIT ? COLOR_LIMIT : amt);
for (int i = 1; i <= amt; i++) {
lua_pushnumber(L, i);
lua_gettable(L, -2);
if (lua_type(L, -1) == LUA_TNUMBER) {
lua_pop(L, 1);
continue;
}
lua_pushnumber(L, 1);
lua_gettable(L, -2);
riko::gfx::palette[i - 1][0] = static_cast<Uint8>luaL_checkint(L, -1);
lua_pushnumber(L, 2);
lua_gettable(L, -3);
riko::gfx::palette[i - 1][1] = static_cast<Uint8>luaL_checkint(L, -1);
lua_pushnumber(L, 3);
lua_gettable(L, -4);
riko::gfx::palette[i - 1][2] = static_cast<Uint8>luaL_checkint(L, -1);
lua_pop(L, 4);
}
riko::gfx::paletteNum++;
return 0;
}
static int gpu_get_palette(lua_State *L) {
lua_newtable(L);
for (int i = 0; i < COLOR_LIMIT; i++) {
lua_pushinteger(L, i + 1);
lua_newtable(L);
for (int j = 0; j < 3; j++) {
lua_pushinteger(L, j + 1);
lua_pushinteger(L, riko::gfx::palette[i][j]);
lua_rawset(L, -3);
}
lua_rawset(L, -3);
}
return 1;
}
static int gpu_get_pixel(lua_State *L) {
auto x = static_cast<Sint16>luaL_checkint(L, 1);
auto y = static_cast<Sint16>luaL_checkint(L, 2);
SDL_Color col = GPU_GetPixel(riko::gfx::buffer->target, x, y);
for (int i = 0; i < COLOR_LIMIT; i++) {
Uint8 *pCol = riko::gfx::palette[i];
if (col.r == pCol[0] && col.g == pCol[1] && col.b == pCol[2]) {
lua_pushinteger(L, i + 1);
return 1;
}
}
lua_pushinteger(L, 1); // Should never happen
return 1;
}
static int gpu_clear(lua_State *L) {
if (lua_gettop(L) > 0) {
int color = getColor(L, 1);
SDL_Color colorS = {riko::gfx::palette[color][0], riko::gfx::palette[color][1],
riko::gfx::palette[color][2], 255};
GPU_ClearColor(riko::gfx::bufferTarget, colorS);
} else {
SDL_Color colorS = {riko::gfx::palette[0][0], riko::gfx::palette[0][1], riko::gfx::palette[0][2], 255};
GPU_ClearColor(riko::gfx::bufferTarget, colorS);
}
return 0;
}
int *translateStack;
int tStackUsed = 0;
int tStackSize = 32;
static int gpu_translate(lua_State *L) {
riko::gfx::drawOffX -= luaL_checkint(L, -2);
riko::gfx::drawOffY -= luaL_checkint(L, -1);
return 0;
}
static int gpu_push(lua_State *L) {
if (tStackUsed == tStackSize) {
tStackSize *= 2;
translateStack = (int *) realloc(translateStack, tStackSize * sizeof(int));
}
translateStack[tStackUsed] = riko::gfx::drawOffX;
translateStack[tStackUsed + 1] = riko::gfx::drawOffY;
tStackUsed += 2;
return 0;
}
static int gpu_pop(lua_State *L) {
if (tStackUsed > 0) {
tStackUsed -= 2;
riko::gfx::drawOffX = translateStack[tStackUsed];
riko::gfx::drawOffY = translateStack[tStackUsed + 1];
lua_pushboolean(L, true);
lua_pushinteger(L, tStackUsed / 2);
return 2;
} else {
lua_pushboolean(L, false);
return 1;
}
}
static int gpu_set_fullscreen(lua_State *L) {
auto fsc = static_cast<bool>(lua_toboolean(L, 1));
if (!GPU_SetFullscreen(fsc, true)) {
riko::gfx::pixelScale = riko::gfx::setPixelScale;
GPU_SetWindowResolution(
riko::gfx::pixelScale * SCRN_WIDTH,
riko::gfx::pixelScale * SCRN_HEIGHT);
SDL_SetWindowPosition(riko::window, riko::gfx::lastWindowX, riko::gfx::lastWindowY);
}
riko::gfx::assessWindow();
return 0;
}
static int gpu_swap(lua_State *L) {
SDL_Color colorS = {riko::gfx::palette[0][0], riko::gfx::palette[0][1], riko::gfx::palette[0][2], 255};
GPU_ClearColor(riko::gfx::renderer, colorS);
riko::shader::updateShader();
GPU_BlitScale(riko::gfx::buffer, nullptr, riko::gfx::renderer,
riko::gfx::windowWidth / 2, riko::gfx::windowHeight / 2,
riko::gfx::pixelScale, riko::gfx::pixelScale);
GPU_Flip(riko::gfx::renderer);
GPU_DeactivateShaderProgram();
return 0;
}
static const luaL_Reg gpuLib[] = {
{"setPaletteColor", gpu_set_palette_color},
{"blitPalette", gpu_blit_palette},
{"getPalette", gpu_get_palette},
{"drawPixel", gpu_draw_pixel},
{"drawRectangle", gpu_draw_rectangle},
{"blitPixels", gpu_blit_pixels},
{"translate", gpu_translate},
{"push", gpu_push},
{"pop", gpu_pop},
{"setFullscreen", gpu_set_fullscreen},
{"getPixel", gpu_get_pixel},
{"clear", gpu_clear},
{"swap", gpu_swap},
{"clip", gpu_set_clipping},
{nullptr, nullptr}
};
LUALIB_API int openLua(lua_State *L) {
translateStack = new int[32];
luaL_openlib(L, RIKO_GPU_NAME, gpuLib, 0);
lua_pushnumber(L, SCRN_WIDTH);
lua_setfield(L, -2, "width");
lua_pushnumber(L, SCRN_HEIGHT);
lua_setfield(L, -2, "height");
return 1;
}
}
#pragma clang diagnostic pop
<|endoftext|> |
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
//
// File contains modifications by: The Gulden developers
// All modifications:
// Copyright (c) 2016-2018 The Gulden developers
// Authored by: Malcolm MacLeod ([email protected])
// Distributed under the GULDEN software license, see the accompanying
// file COPYING
#include "wallet/wallet.h"
#include "wallet/wallettx.h"
#include "validation/validation.h"
#include "net.h"
#include "scheduler.h"
#include "timedata.h"
#include "utilmoneystr.h"
#include "init.h"
#include <unity/appmanager.h>
#include <script/ismine.h>
isminetype CWallet::IsMine(const CTxIn &txin) const
{
{
LOCK(cs_wallet);
std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.getHash());
if (mi != mapWallet.end())
{
const CWalletTx& prev = (*mi).second;
if (txin.prevout.n < prev.tx->vout.size())
return IsMine(prev.tx->vout[txin.prevout.n]);
}
}
return ISMINE_NO;
}
isminetype CWallet::IsMine(const CTxOut& txout) const
{
return ::IsMine(*this, txout);
}
bool CWallet::IsMine(const CTransaction& tx) const
{
for(const CTxOut& txout : tx.vout)
if (IsMine(txout) && txout.nValue >= nMinimumInputValue)
return true;
return false;
}
bool CWallet::IsFromMe(const CTransaction& tx) const
{
return (GetDebit(tx, ISMINE_ALL) > 0);
}
bool CWallet::IsAllFromMe(const CTransaction& tx, const isminefilter& filter) const
{
LOCK(cs_wallet);
for(const CTxIn& txin : tx.vin)
{
auto mi = mapWallet.find(txin.prevout.getHash());
if (mi == mapWallet.end())
return false; // any unknown inputs can't be from us
const CWalletTx& prev = (*mi).second;
if (txin.prevout.n >= prev.tx->vout.size())
return false; // invalid input!
if (!(IsMine(prev.tx->vout[txin.prevout.n]) & filter))
return false;
}
return true;
}
int CWallet::GetTransactionScanProgressPercent()
{
return nTransactionScanProgressPercent;
}
/**
* Scan active chain for relevant transactions after importing keys. This should
* be called whenever new keys are added to the wallet, with the oldest key
* creation time.
*
* @return Earliest timestamp that could be successfully scanned from. Timestamp
* returned will be higher than startTime if relevant blocks could not be read.
*/
int64_t CWallet::RescanFromTime(int64_t startTime, bool update)
{
// Find starting block. May be null if nCreateTime is greater than the
// highest blockchain timestamp, in which case there is nothing that needs
// to be scanned.
CBlockIndex* startBlock = nullptr;
{
LOCK(cs_main);
startBlock = chainActive.FindEarliestAtLeast(startTime - TIMESTAMP_WINDOW);
LogPrintf("%s: Rescanning last %i blocks\n", __func__, startBlock ? chainActive.Height() - startBlock->nHeight + 1 : 0);
}
if (startBlock)
{
const CBlockIndex* const failedBlock = ScanForWalletTransactions(startBlock, update);
if (failedBlock)
{
return failedBlock->GetBlockTimeMax() + TIMESTAMP_WINDOW + 1;
}
}
return startTime;
}
/**
* Scan the block chain (starting in pindexStart) for transactions
* from or to us. If fUpdate is true, found transactions that already
* exist in the wallet will be updated.
*
* Returns null if scan was successful. Otherwise, if a complete rescan was not
* possible (due to pruning or corruption), returns pointer to the most recent
* block that could not be scanned.
*/
CBlockIndex* CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
{
int64_t nNow = GetTime();
const CChainParams& chainParams = Params();
CBlockIndex* pindex = pindexStart;
CBlockIndex* ret = nullptr;
{
LOCK2(cs_main, cs_wallet); // Required for ReadBlockFromDisk.
fAbortRescan = false;
fScanningWallet = true;
// no need to read and scan block, if block was created before
// our wallet birthday (as adjusted for block time variability)
// NB! nTimeFirstKey > TIMESTAMP_WINDOW check is important otherwise we overflow nTimeFirstKey
while (pindex && (nTimeFirstKey > TIMESTAMP_WINDOW) && (pindex->GetBlockTime() < (int64_t)(nTimeFirstKey - TIMESTAMP_WINDOW)))
pindex = chainActive.Next(pindex);
nTransactionScanProgressPercent = 0;
ShowProgress(_("Rescanning..."), nTransactionScanProgressPercent); // show rescan progress in GUI, if -rescan on startup
LogPrintf("Rescanning...\n");
uint64_t nProgressStart = pindex->nHeight;
uint64_t nProgressTip = chainActive.Tip()->nHeight;
uint64_t nWorkQuantity = nProgressTip - nProgressStart;
while (pindex && !fAbortRescan && nWorkQuantity > 0)
{
// Temporarily release lock to allow shadow key allocation a chance to do it's thing
LEAVE_CRITICAL_SECTION(cs_main)
LEAVE_CRITICAL_SECTION(cs_wallet)
nTransactionScanProgressPercent = ((pindex->nHeight-nProgressStart) / (nWorkQuantity)) * 100;
nTransactionScanProgressPercent = std::max(1, std::min(99, nTransactionScanProgressPercent));
if (pindex->nHeight % 100 == 0 && nProgressTip - nProgressStart > 0.0)
{
ShowProgress(_("Rescanning..."), nTransactionScanProgressPercent);
}
if (GetTime() >= nNow + 60) {
nNow = GetTime();
LogPrintf("Still rescanning. At block %d. Progress=%d%%\n", pindex->nHeight, nTransactionScanProgressPercent);
}
ENTER_CRITICAL_SECTION(cs_main)
ENTER_CRITICAL_SECTION(cs_wallet)
if (ShutdownRequested())
return ret;
CBlock block;
if (ReadBlockFromDisk(block, pindex, Params())) {
for (size_t posInBlock = 0; posInBlock < block.vtx.size(); ++posInBlock) {
AddToWalletIfInvolvingMe(block.vtx[posInBlock], pindex, posInBlock, fUpdate);
}
} else {
ret = pindex;
}
pindex = chainActive.Next(pindex);
}
if (pindex && fAbortRescan) {
LogPrintf("Rescan aborted at block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
}
nTransactionScanProgressPercent = 100;
ShowProgress(_("Rescanning..."), nTransactionScanProgressPercent); // hide progress dialog in GUI
fScanningWallet = false;
}
LogPrintf("Rescan done.\n");
return ret;
}
<commit_msg>Fix a bug with wallet rescan progress display.<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
//
// File contains modifications by: The Gulden developers
// All modifications:
// Copyright (c) 2016-2018 The Gulden developers
// Authored by: Malcolm MacLeod ([email protected])
// Distributed under the GULDEN software license, see the accompanying
// file COPYING
#include "wallet/wallet.h"
#include "wallet/wallettx.h"
#include "validation/validation.h"
#include "net.h"
#include "scheduler.h"
#include "timedata.h"
#include "utilmoneystr.h"
#include "init.h"
#include <unity/appmanager.h>
#include <script/ismine.h>
isminetype CWallet::IsMine(const CTxIn &txin) const
{
{
LOCK(cs_wallet);
std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.getHash());
if (mi != mapWallet.end())
{
const CWalletTx& prev = (*mi).second;
if (txin.prevout.n < prev.tx->vout.size())
return IsMine(prev.tx->vout[txin.prevout.n]);
}
}
return ISMINE_NO;
}
isminetype CWallet::IsMine(const CTxOut& txout) const
{
return ::IsMine(*this, txout);
}
bool CWallet::IsMine(const CTransaction& tx) const
{
for(const CTxOut& txout : tx.vout)
if (IsMine(txout) && txout.nValue >= nMinimumInputValue)
return true;
return false;
}
bool CWallet::IsFromMe(const CTransaction& tx) const
{
return (GetDebit(tx, ISMINE_ALL) > 0);
}
bool CWallet::IsAllFromMe(const CTransaction& tx, const isminefilter& filter) const
{
LOCK(cs_wallet);
for(const CTxIn& txin : tx.vin)
{
auto mi = mapWallet.find(txin.prevout.getHash());
if (mi == mapWallet.end())
return false; // any unknown inputs can't be from us
const CWalletTx& prev = (*mi).second;
if (txin.prevout.n >= prev.tx->vout.size())
return false; // invalid input!
if (!(IsMine(prev.tx->vout[txin.prevout.n]) & filter))
return false;
}
return true;
}
int CWallet::GetTransactionScanProgressPercent()
{
return nTransactionScanProgressPercent;
}
/**
* Scan active chain for relevant transactions after importing keys. This should
* be called whenever new keys are added to the wallet, with the oldest key
* creation time.
*
* @return Earliest timestamp that could be successfully scanned from. Timestamp
* returned will be higher than startTime if relevant blocks could not be read.
*/
int64_t CWallet::RescanFromTime(int64_t startTime, bool update)
{
// Find starting block. May be null if nCreateTime is greater than the
// highest blockchain timestamp, in which case there is nothing that needs
// to be scanned.
CBlockIndex* startBlock = nullptr;
{
LOCK(cs_main);
startBlock = chainActive.FindEarliestAtLeast(startTime - TIMESTAMP_WINDOW);
LogPrintf("%s: Rescanning last %i blocks\n", __func__, startBlock ? chainActive.Height() - startBlock->nHeight + 1 : 0);
}
if (startBlock)
{
const CBlockIndex* const failedBlock = ScanForWalletTransactions(startBlock, update);
if (failedBlock)
{
return failedBlock->GetBlockTimeMax() + TIMESTAMP_WINDOW + 1;
}
}
return startTime;
}
/**
* Scan the block chain (starting in pindexStart) for transactions
* from or to us. If fUpdate is true, found transactions that already
* exist in the wallet will be updated.
*
* Returns null if scan was successful. Otherwise, if a complete rescan was not
* possible (due to pruning or corruption), returns pointer to the most recent
* block that could not be scanned.
*/
CBlockIndex* CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
{
int64_t nNow = GetTime();
const CChainParams& chainParams = Params();
CBlockIndex* pindex = pindexStart;
CBlockIndex* ret = nullptr;
{
LOCK2(cs_main, cs_wallet); // Required for ReadBlockFromDisk.
fAbortRescan = false;
fScanningWallet = true;
// no need to read and scan block, if block was created before
// our wallet birthday (as adjusted for block time variability)
// NB! nTimeFirstKey > TIMESTAMP_WINDOW check is important otherwise we overflow nTimeFirstKey
while (pindex && (nTimeFirstKey > TIMESTAMP_WINDOW) && (pindex->GetBlockTime() < (int64_t)(nTimeFirstKey - TIMESTAMP_WINDOW)))
pindex = chainActive.Next(pindex);
nTransactionScanProgressPercent = 0;
ShowProgress(_("Rescanning..."), nTransactionScanProgressPercent); // show rescan progress in GUI, if -rescan on startup
LogPrintf("Rescanning...\n");
uint64_t nProgressStart = pindex->nHeight;
uint64_t nProgressTip = chainActive.Tip()->nHeight;
uint64_t nWorkQuantity = nProgressTip - nProgressStart;
while (pindex && !fAbortRescan && nWorkQuantity > 0)
{
// Temporarily release lock to allow shadow key allocation a chance to do it's thing
LEAVE_CRITICAL_SECTION(cs_main)
LEAVE_CRITICAL_SECTION(cs_wallet)
nTransactionScanProgressPercent = ((pindex->nHeight-nProgressStart) / (double)(nWorkQuantity)) * 100;
nTransactionScanProgressPercent = std::max(1, std::min(99, nTransactionScanProgressPercent));
if (pindex->nHeight % 100 == 0 && nProgressTip - nProgressStart > 0)
{
ShowProgress(_("Rescanning..."), nTransactionScanProgressPercent);
}
if (GetTime() >= nNow + 60) {
nNow = GetTime();
LogPrintf("Still rescanning. At block %d. Progress=%d%%\n", pindex->nHeight, nTransactionScanProgressPercent);
}
ENTER_CRITICAL_SECTION(cs_main)
ENTER_CRITICAL_SECTION(cs_wallet)
if (ShutdownRequested())
return ret;
CBlock block;
if (ReadBlockFromDisk(block, pindex, Params())) {
for (size_t posInBlock = 0; posInBlock < block.vtx.size(); ++posInBlock) {
AddToWalletIfInvolvingMe(block.vtx[posInBlock], pindex, posInBlock, fUpdate);
}
} else {
ret = pindex;
}
pindex = chainActive.Next(pindex);
}
if (pindex && fAbortRescan) {
LogPrintf("Rescan aborted at block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
}
nTransactionScanProgressPercent = 100;
ShowProgress(_("Rescanning..."), nTransactionScanProgressPercent); // hide progress dialog in GUI
fScanningWallet = false;
}
LogPrintf("Rescan done.\n");
return ret;
}
<|endoftext|> |
<commit_before>/* Copyright 2009 SPARTA, Inc., dba Cobham Analytic Solutions
*
* This file is part of WATCHER.
*
* WATCHER 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.
*
* WATCHER is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Watcher. If not, see <http://www.gnu.org/licenses/>.
*/
#include "replayState.h"
#include <deque>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include "libwatcher/message.h"
#include "serverConnection.h"
#include "Assert.h"
#include "database.h"
#include "watcherd.h"
using namespace util;
using namespace watcher;
using namespace watcher::event;
//< default value for number of events to prefetch from the database
const unsigned int DEFAULT_BUFFER_SIZE = 20U; /* db rows */
const unsigned int DEFAULT_STEP = 250U /* ms */;
/** Internal structure used for implementing the class. Used to avoid
* dependencies for the user of the class. These would normally be private
* members of ReplayState.
*/
struct ReplayState::impl {
boost::weak_ptr<ServerConnection> conn;
std::deque<MessagePtr> events;
boost::asio::deadline_timer timer;
Timestamp ts; // the current effective time
Timestamp last_event; // timestamp of last event retrieved from db
float speed; //< playback speed
unsigned int bufsiz; //< number of database rows to prefetch
Timestamp step;
enum run_state { paused, running } state;
timeval wall_time; //< used to correct for clock skew
Timestamp delta;
/*
* Lock used for event queue. This is required due to the seek() member
* function, which can be called from a different thread.
*/
boost::mutex lock;
impl(ServerConnectionPtr& ptr) :
conn(ptr), timer(ptr->io_service()), ts(0), last_event(0), bufsiz(DEFAULT_BUFFER_SIZE),
step(DEFAULT_STEP), state(paused), delta(0)
{
TRACE_ENTER();
wall_time.tv_sec = 0;
wall_time.tv_usec = 0;
TRACE_EXIT();
}
};
ReplayState::ReplayState(ServerConnectionPtr ptr, Timestamp t, float playback_speed) :
impl_(new impl(ptr))
{
TRACE_ENTER();
Assert<Bad_arg>(t >= 0);
impl_->ts = t;
impl_->last_event = t;
speed(playback_speed);
TRACE_EXIT();
}
Timestamp ReplayState::tell() const
{
TRACE_ENTER();
TRACE_EXIT_RET(impl_->ts);
return impl_->ts;
}
ReplayState& ReplayState::pause()
{
TRACE_ENTER();
LOG_DEBUG("cancelling timer");
impl_->timer.cancel();
impl_->state = impl::paused;
TRACE_EXIT();
return *this;
}
ReplayState& ReplayState::seek(Timestamp t)
{
TRACE_ENTER();
impl::run_state oldstate;
{
boost::mutex::scoped_lock L(impl_->lock);
oldstate = impl_->state;
pause();
impl_->events.clear();
impl_->ts = t;
if (t == -1)
impl_->last_event = std::numeric_limits<Timestamp>::max();
else
impl_->last_event = t;
}
if (oldstate == impl::running)
run();
TRACE_EXIT();
return *this;
}
ReplayState& ReplayState::speed(float f)
{
TRACE_ENTER();
Assert<Bad_arg>(f != 0);
/* If speed changes direction, need to clear the event list.
* Check for sign change by noting that positive*negative==negative
*/
if (impl_->speed * f < 0) {
impl::run_state oldstate;
{
boost::mutex::scoped_lock L(impl_->lock);
oldstate = impl_->state;
pause();
impl_->events.clear();
/*
* Avoid setting .last_event when SpeedMessage is received
* prior to the first StartMessage.
*/
if (impl_->ts != 0 && impl_->ts != -1)
impl_->last_event = impl_->ts;
impl_->speed = f;
}
if (oldstate == impl::running)
run();
} else
impl_->speed = f;
LOG_DEBUG("ts=" << impl_->ts << " last_event=" << impl_->last_event);
TRACE_EXIT();
return *this;
}
ReplayState& ReplayState::buffer_size(unsigned int n)
{
TRACE_ENTER();
Assert<Bad_arg>(n != 0);
impl_->bufsiz = n;
TRACE_EXIT();
return *this;
}
ReplayState& ReplayState::time_step(unsigned int n)
{
TRACE_ENTER();
Assert<Bad_arg>(n != 0);
impl_->step = n;
TRACE_EXIT();
return *this;
}
namespace {
/* function object for accepting events output from Database::getEvents() */
struct event_output {
std::deque<MessagePtr>& q;
event_output(std::deque<MessagePtr>& qq) : q(qq) {}
void operator() (MessagePtr m) { q.push_back(m); }
};
}
/** Schedule an asynchronous task to replay events from the database to a GUI
* client. If the local cache of upcoming events is empty, prefetch a block of
* events from the database.
*
* The code is written such that it will work when playing events forward or in
* reverse.
*/
void ReplayState::run()
{
TRACE_ENTER();
boost::mutex::scoped_lock L(impl_->lock);
if (impl_->events.empty()) {
// queue is empty, pre-fetch more items from the DB
boost::function<void(MessagePtr)> cb(event_output(impl_->events));
LOG_DEBUG("fetching events " << (impl_->speed > 0 ? "> " : "< ") << impl_->last_event);
get_db_handle().getEvents(cb,
impl_->last_event,
(impl_->speed >= 0) ? Database::forward : Database::reverse,
impl_->bufsiz);
if (!impl_->events.empty()) {
LOG_DEBUG("got " << impl_->events.size() << " events from the db query");
/* When starting to replay, assume that time T=0 is the time of the
* first event in the stream.
* T= -1 is EOF.
* Convert to timestamp of first item in the returned events.
*
* When playing in reverse, the first item in the list is the last event in the database.
*/
if (impl_->ts == 0 || impl_->ts == -1)
impl_->ts = impl_->events.front()->timestamp;
// save timestamp of last event retrieved to avoid duplication
impl_->last_event = impl_->events.back()->timestamp;
}
}
if (! impl_->events.empty()) {
/*
* Calculate for the skew introduced by the time required to process the events. Skew is calculated
* as the difference between the actual time taken and the expected time. This gets
* subtracted from the wait for the next event to catch up.
*/
timeval tv;
gettimeofday(&tv, 0);
Timestamp skew = (tv.tv_sec - impl_->wall_time.tv_sec) * 1000 + (tv.tv_usec - impl_->wall_time.tv_usec) / 1000;
skew -= impl_->delta;
LOG_DEBUG("calculated skew of " << skew << " ms");
memcpy(&impl_->wall_time, &tv, sizeof(tv));
// time until next event
impl_->delta = impl_->events.front()->timestamp - impl_->ts;
// update our notion of the current time after the timer expires
impl_->ts = impl_->events.front()->timestamp;
/* Adjust for playback speed. Note that when playing events in reverse, both speed
* delta will be negative, which will turn delta into a positive value for the
* async_wait() call, which is exactly what is required. */
impl_->delta = (Timestamp)(impl_->delta/impl_->speed);
/* Correct for skew */
impl_->delta -= skew;
if (impl_->delta < 0)
impl_->delta = 0;
LOG_DEBUG("Next event in " << impl_->delta << " ms");
impl_->timer.expires_from_now(boost::posix_time::millisec(impl_->delta));
impl_->timer.async_wait(boost::bind(&ReplayState::timer_handler, shared_from_this(), boost::asio::placeholders::error));
impl_->state = impl::running;
} else {
/*
* FIXME what should happen when the end of the event stream is reached?
* One option would be to convert to live stream at this point.
*/
LOG_DEBUG("reached end of database, pausing playback");
impl_->state = impl::paused;
}
TRACE_EXIT();
}
/** Replay events to a GUI client when a timer expires.
*
* The run() member function is reponsible for prefetching events from the
* database and storing them in the class object. When a timer expires, run
* through the locally stored events and send those that occurred within the
* last time slice. The task is then rescheduled when the next most recent
* event needs to be transmitted.
*/
void ReplayState::timer_handler(const boost::system::error_code& ec)
{
TRACE_ENTER();
if (ec == boost::asio::error::operation_aborted)
LOG_DEBUG("timer was cancelled");
else if (impl_->state == impl::paused) {
LOG_DEBUG("timer expired but state is paused!");
} else {
std::vector<MessagePtr> msgs;
{
boost::mutex::scoped_lock L(impl_->lock);
while (! impl_->events.empty()) {
MessagePtr m = impl_->events.front();
/* Replay all events in the current time step. Use the absolute value
* of the difference in order for forward and reverse replay to work
* properly. */
if (abs(m->timestamp - impl_->ts) >= impl_->step)
break;
msgs.push_back(m);
impl_->events.pop_front();
}
}
ServerConnectionPtr srv = impl_->conn.lock();
if (srv) { /* connection is still alive */
srv->sendMessage(msgs);
run(); // reschedule this task
}
}
TRACE_EXIT();
}
/* This is required to be defined, otherwise a the default dtor will cause a
* compiler error due to use of scoped_ptr with an incomplete type.
*/
ReplayState::~ReplayState()
{
TRACE_ENTER();
TRACE_EXIT();
}
float ReplayState::speed() const
{
return impl_->speed;
}
<commit_msg>Don't let clock skew be negative, log values of skew and delta<commit_after>/* Copyright 2009 SPARTA, Inc., dba Cobham Analytic Solutions
*
* This file is part of WATCHER.
*
* WATCHER 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.
*
* WATCHER is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Watcher. If not, see <http://www.gnu.org/licenses/>.
*/
#include "replayState.h"
#include <deque>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include "libwatcher/message.h"
#include "serverConnection.h"
#include "Assert.h"
#include "database.h"
#include "watcherd.h"
using namespace util;
using namespace watcher;
using namespace watcher::event;
//< default value for number of events to prefetch from the database
const unsigned int DEFAULT_BUFFER_SIZE = 20U; /* db rows */
const unsigned int DEFAULT_STEP = 250U /* ms */;
/** Internal structure used for implementing the class. Used to avoid
* dependencies for the user of the class. These would normally be private
* members of ReplayState.
*/
struct ReplayState::impl {
boost::weak_ptr<ServerConnection> conn;
std::deque<MessagePtr> events;
boost::asio::deadline_timer timer;
Timestamp ts; // the current effective time
Timestamp last_event; // timestamp of last event retrieved from db
float speed; //< playback speed
unsigned int bufsiz; //< number of database rows to prefetch
Timestamp step;
enum run_state { paused, running } state;
timeval wall_time; //< used to correct for clock skew
Timestamp delta;
/*
* Lock used for event queue. This is required due to the seek() member
* function, which can be called from a different thread.
*/
boost::mutex lock;
impl(ServerConnectionPtr& ptr) :
conn(ptr), timer(ptr->io_service()), ts(0), last_event(0), bufsiz(DEFAULT_BUFFER_SIZE),
step(DEFAULT_STEP), state(paused), delta(0)
{
TRACE_ENTER();
wall_time.tv_sec = 0;
wall_time.tv_usec = 0;
TRACE_EXIT();
}
};
ReplayState::ReplayState(ServerConnectionPtr ptr, Timestamp t, float playback_speed) :
impl_(new impl(ptr))
{
TRACE_ENTER();
Assert<Bad_arg>(t >= 0);
impl_->ts = t;
impl_->last_event = t;
speed(playback_speed);
TRACE_EXIT();
}
Timestamp ReplayState::tell() const
{
TRACE_ENTER();
TRACE_EXIT_RET(impl_->ts);
return impl_->ts;
}
ReplayState& ReplayState::pause()
{
TRACE_ENTER();
LOG_DEBUG("cancelling timer");
impl_->timer.cancel();
impl_->state = impl::paused;
TRACE_EXIT();
return *this;
}
ReplayState& ReplayState::seek(Timestamp t)
{
TRACE_ENTER();
impl::run_state oldstate;
{
boost::mutex::scoped_lock L(impl_->lock);
oldstate = impl_->state;
pause();
impl_->events.clear();
impl_->ts = t;
if (t == -1)
impl_->last_event = std::numeric_limits<Timestamp>::max();
else
impl_->last_event = t;
}
if (oldstate == impl::running)
run();
TRACE_EXIT();
return *this;
}
ReplayState& ReplayState::speed(float f)
{
TRACE_ENTER();
Assert<Bad_arg>(f != 0);
/* If speed changes direction, need to clear the event list.
* Check for sign change by noting that positive*negative==negative
*/
if (impl_->speed * f < 0) {
impl::run_state oldstate;
{
boost::mutex::scoped_lock L(impl_->lock);
oldstate = impl_->state;
pause();
impl_->events.clear();
/*
* Avoid setting .last_event when SpeedMessage is received
* prior to the first StartMessage.
*/
if (impl_->ts != 0 && impl_->ts != -1)
impl_->last_event = impl_->ts;
impl_->speed = f;
}
if (oldstate == impl::running)
run();
} else
impl_->speed = f;
LOG_DEBUG("ts=" << impl_->ts << " last_event=" << impl_->last_event);
TRACE_EXIT();
return *this;
}
ReplayState& ReplayState::buffer_size(unsigned int n)
{
TRACE_ENTER();
Assert<Bad_arg>(n != 0);
impl_->bufsiz = n;
TRACE_EXIT();
return *this;
}
ReplayState& ReplayState::time_step(unsigned int n)
{
TRACE_ENTER();
Assert<Bad_arg>(n != 0);
impl_->step = n;
TRACE_EXIT();
return *this;
}
namespace {
/* function object for accepting events output from Database::getEvents() */
struct event_output {
std::deque<MessagePtr>& q;
event_output(std::deque<MessagePtr>& qq) : q(qq) {}
void operator() (MessagePtr m) { q.push_back(m); }
};
}
/** Schedule an asynchronous task to replay events from the database to a GUI
* client. If the local cache of upcoming events is empty, prefetch a block of
* events from the database.
*
* The code is written such that it will work when playing events forward or in
* reverse.
*/
void ReplayState::run()
{
TRACE_ENTER();
boost::mutex::scoped_lock L(impl_->lock);
if (impl_->events.empty()) {
// queue is empty, pre-fetch more items from the DB
boost::function<void(MessagePtr)> cb(event_output(impl_->events));
LOG_DEBUG("fetching events " << (impl_->speed > 0 ? "> " : "< ") << impl_->last_event);
get_db_handle().getEvents(cb,
impl_->last_event,
(impl_->speed >= 0) ? Database::forward : Database::reverse,
impl_->bufsiz);
if (!impl_->events.empty()) {
LOG_DEBUG("got " << impl_->events.size() << " events from the db query");
/* When starting to replay, assume that time T=0 is the time of the
* first event in the stream.
* T= -1 is EOF.
* Convert to timestamp of first item in the returned events.
*
* When playing in reverse, the first item in the list is the last event in the database.
*/
if (impl_->ts == 0 || impl_->ts == -1)
impl_->ts = impl_->events.front()->timestamp;
// save timestamp of last event retrieved to avoid duplication
impl_->last_event = impl_->events.back()->timestamp;
}
}
if (! impl_->events.empty()) {
/*
* Calculate for the skew introduced by the time required to process the events. Skew is calculated
* as the difference between the actual time taken and the expected time. This gets
* subtracted from the wait for the next event to catch up.
*/
timeval tv;
gettimeofday(&tv, 0);
Timestamp skew = (tv.tv_sec - impl_->wall_time.tv_sec) * 1000 + (tv.tv_usec - impl_->wall_time.tv_usec) / 1000;
LOG_DEBUG("skew=" << skew << " delta=" << impl_->delta);
skew -= impl_->delta;
LOG_DEBUG("calculated skew of " << skew << " ms");
if (skew < 0) {
LOG_DEBUG("something strange happened, skew < delta ??");
skew = 0;
}
memcpy(&impl_->wall_time, &tv, sizeof(tv));
// time until next event
impl_->delta = impl_->events.front()->timestamp - impl_->ts;
// update our notion of the current time after the timer expires
impl_->ts = impl_->events.front()->timestamp;
/* Adjust for playback speed. Note that when playing events in reverse, both speed
* delta will be negative, which will turn delta into a positive value for the
* async_wait() call, which is exactly what is required. */
impl_->delta = (Timestamp)(impl_->delta/impl_->speed);
/* Correct for skew */
impl_->delta -= skew;
if (impl_->delta < 0)
impl_->delta = 0;
LOG_DEBUG("Next event in " << impl_->delta << " ms");
impl_->timer.expires_from_now(boost::posix_time::millisec(impl_->delta));
impl_->timer.async_wait(boost::bind(&ReplayState::timer_handler, shared_from_this(), boost::asio::placeholders::error));
impl_->state = impl::running;
} else {
/*
* FIXME what should happen when the end of the event stream is reached?
* One option would be to convert to live stream at this point.
*/
LOG_DEBUG("reached end of database, pausing playback");
impl_->state = impl::paused;
}
TRACE_EXIT();
}
/** Replay events to a GUI client when a timer expires.
*
* The run() member function is reponsible for prefetching events from the
* database and storing them in the class object. When a timer expires, run
* through the locally stored events and send those that occurred within the
* last time slice. The task is then rescheduled when the next most recent
* event needs to be transmitted.
*/
void ReplayState::timer_handler(const boost::system::error_code& ec)
{
TRACE_ENTER();
if (ec == boost::asio::error::operation_aborted)
LOG_DEBUG("timer was cancelled");
else if (impl_->state == impl::paused) {
LOG_DEBUG("timer expired but state is paused!");
} else {
std::vector<MessagePtr> msgs;
{
boost::mutex::scoped_lock L(impl_->lock);
while (! impl_->events.empty()) {
MessagePtr m = impl_->events.front();
/* Replay all events in the current time step. Use the absolute value
* of the difference in order for forward and reverse replay to work
* properly. */
if (abs(m->timestamp - impl_->ts) >= impl_->step)
break;
msgs.push_back(m);
impl_->events.pop_front();
}
}
ServerConnectionPtr srv = impl_->conn.lock();
if (srv) { /* connection is still alive */
srv->sendMessage(msgs);
run(); // reschedule this task
}
}
TRACE_EXIT();
}
/* This is required to be defined, otherwise a the default dtor will cause a
* compiler error due to use of scoped_ptr with an incomplete type.
*/
ReplayState::~ReplayState()
{
TRACE_ENTER();
TRACE_EXIT();
}
float ReplayState::speed() const
{
return impl_->speed;
}
<|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010-2011, Willow Garage, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id: $
*
*/
#ifndef PCL_SEARCH_IMPL_FLANN_SEARCH_H_
#define PCL_SEARCH_IMPL_FLANN_SEARCH_H_
#include "pcl/search/flann_search.h"
#include <flann/flann.hpp>
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename FlannDistance>
typename pcl::search::FlannSearch<PointT, FlannDistance>::IndexPtr
pcl::search::FlannSearch<PointT, FlannDistance>::KdTreeIndexCreator::createIndex (MatrixConstPtr data)
{
return (IndexPtr (new flann::KDTreeSingleIndex<FlannDistance> (*data,flann::KDTreeSingleIndexParams (max_leaf_size_))));
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename FlannDistance>
pcl::search::FlannSearch<PointT, FlannDistance>::FlannSearch(bool sorted, FlannIndexCreator *creator) : pcl::search::Search<PointT> ("FlannSearch",sorted),
creator_ (creator), eps_ (0), input_copied_for_flann_ (false)
{
point_representation_.reset (new DefaultPointRepresentation<PointT>);
dim_ = point_representation_->getNumberOfDimensions ();
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename FlannDistance>
pcl::search::FlannSearch<PointT, FlannDistance>::~FlannSearch()
{
delete creator_;
if (input_copied_for_flann_)
delete [] input_flann_->ptr();
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename FlannDistance> void
pcl::search::FlannSearch<PointT, FlannDistance>::setInputCloud (const PointCloudConstPtr& cloud, const IndicesConstPtr& indices)
{
input_ = cloud;
indices_ = indices;
convertInputToFlannMatrix ();
index_ = creator_->createIndex (input_flann_);
index_->buildIndex ();
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename FlannDistance> int
pcl::search::FlannSearch<PointT, FlannDistance>::nearestKSearch (const PointT &point, int k, std::vector<int> &indices, std::vector<float> &dists) const
{
bool can_cast = point_representation_->isTrivial ();
float* data = 0;
if (!can_cast)
{
data = new float [point_representation_->getNumberOfDimensions ()];
point_representation_->vectorize (point,data);
}
float* cdata = can_cast ? const_cast<float*> (reinterpret_cast<const float*> (&point)): data;
const flann::Matrix<float> m (cdata ,1, point_representation_->getNumberOfDimensions ());
flann::SearchParams p(-1);
p.eps = eps_;
p.sorted = sorted_results_;
if (indices.size() != (unsigned int) k)
indices.resize (k,-1);
if (dists.size() != (unsigned int) k)
dists.resize (k);
flann::Matrix<int> i (&indices[0],1,k);
flann::Matrix<float> d (&dists[0],1,k);
int result = index_->knnSearch (m,i,d,k, p);
delete [] data;
if (!identity_mapping_)
{
for (size_t i = 0; i < (size_t)k; ++i)
{
int& neighbor_index = indices[i];
neighbor_index = index_mapping_[neighbor_index];
}
}
return result;
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename FlannDistance> void
pcl::search::FlannSearch<PointT, FlannDistance>::nearestKSearch (
const PointCloud& cloud, const std::vector<int>& indices, int k, std::vector< std::vector<int> >& k_indices,
std::vector< std::vector<float> >& k_sqr_distances) const
{
if (indices.empty ())
{
k_indices.resize (cloud.size ());
k_sqr_distances.resize (cloud.size ());
bool can_cast = point_representation_->isTrivial ();
// full point cloud + trivial copy operation = no need to do any conversion/copying to the flann matrix!
float* data=0;
if (!can_cast)
{
data = new float[dim_*cloud.size ()];
for (size_t i = 0; i < cloud.size (); ++i)
{
float* out = data+i*dim_;
point_representation_->vectorize (cloud[i],out);
}
}
// const cast is evil, but the matrix constructor won't change the data, and the
// search won't change the matrix
float* cdata = can_cast ? const_cast<float*> (reinterpret_cast<const float*> (&cloud[0])): data;
const flann::Matrix<float> m (cdata ,cloud.size (), dim_, can_cast ? sizeof (PointT) : dim_ * sizeof (float) );
flann::SearchParams p;
p.sorted = sorted_results_;
p.eps = eps_;
index_->knnSearch (m,k_indices,k_sqr_distances,k, p);
delete [] data;
}
else // if indices are present, the cloud has to be copied anyway. Only copy the relevant parts of the points here.
{
k_indices.resize (indices.size ());
k_sqr_distances.resize (indices.size ());
float* data=new float [dim_*indices.size ()];
for (size_t i = 0; i < indices.size (); ++i)
{
float* out = data+i*dim_;
point_representation_->vectorize (cloud[indices[i]],out);
}
const flann::Matrix<float> m (data ,indices.size (), point_representation_->getNumberOfDimensions ());
flann::SearchParams p;
p.sorted = sorted_results_;
p.eps = eps_;
index_->knnSearch (m,k_indices,k_sqr_distances,k, p);
delete[] data;
}
if (!identity_mapping_)
{
for (size_t j = 0; j < k_indices.size (); ++j)
{
for (size_t i = 0; i < (size_t)k; ++i)
{
int& neighbor_index = k_indices[j][i];
neighbor_index = index_mapping_[neighbor_index];
}
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename FlannDistance> int
pcl::search::FlannSearch<PointT, FlannDistance>::radiusSearch (const PointT& point, double radius,
std::vector<int> &indices, std::vector<float> &distances,
unsigned int max_nn) const
{
bool can_cast = point_representation_->isTrivial ();
float* data = 0;
if (!can_cast)
{
data = new float [point_representation_->getNumberOfDimensions ()];
point_representation_->vectorize (point,data);
}
float* cdata = can_cast ? const_cast<float*> (reinterpret_cast<const float*> (&point)) : data;
const flann::Matrix<float> m (cdata ,1, point_representation_->getNumberOfDimensions ());
flann::SearchParams p;
p.sorted = sorted_results_;
p.eps = eps_;
p.max_neighbors = max_nn > 0 ? max_nn : -1;
std::vector<std::vector<int> > i (1);
std::vector<std::vector<float> > d (1);
int result = index_->radiusSearch (m,i,d,radius*radius, p);
delete [] data;
indices = i [0];
distances = d [0];
if (!identity_mapping_)
{
for (size_t i = 0; i < indices.size (); ++i)
{
int& neighbor_index = indices [i];
neighbor_index = index_mapping_ [neighbor_index];
}
}
return result;
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename FlannDistance> void
pcl::search::FlannSearch<PointT, FlannDistance>::radiusSearch (
const PointCloud& cloud, const std::vector<int>& indices, double radius, std::vector< std::vector<int> >& k_indices,
std::vector< std::vector<float> >& k_sqr_distances, unsigned int max_nn) const
{
if (indices.empty ()) // full point cloud + trivial copy operation = no need to do any conversion/copying to the flann matrix!
{
k_indices.resize (cloud.size ());
k_sqr_distances.resize (cloud.size ());
bool can_cast = point_representation_->isTrivial ();
float* data = 0;
if (!can_cast)
{
data = new float[dim_*cloud.size ()];
for (size_t i = 0; i < cloud.size (); ++i)
{
float* out = data+i*dim_;
point_representation_->vectorize (cloud[i],out);
}
}
float* cdata = can_cast ? const_cast<float*> (reinterpret_cast<const float*> (&cloud[0])) : data;
const flann::Matrix<float> m (cdata ,cloud.size (), dim_, can_cast ? sizeof (PointT) : dim_ * sizeof (float));
flann::SearchParams p;
p.sorted = sorted_results_;
p.eps = eps_;
// here: max_nn==0: take all neighbors. flann: max_nn==0: return no neighbors, only count them. max_nn==-1: return all neighbors
p.max_neighbors = max_nn > 0 ? max_nn : -1;
index_->radiusSearch (m,k_indices,k_sqr_distances,radius*radius, p);
delete [] data;
}
else // if indices are present, the cloud has to be copied anyway. Only copy the relevant parts of the points here.
{
k_indices.resize (indices.size ());
k_sqr_distances.resize (indices.size ());
float* data = new float [dim_ * indices.size ()];
for (size_t i = 0; i < indices.size (); ++i)
{
float* out = data+i*dim_;
point_representation_->vectorize (cloud[indices[i]], out);
}
const flann::Matrix<float> m (data, cloud.size (), point_representation_->getNumberOfDimensions ());
flann::SearchParams p;
p.sorted = sorted_results_;
p.eps = eps_;
// here: max_nn==0: take all neighbors. flann: max_nn==0: return no neighbors, only count them. max_nn==-1: return all neighbors
p.max_neighbors = max_nn > 0 ? max_nn : -1;
index_->radiusSearch (m, k_indices, k_sqr_distances, radius * radius, p);
delete[] data;
}
if (!identity_mapping_)
{
for (size_t j = 0; j < k_indices.size (); ++j )
{
for (size_t i = 0; i < k_indices[j].size (); ++i)
{
int& neighbor_index = k_indices[j][i];
neighbor_index = index_mapping_[neighbor_index];
}
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename FlannDistance> void
pcl::search::FlannSearch<PointT, FlannDistance>::convertInputToFlannMatrix ()
{
int original_no_of_points = indices_ && !indices_->empty () ? indices_->size () : input_->size ();
if (input_copied_for_flann_)
delete input_flann_->ptr();
input_copied_for_flann_ = true;
index_mapping_.clear();
identity_mapping_ = true;
//cloud_ = (float*)malloc (original_no_of_points * dim_ * sizeof (float));
//index_mapping_.reserve(original_no_of_points);
//identity_mapping_ = true;
if (!indices_ || indices_->empty ())
{
// best case: all points can be passed to flann without any conversions
if (input_->is_dense && point_representation_->isTrivial ())
{
// const cast is evil, but flann won't change the data
input_flann_ = MatrixPtr (new flann::Matrix<float> (const_cast<float*>(reinterpret_cast<const float*>(&(*input_) [0])), original_no_of_points, point_representation_->getNumberOfDimensions (),sizeof (PointT)));
input_copied_for_flann_ = false;
}
else
{
input_flann_ = MatrixPtr (new flann::Matrix<float> (new float[original_no_of_points*point_representation_->getNumberOfDimensions ()], original_no_of_points, point_representation_->getNumberOfDimensions ()));
float* cloud_ptr = input_flann_->ptr();
for (int i = 0; i < original_no_of_points; ++i)
{
const PointT& point = (*input_)[i];
// Check if the point is invalid
if (!point_representation_->isValid (point))
{
identity_mapping_ = false;
continue;
}
index_mapping_.push_back (i); // If the returned index should be for the indices vector
point_representation_->vectorize (point, cloud_ptr);
cloud_ptr += dim_;
}
}
}
else
{
input_flann_ = MatrixPtr (new flann::Matrix<float> (new float[original_no_of_points*point_representation_->getNumberOfDimensions ()], original_no_of_points, point_representation_->getNumberOfDimensions ()));
float* cloud_ptr = input_flann_->ptr();
for (int indices_index = 0; indices_index < original_no_of_points; ++indices_index)
{
int cloud_index = (*indices_)[indices_index];
const PointT& point = (*input_)[cloud_index];
// Check if the point is invalid
if (!point_representation_->isValid (point))
{
identity_mapping_ = false;
continue;
}
index_mapping_.push_back (indices_index); // If the returned index should be for the indices vector
point_representation_->vectorize (point, cloud_ptr);
cloud_ptr += dim_;
}
}
if (input_copied_for_flann_)
input_flann_->rows = index_mapping_.size ();
}
#define PCL_INSTANTIATE_FlannSearch(T) template class PCL_EXPORTS pcl::search::FlannSearch<T>;
#endif
<commit_msg>FlannSearch: fixed warnings<commit_after>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010-2011, Willow Garage, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id: $
*
*/
#ifndef PCL_SEARCH_IMPL_FLANN_SEARCH_H_
#define PCL_SEARCH_IMPL_FLANN_SEARCH_H_
#include "pcl/search/flann_search.h"
#include <flann/flann.hpp>
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename FlannDistance>
typename pcl::search::FlannSearch<PointT, FlannDistance>::IndexPtr
pcl::search::FlannSearch<PointT, FlannDistance>::KdTreeIndexCreator::createIndex (MatrixConstPtr data)
{
return (IndexPtr (new flann::KDTreeSingleIndex<FlannDistance> (*data,flann::KDTreeSingleIndexParams (max_leaf_size_))));
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename FlannDistance>
pcl::search::FlannSearch<PointT, FlannDistance>::FlannSearch(bool sorted, FlannIndexCreator *creator) : pcl::search::Search<PointT> ("FlannSearch",sorted),
creator_ (creator), eps_ (0), input_copied_for_flann_ (false)
{
point_representation_.reset (new DefaultPointRepresentation<PointT>);
dim_ = point_representation_->getNumberOfDimensions ();
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename FlannDistance>
pcl::search::FlannSearch<PointT, FlannDistance>::~FlannSearch()
{
delete creator_;
if (input_copied_for_flann_)
delete [] input_flann_->ptr();
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename FlannDistance> void
pcl::search::FlannSearch<PointT, FlannDistance>::setInputCloud (const PointCloudConstPtr& cloud, const IndicesConstPtr& indices)
{
input_ = cloud;
indices_ = indices;
convertInputToFlannMatrix ();
index_ = creator_->createIndex (input_flann_);
index_->buildIndex ();
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename FlannDistance> int
pcl::search::FlannSearch<PointT, FlannDistance>::nearestKSearch (const PointT &point, int k, std::vector<int> &indices, std::vector<float> &dists) const
{
bool can_cast = point_representation_->isTrivial ();
float* data = 0;
if (!can_cast)
{
data = new float [point_representation_->getNumberOfDimensions ()];
point_representation_->vectorize (point,data);
}
float* cdata = can_cast ? const_cast<float*> (reinterpret_cast<const float*> (&point)): data;
const flann::Matrix<float> m (cdata ,1, point_representation_->getNumberOfDimensions ());
flann::SearchParams p(-1);
p.eps = eps_;
p.sorted = sorted_results_;
if (indices.size() != static_cast<unsigned int> (k))
indices.resize (k,-1);
if (dists.size() != static_cast<unsigned int> (k))
dists.resize (k);
flann::Matrix<int> i (&indices[0],1,k);
flann::Matrix<float> d (&dists[0],1,k);
int result = index_->knnSearch (m,i,d,k, p);
delete [] data;
if (!identity_mapping_)
{
for (size_t i = 0; i < static_cast<unsigned int> (k); ++i)
{
int& neighbor_index = indices[i];
neighbor_index = index_mapping_[neighbor_index];
}
}
return result;
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename FlannDistance> void
pcl::search::FlannSearch<PointT, FlannDistance>::nearestKSearch (
const PointCloud& cloud, const std::vector<int>& indices, int k, std::vector< std::vector<int> >& k_indices,
std::vector< std::vector<float> >& k_sqr_distances) const
{
if (indices.empty ())
{
k_indices.resize (cloud.size ());
k_sqr_distances.resize (cloud.size ());
bool can_cast = point_representation_->isTrivial ();
// full point cloud + trivial copy operation = no need to do any conversion/copying to the flann matrix!
float* data=0;
if (!can_cast)
{
data = new float[dim_*cloud.size ()];
for (size_t i = 0; i < cloud.size (); ++i)
{
float* out = data+i*dim_;
point_representation_->vectorize (cloud[i],out);
}
}
// const cast is evil, but the matrix constructor won't change the data, and the
// search won't change the matrix
float* cdata = can_cast ? const_cast<float*> (reinterpret_cast<const float*> (&cloud[0])): data;
const flann::Matrix<float> m (cdata ,cloud.size (), dim_, can_cast ? sizeof (PointT) : dim_ * sizeof (float) );
flann::SearchParams p;
p.sorted = sorted_results_;
p.eps = eps_;
index_->knnSearch (m,k_indices,k_sqr_distances,k, p);
delete [] data;
}
else // if indices are present, the cloud has to be copied anyway. Only copy the relevant parts of the points here.
{
k_indices.resize (indices.size ());
k_sqr_distances.resize (indices.size ());
float* data=new float [dim_*indices.size ()];
for (size_t i = 0; i < indices.size (); ++i)
{
float* out = data+i*dim_;
point_representation_->vectorize (cloud[indices[i]],out);
}
const flann::Matrix<float> m (data ,indices.size (), point_representation_->getNumberOfDimensions ());
flann::SearchParams p;
p.sorted = sorted_results_;
p.eps = eps_;
index_->knnSearch (m,k_indices,k_sqr_distances,k, p);
delete[] data;
}
if (!identity_mapping_)
{
for (size_t j = 0; j < k_indices.size (); ++j)
{
for (size_t i = 0; i < static_cast<unsigned int> (k); ++i)
{
int& neighbor_index = k_indices[j][i];
neighbor_index = index_mapping_[neighbor_index];
}
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename FlannDistance> int
pcl::search::FlannSearch<PointT, FlannDistance>::radiusSearch (const PointT& point, double radius,
std::vector<int> &indices, std::vector<float> &distances,
unsigned int max_nn) const
{
bool can_cast = point_representation_->isTrivial ();
float* data = 0;
if (!can_cast)
{
data = new float [point_representation_->getNumberOfDimensions ()];
point_representation_->vectorize (point,data);
}
float* cdata = can_cast ? const_cast<float*> (reinterpret_cast<const float*> (&point)) : data;
const flann::Matrix<float> m (cdata ,1, point_representation_->getNumberOfDimensions ());
flann::SearchParams p;
p.sorted = sorted_results_;
p.eps = eps_;
p.max_neighbors = max_nn > 0 ? max_nn : -1;
std::vector<std::vector<int> > i (1);
std::vector<std::vector<float> > d (1);
int result = index_->radiusSearch (m,i,d,static_cast<float> (radius * radius), p);
delete [] data;
indices = i [0];
distances = d [0];
if (!identity_mapping_)
{
for (size_t i = 0; i < indices.size (); ++i)
{
int& neighbor_index = indices [i];
neighbor_index = index_mapping_ [neighbor_index];
}
}
return result;
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename FlannDistance> void
pcl::search::FlannSearch<PointT, FlannDistance>::radiusSearch (
const PointCloud& cloud, const std::vector<int>& indices, double radius, std::vector< std::vector<int> >& k_indices,
std::vector< std::vector<float> >& k_sqr_distances, unsigned int max_nn) const
{
if (indices.empty ()) // full point cloud + trivial copy operation = no need to do any conversion/copying to the flann matrix!
{
k_indices.resize (cloud.size ());
k_sqr_distances.resize (cloud.size ());
bool can_cast = point_representation_->isTrivial ();
float* data = 0;
if (!can_cast)
{
data = new float[dim_*cloud.size ()];
for (size_t i = 0; i < cloud.size (); ++i)
{
float* out = data+i*dim_;
point_representation_->vectorize (cloud[i],out);
}
}
float* cdata = can_cast ? const_cast<float*> (reinterpret_cast<const float*> (&cloud[0])) : data;
const flann::Matrix<float> m (cdata ,cloud.size (), dim_, can_cast ? sizeof (PointT) : dim_ * sizeof (float));
flann::SearchParams p;
p.sorted = sorted_results_;
p.eps = eps_;
// here: max_nn==0: take all neighbors. flann: max_nn==0: return no neighbors, only count them. max_nn==-1: return all neighbors
p.max_neighbors = max_nn > 0 ? max_nn : -1;
index_->radiusSearch (m,k_indices,k_sqr_distances,static_cast<float> (radius * radius), p);
delete [] data;
}
else // if indices are present, the cloud has to be copied anyway. Only copy the relevant parts of the points here.
{
k_indices.resize (indices.size ());
k_sqr_distances.resize (indices.size ());
float* data = new float [dim_ * indices.size ()];
for (size_t i = 0; i < indices.size (); ++i)
{
float* out = data+i*dim_;
point_representation_->vectorize (cloud[indices[i]], out);
}
const flann::Matrix<float> m (data, cloud.size (), point_representation_->getNumberOfDimensions ());
flann::SearchParams p;
p.sorted = sorted_results_;
p.eps = eps_;
// here: max_nn==0: take all neighbors. flann: max_nn==0: return no neighbors, only count them. max_nn==-1: return all neighbors
p.max_neighbors = max_nn > 0 ? max_nn : -1;
index_->radiusSearch (m, k_indices, k_sqr_distances, static_cast<float> (radius * radius), p);
delete[] data;
}
if (!identity_mapping_)
{
for (size_t j = 0; j < k_indices.size (); ++j )
{
for (size_t i = 0; i < k_indices[j].size (); ++i)
{
int& neighbor_index = k_indices[j][i];
neighbor_index = index_mapping_[neighbor_index];
}
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename FlannDistance> void
pcl::search::FlannSearch<PointT, FlannDistance>::convertInputToFlannMatrix ()
{
size_t original_no_of_points = indices_ && !indices_->empty () ? indices_->size () : input_->size ();
if (input_copied_for_flann_)
delete input_flann_->ptr();
input_copied_for_flann_ = true;
index_mapping_.clear();
identity_mapping_ = true;
//cloud_ = (float*)malloc (original_no_of_points * dim_ * sizeof (float));
//index_mapping_.reserve(original_no_of_points);
//identity_mapping_ = true;
if (!indices_ || indices_->empty ())
{
// best case: all points can be passed to flann without any conversions
if (input_->is_dense && point_representation_->isTrivial ())
{
// const cast is evil, but flann won't change the data
input_flann_ = MatrixPtr (new flann::Matrix<float> (const_cast<float*>(reinterpret_cast<const float*>(&(*input_) [0])), original_no_of_points, point_representation_->getNumberOfDimensions (),sizeof (PointT)));
input_copied_for_flann_ = false;
}
else
{
input_flann_ = MatrixPtr (new flann::Matrix<float> (new float[original_no_of_points*point_representation_->getNumberOfDimensions ()], original_no_of_points, point_representation_->getNumberOfDimensions ()));
float* cloud_ptr = input_flann_->ptr();
for (size_t i = 0; i < original_no_of_points; ++i)
{
const PointT& point = (*input_)[i];
// Check if the point is invalid
if (!point_representation_->isValid (point))
{
identity_mapping_ = false;
continue;
}
index_mapping_.push_back (static_cast<int> (i)); // If the returned index should be for the indices vector
point_representation_->vectorize (point, cloud_ptr);
cloud_ptr += dim_;
}
}
}
else
{
input_flann_ = MatrixPtr (new flann::Matrix<float> (new float[original_no_of_points*point_representation_->getNumberOfDimensions ()], original_no_of_points, point_representation_->getNumberOfDimensions ()));
float* cloud_ptr = input_flann_->ptr();
for (size_t indices_index = 0; indices_index < original_no_of_points; ++indices_index)
{
int cloud_index = (*indices_)[indices_index];
const PointT& point = (*input_)[cloud_index];
// Check if the point is invalid
if (!point_representation_->isValid (point))
{
identity_mapping_ = false;
continue;
}
index_mapping_.push_back (static_cast<int> (indices_index)); // If the returned index should be for the indices vector
point_representation_->vectorize (point, cloud_ptr);
cloud_ptr += dim_;
}
}
if (input_copied_for_flann_)
input_flann_->rows = index_mapping_.size ();
}
#define PCL_INSTANTIATE_FlannSearch(T) template class PCL_EXPORTS pcl::search::FlannSearch<T>;
#endif
<|endoftext|> |
<commit_before>#pragma once
/*
* Author(s):
* - Chris Kilner <[email protected]>
* - Cedric Gestes <[email protected]>
*
* Copyright (C) 2010 Aldebaran Robotics
*/
#ifndef _QI_SERIALIZATION_SERIALIZE_HXX_
#define _QI_SERIALIZATION_SERIALIZE_HXX_
#if 0
#define __QI_DEBUG_SERIALIZATION_W(x, extra) { \
std::string sig = qi::signature< x >::value(); \
std::cout << "write(" << sig << ")" << extra << std::endl; \
}
#define __QI_DEBUG_SERIALIZATION_R(x, extra) { \
std::string sig = qi::signature< x >::value(); \
std::cout << "read (" << sig << ")" << extra << std::endl; \
}
#define __QI_DEBUG_SERIALIZATION_CONTAINER_W(x, c) { \
std::string sig = qi::signature< x >::value(); \
std::cout << "write(" << sig << ") size: " << c.size() << std::endl; \
}
#define __QI_DEBUG_SERIALIZATION_CONTAINER_R(x, c) { \
std::string sig = qi::signature< x >::value(); \
std::cout << "read (" << sig << ") size: " << c.size() << std::endl; \
}
#else
# define __QI_DEBUG_SERIALIZATION_W(x, extra)
# define __QI_DEBUG_SERIALIZATION_R(x, extra)
# define __QI_DEBUG_SERIALIZATION_CONTAINER_W(x, c)
# define __QI_DEBUG_SERIALIZATION_CONTAINER_R(x, c)
#endif
#ifdef WITH_PROTOBUF
# include <google/protobuf/message.h>
#endif
#include <qi/serialization/serializable.hpp>
#include <iostream>
namespace qi {
namespace serialization {
//Inline this function => they do nothing, they just call Message method
//we keep vector/map not inlined at the moment because they take space.
#define QI_SIMPLE_SERIALIZER(Name, Type) \
template <> \
struct serialize<Type> { \
static inline void write(Message &sd, const Type &val) { \
sd.write##Name(val); \
} \
static inline void read(Message &sd, Type &val) { \
sd.read##Name(val); \
} \
};
QI_SIMPLE_SERIALIZER(Bool, bool);
QI_SIMPLE_SERIALIZER(Char, char);
QI_SIMPLE_SERIALIZER(Int, int);
QI_SIMPLE_SERIALIZER(Float, float);
QI_SIMPLE_SERIALIZER(String, std::string);
template <typename T>
struct serialize<T&> {
static inline void write(Message &sd, const T &val) {
__QI_DEBUG_SERIALIZATION_W(T, "&");
serialize<T>::write(sd, val);
}
static inline void read(Message &sd, T &val) {
__QI_DEBUG_SERIALIZATION_R(T, "&");
serialize<T>::read(sd, val);
}
};
template <typename T>
struct serialize<const T> {
static inline void write(Message &sd, const T &val) {
__QI_DEBUG_SERIALIZATION_W(T, "Const");
serialize<T>::write(sd, val);
}
static inline void read(Message &sd, T &val) {
__QI_DEBUG_SERIALIZATION_R(T, "Const");
serialize<T>::read(sd, val);
}
};
#ifdef WITH_PROTOBUF
template <typename T>
struct serialize<T, typename boost::enable_if< typename boost::is_base_of<google::protobuf::Message , T>::type >::type > {
static void write(Message &sd, const T &val) {
__QI_DEBUG_SERIALIZATION_W(T, "Proto");
std::string ser;
val.SerializeToString(&ser);
sd.writeString(ser);
}
static void read(Message &sd, T &val) {
__QI_DEBUG_SERIALIZATION_R(T, "Proto");
std::string ser;
sd.readString(ser);
val.ParseFromString(ser);
}
};
#endif
template <typename T>
struct serialize<T, typename boost::enable_if< typename boost::is_base_of<qi::serialization::Serializable , T>::type >::type > {
static void write(Message &sd, T &val) {
//__QI_DEBUG_SERIALIZATION_W(T, "Serializable");
//std::cout << "Serialize, Serializable" << std::end;
Serializer s(ACTION_SERIALIZE, sd);
val.serialize(s);
}
static void read(Message &sd, T &val) {
Serializer s(ACTION_DESERIALIZE, sd);
val.serialize(s);
//__QI_DEBUG_SERIALIZATION_R(T, "Serializable");
//std::cout << "DeSerialize, Serializable" << std::end;
}
};
template<typename U>
struct serialize< std::vector<U> > {
static void write(Message &sd, const std::vector<U> &v) {
sd.writeInt(v.size());
if (v.size()) {
// we should find out if the contents is a fixed size type
// and directly assign the contents if we can
typename std::vector<U>::const_iterator it = v.begin();
typename std::vector<U>::const_iterator end = v.end();
for (; it != end; ++it) {
serialize<U>::write(sd, *it);
}
}
__QI_DEBUG_SERIALIZATION_CONTAINER_W(std::vector<U>, v);
}
// non-const write
static void write(Message &sd, std::vector<U> &v) {
sd.writeInt(v.size());
if (v.size()) {
// we should find out if the contents is a fixed size type
// and directly assign the contents if we can
typename std::vector<U>::iterator it = v.begin();
typename std::vector<U>::iterator end = v.end();
for (; it != end; ++it) {
serialize<U>::write(sd, *it);
}
}
__QI_DEBUG_SERIALIZATION_CONTAINER_W(std::vector<U>, v);
}
static void read(Message &sd, std::vector<U> &v) {
int sz;
sd.readInt(sz);
v.clear();
if (sz) {
v.resize(sz);
typename std::vector<U>::iterator it = v.begin();
typename std::vector<U>::iterator end = v.end();
for (; it != end; ++it) {
serialize<U>::read(sd, *it);
}
}
__QI_DEBUG_SERIALIZATION_CONTAINER_R(std::vector<U>, v);
}
};
template<typename K, typename V>
struct serialize< std::map<K, V> > {
static void write(Message &sd, const std::map<K, V> &m) {
sd.writeInt(m.size());
if (m.size()) {
typename std::map<K, V>::const_iterator it = m.begin();
typename std::map<K, V>::const_iterator end = m.end();
for (; it != end; ++it) {
serialize<K>::write(sd, it->first);
serialize<V>::write(sd, it->second);
}
}
typedef std::map<K, V> debugMap;
__QI_DEBUG_SERIALIZATION_CONTAINER_W(debugMap, m);
}
// non-const write
static void write(Message &sd, std::map<K, V> &m) {
sd.writeInt(m.size());
if (m.size()) {
typename std::map<K, V>::iterator it = m.begin();
typename std::map<K, V>::iterator end = m.end();
for (; it != end; ++it) {
serialize<K>::write(sd, it->first);
serialize<V>::write(sd, it->second);
}
}
typedef std::map<K, V> debugMap;
__QI_DEBUG_SERIALIZATION_CONTAINER_W(debugMap, m);
}
static void read(Message &sd, std::map<K, V> &m) {
int sz;
sd.readInt(sz);
m.clear();
if (sz) {
for(int i=0; i < sz; ++i) {
K k;
V v;
serialize<K>::read(sd, k);
serialize<V>::read(sd, v);
m[k] = v;
}
}
typedef std::map<K, V> debugMap;
__QI_DEBUG_SERIALIZATION_CONTAINER_R(debugMap, m);
}
};
}
}
#endif // _QI_SERIALIZATION_SERIALIZE_HXX_
<commit_msg>serialize.hxx: add a missing header<commit_after>#pragma once
/*
* Author(s):
* - Chris Kilner <[email protected]>
* - Cedric Gestes <[email protected]>
*
* Copyright (C) 2010 Aldebaran Robotics
*/
#ifndef _QI_SERIALIZATION_SERIALIZE_HXX_
#define _QI_SERIALIZATION_SERIALIZE_HXX_
#if 0
#define __QI_DEBUG_SERIALIZATION_W(x, extra) { \
std::string sig = qi::signature< x >::value(); \
std::cout << "write(" << sig << ")" << extra << std::endl; \
}
#define __QI_DEBUG_SERIALIZATION_R(x, extra) { \
std::string sig = qi::signature< x >::value(); \
std::cout << "read (" << sig << ")" << extra << std::endl; \
}
#define __QI_DEBUG_SERIALIZATION_CONTAINER_W(x, c) { \
std::string sig = qi::signature< x >::value(); \
std::cout << "write(" << sig << ") size: " << c.size() << std::endl; \
}
#define __QI_DEBUG_SERIALIZATION_CONTAINER_R(x, c) { \
std::string sig = qi::signature< x >::value(); \
std::cout << "read (" << sig << ") size: " << c.size() << std::endl; \
}
#else
# define __QI_DEBUG_SERIALIZATION_W(x, extra)
# define __QI_DEBUG_SERIALIZATION_R(x, extra)
# define __QI_DEBUG_SERIALIZATION_CONTAINER_W(x, c)
# define __QI_DEBUG_SERIALIZATION_CONTAINER_R(x, c)
#endif
#ifdef WITH_PROTOBUF
# include <google/protobuf/message.h>
#endif
#include <qi/serialization/serializer.hpp>
#include <qi/serialization/serializable.hpp>
#include <iostream>
namespace qi {
namespace serialization {
//Inline this function => they do nothing, they just call Message method
//we keep vector/map not inlined at the moment because they take space.
#define QI_SIMPLE_SERIALIZER(Name, Type) \
template <> \
struct serialize<Type> { \
static inline void write(Message &sd, const Type &val) { \
sd.write##Name(val); \
} \
static inline void read(Message &sd, Type &val) { \
sd.read##Name(val); \
} \
};
QI_SIMPLE_SERIALIZER(Bool, bool);
QI_SIMPLE_SERIALIZER(Char, char);
QI_SIMPLE_SERIALIZER(Int, int);
QI_SIMPLE_SERIALIZER(Float, float);
QI_SIMPLE_SERIALIZER(String, std::string);
template <typename T>
struct serialize<T&> {
static inline void write(Message &sd, const T &val) {
__QI_DEBUG_SERIALIZATION_W(T, "&");
serialize<T>::write(sd, val);
}
static inline void read(Message &sd, T &val) {
__QI_DEBUG_SERIALIZATION_R(T, "&");
serialize<T>::read(sd, val);
}
};
template <typename T>
struct serialize<const T> {
static inline void write(Message &sd, const T &val) {
__QI_DEBUG_SERIALIZATION_W(T, "Const");
serialize<T>::write(sd, val);
}
static inline void read(Message &sd, T &val) {
__QI_DEBUG_SERIALIZATION_R(T, "Const");
serialize<T>::read(sd, val);
}
};
#ifdef WITH_PROTOBUF
template <typename T>
struct serialize<T, typename boost::enable_if< typename boost::is_base_of<google::protobuf::Message , T>::type >::type > {
static void write(Message &sd, const T &val) {
__QI_DEBUG_SERIALIZATION_W(T, "Proto");
std::string ser;
val.SerializeToString(&ser);
sd.writeString(ser);
}
static void read(Message &sd, T &val) {
__QI_DEBUG_SERIALIZATION_R(T, "Proto");
std::string ser;
sd.readString(ser);
val.ParseFromString(ser);
}
};
#endif
template <typename T>
struct serialize<T, typename boost::enable_if< typename boost::is_base_of<qi::serialization::Serializable , T>::type >::type > {
static void write(Message &sd, T &val) {
//__QI_DEBUG_SERIALIZATION_W(T, "Serializable");
//std::cout << "Serialize, Serializable" << std::end;
Serializer s(ACTION_SERIALIZE, sd);
val.serialize(s);
}
static void read(Message &sd, T &val) {
Serializer s(ACTION_DESERIALIZE, sd);
val.serialize(s);
//__QI_DEBUG_SERIALIZATION_R(T, "Serializable");
//std::cout << "DeSerialize, Serializable" << std::end;
}
};
template<typename U>
struct serialize< std::vector<U> > {
static void write(Message &sd, const std::vector<U> &v) {
sd.writeInt(v.size());
if (v.size()) {
// we should find out if the contents is a fixed size type
// and directly assign the contents if we can
typename std::vector<U>::const_iterator it = v.begin();
typename std::vector<U>::const_iterator end = v.end();
for (; it != end; ++it) {
serialize<U>::write(sd, *it);
}
}
__QI_DEBUG_SERIALIZATION_CONTAINER_W(std::vector<U>, v);
}
// non-const write
static void write(Message &sd, std::vector<U> &v) {
sd.writeInt(v.size());
if (v.size()) {
// we should find out if the contents is a fixed size type
// and directly assign the contents if we can
typename std::vector<U>::iterator it = v.begin();
typename std::vector<U>::iterator end = v.end();
for (; it != end; ++it) {
serialize<U>::write(sd, *it);
}
}
__QI_DEBUG_SERIALIZATION_CONTAINER_W(std::vector<U>, v);
}
static void read(Message &sd, std::vector<U> &v) {
int sz;
sd.readInt(sz);
v.clear();
if (sz) {
v.resize(sz);
typename std::vector<U>::iterator it = v.begin();
typename std::vector<U>::iterator end = v.end();
for (; it != end; ++it) {
serialize<U>::read(sd, *it);
}
}
__QI_DEBUG_SERIALIZATION_CONTAINER_R(std::vector<U>, v);
}
};
template<typename K, typename V>
struct serialize< std::map<K, V> > {
static void write(Message &sd, const std::map<K, V> &m) {
sd.writeInt(m.size());
if (m.size()) {
typename std::map<K, V>::const_iterator it = m.begin();
typename std::map<K, V>::const_iterator end = m.end();
for (; it != end; ++it) {
serialize<K>::write(sd, it->first);
serialize<V>::write(sd, it->second);
}
}
typedef std::map<K, V> debugMap;
__QI_DEBUG_SERIALIZATION_CONTAINER_W(debugMap, m);
}
// non-const write
static void write(Message &sd, std::map<K, V> &m) {
sd.writeInt(m.size());
if (m.size()) {
typename std::map<K, V>::iterator it = m.begin();
typename std::map<K, V>::iterator end = m.end();
for (; it != end; ++it) {
serialize<K>::write(sd, it->first);
serialize<V>::write(sd, it->second);
}
}
typedef std::map<K, V> debugMap;
__QI_DEBUG_SERIALIZATION_CONTAINER_W(debugMap, m);
}
static void read(Message &sd, std::map<K, V> &m) {
int sz;
sd.readInt(sz);
m.clear();
if (sz) {
for(int i=0; i < sz; ++i) {
K k;
V v;
serialize<K>::read(sd, k);
serialize<V>::read(sd, v);
m[k] = v;
}
}
typedef std::map<K, V> debugMap;
__QI_DEBUG_SERIALIZATION_CONTAINER_R(debugMap, m);
}
};
}
}
#endif // _QI_SERIALIZATION_SERIALIZE_HXX_
<|endoftext|> |
<commit_before>#include <set>
#include <Common.h>
#include <Logging/Logger.h>
#include <Util/Util.h>
#include <Util/UtilMath.h>
#include <Exd/ExdDataGenerated.h>
#include <Database/DatabaseDef.h>
#include <MySqlBase.h>
#include <Connection.h>
#include <Network/GamePacketNew.h>
#include <Network/PacketDef/Zone/ServerZoneDef.h>
#include "Actor/Player.h"
#include "Inventory/ItemContainer.h"
#include "Inventory/Item.h"
#include "Inventory/ItemUtil.h"
#include "Forwards.h"
#include "Land.h"
#include "Framework.h"
#include "House.h"
extern Sapphire::Framework g_fw;
using namespace Sapphire::Common;
Sapphire::Land::Land( uint16_t territoryTypeId, uint8_t wardNum, uint8_t landId, uint32_t landSetId,
Sapphire::Data::HousingLandSetPtr info ) :
m_currentPrice( 0 ),
m_minPrice( 0 ),
m_nextDrop( static_cast< uint32_t >( Util::getTimeSeconds() ) + 21600 ),
m_ownerId( 0 ),
m_landSetId( landSetId ),
m_landInfo( info ),
m_type( Common::LandType::none ),
m_fcIcon( 0 ),
m_fcIconColor( 0 ),
m_fcId( 0 ),
m_iconAddIcon( 0 )
{
memset( &m_tag, 0x00, 3 );
m_landIdent.landId = landId;
m_landIdent.territoryTypeId = territoryTypeId;
m_landIdent.wardNum = wardNum;
m_landIdent.worldId = 67; // todo: fix this
m_minPrice = m_landInfo->minPrice[ m_landIdent.landId ];
m_maxPrice = m_landInfo->initialPrice[ m_landIdent.landId ];
}
Sapphire::Land::~Land() = default;
void Sapphire::Land::init( Common::LandType type, uint8_t size, uint8_t state, uint32_t currentPrice, uint64_t ownerId, uint64_t houseId )
{
m_type = type;
m_size = size;
m_state = state;
m_currentPrice = currentPrice;
m_ownerId = ownerId;
// fetch the house if we have one for this land
if( houseId > 0 )
m_pHouse = make_House( houseId, m_landSetId, getLandIdent() );
auto pExdData = g_fw.get< Data::ExdDataGenerated >();
auto info = pExdData->get< Sapphire::Data::HousingMapMarkerInfo >( m_landIdent.territoryTypeId, m_landIdent.landId );
if( info )
{
m_mapMarkerPosition.x = info->x;
m_mapMarkerPosition.y = info->y;
m_mapMarkerPosition.z = info->z;
}
switch( m_size )
{
case HouseSize::Cottage:
m_maxPlacedExternalItems = 20;
m_maxPlacedInternalItems = 200;
break;
case HouseSize::House:
m_maxPlacedExternalItems = 30;
m_maxPlacedInternalItems = 300;
break;
case HouseSize::Mansion:
m_maxPlacedExternalItems = 40;
m_maxPlacedInternalItems = 400;
break;
default:
break;
}
// init item containers
auto setupContainer = [ this ]( InventoryType type, uint16_t maxSize )
{
m_landInventoryMap[ type ] = make_ItemContainer( type, maxSize, "houseiteminventory", true, true );
};
setupContainer( InventoryType::HousingOutdoorAppearance, 8 );
setupContainer( InventoryType::HousingOutdoorPlacedItems, m_maxPlacedExternalItems );
setupContainer( InventoryType::HousingOutdoorStoreroom, m_maxPlacedExternalItems );
setupContainer( InventoryType::HousingInteriorAppearance, 9 );
// nb: so we're going to store these internally in one container because SE is fucked in the head
// but when an inventory is requested, we will split them into groups of 50
setupContainer( InventoryType::HousingInteriorPlacedItems1, m_maxPlacedInternalItems );
setupContainer( InventoryType::HousingInteriorStoreroom1, m_maxPlacedInternalItems );
loadItemContainerContents();
}
void Sapphire::Land::loadItemContainerContents()
{
if( !m_pHouse )
return;
auto ident = *reinterpret_cast< uint64_t* >( &m_landIdent );
g_fw.get< Sapphire::Logger >()->debug( "Loading housing inventory for ident: " + std::to_string( ident ) );
auto pDB = g_fw.get< Db::DbWorkerPool< Db::ZoneDbConnection > >();
auto stmt = pDB->getPreparedStatement( Db::LAND_INV_SEL_HOUSE );
stmt->setUInt64( 1, ident );
auto res = pDB->query( stmt );
std::unordered_map< uint16_t, std::vector< std::pair< uint16_t, uint32_t > > > items;
while( res->next() )
{
auto containerId = res->getUInt( "ContainerId" );
auto itemId = res->getUInt64( "ItemId" );
auto slotId = res->getUInt( "SlotId" );
items[ containerId ].push_back( std::make_pair( slotId, itemId ) );
}
res.reset();
for( auto it = items.begin(); it != items.end(); it++ )
{
auto container = m_landInventoryMap[ it->first ];
for( auto fuck = it->second.begin(); fuck != it->second.end(); fuck++ )
{
auto item = Sapphire::Items::Util::loadItem( fuck->second );
if( item )
container->setItem( fuck->first, item );
}
}
}
uint32_t Sapphire::Land::convertItemIdToHousingItemId( uint32_t itemId )
{
auto pExdData = g_fw.get< Data::ExdDataGenerated >();
auto info = pExdData->get< Sapphire::Data::Item >( itemId );
return info->additionalData;
}
uint32_t Sapphire::Land::getCurrentPrice() const
{
return m_currentPrice;
}
uint32_t Sapphire::Land::getMaxPrice() const
{
return m_maxPrice;
}
//Primary State
void Sapphire::Land::setSize( uint8_t size )
{
m_size = size;
}
void Sapphire::Land::setState( uint8_t state )
{
m_state = state;
}
void Sapphire::Land::setSharing( uint8_t state )
{
m_iconAddIcon = state;
}
void Sapphire::Land::setLandType( Common::LandType type )
{
m_type = type;
}
uint8_t Sapphire::Land::getSize() const
{
return m_size;
}
uint8_t Sapphire::Land::getState() const
{
return m_state;
}
uint8_t Sapphire::Land::getSharing() const
{
return m_iconAddIcon;
}
uint32_t Sapphire::Land::getLandSetId() const
{
return m_landSetId;
}
Sapphire::Common::LandIdent Sapphire::Land::getLandIdent() const
{
return m_landIdent;
}
Sapphire::HousePtr Sapphire::Land::getHouse() const
{
return m_pHouse;
}
FFXIVARR_POSITION3 Sapphire::Land::getMapMarkerPosition()
{
return m_mapMarkerPosition;
}
Sapphire::Common::LandType Sapphire::Land::getLandType() const
{
return m_type;
}
//Free Comapny
void Sapphire::Land::setFreeCompany( uint32_t id, uint32_t icon, uint32_t color )
{
m_fcId = id;
m_fcIcon = icon;
m_fcIconColor = color; //RGBA
}
uint32_t Sapphire::Land::getFcId()
{
return m_fcIcon;
}
uint32_t Sapphire::Land::getFcIcon()
{
return m_fcIcon;
}
uint32_t Sapphire::Land::getFcColor()
{
return m_fcIconColor;
}
//Player
void Sapphire::Land::setOwnerId( uint64_t id )
{
m_ownerId = id;
}
uint64_t Sapphire::Land::getOwnerId()
{
return m_ownerId;
}
uint32_t Sapphire::Land::getDevaluationTime()
{
return m_nextDrop - static_cast< uint32_t >( Util::getTimeSeconds() );
}
void Sapphire::Land::setCurrentPrice( uint32_t currentPrice )
{
m_currentPrice = currentPrice;
}
void Sapphire::Land::setLandTag( uint8_t slot, uint8_t tag )
{
m_tag[ slot ] = tag;
}
uint8_t Sapphire::Land::getLandTag( uint8_t slot )
{
return m_tag[ slot ];
}
void Sapphire::Land::updateLandDb()
{
uint32_t houseId = 0;
if( getHouse() )
houseId = getHouse()->getHouseId();
// todo: change to prepared statement
auto pDb = g_fw.get< Db::DbWorkerPool< Db::ZoneDbConnection > >();
pDb->directExecute( "UPDATE land SET status = " + std::to_string( m_state )
+ ", LandPrice = " + std::to_string( getCurrentPrice() )
+ ", UpdateTime = " + std::to_string( getDevaluationTime() )
+ ", OwnerId = " + std::to_string( getOwnerId() )
+ ", HouseId = " + std::to_string( houseId )
+ ", Type = " + std::to_string( static_cast< uint32_t >( m_type ) ) //TODO: add house id
+ " WHERE LandSetId = " + std::to_string( m_landSetId )
+ " AND LandId = " + std::to_string( m_landIdent.landId ) + ";" );
if( auto house = getHouse() )
house->updateHouseDb();
}
void Sapphire::Land::update( uint32_t currTime )
{
if( getState() == HouseState::forSale )
{
if( m_nextDrop < currTime && m_minPrice < m_currentPrice )
{
m_nextDrop = currTime + 21600;
m_currentPrice = static_cast< uint32_t >( ( m_currentPrice / 100 ) * 99.58f );
updateLandDb();
}
}
}
uint32_t Sapphire::Land::getNextHouseId()
{
auto pDb = g_fw.get< Db::DbWorkerPool< Db::ZoneDbConnection > >();
auto pQR = pDb->query( "SELECT MAX( HouseId ) FROM house" );
if( !pQR->next() )
return 0;
return pQR->getUInt( 1 ) + 1;
}
bool Sapphire::Land::setPreset( uint32_t itemId )
{
auto housingItemId = convertItemIdToHousingItemId( itemId );
auto exdData = g_fw.get< Sapphire::Data::ExdDataGenerated >();
if( !exdData )
return false;
auto housingPreset = exdData->get< Sapphire::Data::HousingPreset >( housingItemId );
if( !housingPreset )
return false;
if( !getHouse() )
{
// todo: i guess we'd create a house here?
auto newId = getNextHouseId();
m_pHouse = make_House( newId, getLandSetId(), getLandIdent() );
}
getHouse()->setHousePart( Common::HousePartSlot::ExteriorRoof, convertItemIdToHousingItemId( housingPreset->exteriorRoof ) );
getHouse()->setHousePart( Common::HousePartSlot::ExteriorWall, convertItemIdToHousingItemId( housingPreset->exteriorWall ) );
getHouse()->setHousePart( Common::HousePartSlot::ExteriorWindow, convertItemIdToHousingItemId( housingPreset->exteriorWindow ) );
getHouse()->setHousePart( Common::HousePartSlot::ExteriorDoor, convertItemIdToHousingItemId( housingPreset->exteriorDoor ) );
getHouse()->setHouseInteriorPart( Common::HousingInteriorSlot::InteriorWall, convertItemIdToHousingItemId( housingPreset->interiorWall ) );
getHouse()->setHouseInteriorPart( Common::HousingInteriorSlot::InteriorFloor, convertItemIdToHousingItemId( housingPreset->interiorFlooring ) );
getHouse()->setHouseInteriorPart( Common::HousingInteriorSlot::InteriorLight, convertItemIdToHousingItemId( housingPreset->interiorLighting ) );
getHouse()->setHouseInteriorPart( Common::HousingInteriorSlot::InteriorWall_Attic, convertItemIdToHousingItemId( housingPreset->otherFloorWall ) );
getHouse()->setHouseInteriorPart( Common::HousingInteriorSlot::InteriorFloor_Attic, convertItemIdToHousingItemId( housingPreset->otherFloorFlooring ) );
getHouse()->setHouseInteriorPart( Common::HousingInteriorSlot::InteriorLight_Attic, convertItemIdToHousingItemId( housingPreset->otherFloorLighting ) );
getHouse()->setHouseInteriorPart( Common::HousingInteriorSlot::InteriorWall_Basement, convertItemIdToHousingItemId( housingPreset->basementWall ) );
getHouse()->setHouseInteriorPart( Common::HousingInteriorSlot::InteriorFloor_Basement, convertItemIdToHousingItemId( housingPreset->basementFlooring ) );
getHouse()->setHouseInteriorPart( Common::HousingInteriorSlot::InteriorLight_Basement, convertItemIdToHousingItemId( housingPreset->basementLighting ) );
getHouse()->setHouseInteriorPart( Common::HousingInteriorSlot::InteriorLight_Mansion, convertItemIdToHousingItemId( housingPreset->mansionLighting ) );
return true;
}
Sapphire::ItemContainerPtr Sapphire::Land::getItemContainer( uint16_t inventoryType ) const
{
auto container = m_landInventoryMap.find( inventoryType );
if( container == m_landInventoryMap.end() )
return nullptr;
return container->second;
}<commit_msg>a little reminder<commit_after>#include <set>
#include <Common.h>
#include <Logging/Logger.h>
#include <Util/Util.h>
#include <Util/UtilMath.h>
#include <Exd/ExdDataGenerated.h>
#include <Database/DatabaseDef.h>
#include <MySqlBase.h>
#include <Connection.h>
#include <Network/GamePacketNew.h>
#include <Network/PacketDef/Zone/ServerZoneDef.h>
#include "Actor/Player.h"
#include "Inventory/ItemContainer.h"
#include "Inventory/Item.h"
#include "Inventory/ItemUtil.h"
#include "Forwards.h"
#include "Land.h"
#include "Framework.h"
#include "House.h"
extern Sapphire::Framework g_fw;
using namespace Sapphire::Common;
Sapphire::Land::Land( uint16_t territoryTypeId, uint8_t wardNum, uint8_t landId, uint32_t landSetId,
Sapphire::Data::HousingLandSetPtr info ) :
m_currentPrice( 0 ),
m_minPrice( 0 ),
m_nextDrop( static_cast< uint32_t >( Util::getTimeSeconds() ) + 21600 ),
m_ownerId( 0 ),
m_landSetId( landSetId ),
m_landInfo( info ),
m_type( Common::LandType::none ),
m_fcIcon( 0 ),
m_fcIconColor( 0 ),
m_fcId( 0 ),
m_iconAddIcon( 0 )
{
memset( &m_tag, 0x00, 3 );
m_landIdent.landId = landId;
m_landIdent.territoryTypeId = territoryTypeId;
m_landIdent.wardNum = wardNum;
m_landIdent.worldId = 67; // todo: fix this
m_minPrice = m_landInfo->minPrice[ m_landIdent.landId ];
m_maxPrice = m_landInfo->initialPrice[ m_landIdent.landId ];
}
Sapphire::Land::~Land() = default;
void Sapphire::Land::init( Common::LandType type, uint8_t size, uint8_t state, uint32_t currentPrice, uint64_t ownerId, uint64_t houseId )
{
m_type = type;
m_size = size;
m_state = state;
m_currentPrice = currentPrice;
m_ownerId = ownerId;
// fetch the house if we have one for this land
if( houseId > 0 )
m_pHouse = make_House( houseId, m_landSetId, getLandIdent() );
auto pExdData = g_fw.get< Data::ExdDataGenerated >();
auto info = pExdData->get< Sapphire::Data::HousingMapMarkerInfo >( m_landIdent.territoryTypeId, m_landIdent.landId );
if( info )
{
m_mapMarkerPosition.x = info->x;
m_mapMarkerPosition.y = info->y;
m_mapMarkerPosition.z = info->z;
}
switch( m_size )
{
case HouseSize::Cottage:
m_maxPlacedExternalItems = 20;
m_maxPlacedInternalItems = 200;
break;
case HouseSize::House:
m_maxPlacedExternalItems = 30;
m_maxPlacedInternalItems = 300;
break;
case HouseSize::Mansion:
m_maxPlacedExternalItems = 40;
m_maxPlacedInternalItems = 400;
break;
default:
break;
}
// init item containers
auto setupContainer = [ this ]( InventoryType type, uint16_t maxSize )
{
m_landInventoryMap[ type ] = make_ItemContainer( type, maxSize, "houseiteminventory", true, true );
};
setupContainer( InventoryType::HousingOutdoorAppearance, 8 );
setupContainer( InventoryType::HousingOutdoorPlacedItems, m_maxPlacedExternalItems );
setupContainer( InventoryType::HousingOutdoorStoreroom, m_maxPlacedExternalItems );
setupContainer( InventoryType::HousingInteriorAppearance, 9 );
// nb: so we're going to store these internally in one container because SE is fucked in the head
// but when an inventory is requested, we will split them into groups of 50
setupContainer( InventoryType::HousingInteriorPlacedItems1, m_maxPlacedInternalItems );
setupContainer( InventoryType::HousingInteriorStoreroom1, m_maxPlacedInternalItems );
loadItemContainerContents();
}
void Sapphire::Land::loadItemContainerContents()
{
if( !m_pHouse )
return;
auto ident = *reinterpret_cast< uint64_t* >( &m_landIdent );
g_fw.get< Sapphire::Logger >()->debug( "Loading housing inventory for ident: " + std::to_string( ident ) );
auto pDB = g_fw.get< Db::DbWorkerPool< Db::ZoneDbConnection > >();
auto stmt = pDB->getPreparedStatement( Db::LAND_INV_SEL_HOUSE );
stmt->setUInt64( 1, ident );
auto res = pDB->query( stmt );
std::unordered_map< uint16_t, std::vector< std::pair< uint16_t, uint32_t > > > items;
while( res->next() )
{
auto containerId = res->getUInt( "ContainerId" );
auto itemId = res->getUInt64( "ItemId" );
auto slotId = res->getUInt( "SlotId" );
items[ containerId ].push_back( std::make_pair( slotId, itemId ) );
}
res.reset();
for( auto it = items.begin(); it != items.end(); it++ )
{
auto container = m_landInventoryMap[ it->first ];
// todo: delet this
for( auto fuck = it->second.begin(); fuck != it->second.end(); fuck++ )
{
auto item = Sapphire::Items::Util::loadItem( fuck->second );
if( item )
container->setItem( fuck->first, item );
}
}
}
uint32_t Sapphire::Land::convertItemIdToHousingItemId( uint32_t itemId )
{
auto pExdData = g_fw.get< Data::ExdDataGenerated >();
auto info = pExdData->get< Sapphire::Data::Item >( itemId );
return info->additionalData;
}
uint32_t Sapphire::Land::getCurrentPrice() const
{
return m_currentPrice;
}
uint32_t Sapphire::Land::getMaxPrice() const
{
return m_maxPrice;
}
//Primary State
void Sapphire::Land::setSize( uint8_t size )
{
m_size = size;
}
void Sapphire::Land::setState( uint8_t state )
{
m_state = state;
}
void Sapphire::Land::setSharing( uint8_t state )
{
m_iconAddIcon = state;
}
void Sapphire::Land::setLandType( Common::LandType type )
{
m_type = type;
}
uint8_t Sapphire::Land::getSize() const
{
return m_size;
}
uint8_t Sapphire::Land::getState() const
{
return m_state;
}
uint8_t Sapphire::Land::getSharing() const
{
return m_iconAddIcon;
}
uint32_t Sapphire::Land::getLandSetId() const
{
return m_landSetId;
}
Sapphire::Common::LandIdent Sapphire::Land::getLandIdent() const
{
return m_landIdent;
}
Sapphire::HousePtr Sapphire::Land::getHouse() const
{
return m_pHouse;
}
FFXIVARR_POSITION3 Sapphire::Land::getMapMarkerPosition()
{
return m_mapMarkerPosition;
}
Sapphire::Common::LandType Sapphire::Land::getLandType() const
{
return m_type;
}
//Free Comapny
void Sapphire::Land::setFreeCompany( uint32_t id, uint32_t icon, uint32_t color )
{
m_fcId = id;
m_fcIcon = icon;
m_fcIconColor = color; //RGBA
}
uint32_t Sapphire::Land::getFcId()
{
return m_fcIcon;
}
uint32_t Sapphire::Land::getFcIcon()
{
return m_fcIcon;
}
uint32_t Sapphire::Land::getFcColor()
{
return m_fcIconColor;
}
//Player
void Sapphire::Land::setOwnerId( uint64_t id )
{
m_ownerId = id;
}
uint64_t Sapphire::Land::getOwnerId()
{
return m_ownerId;
}
uint32_t Sapphire::Land::getDevaluationTime()
{
return m_nextDrop - static_cast< uint32_t >( Util::getTimeSeconds() );
}
void Sapphire::Land::setCurrentPrice( uint32_t currentPrice )
{
m_currentPrice = currentPrice;
}
void Sapphire::Land::setLandTag( uint8_t slot, uint8_t tag )
{
m_tag[ slot ] = tag;
}
uint8_t Sapphire::Land::getLandTag( uint8_t slot )
{
return m_tag[ slot ];
}
void Sapphire::Land::updateLandDb()
{
uint32_t houseId = 0;
if( getHouse() )
houseId = getHouse()->getHouseId();
// todo: change to prepared statement
auto pDb = g_fw.get< Db::DbWorkerPool< Db::ZoneDbConnection > >();
pDb->directExecute( "UPDATE land SET status = " + std::to_string( m_state )
+ ", LandPrice = " + std::to_string( getCurrentPrice() )
+ ", UpdateTime = " + std::to_string( getDevaluationTime() )
+ ", OwnerId = " + std::to_string( getOwnerId() )
+ ", HouseId = " + std::to_string( houseId )
+ ", Type = " + std::to_string( static_cast< uint32_t >( m_type ) ) //TODO: add house id
+ " WHERE LandSetId = " + std::to_string( m_landSetId )
+ " AND LandId = " + std::to_string( m_landIdent.landId ) + ";" );
if( auto house = getHouse() )
house->updateHouseDb();
}
void Sapphire::Land::update( uint32_t currTime )
{
if( getState() == HouseState::forSale )
{
if( m_nextDrop < currTime && m_minPrice < m_currentPrice )
{
m_nextDrop = currTime + 21600;
m_currentPrice = static_cast< uint32_t >( ( m_currentPrice / 100 ) * 99.58f );
updateLandDb();
}
}
}
uint32_t Sapphire::Land::getNextHouseId()
{
auto pDb = g_fw.get< Db::DbWorkerPool< Db::ZoneDbConnection > >();
auto pQR = pDb->query( "SELECT MAX( HouseId ) FROM house" );
if( !pQR->next() )
return 0;
return pQR->getUInt( 1 ) + 1;
}
bool Sapphire::Land::setPreset( uint32_t itemId )
{
auto housingItemId = convertItemIdToHousingItemId( itemId );
auto exdData = g_fw.get< Sapphire::Data::ExdDataGenerated >();
if( !exdData )
return false;
auto housingPreset = exdData->get< Sapphire::Data::HousingPreset >( housingItemId );
if( !housingPreset )
return false;
if( !getHouse() )
{
// todo: i guess we'd create a house here?
auto newId = getNextHouseId();
m_pHouse = make_House( newId, getLandSetId(), getLandIdent() );
}
getHouse()->setHousePart( Common::HousePartSlot::ExteriorRoof, convertItemIdToHousingItemId( housingPreset->exteriorRoof ) );
getHouse()->setHousePart( Common::HousePartSlot::ExteriorWall, convertItemIdToHousingItemId( housingPreset->exteriorWall ) );
getHouse()->setHousePart( Common::HousePartSlot::ExteriorWindow, convertItemIdToHousingItemId( housingPreset->exteriorWindow ) );
getHouse()->setHousePart( Common::HousePartSlot::ExteriorDoor, convertItemIdToHousingItemId( housingPreset->exteriorDoor ) );
getHouse()->setHouseInteriorPart( Common::HousingInteriorSlot::InteriorWall, convertItemIdToHousingItemId( housingPreset->interiorWall ) );
getHouse()->setHouseInteriorPart( Common::HousingInteriorSlot::InteriorFloor, convertItemIdToHousingItemId( housingPreset->interiorFlooring ) );
getHouse()->setHouseInteriorPart( Common::HousingInteriorSlot::InteriorLight, convertItemIdToHousingItemId( housingPreset->interiorLighting ) );
getHouse()->setHouseInteriorPart( Common::HousingInteriorSlot::InteriorWall_Attic, convertItemIdToHousingItemId( housingPreset->otherFloorWall ) );
getHouse()->setHouseInteriorPart( Common::HousingInteriorSlot::InteriorFloor_Attic, convertItemIdToHousingItemId( housingPreset->otherFloorFlooring ) );
getHouse()->setHouseInteriorPart( Common::HousingInteriorSlot::InteriorLight_Attic, convertItemIdToHousingItemId( housingPreset->otherFloorLighting ) );
getHouse()->setHouseInteriorPart( Common::HousingInteriorSlot::InteriorWall_Basement, convertItemIdToHousingItemId( housingPreset->basementWall ) );
getHouse()->setHouseInteriorPart( Common::HousingInteriorSlot::InteriorFloor_Basement, convertItemIdToHousingItemId( housingPreset->basementFlooring ) );
getHouse()->setHouseInteriorPart( Common::HousingInteriorSlot::InteriorLight_Basement, convertItemIdToHousingItemId( housingPreset->basementLighting ) );
getHouse()->setHouseInteriorPart( Common::HousingInteriorSlot::InteriorLight_Mansion, convertItemIdToHousingItemId( housingPreset->mansionLighting ) );
return true;
}
Sapphire::ItemContainerPtr Sapphire::Land::getItemContainer( uint16_t inventoryType ) const
{
auto container = m_landInventoryMap.find( inventoryType );
if( container == m_landInventoryMap.end() )
return nullptr;
return container->second;
}<|endoftext|> |
<commit_before>#ifndef STAN_MATH_OPENCL_REV_ADD_HPP
#define STAN_MATH_OPENCL_REV_ADD_HPP
#ifdef STAN_OPENCL
#include <stan/math/opencl/rev/adjoint_results.hpp>
#include <stan/math/opencl/matrix_cl.hpp>
#include <stan/math/opencl/kernel_generator.hpp>
#include <stan/math/opencl/prim/sum.hpp>
#include <stan/math/rev/core.hpp>
#include <stan/math/rev/fun/value_of.hpp>
#include <stan/math/rev/core/reverse_pass_callback.hpp>
#include <stan/math/prim/fun/value_of.hpp>
#include <stan/math/prim/meta/is_kernel_expression.hpp>
namespace stan {
namespace math {
/**
* Addition of two reverse mode matrices and/or kernel generator
* expressions.
* @tparam T_a type of first expression
* @tparam T_b type of second expression
* @param a first expression
* @param b second expression
* @return The sum of the given arguments
*/
template <
typename T_a, typename T_b,
require_all_prim_or_rev_kernel_expression_t<T_a, T_b>* = nullptr,
require_any_var_t<T_a, T_b>* = nullptr,
require_any_not_stan_scalar_t<T_a, T_b>* = nullptr>
inline auto add(T_a&& a, T_b&& b) {
arena_t<T_a> a_arena = std::forward<T_a>(a);
arena_t<T_b> b_arena = std::forward<T_b>(b);
return make_callback_var(
value_of(a_arena) + value_of(b_arena),
[a_arena, b_arena](vari_value<matrix_cl<double>>& res) mutable {
adjoint_results(a_arena, b_arena) += expressions(res.adj(), res.adj());
});
}
/**
* Addition of two reverse mode matrices and/or kernel generator
* expressions.
* @tparam T_a type of first expression
* @tparam T_b type of second expression
* @param a first expression
* @param b second expression
* @return The sum of the given arguments
*/
template <
typename T_a, typename T_b,
require_all_nonscalar_prim_or_rev_kernel_expression_t<T_a, T_b>* = nullptr,
require_any_var_t<T_a, T_b>* = nullptr>
inline auto operator+(const T_a& a, const T_b& b) {
return add(a, b);
}
} // namespace math
} // namespace stan
#endif
#endif
<commit_msg>wake up jenkins<commit_after>#ifndef STAN_MATH_OPENCL_REV_ADD_HPP
#define STAN_MATH_OPENCL_REV_ADD_HPP
#ifdef STAN_OPENCL
#include <stan/math/opencl/rev/adjoint_results.hpp>
#include <stan/math/opencl/matrix_cl.hpp>
#include <stan/math/opencl/kernel_generator.hpp>
#include <stan/math/opencl/prim/sum.hpp>
#include <stan/math/rev/core.hpp>
#include <stan/math/rev/fun/value_of.hpp>
#include <stan/math/rev/core/reverse_pass_callback.hpp>
#include <stan/math/prim/fun/value_of.hpp>
#include <stan/math/prim/meta/is_kernel_expression.hpp>
namespace stan {
namespace math {
/**
* Addition of two reverse mode matrices and/or kernel generator
* expressions.
* @tparam T_a type of first expression
* @tparam T_b type of second expression
* @param a first expression
* @param b second expression
* @return The sum of the given arguments
*/
template <typename T_a, typename T_b,
require_all_prim_or_rev_kernel_expression_t<T_a, T_b>* = nullptr,
require_any_var_t<T_a, T_b>* = nullptr,
require_any_not_stan_scalar_t<T_a, T_b>* = nullptr>
inline auto add(T_a&& a, T_b&& b) {
arena_t<T_a> a_arena = std::forward<T_a>(a);
arena_t<T_b> b_arena = std::forward<T_b>(b);
return make_callback_var(
value_of(a_arena) + value_of(b_arena),
[a_arena, b_arena](vari_value<matrix_cl<double>>& res) mutable {
adjoint_results(a_arena, b_arena) += expressions(res.adj(), res.adj());
});
}
/**
* Addition of two reverse mode matrices and/or kernel generator
* expressions.
* @tparam T_a type of first expression
* @tparam T_b type of second expression
* @param a first expression
* @param b second expression
* @return The sum of the given arguments
*/
template <
typename T_a, typename T_b,
require_all_nonscalar_prim_or_rev_kernel_expression_t<T_a, T_b>* = nullptr,
require_any_var_t<T_a, T_b>* = nullptr>
inline auto operator+(const T_a& a, const T_b& b) {
return add(a, b);
}
} // namespace math
} // namespace stan
#endif
#endif
<|endoftext|> |
<commit_before>#ifndef STAN_MATH_PRIM_FUN_LBETA_HPP
#define STAN_MATH_PRIM_FUN_LBETA_HPP
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/constants.hpp>
#include <stan/math/prim/fun/inv.hpp>
#include <stan/math/prim/fun/is_any_nan.hpp>
#include <stan/math/prim/fun/lgamma.hpp>
#include <stan/math/prim/fun/lgamma_stirling.hpp>
#include <stan/math/prim/fun/lgamma_stirling_diff.hpp>
#include <stan/math/prim/fun/log_sum_exp.hpp>
#include <stan/math/prim/fun/log1m.hpp>
#include <stan/math/prim/fun/multiply_log.hpp>
namespace stan {
namespace math {
/**
* Return the log of the beta function applied to the specified
* arguments.
*
* The beta function is defined for \f$a > 0\f$ and \f$b > 0\f$ by
*
* \f$\mbox{B}(a, b) = \frac{\Gamma(a) \Gamma(b)}{\Gamma(a+b)}\f$.
*
* This function returns its log,
*
* \f$\log \mbox{B}(a, b) = \log \Gamma(a) + \log \Gamma(b) - \log
\Gamma(a+b)\f$.
*
* See stan::math::lgamma() for the double-based and stan::math for the
* variable-based log Gamma function.
* This function is numerically more stable than naive evaluation via lgamma.
*
\f[
\mbox{lbeta}(\alpha, \beta) =
\begin{cases}
\ln\int_0^1 u^{\alpha - 1} (1 - u)^{\beta - 1} \, du & \mbox{if } \alpha,
\beta>0 \\[6pt] \textrm{NaN} & \mbox{if } \alpha = \textrm{NaN or } \beta =
\textrm{NaN} \end{cases} \f]
\f[
\frac{\partial\, \mbox{lbeta}(\alpha, \beta)}{\partial \alpha} =
\begin{cases}
\Psi(\alpha)-\Psi(\alpha+\beta) & \mbox{if } \alpha, \beta>0 \\[6pt]
\textrm{NaN} & \mbox{if } \alpha = \textrm{NaN or } \beta = \textrm{NaN}
\end{cases}
\f]
\f[
\frac{\partial\, \mbox{lbeta}(\alpha, \beta)}{\partial \beta} =
\begin{cases}
\Psi(\beta)-\Psi(\alpha+\beta) & \mbox{if } \alpha, \beta>0 \\[6pt]
\textrm{NaN} & \mbox{if } \alpha = \textrm{NaN or } \beta = \textrm{NaN}
\end{cases}
\f]
*
* @param a First value
* @param b Second value
* @return Log of the beta function applied to the two values.
* @tparam T1 Type of first value.
* @tparam T2 Type of second value.
*/
template <typename T1, typename T2>
return_type_t<T1, T2> lbeta(const T1 a, const T2 b) {
using T_ret = return_type_t<T1, T2>;
if (is_any_nan(a, b)) {
return NOT_A_NUMBER;
}
static const char* function = "lbeta";
check_nonnegative(function, "first argument", a);
check_nonnegative(function, "second argument", b);
T_ret x; // x is the smaller of the two
T_ret y;
if (a < b) {
x = a;
y = b;
} else {
x = b;
y = a;
}
// Special cases
if (x == 0) {
return INFTY;
}
if (is_inf(y)) {
return NEGATIVE_INFTY;
}
// For large x or y, separate the lgamma values into Stirling approximations
// and appropriate corrections. The Stirling approximations allow for
// analytic simplification and the corrections are added later.
//
// The overall approach is inspired by the code in R, where the algorithm is
// credited to W. Fullerton of Los Alamos Scientific Laboratory
if (y < lgamma_stirling_diff_useful) {
// both small
return lgamma(x) + lgamma(y) - lgamma(x + y);
}
T_ret x_over_xy = x / (x + y);
if (x < lgamma_stirling_diff_useful) {
// y large, x small
T_ret stirling_diff = lgamma_stirling_diff(y) - lgamma_stirling_diff(x + y);
T_ret stirling = (y - 0.5) * log1m(x_over_xy) + x * (1 - log(x + y));
return stirling + lgamma(x) + stirling_diff;
}
// both large
T_ret stirling_diff = lgamma_stirling_diff(x) + lgamma_stirling_diff(y)
- lgamma_stirling_diff(x + y);
T_ret stirling = (x - 0.5) * log(x_over_xy) + y * log1m(x_over_xy)
+ HALF_LOG_TWO_PI - 0.5 * log(y);
return stirling + stirling_diff;
}
} // namespace math
} // namespace stan
#endif
<commit_msg>[Jenkins] auto-formatting by clang-format version 5.0.0-3~16.04.1 (tags/RELEASE_500/final)<commit_after>#ifndef STAN_MATH_PRIM_FUN_LBETA_HPP
#define STAN_MATH_PRIM_FUN_LBETA_HPP
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/constants.hpp>
#include <stan/math/prim/fun/inv.hpp>
#include <stan/math/prim/fun/is_any_nan.hpp>
#include <stan/math/prim/fun/lgamma.hpp>
#include <stan/math/prim/fun/lgamma_stirling.hpp>
#include <stan/math/prim/fun/lgamma_stirling_diff.hpp>
#include <stan/math/prim/fun/log_sum_exp.hpp>
#include <stan/math/prim/fun/log1m.hpp>
#include <stan/math/prim/fun/multiply_log.hpp>
namespace stan {
namespace math {
/**
* Return the log of the beta function applied to the specified
* arguments.
*
* The beta function is defined for \f$a > 0\f$ and \f$b > 0\f$ by
*
* \f$\mbox{B}(a, b) = \frac{\Gamma(a) \Gamma(b)}{\Gamma(a+b)}\f$.
*
* This function returns its log,
*
* \f$\log \mbox{B}(a, b) = \log \Gamma(a) + \log \Gamma(b) - \log
\Gamma(a+b)\f$.
*
* See stan::math::lgamma() for the double-based and stan::math for the
* variable-based log Gamma function.
* This function is numerically more stable than naive evaluation via lgamma.
*
\f[
\mbox{lbeta}(\alpha, \beta) =
\begin{cases}
\ln\int_0^1 u^{\alpha - 1} (1 - u)^{\beta - 1} \, du & \mbox{if } \alpha,
\beta>0 \\[6pt] \textrm{NaN} & \mbox{if } \alpha = \textrm{NaN or } \beta =
\textrm{NaN} \end{cases} \f]
\f[
\frac{\partial\, \mbox{lbeta}(\alpha, \beta)}{\partial \alpha} =
\begin{cases}
\Psi(\alpha)-\Psi(\alpha+\beta) & \mbox{if } \alpha, \beta>0 \\[6pt]
\textrm{NaN} & \mbox{if } \alpha = \textrm{NaN or } \beta = \textrm{NaN}
\end{cases}
\f]
\f[
\frac{\partial\, \mbox{lbeta}(\alpha, \beta)}{\partial \beta} =
\begin{cases}
\Psi(\beta)-\Psi(\alpha+\beta) & \mbox{if } \alpha, \beta>0 \\[6pt]
\textrm{NaN} & \mbox{if } \alpha = \textrm{NaN or } \beta = \textrm{NaN}
\end{cases}
\f]
*
* @param a First value
* @param b Second value
* @return Log of the beta function applied to the two values.
* @tparam T1 Type of first value.
* @tparam T2 Type of second value.
*/
template <typename T1, typename T2>
return_type_t<T1, T2> lbeta(const T1 a, const T2 b) {
using T_ret = return_type_t<T1, T2>;
if (is_any_nan(a, b)) {
return NOT_A_NUMBER;
}
static const char* function = "lbeta";
check_nonnegative(function, "first argument", a);
check_nonnegative(function, "second argument", b);
T_ret x; // x is the smaller of the two
T_ret y;
if (a < b) {
x = a;
y = b;
} else {
x = b;
y = a;
}
// Special cases
if (x == 0) {
return INFTY;
}
if (is_inf(y)) {
return NEGATIVE_INFTY;
}
// For large x or y, separate the lgamma values into Stirling approximations
// and appropriate corrections. The Stirling approximations allow for
// analytic simplification and the corrections are added later.
//
// The overall approach is inspired by the code in R, where the algorithm is
// credited to W. Fullerton of Los Alamos Scientific Laboratory
if (y < lgamma_stirling_diff_useful) {
// both small
return lgamma(x) + lgamma(y) - lgamma(x + y);
}
T_ret x_over_xy = x / (x + y);
if (x < lgamma_stirling_diff_useful) {
// y large, x small
T_ret stirling_diff = lgamma_stirling_diff(y) - lgamma_stirling_diff(x + y);
T_ret stirling = (y - 0.5) * log1m(x_over_xy) + x * (1 - log(x + y));
return stirling + lgamma(x) + stirling_diff;
}
// both large
T_ret stirling_diff = lgamma_stirling_diff(x) + lgamma_stirling_diff(y)
- lgamma_stirling_diff(x + y);
T_ret stirling = (x - 0.5) * log(x_over_xy) + y * log1m(x_over_xy)
+ HALF_LOG_TWO_PI - 0.5 * log(y);
return stirling + stirling_diff;
}
} // namespace math
} // namespace stan
#endif
<|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()
{
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)
{
}
<commit_msg>Fix rotation on wheel spin.<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().x());
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>#include "fluidsystem.h"
#include "camera.h"
#include "vertexrecorder.h"
#include <iostream>
#include <math.h>
#include "particle.h"
#include "wall.h"
using namespace std;
// your system should at least contain 8x8 particles.
const int N = 5;
<<<<<<< HEAD
const float PARTICLE_RADIUS = .1;
const float PARTICLE_SPACING = 2*PARTICLE_RADIUS;
const float BOX_SIZE = 2;
const float H = 0.1;
const float mu = 1;
=======
const float PARTICLE_RADIUS = .015;
const float PARTICLE_SPACING = .02;
const float H = .0457;
const float mu = 3.5;//0.001;
>>>>>>> 9dd08cd861ada6137c7a0281dcc3a7312aabd6b9
const float SPRING_CONSTANT = 5; // N/m
const float PARTICLE_MASS = 0.02;//.03; // kg
const float GRAVITY = 9.8; // m/s
const float DRAG_CONSTANT = .05;
<<<<<<< HEAD
Vector3f boxSize;
=======
float WPoly6(Vector3f R);
Vector3f WSpiky(Vector3f R);
float WViscosity(Vector3f R);
>>>>>>> 9dd08cd861ada6137c7a0281dcc3a7312aabd6b9
FluidSystem::FluidSystem()
{
// back, front, left, right, bottom - respectively
_walls.push_back(Wall(Vector3f(0,-0.5,-1), Vector3f(0,0,1)));
_walls.push_back(Wall(Vector3f(0,-0.5,1), Vector3f(0,0,-1)));
_walls.push_back(Wall(Vector3f(-1,-0.5,0), Vector3f(1,0,0)));
_walls.push_back(Wall(Vector3f(1,-0.5,0), Vector3f(-1,0,0)));
_walls.push_back(Wall(Vector3f(0,-1,0), Vector3f(0,1,0)));
// Initialize m_vVecState with fluid particles.
// You can again use rand_uniform(lo, hi) to make things a bit more interesting
m_vVecState.clear();
int particleCount = 0;
for (unsigned i = 0; i < N; i++){
for (unsigned j = 0; j< N; j++){
for (unsigned l = 0; l < N; l++){
float x = i*PARTICLE_SPACING;
float y = j*PARTICLE_SPACING;
float z = l*PARTICLE_SPACING;
// particles evenly spaced
Vector3f position = Vector3f(x, y, z);
// all particles stationary
// Vector3f velocity = Vector3f( rand_uniform(-1, 1), 0, rand_uniform( -1, 1));
Vector3f velocity = Vector3f(0);
Particle particle = Particle(particleCount, position, velocity);
m_vVecState.push_back(particle);
particleCount += 1;
}
}
}
}
std::vector<Particle> FluidSystem::evalF(std::vector<Particle> state)
{
std::vector<Particle> f;
// FLuid Particles undergo the following forces:
// - gravity
// - viscous drag
// - pressure
// ---Below Not Implemented---
// - surface tension
// - collision forces
// F = mg -> GRAVITY
// ----------------------------------------
float gForce = PARTICLE_MASS*GRAVITY;
// only in the y-direction
Vector3f gravityForce = Vector3f(0,-gForce, 0);
// ----------------------------------------
for (unsigned i = 0; i < m_vVecState.size(); i+=1){
Particle& particle = state[i];
Vector3f position = particle.getPosition();
Vector3f velocity = particle.getVelocity();
// compute density of every particle first
float density_i = 0;
for (unsigned j = 0; j < state.size(); j+=1) {
if (j != i) {
Particle particle_j = state[j];
Vector3f delta = position - particle_j.getPosition();
if (delta.absSquared() < H*H) {
density_i += PARTICLE_MASS*WPoly6(delta);
// cout << WPoly6(delta) << endl;
}
}
}
if (density_i > 100){
particle.density() = density_i;
// cout << density_i << endl;
}
}
for (unsigned i = 0; i < m_vVecState.size(); i+=1){
Particle particle = state[i];
Vector3f position = particle.getPosition();
Vector3f velocity = particle.getVelocity();
float density = particle.density();
cout << density << endl;
float pressure = particle.getPressure();
// compute updated density and gradient of pressure
// based on all other particles
Vector3f f_pressure;
Vector3f f_viscosity;
for (unsigned j = 0; j < state.size(); j+=1) {
if (j != i) {
Particle particle_j = state[j];
Vector3f delta = position - particle_j.getPosition() - Vector3f(2 * PARTICLE_RADIUS);
if (delta.absSquared() < H*H) {
// ---------------gradient of pressure computation-----------------
// Mueller value: (pi + pj) / 2roj
float p_factor = (pressure+particle_j.getPressure()) / (2*particle_j.getDensity());
// Lecture video value: pi/roi + pj/roj
// float p_factor = pressure/density + particle_j.getPressure()/particle_j.getDensity();
f_pressure += PARTICLE_MASS*p_factor*WSpiky(delta);
// ---------------viscosity computation-----------------
float kernel_distance_viscosity = H-delta.abs();
Vector3f v_factor = (particle_j.getVelocity() - velocity) / particle_j.getDensity();
Vector3f viscosity_term = PARTICLE_MASS*WViscosity(delta)*v_factor;
// cout << "delta " << kernel_constant_pressure << endl;
// viscosity_term.print();
f_viscosity += viscosity_term;
// velocity.print();
}
}
}
// Total Force
Vector3f totalForce = (gravityForce +(mu*f_viscosity) + f_pressure)/density;
// totalForce.print();
Vector3f acceleration = (1.0/PARTICLE_MASS)*totalForce;
if (position.y() < -0.95){
velocity = Vector3f(1,0,1)* velocity;
acceleration = Vector3f(1,-.5,1)*acceleration;
}
if (position.x() < -0.95){
velocity = Vector3f(-1,1,1)* velocity;
acceleration = Vector3f(-1,1,1)*acceleration;
}
if (position.x() > 0.95){
velocity = Vector3f(0, velocity.y(), velocity.z());
acceleration = Vector3f(-1,1,1)*acceleration;
}
if (position.z() < -0.95){
velocity = Vector3f(velocity.x(), velocity.y(), 0);
acceleration = Vector3f(1,1,-1)*acceleration;
}
if (position.z() > 0.95){
velocity = Vector3f(velocity.x(), velocity.y(), 0);
acceleration = Vector3f(1,1,-1)*acceleration;
}
Particle newParticle = Particle(i, velocity, acceleration);
f.push_back(newParticle);
}
return f;
}
float WPoly6(Vector3f R){
float constant_term = 315.0 / (64.0 * M_PI * pow(H, 9));
float kernel_distance_density = pow((H*H - R.absSquared()), 3);
return kernel_distance_density*constant_term;
}
Vector3f WSpiky(Vector3f R){
if (R.abs() < .1){
return Vector3f(0,0,0);
}
float constant_term = -45.0 / (M_PI * pow(H, 6));
Vector3f kernel_distance_pressure = pow((H - R.abs()), 2) * R.normalized();
return constant_term * kernel_distance_pressure;
}
float WViscosity(Vector3f R){
float constant_term = 45.0 / (M_PI * pow(H, 6));
float kernel_distance_viscosity = H-R.abs();
return constant_term * kernel_distance_viscosity;
}
void FluidSystem::draw(GLProgram& gl)
{
//TODO 5: render the system
// - ie draw the particles as little spheres
// - or draw the springs as little lines or cylinders
// - or draw wireframe mesh
const Vector3f blue(0.0f, 0.0f, 1.0f);
// EXAMPLE for how to render cloth particles.
// - you should replace this code.
// EXAMPLE: This shows you how to render lines to debug the spring system.
//
// You should replace this code.
//
// Since lines don't have a clearly defined normal, we can't use
// a regular lighting model.
// GLprogram has a "color only" mode, where illumination
// is disabled, and you specify color directly as vertex attribute.
// Note: enableLighting/disableLighting invalidates uniforms,
// so you'll have to update the transformation/material parameters
// after a mode change.
gl.disableLighting();
gl.updateModelMatrix(Matrix4f::identity()); // update uniforms after mode change
// drawBox(Vector3f(0,0,0), 1);
// not working :(
gl.updateMaterial(blue);
for (unsigned i = 0; i < m_vVecState.size(); i+=1){
Particle p = m_vVecState[i];
Vector3f pos = p.getPosition();
gl.updateModelMatrix(Matrix4f::translation(pos));
drawSphere(PARTICLE_RADIUS, 5, 4);
}
gl.enableLighting(); // reset to default lighting model
}
<commit_msg>Fixed merges<commit_after>#include "fluidsystem.h"
#include "camera.h"
#include "vertexrecorder.h"
#include <iostream>
#include <math.h>
#include "particle.h"
#include "wall.h"
using namespace std;
// your system should at least contain 8x8 particles.
const int N = 5;
const float PARTICLE_RADIUS = .015;
const float PARTICLE_SPACING = .02;
const float H = .0457;
const float mu = 3.5;//0.001;
const float SPRING_CONSTANT = 5; // N/m
const float PARTICLE_MASS = 0.02;//.03; // kg
const float GRAVITY = 9.8; // m/s
const float DRAG_CONSTANT = .05;
float WPoly6(Vector3f R);
Vector3f WSpiky(Vector3f R);
float WViscosity(Vector3f R);
FluidSystem::FluidSystem()
{
// back, front, left, right, bottom - respectively
_walls.push_back(Wall(Vector3f(0,-0.5,-1), Vector3f(0,0,1)));
_walls.push_back(Wall(Vector3f(0,-0.5,1), Vector3f(0,0,-1)));
_walls.push_back(Wall(Vector3f(-1,-0.5,0), Vector3f(1,0,0)));
_walls.push_back(Wall(Vector3f(1,-0.5,0), Vector3f(-1,0,0)));
_walls.push_back(Wall(Vector3f(0,-1,0), Vector3f(0,1,0)));
// Initialize m_vVecState with fluid particles.
// You can again use rand_uniform(lo, hi) to make things a bit more interesting
m_vVecState.clear();
int particleCount = 0;
for (unsigned i = 0; i < N; i++){
for (unsigned j = 0; j< N; j++){
for (unsigned l = 0; l < N; l++){
float x = i*PARTICLE_SPACING;
float y = j*PARTICLE_SPACING;
float z = l*PARTICLE_SPACING;
// particles evenly spaced
Vector3f position = Vector3f(x, y, z);
// all particles stationary
// Vector3f velocity = Vector3f( rand_uniform(-1, 1), 0, rand_uniform( -1, 1));
Vector3f velocity = Vector3f(0);
Particle particle = Particle(particleCount, position, velocity);
m_vVecState.push_back(particle);
particleCount += 1;
}
}
}
}
std::vector<Particle> FluidSystem::evalF(std::vector<Particle> state)
{
std::vector<Particle> f;
// FLuid Particles undergo the following forces:
// - gravity
// - viscous drag
// - pressure
// ---Below Not Implemented---
// - surface tension
// - collision forces
// F = mg -> GRAVITY
// ----------------------------------------
float gForce = PARTICLE_MASS*GRAVITY;
// only in the y-direction
Vector3f gravityForce = Vector3f(0,-gForce, 0);
// ----------------------------------------
for (unsigned i = 0; i < m_vVecState.size(); i+=1){
Particle& particle = state[i];
Vector3f position = particle.getPosition();
Vector3f velocity = particle.getVelocity();
// compute density of every particle first
float density_i = 0;
for (unsigned j = 0; j < state.size(); j+=1) {
if (j != i) {
Particle particle_j = state[j];
Vector3f delta = position - particle_j.getPosition();
if (delta.absSquared() < H*H) {
density_i += PARTICLE_MASS*WPoly6(delta);
// cout << WPoly6(delta) << endl;
}
}
}
particle.density() = density_i;
// cout << density_i << endl;
}
for (unsigned i = 0; i < m_vVecState.size(); i+=1){
Particle particle = state[i];
Vector3f position = particle.getPosition();
Vector3f velocity = particle.getVelocity();
float density = particle.density();
// cout << density << endl;
float pressure = particle.getPressure();
// compute updated density and gradient of pressure
// based on all other particles
Vector3f f_pressure;
Vector3f f_viscosity;
for (unsigned j = 0; j < state.size(); j+=1) {
if (j != i) {
Particle particle_j = state[j];
Vector3f delta = position - particle_j.getPosition() - Vector3f(2 * PARTICLE_RADIUS);
if (delta.absSquared() < H*H) {
// ---------------gradient of pressure computation-----------------
// Mueller value: (pi + pj) / 2roj
float p_factor = (pressure+particle_j.getPressure()) / (2*particle_j.getDensity());
// Lecture video value: pi/roi + pj/roj
// float p_factor = pressure/density + particle_j.getPressure()/particle_j.getDensity();
f_pressure += PARTICLE_MASS*p_factor*WSpiky(delta);
// ---------------viscosity computation-----------------
float kernel_distance_viscosity = H-delta.abs();
Vector3f v_factor = (particle_j.getVelocity() - velocity) / particle_j.getDensity();
Vector3f viscosity_term = PARTICLE_MASS*WViscosity(delta)*v_factor;
// cout << "delta " << kernel_constant_pressure << endl;
// viscosity_term.print();
f_viscosity += viscosity_term;
// velocity.print();
}
}
}
// Total Force
Vector3f totalForce = (gravityForce +(mu*f_viscosity) + f_pressure)/density;
// totalForce.print();
Vector3f acceleration = (1.0/PARTICLE_MASS)*totalForce;
if (position.y() < -0.95){
velocity = Vector3f(1,0,1)* velocity;
acceleration = Vector3f(1,-.5,1)*acceleration;
}
if (position.x() < -0.95){
velocity = Vector3f(-1,1,1)* velocity;
acceleration = Vector3f(-1,1,1)*acceleration;
}
if (position.x() > 0.95){
velocity = Vector3f(0, velocity.y(), velocity.z());
acceleration = Vector3f(-1,1,1)*acceleration;
}
if (position.z() < -0.95){
velocity = Vector3f(velocity.x(), velocity.y(), 0);
acceleration = Vector3f(1,1,-1)*acceleration;
}
if (position.z() > 0.95){
velocity = Vector3f(velocity.x(), velocity.y(), 0);
acceleration = Vector3f(1,1,-1)*acceleration;
}
Particle newParticle = Particle(i, velocity, acceleration);
f.push_back(newParticle);
}
return f;
}
float WPoly6(Vector3f R){
float constant_term = 315.0 / (64.0 * M_PI * pow(H, 9));
float kernel_distance_density = pow((H*H - R.absSquared()), 3);
return kernel_distance_density*constant_term;
}
Vector3f WSpiky(Vector3f R){
if (R.abs() < .1){
return Vector3f(0,0,0);
}
float constant_term = -45.0 / (M_PI * pow(H, 6));
Vector3f kernel_distance_pressure = pow((H - R.abs()), 2) * R.normalized();
return constant_term * kernel_distance_pressure;
}
float WViscosity(Vector3f R){
float constant_term = 45.0 / (M_PI * pow(H, 6));
float kernel_distance_viscosity = H-R.abs();
return constant_term * kernel_distance_viscosity;
}
void FluidSystem::draw(GLProgram& gl)
{
//TODO 5: render the system
// - ie draw the particles as little spheres
// - or draw the springs as little lines or cylinders
// - or draw wireframe mesh
const Vector3f blue(0.0f, 0.0f, 1.0f);
// EXAMPLE for how to render cloth particles.
// - you should replace this code.
// EXAMPLE: This shows you how to render lines to debug the spring system.
//
// You should replace this code.
//
// Since lines don't have a clearly defined normal, we can't use
// a regular lighting model.
// GLprogram has a "color only" mode, where illumination
// is disabled, and you specify color directly as vertex attribute.
// Note: enableLighting/disableLighting invalidates uniforms,
// so you'll have to update the transformation/material parameters
// after a mode change.
gl.disableLighting();
gl.updateModelMatrix(Matrix4f::identity()); // update uniforms after mode change
// drawBox(Vector3f(0,0,0), 1);
// not working :(
gl.updateMaterial(blue);
for (unsigned i = 0; i < m_vVecState.size(); i+=1){
Particle p = m_vVecState[i];
Vector3f pos = p.getPosition();
gl.updateModelMatrix(Matrix4f::translation(pos));
drawSphere(PARTICLE_RADIUS, 5, 4);
}
gl.enableLighting(); // reset to default lighting model
}
<|endoftext|> |
<commit_before>/*!
* Copyright by Denys Khanzhiyev aka xdenser
*
* See license text in LICENSE file
*/
/**
* Include headers
*
* @ignore
*/
#include "./fb-bindings-connection.h"
#include "./fb-bindings-fbresult.h"
#include "./fb-bindings-fbeventemitter.h"
#include "./fb-bindings-eventblock.h"
#include "./fb-bindings-blob.h"
#include "./fb-bindings-statement.h"
/**
* Init V8 structures
*
* Classes to populate in JavaScript:
*
* * Connection
* * FBResult
* *
*/
char * ErrorMessage(const ISC_STATUS *pvector, char *err_msg, int max_len)
{
err_msg[0] = 0;
char s[512], *p, *t;
t = err_msg;
while(fb_interpret(s,sizeof(s),&pvector)){
for(p=s;(*p)&&((t-err_msg)<max_len);){ *t++ = *p++; }
if((t-err_msg+1)<max_len) *t++='\n';
};
if((t-err_msg)<max_len) *t = 0;
return err_msg;
}
void
init (Handle<Object> target)
{
HandleScope scope;
event_block::Init();
FBEventEmitter::Initialize(target);
FBResult::Initialize(target);
Connection::Initialize(target);
FBblob::Initialize(target);
FBStatement::Initialize (target);
}
NODE_MODULE(binding, init)
<commit_msg>fb-bindings<commit_after>/*!
* Copyright by Denys Khanzhiyev aka xdenser
*
* See license text in LICENSE file
*/
/**
* Include headers
*
* @ignore
*/
#include "./fb-bindings-connection.h"
#include "./fb-bindings-fbresult.h"
#include "./fb-bindings-fbeventemitter.h"
#include "./fb-bindings-eventblock.h"
#include "./fb-bindings-blob.h"
#include "./fb-bindings-statement.h"
/**
* Init V8 structures
*
* Classes to populate in JavaScript:
*
* * Connection
* * FBResult
* *
*/
char * ErrorMessage(const ISC_STATUS *pvector, char *err_msg, int max_len)
{
err_msg[0] = 0;
char s[512], *p, *t;
t = err_msg;
while(fb_interpret(s,sizeof(s),&pvector)){
for(p=s;(*p)&&((t-err_msg)<max_len);){ *t++ = *p++; }
if((t-err_msg+1)<max_len) *t++='\n';
};
if((t-err_msg)<max_len) *t = 0;
return err_msg;
}
void
init (Handle<Object> target)
{
NanScope();
event_block::Init();
FBEventEmitter::Initialize(target);
FBResult::Initialize(target);
Connection::Initialize(target);
FBblob::Initialize(target);
FBStatement::Initialize (target);
}
NODE_MODULE(binding, init)
<|endoftext|> |
<commit_before>namespace mant {
namespace bbob2009 {
class WeierstrassFunction : public BlackBoxOptimisationBenchmark2009 {
public:
inline explicit WeierstrassFunction(
const unsigned int& numberOfDimensions) noexcept;
inline void setParameterRotationR(
const arma::Mat<double>& parameterRotationR);
inline void setParameterRotationQ(
const arma::Mat<double>& parameterRotationQ);
inline std::string toString() const noexcept override;
protected:
const double f0_;
const arma::Col<double> parameterConditioning_;
arma::Mat<double> parameterRotationR_;
arma::Mat<double> parameterRotationQ_;
inline double getSoftConstraintsValueImplementation(
const arma::Col<double>& parameter) const noexcept override;
inline double getObjectiveValueImplementation(
const arma::Col<double>& parameter) const noexcept override;
#if defined(MANTELLA_USE_PARALLEL)
friend class cereal::access;
template <typename Archive>
void serialize(
Archive& archive) noexcept {
archive(cereal::make_nvp("BlackBoxOptimisationBenchmark2009", cereal::base_class<BlackBoxOptimisationBenchmark2009>(this)));
archive(cereal::make_nvp("numberOfDimensions", numberOfDimensions_));
archive(cereal::make_nvp("parameterRotationR", parameterRotationR_));
archive(cereal::make_nvp("parameterRotationQ", parameterRotationQ_));
}
template <typename Archive>
static void load_and_construct(
Archive& archive,
cereal::construct<WeierstrassFunction>& construct) noexcept {
unsigned int numberOfDimensions;
archive(cereal::make_nvp("numberOfDimensions", numberOfDimensions));
construct(numberOfDimensions);
archive(cereal::make_nvp("BlackBoxOptimisationBenchmark2009", cereal::base_class<BlackBoxOptimisationBenchmark2009>(construct.ptr())));
archive(cereal::make_nvp("parameterRotationR", construct->parameterRotationR_));
archive(cereal::make_nvp("parameterRotationQ", construct->parameterRotationQ_));
}
#endif
};
//
// Implementation
//
inline WeierstrassFunction::WeierstrassFunction(
const unsigned int& numberOfDimensions) noexcept
: BlackBoxOptimisationBenchmark2009(numberOfDimensions),
f0_(-1.99951171875),
parameterConditioning_(getParameterConditioning(std::sqrt(0.01))) {
setParameterTranslation(getRandomParameterTranslation());
setParameterRotationR(getRandomRotationMatrix(numberOfDimensions_));
setParameterRotationQ(getRandomRotationMatrix(numberOfDimensions_));
}
inline void WeierstrassFunction::setParameterRotationR(
const arma::Mat<double>& parameterRotationR) {
checkDimensionCompatible("The number of rows", parameterRotationR_.n_rows, "the number of dimensions", numberOfDimensions_);
checkRotationMatrix("The matrix", parameterRotationR_);
parameterRotationR_ = parameterRotationR;
}
inline void WeierstrassFunction::setParameterRotationQ(
const arma::Mat<double>& parameterRotationQ) {
checkDimensionCompatible("The number of rows", parameterRotationQ.n_rows, "the number of dimensions", numberOfDimensions_);
checkRotationMatrix("The matrix", parameterRotationQ);
parameterRotationQ_ = parameterRotationQ;
}
inline double WeierstrassFunction::getSoftConstraintsValueImplementation(
const arma::Col<double>& parameter) const noexcept {
return 10.0 * getBoundConstraintsValue(parameter) / static_cast<double>(numberOfDimensions_);
}
inline double WeierstrassFunction::getObjectiveValueImplementation(
const arma::Col<double>& parameter) const noexcept {
const arma::Col<double>& z = parameterRotationR_ * (parameterConditioning_ % (parameterRotationQ_ * getOscillatedParameter(parameterRotationR_ * parameter)));
double sum = 0.0;
for (std::size_t n = 0; n < parameter.n_elem; ++n) {
for (unsigned int k = 0; k < 12; ++k) {
sum += std::pow(0.5, k) * std::cos(2.0 * arma::datum::pi * std::pow(3.0, k) * (z(n) + 0.5));
}
}
return 10 * std::pow(sum / static_cast<double>(numberOfDimensions_) - f0_, 3);
}
inline std::string WeierstrassFunction::toString() const noexcept {
return "weierstrass-function";
}
}
}
#if defined(MANTELLA_USE_PARALLEL)
CEREAL_REGISTER_TYPE(mant::bbob2009::WeierstrassFunction);
#endif
<commit_msg>Fixed member field usage before initialising it<commit_after>namespace mant {
namespace bbob2009 {
class WeierstrassFunction : public BlackBoxOptimisationBenchmark2009 {
public:
inline explicit WeierstrassFunction(
const unsigned int& numberOfDimensions) noexcept;
inline void setParameterRotationR(
const arma::Mat<double>& parameterRotationR);
inline void setParameterRotationQ(
const arma::Mat<double>& parameterRotationQ);
inline std::string toString() const noexcept override;
protected:
const double f0_;
const arma::Col<double> parameterConditioning_;
arma::Mat<double> parameterRotationR_;
arma::Mat<double> parameterRotationQ_;
inline double getSoftConstraintsValueImplementation(
const arma::Col<double>& parameter) const noexcept override;
inline double getObjectiveValueImplementation(
const arma::Col<double>& parameter) const noexcept override;
#if defined(MANTELLA_USE_PARALLEL)
friend class cereal::access;
template <typename Archive>
void serialize(
Archive& archive) noexcept {
archive(cereal::make_nvp("BlackBoxOptimisationBenchmark2009", cereal::base_class<BlackBoxOptimisationBenchmark2009>(this)));
archive(cereal::make_nvp("numberOfDimensions", numberOfDimensions_));
archive(cereal::make_nvp("parameterRotationR", parameterRotationR_));
archive(cereal::make_nvp("parameterRotationQ", parameterRotationQ_));
}
template <typename Archive>
static void load_and_construct(
Archive& archive,
cereal::construct<WeierstrassFunction>& construct) noexcept {
unsigned int numberOfDimensions;
archive(cereal::make_nvp("numberOfDimensions", numberOfDimensions));
construct(numberOfDimensions);
archive(cereal::make_nvp("BlackBoxOptimisationBenchmark2009", cereal::base_class<BlackBoxOptimisationBenchmark2009>(construct.ptr())));
archive(cereal::make_nvp("parameterRotationR", construct->parameterRotationR_));
archive(cereal::make_nvp("parameterRotationQ", construct->parameterRotationQ_));
}
#endif
};
//
// Implementation
//
inline WeierstrassFunction::WeierstrassFunction(
const unsigned int& numberOfDimensions) noexcept
: BlackBoxOptimisationBenchmark2009(numberOfDimensions),
f0_(-1.99951171875),
parameterConditioning_(getParameterConditioning(std::sqrt(0.01))) {
setParameterTranslation(getRandomParameterTranslation());
setParameterRotationR(getRandomRotationMatrix(numberOfDimensions_));
setParameterRotationQ(getRandomRotationMatrix(numberOfDimensions_));
}
inline void WeierstrassFunction::setParameterRotationR(
const arma::Mat<double>& parameterRotationR) {
checkDimensionCompatible("The number of rows", parameterRotationR.n_rows, "the number of dimensions", numberOfDimensions_);
checkRotationMatrix("The matrix", parameterRotationR);
parameterRotationR_ = parameterRotationR;
}
inline void WeierstrassFunction::setParameterRotationQ(
const arma::Mat<double>& parameterRotationQ) {
checkDimensionCompatible("The number of rows", parameterRotationQ.n_rows, "the number of dimensions", numberOfDimensions_);
checkRotationMatrix("The matrix", parameterRotationQ);
parameterRotationQ_ = parameterRotationQ;
}
inline double WeierstrassFunction::getSoftConstraintsValueImplementation(
const arma::Col<double>& parameter) const noexcept {
return 10.0 * getBoundConstraintsValue(parameter) / static_cast<double>(numberOfDimensions_);
}
inline double WeierstrassFunction::getObjectiveValueImplementation(
const arma::Col<double>& parameter) const noexcept {
const arma::Col<double>& z = parameterRotationR_ * (parameterConditioning_ % (parameterRotationQ_ * getOscillatedParameter(parameterRotationR_ * parameter)));
double sum = 0.0;
for (std::size_t n = 0; n < parameter.n_elem; ++n) {
for (unsigned int k = 0; k < 12; ++k) {
sum += std::pow(0.5, k) * std::cos(2.0 * arma::datum::pi * std::pow(3.0, k) * (z(n) + 0.5));
}
}
return 10 * std::pow(sum / static_cast<double>(numberOfDimensions_) - f0_, 3);
}
inline std::string WeierstrassFunction::toString() const noexcept {
return "weierstrass-function";
}
}
}
#if defined(MANTELLA_USE_PARALLEL)
CEREAL_REGISTER_TYPE(mant::bbob2009::WeierstrassFunction);
#endif
<|endoftext|> |
<commit_before>#ifndef _WHERE_CLAUSES_HPP
#define _WHERE_CLAUSES_HPP
#include "int_sequence.hpp"
#include "lexical_cast.hpp"
#include "nth_type_of.hpp"
#include "record.hpp"
#include "type_sequence.hpp"
#include <string>
#include <sstream>
namespace fp {
template<typename, int> struct field;
namespace where_clauses {
template<int, typename> struct where_eq;
template<int, typename> struct where_neq;
template<int, typename> struct where_lt;
template<int, typename> struct where_gt;
template<int, typename> struct where_lte;
template<int, typename> struct where_gte;
template<int, typename> struct where_contains;
template<typename, typename> struct where_or;
template<typename, typename> struct where_and;
template<typename T> struct where_condition {
template<typename TRecord> bool operator()(TRecord const & r) const {
return static_cast<T const *>(this)->operator()(r);
}
template<typename TDescriptor> std::string to_string() const {
return static_cast<T const *>(this)->to_string<TDescriptor>();
}
template<typename C> where_or<T, C> operator|(C c) const {
return where_or<T, C>(*static_cast<T const *>(this), c);
}
template<typename C> where_and<T, C> operator&(C c) const {
return where_and<T, C>(*static_cast<T const *>(this), c);
}
};
template<int I, typename T> struct where_eq : where_condition<where_eq<I, T> > {
public:
enum { index = I };
protected:
T const value;
public:
where_eq(T v) : value(v) { }
template<typename TRecord> bool operator()(TRecord const & r) const {
return (fp::get<I > (r) == value);
}
template<typename TDescriptor> std::string to_string() const {
std::stringstream ss;
ss << '(' << TDescriptor::template field<I>::name << " = " << lexical_cast<std::string>(value) << ')';
return ss.str();
}
};
template<int I, typename T> struct where_neq : where_condition<where_neq<I, T> > {
public:
enum { index = I };
protected:
T const value;
public:
where_neq(T v) : value(v) { }
template<typename TRecord> bool operator()(TRecord const & r) const {
return (fp::get<I>(r) != value);
}
template<typename TDescriptor> std::string to_string() const {
std::stringstream ss;
ss << '(' << TDescriptor::template field<I>::name << " != " << lexical_cast<std::string>(value) << ')';
return ss.str();
}
};
template<int I, typename T> struct where_lt : where_condition<where_lt<I, T> > {
public:
enum { index = I };
protected:
T const value;
public:
where_lt(T v) : value(v) { }
template<typename TRecord> bool operator()(TRecord const & r) const {
return (fp::get<I>(r) < value);
}
template<typename TDescriptor> std::string to_string() const {
std::stringstream ss;
ss << '(' << TDescriptor::template field<I>::name << " < " << lexical_cast<std::string>(value) << ')';
return ss.str();
}
};
template<int I, typename T> struct where_gt : where_condition<where_gt<I, T> > {
public:
enum { index = I };
protected:
T const value;
public:
where_gt(T v) : value(v) { }
template<typename TRecord> bool operator()(TRecord const & r) const {
return (fp::get<I>(r) > value);
}
template<typename TDescriptor> std::string to_string() const {
std::stringstream ss;
ss << '(' << TDescriptor::template field<I>::name << " > " << lexical_cast<std::string>(value) << ')';
return ss.str();
}
};
template<int I, typename T> struct where_lte : where_condition<where_lte<I, T> > {
public:
enum { index = I };
protected:
T const value;
public:
where_lte(T v) : value(v) { }
template<typename TRecord> bool operator()(TRecord const & r) const {
return (fp::get<I>(r) <= value);
}
template<typename TDescriptor> std::string to_string() const {
std::stringstream ss;
ss << '(' << TDescriptor::template field<I>::name << " <= " << lexical_cast<std::string>(value) << ')';
return ss.str();
}
};
template<int I, typename T> struct where_gte : where_condition<where_gte<I, T> > {
public:
enum { index = I };
protected:
T const value;
public:
where_gte(T v) : value(v) { }
template<typename TRecord> bool operator()(TRecord const & r) const {
return (fp::get<I>(r) >= value);
}
template<typename TDescriptor> std::string to_string() const {
std::stringstream ss;
ss << '(' << TDescriptor::template field<I>::name << " >= " << lexical_cast<std::string>(value) << ')';
return ss.str();
}
};
template<int I, typename T> struct where_contains : where_condition<where_contains<I, T> > {
public:
enum { index = I };
protected:
T const value;
public:
where_contains(T v) : value(v) { }
template<typename TRecord> bool operator()(TRecord const & r) const {
return (T::npos != fp::get<I>(r).find(value));
}
template<typename TDescriptor> std::string to_string() const {
std::stringstream ss;
ss << '(' << TDescriptor::template field<I>::name << " LIKE \"%" << lexical_cast<std::string>(value) << "%\")";
return ss.str();
}
};
template<typename L, typename R> struct where_or : where_condition<where_or<L, R> > {
protected:
L m_left;
R m_right;
public:
where_or(L l, R r) : m_left(l), m_right(r) { }
template<typename TRecord> bool operator()(TRecord const & r) const {
return (m_left(r) || m_right(r));
}
template<typename TDescriptor> std::string to_string() const {
std::stringstream ss;
ss << '(' << m_left.to_string<TDescriptor > () << " OR " << m_right.to_string<TDescriptor>() << ')';
return ss.str();
}
};
template<typename L, typename R> struct where_and : where_condition<where_and<L, R> > {
protected:
L m_left;
R m_right;
public:
where_and(L l, R r) : m_left(l), m_right(r) { }
template<typename TRecord> bool operator()(TRecord const & r) const {
return (m_left(r) && m_right(r));
}
template<typename TDescriptor> std::string to_string() const {
std::stringstream ss;
ss << '(' << m_left.to_string<TDescriptor > () << " AND " << m_right.to_string<TDescriptor>() << ')';
return ss.str();
}
};
}
template<typename TDescriptor, int I, typename T>
inline where_clauses::where_eq<I, T> operator==(field<TDescriptor, I>, T v) {
return where_clauses::where_eq<I, T>(v);
}
template<typename TDescriptor, int I, typename T>
inline where_clauses::where_neq<I, T> operator!=(field<TDescriptor, I>, T v) {
return where_clauses::where_neq<I, T>(v);
}
template<typename TDescriptor, int I, typename T>
inline where_clauses::where_lt<I, T> operator<(field<TDescriptor, I>, T v) {
return where_clauses::where_lt<I, T>(v);
}
template<typename TDescriptor, int I, typename T>
inline where_clauses::where_gt<I, T> operator>(field<TDescriptor, I>, T v) {
return where_clauses::where_gt<I, T>(v);
}
template<typename TDescriptor, int I, typename T>
inline where_clauses::where_lte<I, T> operator<=(field<TDescriptor, I>, T v) {
return where_clauses::where_lte<I, T>(v);
}
template<typename TDescriptor, int I, typename T>
inline where_clauses::where_gte<I, T> operator>=(field<TDescriptor, I>, T v) {
return where_clauses::where_gte<I, T>(v);
}
template<typename TDescriptor, int I, typename T>
inline where_clauses::where_contains<I, T> operator%(field<TDescriptor, I>, T v) {
return where_clauses::where_contains<I, T>(v);
}
}
#endif<commit_msg>added functions<commit_after>#ifndef _WHERE_CLAUSES_HPP
#define _WHERE_CLAUSES_HPP
#include "lexical_cast.hpp"
#include <string>
#include <sstream>
namespace fp {
template<typename, int> struct field;
namespace where_clauses {
template<int, typename> struct where_eq;
template<int, typename> struct where_neq;
template<int, typename> struct where_lt;
template<int, typename> struct where_gt;
template<int, typename> struct where_lte;
template<int, typename> struct where_gte;
template<int, typename> struct where_contains;
template<typename, typename> struct where_or;
template<typename, typename> struct where_and;
template<typename T> struct where_condition {
template<typename TRecord> bool operator()(TRecord const & r) const {
return static_cast<T const *>(this)->operator()(r);
}
template<typename TDescriptor> std::string to_string() const {
return static_cast<T const *>(this)->to_string<TDescriptor>();
}
template<typename C> where_or<T, C> operator|(C c) const {
return where_or<T, C>(*static_cast<T const *>(this), c);
}
template<typename C> where_and<T, C> operator&(C c) const {
return where_and<T, C>(*static_cast<T const *>(this), c);
}
};
template<int I, typename T> struct where_eq : where_condition<where_eq<I, T> > {
public:
enum { index = I };
protected:
T const value;
public:
where_eq(T v) : value(v) { }
template<typename TRecord> bool operator()(TRecord const & r) const {
return (fp::get<I>(r) == value);
}
template<typename TDescriptor> std::string to_string() const {
std::stringstream ss;
ss << '(' << fp::get_field_identifier<TDescriptor, I>() << " = " << lexical_cast<std::string>(value) << ')';
return ss.str();
}
};
template<int I, typename T> struct where_neq : where_condition<where_neq<I, T> > {
public:
enum { index = I };
protected:
T const value;
public:
where_neq(T v) : value(v) { }
template<typename TRecord> bool operator()(TRecord const & r) const {
return (fp::get<I>(r) != value);
}
template<typename TDescriptor> std::string to_string() const {
std::stringstream ss;
ss << '(' << fp::get_field_identifier<TDescriptor, I>() << " != " << lexical_cast<std::string>(value) << ')';
return ss.str();
}
};
template<int I, typename T> struct where_lt : where_condition<where_lt<I, T> > {
public:
enum { index = I };
protected:
T const value;
public:
where_lt(T v) : value(v) { }
template<typename TRecord> bool operator()(TRecord const & r) const {
return (fp::get<I>(r) < value);
}
template<typename TDescriptor> std::string to_string() const {
std::stringstream ss;
ss << '(' << fp::get_field_identifier<TDescriptor, I>() << " < " << lexical_cast<std::string>(value) << ')';
return ss.str();
}
};
template<int I, typename T> struct where_gt : where_condition<where_gt<I, T> > {
public:
enum { index = I };
protected:
T const value;
public:
where_gt(T v) : value(v) { }
template<typename TRecord> bool operator()(TRecord const & r) const {
return (fp::get<I>(r) > value);
}
template<typename TDescriptor> std::string to_string() const {
std::stringstream ss;
ss << '(' << fp::get_field_identifier<TDescriptor, I>() << " > " << lexical_cast<std::string>(value) << ')';
return ss.str();
}
};
template<int I, typename T> struct where_lte : where_condition<where_lte<I, T> > {
public:
enum { index = I };
protected:
T const value;
public:
where_lte(T v) : value(v) { }
template<typename TRecord> bool operator()(TRecord const & r) const {
return (fp::get<I>(r) <= value);
}
template<typename TDescriptor> std::string to_string() const {
std::stringstream ss;
ss << '(' << fp::get_field_identifier<TDescriptor, I>() << " <= " << lexical_cast<std::string>(value) << ')';
return ss.str();
}
};
template<int I, typename T> struct where_gte : where_condition<where_gte<I, T> > {
public:
enum { index = I };
protected:
T const value;
public:
where_gte(T v) : value(v) { }
template<typename TRecord> bool operator()(TRecord const & r) const {
return (fp::get<I>(r) >= value);
}
template<typename TDescriptor> std::string to_string() const {
std::stringstream ss;
ss << '(' << fp::get_field_identifier<TDescriptor, I>() << " >= " << lexical_cast<std::string>(value) << ')';
return ss.str();
}
};
template<int I, typename T> struct where_contains : where_condition<where_contains<I, T> > {
public:
enum { index = I };
protected:
T const value;
public:
where_contains(T v) : value(v) { }
template<typename TRecord> bool operator()(TRecord const & r) const {
return (T::npos != fp::get<I>(r).find(value));
}
template<typename TDescriptor> std::string to_string() const {
std::stringstream ss;
ss << '(' << fp::get_field_identifier<TDescriptor, I>() << " LIKE \"%" << lexical_cast<std::string>(value) << "%\")";
return ss.str();
}
};
template<typename L, typename R> struct where_or : where_condition<where_or<L, R> > {
protected:
L m_left;
R m_right;
public:
where_or(L l, R r) : m_left(l), m_right(r) { }
template<typename TRecord> bool operator()(TRecord const & r) const {
return (m_left(r) || m_right(r));
}
template<typename TDescriptor> std::string to_string() const {
std::stringstream ss;
ss << '(' << m_left.to_string<TDescriptor> () << " OR " << m_right.to_string<TDescriptor>() << ')';
return ss.str();
}
};
template<typename L, typename R> struct where_and : where_condition<where_and<L, R> > {
protected:
L m_left;
R m_right;
public:
where_and(L l, R r) : m_left(l), m_right(r) { }
template<typename TRecord> bool operator()(TRecord const & r) const {
return (m_left(r) && m_right(r));
}
template<typename TDescriptor> std::string to_string() const {
std::stringstream ss;
ss << '(' << m_left.to_string<TDescriptor>() << " AND " << m_right.to_string<TDescriptor>() << ')';
return ss.str();
}
};
}
template<typename TDescriptor, int I>
inline where_clauses::where_eq<I, typename field<TDescriptor, I>::type> eq(field<TDescriptor, I>, typename field<TDescriptor, I>::type v) {
return where_clauses::where_eq<I, typename field<TDescriptor, I>::type>(v);
}
template<typename TDescriptor, int I>
inline where_clauses::where_neq<I, typename field<TDescriptor, I>::type> neq(field<TDescriptor, I>, typename field<TDescriptor, I>::type v) {
return where_clauses::where_neq<I, typename field<TDescriptor, I>::type>(v);
}
template<typename TDescriptor, int I>
inline where_clauses::where_lt<I, typename field<TDescriptor, I>::type> lt(field<TDescriptor, I>, typename field<TDescriptor, I>::type v) {
return where_clauses::where_lt<I, typename field<TDescriptor, I>::type>(v);
}
template<typename TDescriptor, int I>
inline where_clauses::where_gt<I, typename field<TDescriptor, I>::type> gt(field<TDescriptor, I>, typename field<TDescriptor, I>::type v) {
return where_clauses::where_gt<I, typename field<TDescriptor, I>::type>(v);
}
template<typename TDescriptor, int I>
inline where_clauses::where_lte<I, typename field<TDescriptor, I>::type> lte(field<TDescriptor, I>, typename field<TDescriptor, I>::type v) {
return where_clauses::where_lte<I, typename field<TDescriptor, I>::type>(v);
}
template<typename TDescriptor, int I>
inline where_clauses::where_gte<I, typename field<TDescriptor, I>::type> gte(field<TDescriptor, I>, typename field<TDescriptor, I>::type v) {
return where_clauses::where_gte<I, typename field<TDescriptor, I>::type>(v);
}
template<typename TDescriptor, int I>
inline where_clauses::where_contains<I, typename field<TDescriptor, I>::type> contains(field<TDescriptor, I>, typename field<TDescriptor, I>::type v) {
return where_clauses::where_contains<I, typename field<TDescriptor, I>::type>(v);
}
template<typename TDescriptor, int I>
inline auto operator==(field<TDescriptor, I> f, typename field<TDescriptor, I>::type v) -> decltype(fp::eq(f, v)) {
return fp::eq(f, v);
}
template<typename TDescriptor, int I>
inline auto operator!=(field<TDescriptor, I> f, typename field<TDescriptor, I>::type v) -> decltype(fp::neq(f, v)) {
return fp::neq(f, v);
}
template<typename TDescriptor, int I>
inline auto operator<(field<TDescriptor, I> f, typename field<TDescriptor, I>::type v) -> decltype(fp::lt(f, v)) {
return fp::lt(f, v);
}
template<typename TDescriptor, int I>
inline auto operator>(field<TDescriptor, I> f, typename field<TDescriptor, I>::type v) -> decltype(fp::gt(f, v)) {
return fp::gt(f, v);
}
template<typename TDescriptor, int I>
inline auto operator<=(field<TDescriptor, I> f, typename field<TDescriptor, I>::type v) -> decltype(fp::lte(f, v)) {
return fp::lte(f, v);
}
template<typename TDescriptor, int I>
inline auto operator>=(field<TDescriptor, I> f, typename field<TDescriptor, I>::type v) -> decltype(fp::gte(f, v)) {
return fp::gte(f, v);
}
template<typename TDescriptor, int I>
inline auto operator%(field<TDescriptor, I> f, typename field<TDescriptor, I>::type v) -> decltype(fp::contains(f, v)) {
return fp::contains(f, v);
}
}
#endif<|endoftext|> |
<commit_before>/*
* Copyright 2015 - 2018 [email protected]
*
* 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/.
*/
#pragma once
#include "defines.hpp"
#include "error.hpp"
namespace ox {
template<typename T>
void assertFunc(const char*, int, T, const char*) {
}
template<>
void assertFunc<bool>(const char *file, int line, bool pass, const char *msg);
template<>
void assertFunc<Error>(const char *file, int line, Error err, const char*);
void panic([[maybe_unused]]const char *file, [[maybe_unused]]int line, [[maybe_unused]]const char *msg, [[maybe_unused]]Error err = OxError(0));
}
#define oxPanic(pass, msg) ox::panic(__FILE__, __LINE__, pass, msg)
#ifndef NDEBUG
#define oxAssert(pass, msg) ox::assertFunc<decltype(pass)>(__FILE__, __LINE__, pass, msg)
#else
inline void oxAssert(bool, const char*) {}
inline void oxAssert(ox::Error, const char*) {}
#endif
<commit_msg>[ox/std] Fix oxPanic parameter order<commit_after>/*
* Copyright 2015 - 2018 [email protected]
*
* 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/.
*/
#pragma once
#include "defines.hpp"
#include "error.hpp"
namespace ox {
template<typename T>
void assertFunc(const char*, int, T, const char*) {
}
template<>
void assertFunc<bool>(const char *file, int line, bool pass, const char *msg);
template<>
void assertFunc<Error>(const char *file, int line, Error err, const char*);
void panic([[maybe_unused]]const char *file, [[maybe_unused]]int line, [[maybe_unused]]const char *msg, [[maybe_unused]]Error err = OxError(0));
}
#define oxPanic(pass, msg) ox::panic(__FILE__, __LINE__, msg, pass)
#ifndef NDEBUG
#define oxAssert(pass, msg) ox::assertFunc<decltype(pass)>(__FILE__, __LINE__, pass, msg)
#else
inline void oxAssert(bool, const char*) {}
inline void oxAssert(ox::Error, const char*) {}
#endif
<|endoftext|> |
<commit_before>//===-- sanitizer_symbolizer_itanium.cc -----------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is shared between the sanitizer run-time libraries.
// Itanium C++ ABI-specific implementation of symbolizer parts.
//===----------------------------------------------------------------------===//
#include "sanitizer_platform.h"
#if SANITIZER_MAC || SANITIZER_LINUX
#include "sanitizer_symbolizer.h"
#include <stdlib.h>
// C++ demangling function, as required by Itanium C++ ABI. This is weak,
// because we do not require a C++ ABI library to be linked to a program
// using sanitizers; if it's not present, we'll just use the mangled name.
namespace __cxxabiv1 {
SANITIZER_WEAK_ATTRIBUTE
extern "C" char *__cxa_demangle(const char *mangled, char *buffer,
size_t *length, int *status);
}
const char *__sanitizer::DemangleCXXABI(const char *name) {
// FIXME: __cxa_demangle aggressively insists on allocating memory.
// There's not much we can do about that, short of providing our
// own demangler (libc++abi's implementation could be adapted so that
// it does not allocate). For now, we just call it anyway, and we leak
// the returned value.
if (__cxxabiv1::__cxa_demangle)
if (const char *demangled_name =
__cxxabiv1::__cxa_demangle(name, 0, 0, 0))
return demangled_name;
return name;
}
#endif // SANITIZER_MAC || SANITIZER_LINUX
<commit_msg>[*San/RTL] One more minor fix<commit_after>//===-- sanitizer_symbolizer_itanium.cc -----------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is shared between the sanitizer run-time libraries.
// Itanium C++ ABI-specific implementation of symbolizer parts.
//===----------------------------------------------------------------------===//
#include "sanitizer_platform.h"
#if SANITIZER_MAC || SANITIZER_LINUX
#include "sanitizer_symbolizer.h"
#include <stdlib.h>
// C++ demangling function, as required by Itanium C++ ABI. This is weak,
// because we do not require a C++ ABI library to be linked to a program
// using sanitizers; if it's not present, we'll just use the mangled name.
namespace __cxxabiv1 {
extern "C" SANITIZER_WEAK_ATTRIBUTE
char *__cxa_demangle(const char *mangled, char *buffer,
size_t *length, int *status);
}
const char *__sanitizer::DemangleCXXABI(const char *name) {
// FIXME: __cxa_demangle aggressively insists on allocating memory.
// There's not much we can do about that, short of providing our
// own demangler (libc++abi's implementation could be adapted so that
// it does not allocate). For now, we just call it anyway, and we leak
// the returned value.
if (__cxxabiv1::__cxa_demangle)
if (const char *demangled_name =
__cxxabiv1::__cxa_demangle(name, 0, 0, 0))
return demangled_name;
return name;
}
#endif // SANITIZER_MAC || SANITIZER_LINUX
<|endoftext|> |
<commit_before>#include <iostream>
#include <iterator>
#include <memory>
#include <sstream>
#include <string>
#include "view.h"
namespace derecho {
using std::string;
using std::shared_ptr;
SubView::SubView(int32_t num_members)
: mode(Mode::ORDERED),
members(num_members),
is_sender(num_members, 1),
member_ips(num_members),
joined(0),
departed(0),
my_rank(-1) {}
SubView::SubView(Mode mode,
const std::vector<node_id_t>& members,
std::vector<int> is_sender,
const std::vector<ip_addr>& member_ips)
: mode(mode),
members(members),
member_ips(member_ips),
my_rank(-1) {
// if the sender information is not provided, assume that all members are senders
if(is_sender.size()) {
this->is_sender = is_sender;
}
else {
this->is_sender.resize(members.size(), 1);
}
}
int SubView::rank_of(const node_id_t& who) const {
for(std::size_t rank = 0; rank < members.size(); ++rank) {
if(members[rank] == who) {
return rank;
}
}
return -1;
}
int SubView::sender_rank_of(uint32_t rank) const {
if(!is_sender[rank]) {
return -1;
}
int num = 0;
for(uint i = 0; i < rank; ++i) {
if(is_sender[i]) {
num++;
}
}
return num;
}
uint32_t SubView::num_senders() const {
uint32_t num = 0;
for(const auto i : is_sender) {
if(i) {
num++;
}
}
return num;
}
View::View(const int32_t vid, const std::vector<node_id_t>& members, const std::vector<ip_addr>& member_ips,
const std::vector<char>& failed, const int32_t num_failed, const std::vector<node_id_t>& joined,
const std::vector<node_id_t>& departed, const int32_t num_members,
const int32_t next_unassigned_rank)
: vid(vid),
members(members),
member_ips(member_ips),
failed(failed),
num_failed(num_failed),
joined(joined),
departed(departed),
num_members(num_members),
my_rank(0), //This will always get overwritten by the receiver after deserializing
next_unassigned_rank(next_unassigned_rank) {
for(int rank = 0; rank < num_members; ++rank) {
node_id_to_rank[members[rank]] = rank;
}
}
int View::rank_of_leader() const {
for(int r = 0; r < num_members; ++r) {
if(!failed[r]) {
return r;
}
}
return -1;
}
View::View(const int32_t vid, const std::vector<node_id_t>& members, const std::vector<ip_addr>& member_ips,
const std::vector<char>& failed, const std::vector<node_id_t>& joined,
const std::vector<node_id_t>& departed, const int32_t my_rank, const int32_t next_unassigned_rank)
: vid(vid),
members(members),
member_ips(member_ips),
failed(failed),
joined(joined),
departed(departed),
num_members(members.size()),
my_rank(my_rank),
next_unassigned_rank(next_unassigned_rank) {
for(int rank = 0; rank < num_members; ++rank) {
node_id_to_rank[members[rank]] = rank;
}
for(auto c : failed) {
if(c) {
num_failed++;
}
}
}
int View::rank_of(const ip_addr& who) const {
for(int rank = 0; rank < num_members; ++rank) {
if(member_ips[rank] == who) {
return rank;
}
}
return -1;
}
int View::rank_of(const node_id_t& who) const {
auto it = node_id_to_rank.find(who);
if(it != node_id_to_rank.end()) {
return it->second;
}
return -1;
}
SubView View::make_subview(const std::vector<node_id_t>& with_members, const Mode mode, const std::vector<int>& is_sender) const {
std::vector<ip_addr> subview_member_ips(with_members.size());
for(std::size_t subview_rank = 0; subview_rank < with_members.size(); ++subview_rank) {
std::size_t member_pos = std::distance(
members.begin(), std::find(members.begin(), members.end(), with_members[subview_rank]));
if(member_pos == members.size()) {
//The ID wasn't found in members[]
throw subgroup_provisioning_exception();
}
subview_member_ips[subview_rank] = member_ips[member_pos];
}
//Note that joined and departed do not need to get initialized here; they will be initialized by ViewManager
return SubView(mode, with_members, is_sender, subview_member_ips);
}
int View::subview_rank_of_shard_leader(subgroup_id_t subgroup_id, int shard_index) const {
const SubView& shard_view = subgroup_shard_views.at(subgroup_id).at(shard_index);
for(std::size_t rank = 0; rank < shard_view.members.size(); ++rank) {
//Inefficient to call rank_of every time, but no guarantee the subgroup members will have ascending ranks
if(!failed[rank_of(shard_view.members[rank])]) {
return rank;
}
}
return -1;
}
bool View::i_am_leader() const {
return (rank_of_leader() == my_rank); // True if I know myself to be the leader
}
bool View::i_am_new_leader() {
if(i_know_i_am_leader) {
return false; // I am the OLD leader
}
for(int n = 0; n < my_rank; n++) {
for(int row = 0; row < my_rank; row++) {
if(!failed[n] && !gmsSST->suspected[row][n]) {
return false; // I'm not the new leader, or some failure suspicion hasn't fully propagated
}
}
}
i_know_i_am_leader = true;
return true;
}
void View::merge_changes() {
int myRank = my_rank;
// Merge the change lists
for(int n = 0; n < num_members; n++) {
if(gmsSST->num_changes[myRank] < gmsSST->num_changes[n]) {
gmssst::set(gmsSST->changes[myRank], gmsSST->changes[n], gmsSST->changes.size());
gmssst::set(gmsSST->num_changes[myRank], gmsSST->num_changes[n]);
}
if(gmsSST->num_committed[myRank] < gmsSST->num_committed[n]) // How many I know to have been committed
{
gmssst::set(gmsSST->num_committed[myRank], gmsSST->num_committed[n]);
}
}
bool found = false;
for(int n = 0; n < num_members; n++) {
if(failed[n]) {
// Make sure that the failed process is listed in the Changes vector as a proposed change
for(int c = gmsSST->num_committed[myRank]; c < gmsSST->num_changes[myRank] && !found; c++) {
if(gmsSST->changes[myRank][c % gmsSST->changes.size()] == members[n]) {
// Already listed
found = true;
}
}
} else {
// Not failed
found = true;
}
if(!found) {
gmssst::set(gmsSST->changes[myRank][gmsSST->num_changes[myRank] % gmsSST->changes.size()],
members[n]);
gmssst::increment(gmsSST->num_changes[myRank]);
}
}
gmsSST->put((char*)std::addressof(gmsSST->changes[0][0]) - gmsSST->getBaseAddress(), gmsSST->changes.size() * sizeof(node_id_t) + gmsSST->joiner_ips.size() * sizeof(uint32_t) + sizeof(int) + sizeof(int));
}
void View::wedge() {
multicast_group->wedge(); // RDMC finishes sending, stops new sends or receives in Vc
gmssst::set(gmsSST->wedged[my_rank], true);
gmsSST->put((char*)std::addressof(gmsSST->wedged[0]) - gmsSST->getBaseAddress(), sizeof(bool));
}
std::string View::debug_string() const {
// need to add member ips and other fields
std::stringstream s;
s << "View " << vid << ": MyRank=" << my_rank << ". ";
s << "Members={ ";
for(int m = 0; m < num_members; m++) {
s << members[m] << " ";
}
s << "}, ";
string fs = (" ");
for(int m = 0; m < num_members; m++) {
fs += failed[m] ? string(" T ") : string(" F ");
}
s << "Failed={" << fs << " }, num_failed=" << num_failed;
s << ", Departed: { ";
for(uint i = 0; i < departed.size(); ++i) {
s << members[departed[i]] << " ";
}
s << "} , Joined: { ";
for(uint i = 0; i < joined.size(); ++i) {
s << members[joined[i]] << " ";
}
s << "}";
return s.str();
}
std::unique_ptr<View> load_view(const std::string& view_file_name) {
std::ifstream view_file(view_file_name);
std::ifstream view_file_swap(view_file_name + persistence::SWAP_FILE_EXTENSION);
std::unique_ptr<View> view;
std::unique_ptr<View> swap_view;
//The expected view file might not exist, in which case we'll fall back to the swap file
if(view_file.good()) {
//Each file contains the size of the view (an int copied as bytes),
//followed by a serialized view
std::size_t size_of_view;
view_file.read((char*)&size_of_view, sizeof(size_of_view));
char buffer[size_of_view];
view_file.read(buffer, size_of_view);
//If the view file doesn't contain a complete view (due to a crash
//during writing), the read() call will set failbit
if(!view_file.fail()) {
view = mutils::from_bytes<View>(nullptr, buffer);
}
}
if(view_file_swap.good()) {
std::size_t size_of_view;
view_file_swap.read((char*)&size_of_view, sizeof(size_of_view));
char buffer[size_of_view];
view_file_swap.read(buffer, size_of_view);
if(!view_file_swap.fail()) {
swap_view = mutils::from_bytes<View>(nullptr, buffer);
}
}
if(swap_view == nullptr || (view != nullptr && view->vid >= swap_view->vid)) {
return view;
} else {
return swap_view;
}
}
std::ostream& operator<<(std::ostream& stream, const View& view) {
stream << view.vid << std::endl;
std::copy(view.members.begin(), view.members.end(), std::ostream_iterator<node_id_t>(stream, " "));
stream << std::endl;
std::copy(view.member_ips.begin(), view.member_ips.end(), std::ostream_iterator<ip_addr>(stream, " "));
stream << std::endl;
for(const auto& fail_val : view.failed) {
stream << (fail_val ? "T" : "F") << " ";
}
stream << std::endl;
stream << view.num_failed << std::endl;
stream << view.num_members << std::endl;
stream << view.my_rank << std::endl;
return stream;
}
View parse_view(std::istream& stream) {
std::string line;
int32_t vid = 0;
if(std::getline(stream, line)) {
vid = std::stoi(line);
}
std::vector<node_id_t> members;
//"List of member IDs" line
if(std::getline(stream, line)) {
std::istringstream linestream(line);
std::copy(std::istream_iterator<node_id_t>(linestream), std::istream_iterator<node_id_t>(),
std::back_inserter(members));
}
std::vector<ip_addr> member_ips;
//"List of member IPs" line
if(std::getline(stream, line)) {
std::istringstream linestream(line);
std::copy(std::istream_iterator<ip_addr>(linestream), std::istream_iterator<ip_addr>(),
std::back_inserter(member_ips));
}
std::vector<char> failed;
//Failures array line, which was printed as "T" or "F" strings
if(std::getline(stream, line)) {
std::istringstream linestream(line);
std::string fail_str;
while(linestream >> fail_str) {
failed.emplace_back(fail_str == "T" ? true : false);
}
}
int32_t num_failed = 0;
//The last three lines each contain a single number
if(std::getline(stream, line)) {
num_failed = std::stoi(line);
}
int32_t num_members = 0;
if(std::getline(stream, line)) {
num_members = std::stoi(line);
}
int32_t my_rank = -1;
if(std::getline(stream, line)) {
my_rank = std::stoi(line);
}
return View(vid, members, member_ips, failed, num_failed, {}, {}, num_members, my_rank);
}
}
<commit_msg>squash! Fixed a bug in view.cpp introduced by Edward's refactoring<commit_after>#include <iostream>
#include <iterator>
#include <memory>
#include <sstream>
#include <string>
#include "view.h"
namespace derecho {
using std::string;
using std::shared_ptr;
SubView::SubView(int32_t num_members)
: mode(Mode::ORDERED),
members(num_members),
is_sender(num_members, 1),
member_ips(num_members),
joined(0),
departed(0),
my_rank(-1) {}
SubView::SubView(Mode mode,
const std::vector<node_id_t>& members,
std::vector<int> is_sender,
const std::vector<ip_addr>& member_ips)
: mode(mode),
members(members),
is_sender(members.size(), 1),
member_ips(member_ips),
my_rank(-1) {
// if the sender information is not provided, assume that all members are senders
if(is_sender.size()) {
this->is_sender = is_sender;
}
}
int SubView::rank_of(const node_id_t& who) const {
for(std::size_t rank = 0; rank < members.size(); ++rank) {
if(members[rank] == who) {
return rank;
}
}
return -1;
}
int SubView::sender_rank_of(uint32_t rank) const {
if(!is_sender[rank]) {
return -1;
}
int num = 0;
for(uint i = 0; i < rank; ++i) {
if(is_sender[i]) {
num++;
}
}
return num;
}
uint32_t SubView::num_senders() const {
uint32_t num = 0;
for(const auto i : is_sender) {
if(i) {
num++;
}
}
return num;
}
View::View(const int32_t vid, const std::vector<node_id_t>& members, const std::vector<ip_addr>& member_ips,
const std::vector<char>& failed, const int32_t num_failed, const std::vector<node_id_t>& joined,
const std::vector<node_id_t>& departed, const int32_t num_members,
const int32_t next_unassigned_rank)
: vid(vid),
members(members),
member_ips(member_ips),
failed(failed),
num_failed(num_failed),
joined(joined),
departed(departed),
num_members(num_members),
my_rank(0), //This will always get overwritten by the receiver after deserializing
next_unassigned_rank(next_unassigned_rank) {
for(int rank = 0; rank < num_members; ++rank) {
node_id_to_rank[members[rank]] = rank;
}
}
int View::rank_of_leader() const {
for(int r = 0; r < num_members; ++r) {
if(!failed[r]) {
return r;
}
}
return -1;
}
View::View(const int32_t vid, const std::vector<node_id_t>& members, const std::vector<ip_addr>& member_ips,
const std::vector<char>& failed, const std::vector<node_id_t>& joined,
const std::vector<node_id_t>& departed, const int32_t my_rank, const int32_t next_unassigned_rank)
: vid(vid),
members(members),
member_ips(member_ips),
failed(failed),
joined(joined),
departed(departed),
num_members(members.size()),
my_rank(my_rank),
next_unassigned_rank(next_unassigned_rank) {
for(int rank = 0; rank < num_members; ++rank) {
node_id_to_rank[members[rank]] = rank;
}
for(auto c : failed) {
if(c) {
num_failed++;
}
}
}
int View::rank_of(const ip_addr& who) const {
for(int rank = 0; rank < num_members; ++rank) {
if(member_ips[rank] == who) {
return rank;
}
}
return -1;
}
int View::rank_of(const node_id_t& who) const {
auto it = node_id_to_rank.find(who);
if(it != node_id_to_rank.end()) {
return it->second;
}
return -1;
}
SubView View::make_subview(const std::vector<node_id_t>& with_members, const Mode mode, const std::vector<int>& is_sender) const {
std::vector<ip_addr> subview_member_ips(with_members.size());
for(std::size_t subview_rank = 0; subview_rank < with_members.size(); ++subview_rank) {
std::size_t member_pos = std::distance(
members.begin(), std::find(members.begin(), members.end(), with_members[subview_rank]));
if(member_pos == members.size()) {
//The ID wasn't found in members[]
throw subgroup_provisioning_exception();
}
subview_member_ips[subview_rank] = member_ips[member_pos];
}
//Note that joined and departed do not need to get initialized here; they will be initialized by ViewManager
return SubView(mode, with_members, is_sender, subview_member_ips);
}
int View::subview_rank_of_shard_leader(subgroup_id_t subgroup_id, int shard_index) const {
const SubView& shard_view = subgroup_shard_views.at(subgroup_id).at(shard_index);
for(std::size_t rank = 0; rank < shard_view.members.size(); ++rank) {
//Inefficient to call rank_of every time, but no guarantee the subgroup members will have ascending ranks
if(!failed[rank_of(shard_view.members[rank])]) {
return rank;
}
}
return -1;
}
bool View::i_am_leader() const {
return (rank_of_leader() == my_rank); // True if I know myself to be the leader
}
bool View::i_am_new_leader() {
if(i_know_i_am_leader) {
return false; // I am the OLD leader
}
for(int n = 0; n < my_rank; n++) {
for(int row = 0; row < my_rank; row++) {
if(!failed[n] && !gmsSST->suspected[row][n]) {
return false; // I'm not the new leader, or some failure suspicion hasn't fully propagated
}
}
}
i_know_i_am_leader = true;
return true;
}
void View::merge_changes() {
int myRank = my_rank;
// Merge the change lists
for(int n = 0; n < num_members; n++) {
if(gmsSST->num_changes[myRank] < gmsSST->num_changes[n]) {
gmssst::set(gmsSST->changes[myRank], gmsSST->changes[n], gmsSST->changes.size());
gmssst::set(gmsSST->num_changes[myRank], gmsSST->num_changes[n]);
}
if(gmsSST->num_committed[myRank] < gmsSST->num_committed[n]) // How many I know to have been committed
{
gmssst::set(gmsSST->num_committed[myRank], gmsSST->num_committed[n]);
}
}
bool found = false;
for(int n = 0; n < num_members; n++) {
if(failed[n]) {
// Make sure that the failed process is listed in the Changes vector as a proposed change
for(int c = gmsSST->num_committed[myRank]; c < gmsSST->num_changes[myRank] && !found; c++) {
if(gmsSST->changes[myRank][c % gmsSST->changes.size()] == members[n]) {
// Already listed
found = true;
}
}
} else {
// Not failed
found = true;
}
if(!found) {
gmssst::set(gmsSST->changes[myRank][gmsSST->num_changes[myRank] % gmsSST->changes.size()],
members[n]);
gmssst::increment(gmsSST->num_changes[myRank]);
}
}
gmsSST->put((char*)std::addressof(gmsSST->changes[0][0]) - gmsSST->getBaseAddress(), gmsSST->changes.size() * sizeof(node_id_t) + gmsSST->joiner_ips.size() * sizeof(uint32_t) + sizeof(int) + sizeof(int));
}
void View::wedge() {
multicast_group->wedge(); // RDMC finishes sending, stops new sends or receives in Vc
gmssst::set(gmsSST->wedged[my_rank], true);
gmsSST->put((char*)std::addressof(gmsSST->wedged[0]) - gmsSST->getBaseAddress(), sizeof(bool));
}
std::string View::debug_string() const {
// need to add member ips and other fields
std::stringstream s;
s << "View " << vid << ": MyRank=" << my_rank << ". ";
s << "Members={ ";
for(int m = 0; m < num_members; m++) {
s << members[m] << " ";
}
s << "}, ";
string fs = (" ");
for(int m = 0; m < num_members; m++) {
fs += failed[m] ? string(" T ") : string(" F ");
}
s << "Failed={" << fs << " }, num_failed=" << num_failed;
s << ", Departed: { ";
for(uint i = 0; i < departed.size(); ++i) {
s << members[departed[i]] << " ";
}
s << "} , Joined: { ";
for(uint i = 0; i < joined.size(); ++i) {
s << members[joined[i]] << " ";
}
s << "}";
return s.str();
}
std::unique_ptr<View> load_view(const std::string& view_file_name) {
std::ifstream view_file(view_file_name);
std::ifstream view_file_swap(view_file_name + persistence::SWAP_FILE_EXTENSION);
std::unique_ptr<View> view;
std::unique_ptr<View> swap_view;
//The expected view file might not exist, in which case we'll fall back to the swap file
if(view_file.good()) {
//Each file contains the size of the view (an int copied as bytes),
//followed by a serialized view
std::size_t size_of_view;
view_file.read((char*)&size_of_view, sizeof(size_of_view));
char buffer[size_of_view];
view_file.read(buffer, size_of_view);
//If the view file doesn't contain a complete view (due to a crash
//during writing), the read() call will set failbit
if(!view_file.fail()) {
view = mutils::from_bytes<View>(nullptr, buffer);
}
}
if(view_file_swap.good()) {
std::size_t size_of_view;
view_file_swap.read((char*)&size_of_view, sizeof(size_of_view));
char buffer[size_of_view];
view_file_swap.read(buffer, size_of_view);
if(!view_file_swap.fail()) {
swap_view = mutils::from_bytes<View>(nullptr, buffer);
}
}
if(swap_view == nullptr || (view != nullptr && view->vid >= swap_view->vid)) {
return view;
} else {
return swap_view;
}
}
std::ostream& operator<<(std::ostream& stream, const View& view) {
stream << view.vid << std::endl;
std::copy(view.members.begin(), view.members.end(), std::ostream_iterator<node_id_t>(stream, " "));
stream << std::endl;
std::copy(view.member_ips.begin(), view.member_ips.end(), std::ostream_iterator<ip_addr>(stream, " "));
stream << std::endl;
for(const auto& fail_val : view.failed) {
stream << (fail_val ? "T" : "F") << " ";
}
stream << std::endl;
stream << view.num_failed << std::endl;
stream << view.num_members << std::endl;
stream << view.my_rank << std::endl;
return stream;
}
View parse_view(std::istream& stream) {
std::string line;
int32_t vid = 0;
if(std::getline(stream, line)) {
vid = std::stoi(line);
}
std::vector<node_id_t> members;
//"List of member IDs" line
if(std::getline(stream, line)) {
std::istringstream linestream(line);
std::copy(std::istream_iterator<node_id_t>(linestream), std::istream_iterator<node_id_t>(),
std::back_inserter(members));
}
std::vector<ip_addr> member_ips;
//"List of member IPs" line
if(std::getline(stream, line)) {
std::istringstream linestream(line);
std::copy(std::istream_iterator<ip_addr>(linestream), std::istream_iterator<ip_addr>(),
std::back_inserter(member_ips));
}
std::vector<char> failed;
//Failures array line, which was printed as "T" or "F" strings
if(std::getline(stream, line)) {
std::istringstream linestream(line);
std::string fail_str;
while(linestream >> fail_str) {
failed.emplace_back(fail_str == "T" ? true : false);
}
}
int32_t num_failed = 0;
//The last three lines each contain a single number
if(std::getline(stream, line)) {
num_failed = std::stoi(line);
}
int32_t num_members = 0;
if(std::getline(stream, line)) {
num_members = std::stoi(line);
}
int32_t my_rank = -1;
if(std::getline(stream, line)) {
my_rank = std::stoi(line);
}
return View(vid, members, member_ips, failed, num_failed, {}, {}, num_members, my_rank);
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2016 Rhys Ulerich
*
* 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/.
*/
#ifndef DESCENDU_HEX_H
#define DESCENDU_HEX_H
#include <cstdlib>
#include "d.hpp"
namespace descendu {
template <typename T, spec S>
class hex : d<T,2,S>
{
typedef d<T,2,S> base_type;
hex(const base_type& src) : base_type(src) {}
const base_type& base() const { return *this; }
base_type& base() { return *this; }
public:
constexpr hex(const T& q, const T& r) : base_type{q, r} {}
T q() const { return this->operator[](0); }
T r() const { return this->operator[](1); }
T s() const { return - (q() + r()); }
bool operator==(const hex& o) const { return base() == o.base(); }
bool operator!=(const hex& o) const { return base() != o.base(); }
template <typename U, spec R>
friend class hex;
template <typename U, spec R>
auto operator+(const hex<U,R>& o) const {
return hex(base() + o.base());
}
template <typename U, spec R>
auto operator-(const hex<U,R>& o) const {
return hex(base() - o.base());
}
template <typename U>
auto distance(const hex<U,S>& o) const {
// Does not use operator- on account of spec compatibility
using namespace std;
return (abs(q()-o.q()) + abs(r()-o.r()) + abs(s()-o.s())) / 2;
}
hex neighbor(int i) const {
switch (i % 6) { // C++11 modulo semantics
case +0: default: return hex(q()+1, r() );
case +1: case -5: return hex(q()+1, r()-1);
case +2: case -4: return hex(q() , r()-1);
case +3: case -3: return hex(q()-1, r() );
case +4: case -2: return hex(q()-1, r()+1);
case +5: case -1: return hex(q() , r()+1);
}
}
hex diagonal(int i) const {
switch (i % 6) { // C++11 modulo semantics
case +0: default: return hex(q()+2, r()-1);
case +1: case -5: return hex(q()+1, r()-2);
case +2: case -4: return hex(q()-1, r()-1);
case +3: case -3: return hex(q()-2, r()+1);
case +4: case -2: return hex(q()-1, r()+2);
case +5: case -1: return hex(q()+1, r()+1);
}
}
};
template<class chart, class traits, typename T, spec S>
auto& operator<<(std::basic_ostream<chart,traits>& os, const hex<T,S>& p)
{
os << '['
<< S << ':'
<< p.q() << ','
<< p.r() << ','
<< p.s()
<< ']';
return os;
}
} // namespace
namespace std {
template <typename T, descendu::spec S>
struct hash<descendu::hex<T,S>>
{
typedef descendu::hex<T,S> argument_type;
typedef size_t result_type;
result_type operator()(const argument_type& a) const {
return static_cast<result_type>(S) + 31*(a.q() + 31*a.r());
}
};
}
#endif
<commit_msg>Note source<commit_after>/*
* Copyright (C) 2016 Rhys Ulerich
*
* 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/.
*/
#ifndef DESCENDU_HEX_H
#define DESCENDU_HEX_H
#include <cstdlib>
#include "d.hpp"
namespace descendu {
// Based upon http://www.redblobgames.com/grids/hexagons/
template <typename T, spec S>
class hex : d<T,2,S>
{
typedef d<T,2,S> base_type;
hex(const base_type& src) : base_type(src) {}
const base_type& base() const { return *this; }
base_type& base() { return *this; }
public:
constexpr hex(const T& q, const T& r) : base_type{q, r} {}
T q() const { return this->operator[](0); }
T r() const { return this->operator[](1); }
T s() const { return - (q() + r()); }
bool operator==(const hex& o) const { return base() == o.base(); }
bool operator!=(const hex& o) const { return base() != o.base(); }
template <typename U, spec R>
friend class hex;
template <typename U, spec R>
auto operator+(const hex<U,R>& o) const {
return hex(base() + o.base());
}
template <typename U, spec R>
auto operator-(const hex<U,R>& o) const {
return hex(base() - o.base());
}
template <typename U>
auto distance(const hex<U,S>& o) const {
// Does not use operator- on account of spec compatibility
using namespace std;
return (abs(q()-o.q()) + abs(r()-o.r()) + abs(s()-o.s())) / 2;
}
hex neighbor(int i) const {
switch (i % 6) { // C++11 modulo semantics
case +0: default: return hex(q()+1, r() );
case +1: case -5: return hex(q()+1, r()-1);
case +2: case -4: return hex(q() , r()-1);
case +3: case -3: return hex(q()-1, r() );
case +4: case -2: return hex(q()-1, r()+1);
case +5: case -1: return hex(q() , r()+1);
}
}
hex diagonal(int i) const {
switch (i % 6) { // C++11 modulo semantics
case +0: default: return hex(q()+2, r()-1);
case +1: case -5: return hex(q()+1, r()-2);
case +2: case -4: return hex(q()-1, r()-1);
case +3: case -3: return hex(q()-2, r()+1);
case +4: case -2: return hex(q()-1, r()+2);
case +5: case -1: return hex(q()+1, r()+1);
}
}
};
template<class chart, class traits, typename T, spec S>
auto& operator<<(std::basic_ostream<chart,traits>& os, const hex<T,S>& p)
{
os << '['
<< S << ':'
<< p.q() << ','
<< p.r() << ','
<< p.s()
<< ']';
return os;
}
} // namespace
namespace std {
template <typename T, descendu::spec S>
struct hash<descendu::hex<T,S>>
{
typedef descendu::hex<T,S> argument_type;
typedef size_t result_type;
result_type operator()(const argument_type& a) const {
return static_cast<result_type>(S) + 31*(a.q() + 31*a.r());
}
};
}
#endif
<|endoftext|> |
<commit_before>/**************************************************************************************/
/* */
/* Visualization Library */
/* http://www.visualizationlibrary.org */
/* */
/* Copyright (c) 2005-2010, Michele Bosi */
/* All rights reserved. */
/* */
/* Redistribution and use in source and binary forms, with or without modification, */
/* are permitted provided that the following conditions are met: */
/* */
/* - Redistributions of source code must retain the above copyright notice, this */
/* list of conditions and the following disclaimer. */
/* */
/* - Redistributions in binary form must reproduce the above copyright notice, this */
/* list of conditions and the following disclaimer in the documentation and/or */
/* other materials provided with the distribution. */
/* */
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND */
/* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */
/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */
/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR */
/* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */
/* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */
/* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */
/* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */
/* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS */
/* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/* */
/**************************************************************************************/
#ifndef Qt5Window_INCLUDE_ONCE
#define Qt5Window_INCLUDE_ONCE
#include <vlQt5/link_config.hpp>
#include <vlCore/VisualizationLibrary.hpp>
#include <vlGraphics/OpenGLContext.hpp>
//#include <QtWidgets>
//#include <QtGui/QApplication>
#include <QApplication>
#include <QtGui/QMouseEvent>
//#include <QtGui/QWidget>
#include <QWidget>
#include <QtCore/QUrl>
#include <QtCore/QTimer>
#include <QtCore/QObject>
#include <QtOpenGL/QGLWidget>
#include <QtOpenGL/QGLFormat>
#include <QMimeData>
namespace vlQt5
{
//-----------------------------------------------------------------------------
// Qt5Widget
//-----------------------------------------------------------------------------
/** The Qt5Widget class implements an OpenGLContext using the Qt5 API. */
class VLQT5_EXPORT Qt5Widget : public QGLWidget, public vl::OpenGLContext
{
Q_OBJECT
public:
using vl::Object::setObjectName;
using QObject::setObjectName;
Qt5Widget(QWidget* parent=NULL, const QGLWidget* shareWidget=NULL, Qt::WindowFlags f=0)
:QGLWidget(parent,shareWidget,f)
{
setContinuousUpdate(true);
setMouseTracking(true);
setAutoBufferSwap(false);
setAcceptDrops(true);
// let Qt take care of object destruction.
vl::OpenGLContext::setAutomaticDelete(false);
}
~Qt5Widget()
{
dispatchDestroyEvent();
}
void dragEnterEvent(QDragEnterEvent *ev)
{
if (ev->mimeData()->hasUrls())
ev->acceptProposedAction();
}
void dropEvent(QDropEvent* ev)
{
if ( ev->mimeData()->hasUrls() )
{
std::vector<vl::String> files;
QList<QUrl> list = ev->mimeData()->urls();
for(int i=0; i<list.size(); ++i)
{
if (list[i].path().isEmpty())
continue;
#ifdef WIN32
if (list[i].path()[0] == '/')
files.push_back( list[i].path().toStdString().c_str()+1 );
else
files.push_back( list[i].path().toStdString().c_str() );
#else
files.push_back( list[i].path().toStdString().c_str() );
#endif
}
dispatchFileDroppedEvent(files);
}
}
bool initQt5Widget(const vl::String& title, const vl::OpenGLContextFormat& info, const QGLContext* shareContext=0, int x=0, int y=0, int width=640, int height=480)
{
// setFormat(fmt) is marked as deprecated so we use this other method
QGLContext* glctx = new QGLContext(context()->format(), this);
QGLFormat fmt = context()->format();
// double buffer
fmt.setDoubleBuffer( info.doubleBuffer() );
// color buffer
fmt.setRedBufferSize( info.rgbaBits().r() );
fmt.setGreenBufferSize( info.rgbaBits().g() );
fmt.setBlueBufferSize( info.rgbaBits().b() );
// setAlpha == true makes the create() function alway fail
// even if the returned format has the requested alpha channel
fmt.setAlphaBufferSize( info.rgbaBits().a() );
fmt.setAlpha( info.rgbaBits().a() != 0 );
// accumulation buffer
int accum = vl::max( info.accumRGBABits().r(), info.accumRGBABits().g() );
accum = vl::max( accum, info.accumRGBABits().b() );
accum = vl::max( accum, info.accumRGBABits().a() );
fmt.setAccumBufferSize( accum );
fmt.setAccum( accum != 0 );
// multisampling
if (info.multisample())
fmt.setSamples( info.multisampleSamples() );
fmt.setSampleBuffers( info.multisample() );
// depth buffer
fmt.setDepthBufferSize( info.depthBufferBits() );
fmt.setDepth( info.depthBufferBits() != 0 );
// stencil buffer
fmt.setStencilBufferSize( info.stencilBufferBits() );
fmt.setStencil( info.stencilBufferBits() != 0 );
// stereo
fmt.setStereo( info.stereo() );
// swap interval / v-sync
fmt.setSwapInterval( info.vSync() ? 1 : 0 );
glctx->setFormat(fmt);
// this function returns false when we request an alpha buffer
// even if the created context seem to have the alpha buffer
/*bool ok = */glctx->create(shareContext);
setContext(glctx);
initGLContext();
mFramebuffer->setWidth(width);
mFramebuffer->setHeight(height);
#ifndef NDEBUG
printf("--------------------------------------------\n");
printf("REQUESTED OpenGL Format:\n");
printf("--------------------------------------------\n");
printf("rgba = %d %d %d %d\n", fmt.redBufferSize(), fmt.greenBufferSize(), fmt.blueBufferSize(), fmt.alphaBufferSize() );
printf("double buffer = %d\n", (int)fmt.doubleBuffer() );
printf("depth buffer size = %d\n", fmt.depthBufferSize() );
printf("depth buffer = %d\n", fmt.depth() );
printf("stencil buffer size = %d\n", fmt.stencilBufferSize() );
printf("stencil buffer = %d\n", fmt.stencil() );
printf("accum buffer size %d\n", fmt.accumBufferSize() );
printf("accum buffer %d\n", fmt.accum() );
printf("stereo = %d\n", (int)fmt.stereo() );
printf("swap interval = %d\n", fmt.swapInterval() );
printf("multisample = %d\n", (int)fmt.sampleBuffers() );
printf("multisample samples = %d\n", (int)fmt.samples() );
fmt = format();
printf("--------------------------------------------\n");
printf("OBTAINED OpenGL Format:\n");
printf("--------------------------------------------\n");
printf("rgba = %d %d %d %d\n", fmt.redBufferSize(), fmt.greenBufferSize(), fmt.blueBufferSize(), fmt.alphaBufferSize() );
printf("double buffer = %d\n", (int)fmt.doubleBuffer() );
printf("depth buffer size = %d\n", fmt.depthBufferSize() );
printf("depth buffer = %d\n", fmt.depth() );
printf("stencil buffer size = %d\n", fmt.stencilBufferSize() );
printf("stencil buffer = %d\n", fmt.stencil() );
printf("accum buffer size %d\n", fmt.accumBufferSize() );
printf("accum buffer %d\n", fmt.accum() );
printf("stereo = %d\n", (int)fmt.stereo() );
printf("swap interval = %d\n", fmt.swapInterval() );
printf("multisample = %d\n", (int)fmt.sampleBuffers() );
printf("multisample samples = %d\n", (int)fmt.samples() );
printf("--------------------------------------------\n");
#endif
setWindowTitle(title);
move(x,y);
resize(width,height);
if (info.fullscreen())
setFullscreen(true);
return true;
}
virtual void setContinuousUpdate(bool continuous)
{
mContinuousUpdate = continuous;
if (continuous)
{
disconnect(&mUpdateTimer, SIGNAL(timeout()), this, SLOT(updateGL()));
connect(&mUpdateTimer, SIGNAL(timeout()), this, SLOT(updateGL()));
mUpdateTimer.setSingleShot(false);
mUpdateTimer.start(0);
}
else
{
disconnect(&mUpdateTimer, SIGNAL(timeout()), this, SLOT(updateGL()));
mUpdateTimer.stop();
}
}
void initializeGL()
{
// OpenGL extensions initialization
dispatchInitEvent();
}
void resizeGL(int width, int height)
{
dispatchResizeEvent(width, height);
}
void paintGL()
{
dispatchRunEvent();
}
void update()
{
QGLWidget::update();
// QGLWidget::updateGL();
}
virtual void setWindowTitle(const vl::String& title)
{
QGLWidget::setWindowTitle( QString::fromStdString(title.toStdString()) );
}
virtual bool setFullscreen(bool fullscreen)
{
mFullscreen = fullscreen;
if (fullscreen)
QGLWidget::setWindowState(QGLWidget::windowState() | Qt::WindowFullScreen);
else
QGLWidget::setWindowState(QGLWidget::windowState() & (~Qt::WindowFullScreen));
return true;
}
virtual void quitApplication()
{
eraseAllEventListeners();
QApplication::quit();
}
virtual void show()
{
QGLWidget::show();
}
virtual void hide()
{
QGLWidget::hide();
}
virtual void setPosition(int x, int y)
{
QGLWidget::move(x,y);
}
virtual vl::ivec2 position() const
{
return vl::ivec2(QGLWidget::pos().x(), QGLWidget::pos().y());
}
virtual void setSize(int w, int h)
{
// this already excludes the window's frame so it's ok for Visualization Library standards
QGLWidget::resize(w,h);
}
virtual vl::ivec2 size() const
{
// this already excludes the window's frame so it's ok for Visualization Library standards
return vl::ivec2(QGLWidget::size().width(), QGLWidget::size().height());
}
void swapBuffers()
{
QGLWidget::swapBuffers();
}
void makeCurrent()
{
QGLWidget::makeCurrent();
}
void setMousePosition(int x, int y)
{
QCursor::setPos( mapToGlobal(QPoint(x,y)) );
}
void mouseMoveEvent(QMouseEvent* ev)
{
if (!mIgnoreNextMouseMoveEvent)
dispatchMouseMoveEvent(ev->x(), ev->y());
mIgnoreNextMouseMoveEvent = false;
}
void mousePressEvent(QMouseEvent* ev)
{
vl::EMouseButton bt = vl::NoButton;
switch(ev->button())
{
case Qt::LeftButton: bt = vl::LeftButton; break;
case Qt::RightButton: bt = vl::RightButton; break;
case Qt::MidButton: bt = vl::MiddleButton; break;
default:
bt = vl::UnknownButton; break;
}
dispatchMouseDownEvent(bt, ev->x(), ev->y());
}
void mouseReleaseEvent(QMouseEvent* ev)
{
vl::EMouseButton bt = vl::NoButton;
switch(ev->button())
{
case Qt::LeftButton: bt = vl::LeftButton; break;
case Qt::RightButton: bt = vl::RightButton; break;
case Qt::MidButton: bt = vl::MiddleButton; break;
default:
bt = vl::UnknownButton; break;
}
dispatchMouseUpEvent(bt, ev->x(), ev->y());
}
void wheelEvent(QWheelEvent* ev)
{
dispatchMouseWheelEvent(ev->delta() / 120);
}
void keyPressEvent(QKeyEvent* ev)
{
unsigned short unicode_ch = 0;
vl::EKey key = vl::Key_None;
translateKeyEvent(ev, unicode_ch, key);
dispatchKeyPressEvent(unicode_ch, key);
}
void keyReleaseEvent(QKeyEvent* ev)
{
unsigned short unicode_ch = 0;
vl::EKey key = vl::Key_None;
translateKeyEvent(ev, unicode_ch, key);
dispatchKeyReleaseEvent(unicode_ch, key);
}
virtual void setMouseVisible(bool visible)
{
mMouseVisible=visible;
if (visible)
QGLWidget::setCursor(Qt::ArrowCursor);
else
QGLWidget::setCursor(Qt::BlankCursor);
}
virtual void getFocus()
{
QGLWidget::setFocus(Qt::OtherFocusReason);
}
protected:
void translateKeyEvent(QKeyEvent* ev, unsigned short& unicode_out, vl::EKey& key_out);
protected:
QTimer mUpdateTimer;
};
//-----------------------------------------------------------------------------
}
#endif
<commit_msg>set opengl compatibility profile<commit_after>/**************************************************************************************/
/* */
/* Visualization Library */
/* http://www.visualizationlibrary.org */
/* */
/* Copyright (c) 2005-2010, Michele Bosi */
/* All rights reserved. */
/* */
/* Redistribution and use in source and binary forms, with or without modification, */
/* are permitted provided that the following conditions are met: */
/* */
/* - Redistributions of source code must retain the above copyright notice, this */
/* list of conditions and the following disclaimer. */
/* */
/* - Redistributions in binary form must reproduce the above copyright notice, this */
/* list of conditions and the following disclaimer in the documentation and/or */
/* other materials provided with the distribution. */
/* */
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND */
/* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */
/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */
/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR */
/* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */
/* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */
/* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */
/* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */
/* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS */
/* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/* */
/**************************************************************************************/
#ifndef Qt5Window_INCLUDE_ONCE
#define Qt5Window_INCLUDE_ONCE
#include <vlQt5/link_config.hpp>
#include <vlCore/VisualizationLibrary.hpp>
#include <vlGraphics/OpenGLContext.hpp>
//#include <QtWidgets>
//#include <QtGui/QApplication>
#include <QApplication>
#include <QtGui/QMouseEvent>
//#include <QtGui/QWidget>
#include <QWidget>
#include <QtCore/QUrl>
#include <QtCore/QTimer>
#include <QtCore/QObject>
#include <QtOpenGL/QGLWidget>
#include <QtOpenGL/QGLFormat>
#include <QMimeData>
namespace vlQt5
{
//-----------------------------------------------------------------------------
// Qt5Widget
//-----------------------------------------------------------------------------
/** The Qt5Widget class implements an OpenGLContext using the Qt5 API. */
class VLQT5_EXPORT Qt5Widget : public QGLWidget, public vl::OpenGLContext
{
Q_OBJECT
public:
using vl::Object::setObjectName;
using QObject::setObjectName;
Qt5Widget(QWidget* parent=NULL, const QGLWidget* shareWidget=NULL, Qt::WindowFlags f=0)
:QGLWidget(parent,shareWidget,f)
{
setContinuousUpdate(true);
setMouseTracking(true);
setAutoBufferSwap(false);
setAcceptDrops(true);
// let Qt take care of object destruction.
vl::OpenGLContext::setAutomaticDelete(false);
}
~Qt5Widget()
{
dispatchDestroyEvent();
}
void dragEnterEvent(QDragEnterEvent *ev)
{
if (ev->mimeData()->hasUrls())
ev->acceptProposedAction();
}
void dropEvent(QDropEvent* ev)
{
if ( ev->mimeData()->hasUrls() )
{
std::vector<vl::String> files;
QList<QUrl> list = ev->mimeData()->urls();
for(int i=0; i<list.size(); ++i)
{
if (list[i].path().isEmpty())
continue;
#ifdef WIN32
if (list[i].path()[0] == '/')
files.push_back( list[i].path().toStdString().c_str()+1 );
else
files.push_back( list[i].path().toStdString().c_str() );
#else
files.push_back( list[i].path().toStdString().c_str() );
#endif
}
dispatchFileDroppedEvent(files);
}
}
bool initQt5Widget(const vl::String& title, const vl::OpenGLContextFormat& info, const QGLContext* shareContext=0, int x=0, int y=0, int width=640, int height=480)
{
// setFormat(fmt) is marked as deprecated so we use this other method
QGLContext* glctx = new QGLContext(context()->format(), this);
QGLFormat fmt = context()->format();
fmt.setProfile(QGLFormat::CompatibilityProfile);
// double buffer
fmt.setDoubleBuffer( info.doubleBuffer() );
// color buffer
fmt.setRedBufferSize( info.rgbaBits().r() );
fmt.setGreenBufferSize( info.rgbaBits().g() );
fmt.setBlueBufferSize( info.rgbaBits().b() );
// setAlpha == true makes the create() function alway fail
// even if the returned format has the requested alpha channel
fmt.setAlphaBufferSize( info.rgbaBits().a() );
fmt.setAlpha( info.rgbaBits().a() != 0 );
// accumulation buffer
int accum = vl::max( info.accumRGBABits().r(), info.accumRGBABits().g() );
accum = vl::max( accum, info.accumRGBABits().b() );
accum = vl::max( accum, info.accumRGBABits().a() );
fmt.setAccumBufferSize( accum );
fmt.setAccum( accum != 0 );
// multisampling
if (info.multisample())
fmt.setSamples( info.multisampleSamples() );
fmt.setSampleBuffers( info.multisample() );
// depth buffer
fmt.setDepthBufferSize( info.depthBufferBits() );
fmt.setDepth( info.depthBufferBits() != 0 );
// stencil buffer
fmt.setStencilBufferSize( info.stencilBufferBits() );
fmt.setStencil( info.stencilBufferBits() != 0 );
// stereo
fmt.setStereo( info.stereo() );
// swap interval / v-sync
fmt.setSwapInterval( info.vSync() ? 1 : 0 );
glctx->setFormat(fmt);
// this function returns false when we request an alpha buffer
// even if the created context seem to have the alpha buffer
/*bool ok = */glctx->create(shareContext);
setContext(glctx);
initGLContext();
mFramebuffer->setWidth(width);
mFramebuffer->setHeight(height);
#ifndef NDEBUG
printf("--------------------------------------------\n");
printf("REQUESTED OpenGL Format:\n");
printf("--------------------------------------------\n");
printf("rgba = %d %d %d %d\n", fmt.redBufferSize(), fmt.greenBufferSize(), fmt.blueBufferSize(), fmt.alphaBufferSize() );
printf("double buffer = %d\n", (int)fmt.doubleBuffer() );
printf("depth buffer size = %d\n", fmt.depthBufferSize() );
printf("depth buffer = %d\n", fmt.depth() );
printf("stencil buffer size = %d\n", fmt.stencilBufferSize() );
printf("stencil buffer = %d\n", fmt.stencil() );
printf("accum buffer size %d\n", fmt.accumBufferSize() );
printf("accum buffer %d\n", fmt.accum() );
printf("stereo = %d\n", (int)fmt.stereo() );
printf("swap interval = %d\n", fmt.swapInterval() );
printf("multisample = %d\n", (int)fmt.sampleBuffers() );
printf("multisample samples = %d\n", (int)fmt.samples() );
printf("opengl version: = %s\n", glGetString(GL_VERSION) );
fmt = format();
printf("--------------------------------------------\n");
printf("OBTAINED OpenGL Format:\n");
printf("--------------------------------------------\n");
printf("rgba = %d %d %d %d\n", fmt.redBufferSize(), fmt.greenBufferSize(), fmt.blueBufferSize(), fmt.alphaBufferSize() );
printf("double buffer = %d\n", (int)fmt.doubleBuffer() );
printf("depth buffer size = %d\n", fmt.depthBufferSize() );
printf("depth buffer = %d\n", fmt.depth() );
printf("stencil buffer size = %d\n", fmt.stencilBufferSize() );
printf("stencil buffer = %d\n", fmt.stencil() );
printf("accum buffer size %d\n", fmt.accumBufferSize() );
printf("accum buffer %d\n", fmt.accum() );
printf("stereo = %d\n", (int)fmt.stereo() );
printf("swap interval = %d\n", fmt.swapInterval() );
printf("multisample = %d\n", (int)fmt.sampleBuffers() );
printf("multisample samples = %d\n", (int)fmt.samples() );
printf("opengl version: = %s\n", glGetString(GL_VERSION) );
printf("--------------------------------------------\n");
#endif
setWindowTitle(title);
move(x,y);
resize(width,height);
if (info.fullscreen())
setFullscreen(true);
return true;
}
virtual void setContinuousUpdate(bool continuous)
{
mContinuousUpdate = continuous;
if (continuous)
{
disconnect(&mUpdateTimer, SIGNAL(timeout()), this, SLOT(updateGL()));
connect(&mUpdateTimer, SIGNAL(timeout()), this, SLOT(updateGL()));
mUpdateTimer.setSingleShot(false);
mUpdateTimer.start(0);
}
else
{
disconnect(&mUpdateTimer, SIGNAL(timeout()), this, SLOT(updateGL()));
mUpdateTimer.stop();
}
}
void initializeGL()
{
// OpenGL extensions initialization
dispatchInitEvent();
}
void resizeGL(int width, int height)
{
dispatchResizeEvent(width, height);
}
void paintGL()
{
dispatchRunEvent();
}
void update()
{
QGLWidget::update();
// QGLWidget::updateGL();
}
virtual void setWindowTitle(const vl::String& title)
{
QGLWidget::setWindowTitle( QString::fromStdString(title.toStdString()) );
}
virtual bool setFullscreen(bool fullscreen)
{
mFullscreen = fullscreen;
if (fullscreen)
QGLWidget::setWindowState(QGLWidget::windowState() | Qt::WindowFullScreen);
else
QGLWidget::setWindowState(QGLWidget::windowState() & (~Qt::WindowFullScreen));
return true;
}
virtual void quitApplication()
{
eraseAllEventListeners();
QApplication::quit();
}
virtual void show()
{
QGLWidget::show();
}
virtual void hide()
{
QGLWidget::hide();
}
virtual void setPosition(int x, int y)
{
QGLWidget::move(x,y);
}
virtual vl::ivec2 position() const
{
return vl::ivec2(QGLWidget::pos().x(), QGLWidget::pos().y());
}
virtual void setSize(int w, int h)
{
// this already excludes the window's frame so it's ok for Visualization Library standards
QGLWidget::resize(w,h);
}
virtual vl::ivec2 size() const
{
// this already excludes the window's frame so it's ok for Visualization Library standards
return vl::ivec2(QGLWidget::size().width(), QGLWidget::size().height());
}
void swapBuffers()
{
QGLWidget::swapBuffers();
}
void makeCurrent()
{
QGLWidget::makeCurrent();
}
void setMousePosition(int x, int y)
{
QCursor::setPos( mapToGlobal(QPoint(x,y)) );
}
void mouseMoveEvent(QMouseEvent* ev)
{
if (!mIgnoreNextMouseMoveEvent)
dispatchMouseMoveEvent(ev->x(), ev->y());
mIgnoreNextMouseMoveEvent = false;
}
void mousePressEvent(QMouseEvent* ev)
{
vl::EMouseButton bt = vl::NoButton;
switch(ev->button())
{
case Qt::LeftButton: bt = vl::LeftButton; break;
case Qt::RightButton: bt = vl::RightButton; break;
case Qt::MidButton: bt = vl::MiddleButton; break;
default:
bt = vl::UnknownButton; break;
}
dispatchMouseDownEvent(bt, ev->x(), ev->y());
}
void mouseReleaseEvent(QMouseEvent* ev)
{
vl::EMouseButton bt = vl::NoButton;
switch(ev->button())
{
case Qt::LeftButton: bt = vl::LeftButton; break;
case Qt::RightButton: bt = vl::RightButton; break;
case Qt::MidButton: bt = vl::MiddleButton; break;
default:
bt = vl::UnknownButton; break;
}
dispatchMouseUpEvent(bt, ev->x(), ev->y());
}
void wheelEvent(QWheelEvent* ev)
{
dispatchMouseWheelEvent(ev->delta() / 120);
}
void keyPressEvent(QKeyEvent* ev)
{
unsigned short unicode_ch = 0;
vl::EKey key = vl::Key_None;
translateKeyEvent(ev, unicode_ch, key);
dispatchKeyPressEvent(unicode_ch, key);
}
void keyReleaseEvent(QKeyEvent* ev)
{
unsigned short unicode_ch = 0;
vl::EKey key = vl::Key_None;
translateKeyEvent(ev, unicode_ch, key);
dispatchKeyReleaseEvent(unicode_ch, key);
}
virtual void setMouseVisible(bool visible)
{
mMouseVisible=visible;
if (visible)
QGLWidget::setCursor(Qt::ArrowCursor);
else
QGLWidget::setCursor(Qt::BlankCursor);
}
virtual void getFocus()
{
QGLWidget::setFocus(Qt::OtherFocusReason);
}
protected:
void translateKeyEvent(QKeyEvent* ev, unsigned short& unicode_out, vl::EKey& key_out);
protected:
QTimer mUpdateTimer;
};
//-----------------------------------------------------------------------------
}
#endif
<|endoftext|> |
<commit_before>#include "config.h"
#include "libs/mpq_libmpq04.h"
int main() {
MPQArchive locale(WOW_INSTALL_DIR"Data/"WOW_LOCALE"/locale-"WOW_LOCALE".MPQ");
MPQFile wmc("DBFilesClient\\WorldMapContinent.dbc");
printf("size: %i\n", wmc.getSize());
return 0;
}
<commit_msg>Extract data from WorldMapContinent.dbc.<commit_after>#include "config.h"
#include "libs/mpq_libmpq04.h"
#include "libs/dbcfile.h"
int main() {
printf("Opening locale.mpq...\n");
MPQArchive locale(WOW_INSTALL_DIR"Data/"WOW_LOCALE"/locale-"WOW_LOCALE".MPQ");
printf("Opening WorldMapContinent.dbc...\n");
DBCFile wmc("DBFilesClient\\WorldMapContinent.dbc");
bool res = wmc.open();
if(!res)
return 1;
printf("Extracting %i continents...\n", wmc.getRecordCount());
for(DBCFile::Iterator itr = wmc.begin(); itr != wmc.end(); ++itr) {
const DBCFile::Record& r(*itr);
int cid = r.getInt(1);
int mid = r.getInt(2);
float x1 = r.getFloat(9);
float y1 = r.getFloat(10);
float x2 = r.getFloat(11);
float y2 = r.getFloat(12);
printf("%i, %i, %g, %g, %g, %g\n", cid, mid, x1, y1, x2, y2);
}
printf("Opening Map.dbc...\n");
DBCFile map("DBFilesClient\\Map.dbc");
return 0;
}
<|endoftext|> |
<commit_before>/*!
* File: guiManager.cpp
*
* Description: Implements gui manager
*/
#include <guiManager.hpp>
#include <gui.hpp>
#include <inputManager.hpp>
#include <assert.h>
/*!
* @fn GUIManager::GUIManager()
* @brief Constructor method for general user interface
* @return A GUIManager object
*/
GUIManager::GUIManager() {
}
/*!
* @fn GUIManager::~GUIManager()
* @brief Destructor method for general user interface
*/
GUIManager::~GUIManager() {
gui_elements.clear();
}
/*!
* @fn void GUIManager::remove_last_gui_element_requested()
* @brief Remove last element if requested
* @return The method returns no param
*/
void GUIManager::remove_last_gui_element_requested() {
//! Remove last element if requested
if (element_pop_requested) {
selected_gui_window = nullptr;
selected_gui_button = nullptr;
gui_elements.pop_back();
}
else {
// Do nothing
}
}
/*!
* @fn void GUIManager::reset_gui_button()
* @brief Reset the button if it is selected
* @return The method returns no param
*/
void GUIManager::reset_gui_button() {
//! Reset the button if it is selected
if (selected_gui_button) {
assert(selected_gui_button != NULL);
selected_gui_button->Reset();
selected_gui_button = nullptr;
}
else {
// Do nothing
}
}
/*!
* @fn void GUIManager::add_stored_element_to_gui()
* @brief If there's element stored puts it in gui elements vector
* @return The method returns no param
*/
void GUIManager::add_stored_element_to_gui() {
//! If there's element stored puts it in gui elements vector
if (stored_gui_element) {
assert(stored_gui_element != NULL);
selected_gui_window = nullptr;
reset_gui_button();
gui_elements.emplace_back(unique_ptr<GUI_Element>(stored_gui_element));
stored_gui_element = nullptr;
}
else {
// Do nothing
}
}
/*!
* @fn void GUIManager::assing_pressed_button_to_current()
* @brief Check if current button is pressed and assings it to current_button_state
* @return The method returns no param
*/
void GUIManager::assing_pressed_button_to_current() {
//! Check if current button is pressed and assings it to current_button_state
if (selected_gui_button) {
GUI_Button* selected_gui_buttonCopy = selected_gui_button;
assert(selected_gui_buttonCopy != NULL);
selected_gui_button = nullptr;
selected_gui_buttonCopy->update();
selected_gui_button = selected_gui_buttonCopy;
current_button_state = selected_gui_button->IsPressed();
}
else {
// Do nothing
}
}
/*!
* @fn void GUIManager::update_gui_elements()
* @brief Updates general user interface
* @return The method returns no param
*/
void GUIManager::update_gui_elements() {
remove_last_gui_element_requested();
add_stored_element_to_gui();
//! If there's no elements in the gui, returns
if (gui_elements.empty()) {
return;
}
else {
// Do nothing
}
element_pop_requested = false;
previous_button_state = current_button_state;
assing_pressed_button_to_current();
gui_elements.back()->update();
}
/*!
* @fn void GUIManager::render_gui_elements()
* @brief Renders general user interface
* @return The method returns no param
*/
void GUIManager::render_gui_elements() {
//! Iterates trough elements of interface to render it
for (auto& it:gui_elements){
//! If elements is visible renders it
if (it->IsVisible()){
it->render();
}
else {
// Do nothing
}
}
}
/*!
* @fn void GUIManager::push_gui_element(GUI_Element* element)
* @brief Push element to the general user interface
* @param GUI_Element* element
* @return The method returns no param
*/
void GUIManager::push_gui_element(GUI_Element* element) {
//! Checks if there's an element alredy stored, and deletes it
if (stored_gui_element) {
delete stored_gui_element;
assert(stored_gui_element == NULL);
}
else {
// Do nothing
}
stored_gui_element = element;
}
/*!
* @fn void GUIManager::request_gui_element_pop(GUI_Element* element)
* @brief Changes element_pop_requested value if requested
* @param GUI_Element* element
* @return The method returns no param
*/
void GUIManager::request_gui_element_pop(GUI_Element* element) {
//! If last object of elements vector is equal to the param
//! Change element_pop_requested value
if (element == gui_elements.back().get()) {
element_pop_requested = true;
}
else {
// Do nothing
}
}
/*!
* @fn void GUIManager::select_gui_window(GUI_Window* window)
* @brief Select window in the general user interface
* @param GUI_Window* window
* @return The method returns no param
*/
void GUIManager::select_gui_window(GUI_Window* window) {
assert(window != NULL);
selected_gui_window = window;
}
/*!
* @fn bool GUIManager::gui_window_is_selected(GUI_Window* window)const
* @brief Return if window is select
* @param GUI_Window* window
* @return true of false
*/
bool GUIManager::gui_window_is_selected(GUI_Window* window)const {
assert(window != NULL);
return window==selected_gui_window;
}
/*!
* @fn int GUIManager::get_gui_selected_window_ID()const
* @brief Get selected window ID of general user interface
* @return integer
*/
int GUIManager::get_gui_selected_window_ID()const {
//If there's a window selected, returns it ID
if (selected_gui_window){
return selected_gui_window->id;
}
else if (gui_elements.size() == 1) {
return 0;
}
else {
return -1;
}
}
/*!
* @fn void GUIManager::select_gui_button(GUI_Button* button)
* @brief Assing button object to selected_gui_button attribute
* @param GUI_Button* button
* @return The method returns no param
*/
void GUIManager::select_gui_button(GUI_Button* button) {
assert(button!= NULL);
selected_gui_button = button;
}
/*!
* @fn bool GUIManager::gui_button_is_selected(GUI_Button* button)const
* @brief Avaliate if button is selected
* @param GUI_Button* button
* @return True of False
*/
bool GUIManager::gui_button_is_selected(GUI_Button* button)const{
assert(button!= NULL);
return button && button==selected_gui_button;
}
/*!
* @fn bool GUIManager::selected_button_is_empty()
* @brief Avaliate if button is empty
* @return True of False
*/
bool GUIManager::selected_button_is_empty()const {
//! Return false for empty selected_gui_button
if (!selected_gui_button) {
return true;
}
else {
return false;
}
}
/*!
* @fn bool GUIManager::selected_button_is_empty()
* @brief Avaliate if button action is different from the param
* @param uint action
* @return True of False
*/
bool GUIManager::is_button_action_different(uint action)const {
//! Return false for action different from the selected button
if (action && selected_gui_button->action != action) {
return true;
}
else {
return false;
}
}
/*!
* @fn bool GUIManager::gui_button_was_pressed(uint action)const
* @brief Avaliate if button was pressed
* @param unsigned int action
* @return True of False
* @warning Simplify return of the method
*/
bool GUIManager::gui_button_was_pressed(uint action)const{
if(selected_button_is_empty() || is_button_action_different(action)) {
return false;
}
else {
return (!previous_button_state && current_button_state);
}
}
/*!
* @fn bool GUIManager::gui_button_was_released(uint action)const
* @brief Avaliate if button was released
* @param unsigned int action
* @return True of False
* @warning Simplify return of the method
*/
bool GUIManager::gui_button_was_released(uint action)const{
if(selected_button_is_empty() || is_button_action_different(action)) {
return false;
}
else {
return (previous_button_state && !current_button_state);
}
}
/*!
* @fn bool GUIManager::gui_button_was_clicked(uint action)const
* @brief Avaliate if button was clicked
* @param unsigned int action
* @return True of False
* @warning Simplify return of the method
*/
bool GUIManager::gui_button_was_clicked(uint action)const{
if(selected_button_is_empty() || is_button_action_different(action)) {
return false;
}
else {
return (previous_button_state && !current_button_state && selected_gui_button->IsHovered());
}
}
/*!
* @fn bool GUIManager::gui_button_is_down(uint action)const
* @brief Avaliate if button is down
* @param unsigned int action
* @return True of False
*/
bool GUIManager::gui_button_is_down(uint action)const{
if(selected_button_is_empty() || is_button_action_different(action)) {
return false;
}
else {
return current_button_state;
}
}
<commit_msg>Apply logging on guiManager.cpp<commit_after>/*!
* File: guiManager.cpp
*
* Description: Implements gui manager
*/
#include <guiManager.hpp>
#include <gui.hpp>
#include <inputManager.hpp>
#include <assert.h>
/*!
* @fn GUIManager::GUIManager()
* @brief Constructor method for general user interface
* @return A GUIManager object
*/
GUIManager::GUIManager() {
LOG_MSG("GUIManager constructor");
LOG_METHOD_CLOSE("GUIManager::GUIManager()","GUIManager");
}
/*!
* @fn GUIManager::~GUIManager()
* @brief Destructor method for general user interface
*/
GUIManager::~GUIManager() {
LOG_MSG("GUIManager destructor");
gui_elements.clear();
LOG_METHOD_CLOSE("GUIManager::~GUIManager()","void");
}
/*!
* @fn void GUIManager::remove_last_gui_element_requested()
* @brief Remove last element if requested
* @return The method returns no param
*/
void GUIManager::remove_last_gui_element_requested() {
LOG_METHOD_START("GUIManager::remove_last_gui_element_requested");
//! Remove last element if requested
if (element_pop_requested) {
selected_gui_window = nullptr;
selected_gui_button = nullptr;
LOG_MSG("Pop gui element back");
gui_elements.pop_back();
}
else {
// Do nothing
}
LOG_METHOD_CLOSE("GUIManager::remove_last_gui_element_requested", "void");
}
/*!
* @fn void GUIManager::reset_gui_button()
* @brief Reset the button if it is selected
* @return The method returns no param
*/
void GUIManager::reset_gui_button() {
LOG_METHOD_START("GUIManager::reset_gui_button");
//! Reset the button if it is selected
if (selected_gui_button) {
assert(selected_gui_button != NULL);
LOG_MSG("Reset gui button");
selected_gui_button->Reset();
selected_gui_button = nullptr;
}
else {
// Do nothing
}
LOG_METHOD_CLOSE("GUIManager::reset_gui_button","void");
}
/*!
* @fn void GUIManager::add_stored_element_to_gui()
* @brief If there's element stored puts it in gui elements vector
* @return The method returns no param
*/
void GUIManager::add_stored_element_to_gui() {
LOG_METHOD_START("GUIManager::add_stored_element_to_gui");
//! If there's element stored puts it in gui elements vector
if (stored_gui_element) {
assert(stored_gui_element != NULL);
selected_gui_window = nullptr;
reset_gui_button();
gui_elements.emplace_back(unique_ptr<GUI_Element>(stored_gui_element));
stored_gui_element = nullptr;
}
else {
// Do nothing
}
LOG_METHOD_CLOSE("GUIManager::add_stored_element_to_gui","void");
}
/*!
* @fn void GUIManager::assing_pressed_button_to_current()
* @brief Check if current button is pressed and assings it to current_button_state
* @return The method returns no param
*/
void GUIManager::assing_pressed_button_to_current() {
LOG_METHOD_START("GUIManager::assing_pressed_button_to_current");
//! Check if current button is pressed and assings it to current_button_state
if (selected_gui_button) {
GUI_Button* selected_gui_buttonCopy = selected_gui_button;
assert(selected_gui_buttonCopy != NULL);
selected_gui_button = nullptr;
selected_gui_buttonCopy->update();
selected_gui_button = selected_gui_buttonCopy;
current_button_state = selected_gui_button->IsPressed();
LOG_VARIABLE("current_button_state",current_button_state);
}
else {
// Do nothing
}
LOG_METHOD_CLOSE("GUIManager::assing_pressed_button_to_current","void");
}
/*!
* @fn void GUIManager::update_gui_elements()
* @brief Updates general user interface
* @return The method returns no param
*/
void GUIManager::update_gui_elements() {
LOG_METHOD_START("GUIManager::update_gui_elements");
remove_last_gui_element_requested();
add_stored_element_to_gui();
//! If there's no elements in the gui, returns
if (gui_elements.empty()) {
return;
}
else {
// Do nothing
}
element_pop_requested = false;
previous_button_state = current_button_state;
assing_pressed_button_to_current();
gui_elements.back()->update();
LOG_METHOD_CLOSE("GUIManager::update_gui_elements","void");
}
/*!
* @fn void GUIManager::render_gui_elements()
* @brief Renders general user interface
* @return The method returns no param
*/
void GUIManager::render_gui_elements() {
LOG_METHOD_START("GUIManager::render_gui_elements");
//! Iterates trough elements of interface to render it
for (auto& it:gui_elements){
//! If elements is visible renders it
if (it->IsVisible()){
LOG_MSG("Render gui element");
it->render();
}
else {
// Do nothing
}
}
LOG_METHOD_CLOSE("GUIManager::render_gui_elements","void");
}
/*!
* @fn void GUIManager::push_gui_element(GUI_Element* element)
* @brief Push element to the general user interface
* @param GUI_Element* element
* @return The method returns no param
*/
void GUIManager::push_gui_element(GUI_Element* element) {
LOG_METHOD_START("GUIManager::push_gui_element");
//! Checks if there's an element alredy stored, and deletes it
if (stored_gui_element) {
LOG_MSG("Delete stored gui element");
delete stored_gui_element;
assert(stored_gui_element == NULL);
}
else {
// Do nothing
}
stored_gui_element = element;
LOG_METHOD_CLOSE("GUIManager::push_gui_element","void");
}
/*!
* @fn void GUIManager::request_gui_element_pop(GUI_Element* element)
* @brief Changes element_pop_requested value if requested
* @param GUI_Element* element
* @return The method returns no param
*/
void GUIManager::request_gui_element_pop(GUI_Element* element) {
LOG_METHOD_START("GUIManager::request_gui_element_pop");
//! If last object of elements vector is equal to the param
//! Change element_pop_requested value
if (element == gui_elements.back().get()) {
element_pop_requested = true;
}
else {
// Do nothing
}
LOG_METHOD_CLOSE("GUIManager::request_gui_element_pop","void");
}
/*!
* @fn void GUIManager::select_gui_window(GUI_Window* window)
* @brief Select window in the general user interface
* @param GUI_Window* window
* @return The method returns no param
*/
void GUIManager::select_gui_window(GUI_Window* window) {
LOG_METHOD_START("GUIManager::select_gui_window");
assert(window != NULL);
selected_gui_window = window;
LOG_METHOD_CLOSE("GUIManager::select_gui_window","void");
}
/*!
* @fn bool GUIManager::gui_window_is_selected(GUI_Window* window)const
* @brief Return if window is select
* @param GUI_Window* window
* @return true of false
*/
bool GUIManager::gui_window_is_selected(GUI_Window* window)const {
LOG_METHOD_START("GUIManager::gui_window_is_selected");
assert(window != NULL);
return window==selected_gui_window;
LOG_METHOD_CLOSE("GUIManager::gui_window_is_selected","void");
}
/*!
* @fn int GUIManager::get_gui_selected_window_ID()const
* @brief Get selected window ID of general user interface
* @return integer
*/
int GUIManager::get_gui_selected_window_ID()const {
LOG_METHOD_START("GUIManager::get_gui_selected_window_ID");
//If there's a window selected, returns it ID
if (selected_gui_window){
return selected_gui_window->id;
}
else if (gui_elements.size() == 1) {
return 0;
}
else {
return -1;
}
LOG_METHOD_CLOSE("GUIManager::get_gui_selected_window_ID","void");
}
/*!
* @fn void GUIManager::select_gui_button(GUI_Button* button)
* @brief Assing button object to selected_gui_button attribute
* @param GUI_Button* button
* @return The method returns no param
*/
void GUIManager::select_gui_button(GUI_Button* button) {
LOG_METHOD_START("GUIManager::select_gui_button");
assert(button!= NULL);
selected_gui_button = button;
LOG_METHOD_CLOSE("GUIManager::select_gui_button","void");
}
/*!
* @fn bool GUIManager::gui_button_is_selected(GUI_Button* button)const
* @brief Avaliate if button is selected
* @param GUI_Button* button
* @return True of False
*/
bool GUIManager::gui_button_is_selected(GUI_Button* button)const{
LOG_METHOD_START("GUIManager::gui_button_is_selected");
assert(button!= NULL);
LOG_METHOD_CLOSE("GUIManager::gui_button_is_selected","bool");
return button && button==selected_gui_button;
}
/*!
* @fn bool GUIManager::selected_button_is_empty()
* @brief Avaliate if button is empty
* @return True of False
*/
bool GUIManager::selected_button_is_empty()const {
LOG_METHOD_START("GUIManager::selected_button_is_empty");
//! Return false for empty selected_gui_button
if (!selected_gui_button) {
LOG_MSG("Selected gui button is empty");
return true;
}
else {
LOG_MSG("Selected gui button is not empty");
return false;
}
LOG_METHOD_CLOSE("GUIManager::selected_button_is_empty","bool");
}
/*!
* @fn bool GUIManager::selected_button_is_empty()
* @brief Avaliate if button action is different from the param
* @param uint action
* @return True of False
*/
bool GUIManager::is_button_action_different(uint action)const {
LOG_METHOD_START("GUIManager::is_button_action_different");
//! Return false for action different from the selected button
if (action && selected_gui_button->action != action) {
LOG_MSG("Selected gui button action is different");
return true;
}
else {
LOG_MSG("Selected gui button action is not different");
return false;
}
LOG_METHOD_CLOSE("GUIManager::is_button_action_different","bool");
}
/*!
* @fn bool GUIManager::gui_button_was_pressed(uint action)const
* @brief Avaliate if button was pressed
* @param unsigned int action
* @return True of False
* @warning Simplify return of the method
*/
bool GUIManager::gui_button_was_pressed(uint action)const{
LOG_METHOD_START("GUIManager::gui_button_was_pressed");
if(selected_button_is_empty() || is_button_action_different(action)) {
LOG_MSG("Gui button was not pressed");
return false;
}
else {
return (!previous_button_state && current_button_state);
}
LOG_METHOD_CLOSE("GUIManager::gui_button_was_pressed","bool");
}
/*!
* @fn bool GUIManager::gui_button_was_released(uint action)const
* @brief Avaliate if button was released
* @param unsigned int action
* @return True of False
* @warning Simplify return of the method
*/
bool GUIManager::gui_button_was_released(uint action)const{
LOG_METHOD_START("GUIManager::gui_button_was_released");
if(selected_button_is_empty() || is_button_action_different(action)) {
LOG_MSG("Gui button was not released");
return false;
}
else {
LOG_MSG("Gui button was released");
return (previous_button_state && !current_button_state);
}
LOG_METHOD_CLOSE("GUIManager::gui_button_was_released","bool");
}
/*!
* @fn bool GUIManager::gui_button_was_clicked(uint action)const
* @brief Avaliate if button was clicked
* @param unsigned int action
* @return True of False
* @warning Simplify return of the method
*/
bool GUIManager::gui_button_was_clicked(uint action)const{
LOG_METHOD_START("GUIManager::gui_button_was_clicked");
if(selected_button_is_empty() || is_button_action_different(action)) {
LOG_MSG("Gui button was not clicked");
return false;
}
else {
LOG_MSG("Gui button was clicked");
return (previous_button_state && !current_button_state && selected_gui_button->IsHovered());
}
LOG_METHOD_CLOSE("GUIManager::gui_button_was_clicked","bool");
}
/*!
* @fn bool GUIManager::gui_button_is_down(uint action)const
* @brief Avaliate if button is down
* @param unsigned int action
* @return True of False
*/
bool GUIManager::gui_button_is_down(uint action)const{
LOG_METHOD_START("GUIManager::gui_button_is_down");
if(selected_button_is_empty() || is_button_action_different(action)) {
LOG_MSG("Gui button is not down");
return false;
}
else {
LOG_MSG("Gui button is down");
return current_button_state;
}
LOG_METHOD_CLOSE("GUIManager::gui_button_is_down","bool");
}
<|endoftext|> |
<commit_before>#pragma once
#include <cstdint>
#include <string>
#include <boost/asio.hpp>
#include "blackhole/utils/unique.hpp"
#include "backend.hpp"
#include "connect.hpp"
namespace blackhole {
namespace sink {
namespace socket {
template<>
class boost_backend_t<boost::asio::ip::tcp> {
typedef boost::asio::ip::tcp Protocol;
const std::string m_host;
const std::uint16_t m_port;
boost::asio::io_service m_io_service;
std::unique_ptr<Protocol::socket> m_socket;
public:
static const char* name() {
return "tcp";
}
boost_backend_t(const std::string& host, std::uint16_t port) :
m_host(host),
m_port(port),
m_socket(initialize(m_io_service, host, port))
{
}
ssize_t write(const std::string& message) {
if (!m_socket) {
m_socket = initialize(m_io_service, m_host, m_port);
}
try {
return m_socket->write_some(boost::asio::buffer(message.data(), message.size()));
} catch (const boost::system::system_error&) {
m_socket.release();
std::rethrow_exception(std::current_exception());
}
}
private:
static inline
std::unique_ptr<Protocol::socket>
initialize(boost::asio::io_service& io_service, const std::string& host, std::uint16_t port) {
std::unique_ptr<Protocol::socket> socket = utils::make_unique<Protocol::socket>(io_service);
connect<Protocol>(io_service, *socket, host, port);
return socket;
}
};
} // namespace socket
} // namespace sink
} // namespace blackhole
<commit_msg>[Aux] Code reordering.<commit_after>#pragma once
#include <cstdint>
#include <string>
#include <boost/asio.hpp>
#include "blackhole/utils/unique.hpp"
#include "backend.hpp"
#include "connect.hpp"
namespace blackhole {
namespace sink {
namespace socket {
template<>
class boost_backend_t<boost::asio::ip::tcp> {
typedef boost::asio::ip::tcp Protocol;
const std::string m_host;
const std::uint16_t m_port;
boost::asio::io_service m_io_service;
std::unique_ptr<Protocol::socket> m_socket;
public:
boost_backend_t(const std::string& host, std::uint16_t port) :
m_host(host),
m_port(port),
m_socket(initialize(m_io_service, host, port))
{}
static const char* name() {
return "tcp";
}
ssize_t write(const std::string& message) {
if (!m_socket) {
m_socket = initialize(m_io_service, m_host, m_port);
}
try {
return m_socket->write_some(boost::asio::buffer(message.data(), message.size()));
} catch (const boost::system::system_error&) {
m_socket.release();
std::rethrow_exception(std::current_exception());
}
}
private:
static inline
std::unique_ptr<Protocol::socket>
initialize(boost::asio::io_service& io_service, const std::string& host, std::uint16_t port) {
std::unique_ptr<Protocol::socket> socket = utils::make_unique<Protocol::socket>(io_service);
connect<Protocol>(io_service, *socket, host, port);
return socket;
}
};
} // namespace socket
} // namespace sink
} // namespace blackhole
<|endoftext|> |
<commit_before>/* _______ __ __ __ ______ __ __ _______ __ __
* / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\
* / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / /
* / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / /
* / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / /
* /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ /
* \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/
*
* Copyright (c) 2004, 2005, 2006, 2007 Olof Naessn and Per Larsson
*
* Js_./
* Per Larsson a.k.a finalman _RqZ{a<^_aa
* Olof Naessn a.k.a jansem/yakslem _asww7!uY`> )\a//
* _Qhm`] _f "'c 1!5m
* Visit: http://guichan.darkbits.org )Qk<P ` _: :+' .' "{[
* .)j(] .d_/ '-( P . S
* License: (BSD) <Td/Z <fP"5(\"??"\a. .L
* Redistribution and use in source and _dV>ws?a-?' ._/L #'
* binary forms, with or without )4d[#7r, . ' )d`)[
* modification, are permitted provided _Q-5'5W..j/?' -?!\)cam'
* that the following conditions are met: j<<WP+k/);. _W=j f
* 1. Redistributions of source code must .$%w\/]Q . ."' . mj$
* retain the above copyright notice, ]E.pYY(Q]>. a J@\
* this list of conditions and the j(]1u<sE"L,. . ./^ ]{a
* following disclaimer. 4'_uomm\. )L);-4 (3=
* 2. Redistributions in binary form must )_]X{Z('a_"a7'<a"a, ]"[
* reproduce the above copyright notice, #}<]m7`Za??4,P-"'7. ).m
* this list of conditions and the ]d2e)Q(<Q( ?94 b- LQ/
* following disclaimer in the <B!</]C)d_, '(<' .f. =C+m
* documentation and/or other materials .Z!=J ]e []('-4f _ ) -.)m]'
* provided with the distribution. .w[5]' _[ /.)_-"+? _/ <W"
* 3. Neither the name of Guichan nor the :$we` _! + _/ . j?
* names of its contributors may be used =3)= _f (_yQmWW$#( "
* to endorse or promote products derived - W, sQQQQmZQ#Wwa]..
* from this software without specific (js, \[QQW$QWW#?!V"".
* prior written permission. ]y:.<\.. .
* -]n w/ ' [.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT )/ )/ !
* HOLDERS AND CONTRIBUTORS "AS IS" AND ANY < (; sac , '
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ]^ .- %
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF c < r
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR aga< <La
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 5% )P'-3L
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR _bQf` y`..)a
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ,J?4P'.P"_(\?d'.,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES _Pa,)!f/<[]/ ?"
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT _2-..:. .r+_,.. .
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ?a.<%"' " -'.a_ _,
* 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.
*/
/*
* For comments regarding functions please see the header file.
*/
#include "guichan/widgets/listbox.hpp"
#include "guichan/basiccontainer.hpp"
#include "guichan/font.hpp"
#include "guichan/graphics.hpp"
#include "guichan/key.hpp"
#include "guichan/listmodel.hpp"
#include "guichan/mouseinput.hpp"
#include "guichan/selectionlistener.hpp"
namespace gcn
{
ListBox::ListBox()
: mSelected(-1),
mListModel(NULL),
mWrappingEnabled(false)
{
setWidth(100);
setFocusable(true);
addMouseListener(this);
addKeyListener(this);
}
ListBox::ListBox(ListModel *listModel)
: mSelected(-1),
mWrappingEnabled(false)
{
setWidth(100);
setListModel(listModel);
setFocusable(true);
addMouseListener(this);
addKeyListener(this);
}
void ListBox::draw(Graphics* graphics)
{
graphics->setColor(getBackgroundColor());
graphics->fillRectangle(Rectangle(0, 0, getWidth(), getHeight()));
if (mListModel == NULL)
{
return;
}
graphics->setColor(getForegroundColor());
graphics->setFont(getFont());
int i, fontHeight;
int y = 0;
fontHeight = getFont()->getHeight();
/**
* @todo Check cliprects so we do not have to iterate over elements in the list model
*/
for (i = 0; i < mListModel->getNumberOfElements(); ++i)
{
if (i == mSelected)
{
graphics->setColor(getSelectionColor());
graphics->fillRectangle(Rectangle(0, y, getWidth(), fontHeight));
graphics->setColor(getForegroundColor());
}
graphics->drawText(mListModel->getElementAt(i), 1, y);
y += fontHeight;
}
}
void ListBox::logic()
{
adjustSize();
}
int ListBox::getSelected() const
{
return mSelected;
}
void ListBox::setSelected(int selected)
{
if (mListModel == NULL)
{
mSelected = -1;
}
else
{
if (selected < 0)
{
mSelected = -1;
}
else if (selected >= mListModel->getNumberOfElements())
{
mSelected = mListModel->getNumberOfElements() - 1;
}
else
{
mSelected = selected;
}
Widget *par = getParent();
if (par == NULL)
{
return;
}
Rectangle scroll;
if (mSelected < 0)
{
scroll.y = 0;
}
else
{
scroll.y = getFont()->getHeight() * mSelected;
}
scroll.height = getFont()->getHeight();
par->showWidgetPart(this, scroll);
}
distributeValueChangedEvent();
}
void ListBox::keyPressed(KeyEvent& keyEvent)
{
Key key = keyEvent.getKey();
if (key.getValue() == Key::ENTER || key.getValue() == Key::SPACE)
{
generateAction();
keyEvent.consume();
}
else if (key.getValue() == Key::UP)
{
setSelected(mSelected - 1);
if (mSelected == -1)
{
if (mWrappingEnabled)
{
setSelected(getListModel()->getNumberOfElements() - 1);
}
else
{
setSelected(0);
}
}
keyEvent.consume();
}
else if (key.getValue() == Key::DOWN)
{
if (mWrappingEnabled
&& getSelected() == getListModel()->getNumberOfElements() - 1)
{
setSelected(0);
}
else
{
setSelected(getSelected() + 1);
}
keyEvent.consume();
}
else if (key.getValue() == Key::HOME)
{
setSelected(0);
keyEvent.consume();
}
else if (key.getValue() == Key::END)
{
setSelected(getListModel()->getNumberOfElements() - 1);
keyEvent.consume();
}
}
void ListBox::mousePressed(MouseEvent& mouseEvent)
{
if (mouseEvent.getButton() == MouseEvent::LEFT)
{
setSelected(mouseEvent.getY() / getFont()->getHeight());
generateAction();
}
}
void ListBox::mouseWheelMovedUp(MouseEvent& mouseEvent)
{
if (isFocused())
{
if (getSelected() > 0 )
{
setSelected(getSelected() - 1);
}
mouseEvent.consume();
}
}
void ListBox::mouseWheelMovedDown(MouseEvent& mouseEvent)
{
if (isFocused())
{
setSelected(getSelected() + 1);
mouseEvent.consume();
}
}
void ListBox::mouseDragged(MouseEvent& mouseEvent)
{
mouseEvent.consume();
}
void ListBox::setListModel(ListModel *listModel)
{
mSelected = -1;
mListModel = listModel;
adjustSize();
}
ListModel* ListBox::getListModel()
{
return mListModel;
}
void ListBox::adjustSize()
{
if (mListModel != NULL)
{
setHeight(getFont()->getHeight() * mListModel->getNumberOfElements());
}
}
bool ListBox::isWrappingEnabled() const
{
return mWrappingEnabled;
}
void ListBox::setWrappingEnabled(bool wrappingEnabled)
{
mWrappingEnabled = wrappingEnabled;
}
void ListBox::addSelectionListener(SelectionListener* selectionListener)
{
mSelectionListeners.push_back(selectionListener);
}
void ListBox::removeSelectionListener(SelectionListener* selectionListener)
{
mSelectionListeners.remove(selectionListener);
}
void ListBox::distributeValueChangedEvent()
{
SelectionListenerIterator iter;
for (iter = mSelectionListeners.begin(); iter != mSelectionListeners.end(); ++iter)
{
SelectionEvent event(this);
(*iter)->valueChanged(event);
}
}
}
<commit_msg>List box has been optimized to only draw the items in the list that's actually visible.<commit_after>/* _______ __ __ __ ______ __ __ _______ __ __
* / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\
* / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / /
* / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / /
* / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / /
* /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ /
* \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/
*
* Copyright (c) 2004, 2005, 2006, 2007 Olof Naessn and Per Larsson
*
* Js_./
* Per Larsson a.k.a finalman _RqZ{a<^_aa
* Olof Naessn a.k.a jansem/yakslem _asww7!uY`> )\a//
* _Qhm`] _f "'c 1!5m
* Visit: http://guichan.darkbits.org )Qk<P ` _: :+' .' "{[
* .)j(] .d_/ '-( P . S
* License: (BSD) <Td/Z <fP"5(\"??"\a. .L
* Redistribution and use in source and _dV>ws?a-?' ._/L #'
* binary forms, with or without )4d[#7r, . ' )d`)[
* modification, are permitted provided _Q-5'5W..j/?' -?!\)cam'
* that the following conditions are met: j<<WP+k/);. _W=j f
* 1. Redistributions of source code must .$%w\/]Q . ."' . mj$
* retain the above copyright notice, ]E.pYY(Q]>. a J@\
* this list of conditions and the j(]1u<sE"L,. . ./^ ]{a
* following disclaimer. 4'_uomm\. )L);-4 (3=
* 2. Redistributions in binary form must )_]X{Z('a_"a7'<a"a, ]"[
* reproduce the above copyright notice, #}<]m7`Za??4,P-"'7. ).m
* this list of conditions and the ]d2e)Q(<Q( ?94 b- LQ/
* following disclaimer in the <B!</]C)d_, '(<' .f. =C+m
* documentation and/or other materials .Z!=J ]e []('-4f _ ) -.)m]'
* provided with the distribution. .w[5]' _[ /.)_-"+? _/ <W"
* 3. Neither the name of Guichan nor the :$we` _! + _/ . j?
* names of its contributors may be used =3)= _f (_yQmWW$#( "
* to endorse or promote products derived - W, sQQQQmZQ#Wwa]..
* from this software without specific (js, \[QQW$QWW#?!V"".
* prior written permission. ]y:.<\.. .
* -]n w/ ' [.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT )/ )/ !
* HOLDERS AND CONTRIBUTORS "AS IS" AND ANY < (; sac , '
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ]^ .- %
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF c < r
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR aga< <La
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 5% )P'-3L
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR _bQf` y`..)a
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ,J?4P'.P"_(\?d'.,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES _Pa,)!f/<[]/ ?"
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT _2-..:. .r+_,.. .
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ?a.<%"' " -'.a_ _,
* 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.
*/
/*
* For comments regarding functions please see the header file.
*/
#include "guichan/widgets/listbox.hpp"
#include "guichan/basiccontainer.hpp"
#include "guichan/font.hpp"
#include "guichan/graphics.hpp"
#include "guichan/key.hpp"
#include "guichan/listmodel.hpp"
#include "guichan/mouseinput.hpp"
#include "guichan/selectionlistener.hpp"
namespace gcn
{
ListBox::ListBox()
: mSelected(-1),
mListModel(NULL),
mWrappingEnabled(false)
{
setWidth(100);
setFocusable(true);
addMouseListener(this);
addKeyListener(this);
}
ListBox::ListBox(ListModel *listModel)
: mSelected(-1),
mWrappingEnabled(false)
{
setWidth(100);
setListModel(listModel);
setFocusable(true);
addMouseListener(this);
addKeyListener(this);
}
void ListBox::draw(Graphics* graphics)
{
graphics->setColor(getBackgroundColor());
graphics->fillRectangle(Rectangle(0, 0, getWidth(), getHeight()));
if (mListModel == NULL)
{
return;
}
graphics->setColor(getForegroundColor());
graphics->setFont(getFont());
const ClipRectangle currentClipArea = graphics->getCurrentClipArea();
int fontHeight = getFont()->getHeight();
int i = currentClipArea.y / getFont()->getHeight();
int end = (currentClipArea.y + currentClipArea.height) / getFont()->getHeight();
int y = 0;
for (i = 0; i < end; ++i)
{
if (i == mSelected)
{
graphics->setColor(getSelectionColor());
graphics->fillRectangle(Rectangle(0, y, getWidth(), fontHeight));
graphics->setColor(getForegroundColor());
}
graphics->drawText(mListModel->getElementAt(i), 1, y);
y += fontHeight;
}
}
void ListBox::logic()
{
adjustSize();
}
int ListBox::getSelected() const
{
return mSelected;
}
void ListBox::setSelected(int selected)
{
if (mListModel == NULL)
{
mSelected = -1;
}
else
{
if (selected < 0)
{
mSelected = -1;
}
else if (selected >= mListModel->getNumberOfElements())
{
mSelected = mListModel->getNumberOfElements() - 1;
}
else
{
mSelected = selected;
}
Widget *par = getParent();
if (par == NULL)
{
return;
}
Rectangle scroll;
if (mSelected < 0)
{
scroll.y = 0;
}
else
{
scroll.y = getFont()->getHeight() * mSelected;
}
scroll.height = getFont()->getHeight();
par->showWidgetPart(this, scroll);
}
distributeValueChangedEvent();
}
void ListBox::keyPressed(KeyEvent& keyEvent)
{
Key key = keyEvent.getKey();
if (key.getValue() == Key::ENTER || key.getValue() == Key::SPACE)
{
generateAction();
keyEvent.consume();
}
else if (key.getValue() == Key::UP)
{
setSelected(mSelected - 1);
if (mSelected == -1)
{
if (mWrappingEnabled)
{
setSelected(getListModel()->getNumberOfElements() - 1);
}
else
{
setSelected(0);
}
}
keyEvent.consume();
}
else if (key.getValue() == Key::DOWN)
{
if (mWrappingEnabled
&& getSelected() == getListModel()->getNumberOfElements() - 1)
{
setSelected(0);
}
else
{
setSelected(getSelected() + 1);
}
keyEvent.consume();
}
else if (key.getValue() == Key::HOME)
{
setSelected(0);
keyEvent.consume();
}
else if (key.getValue() == Key::END)
{
setSelected(getListModel()->getNumberOfElements() - 1);
keyEvent.consume();
}
}
void ListBox::mousePressed(MouseEvent& mouseEvent)
{
if (mouseEvent.getButton() == MouseEvent::LEFT)
{
setSelected(mouseEvent.getY() / getFont()->getHeight());
generateAction();
}
}
void ListBox::mouseWheelMovedUp(MouseEvent& mouseEvent)
{
if (isFocused())
{
if (getSelected() > 0 )
{
setSelected(getSelected() - 1);
}
mouseEvent.consume();
}
}
void ListBox::mouseWheelMovedDown(MouseEvent& mouseEvent)
{
if (isFocused())
{
setSelected(getSelected() + 1);
mouseEvent.consume();
}
}
void ListBox::mouseDragged(MouseEvent& mouseEvent)
{
mouseEvent.consume();
}
void ListBox::setListModel(ListModel *listModel)
{
mSelected = -1;
mListModel = listModel;
adjustSize();
}
ListModel* ListBox::getListModel()
{
return mListModel;
}
void ListBox::adjustSize()
{
if (mListModel != NULL)
{
setHeight(getFont()->getHeight() * mListModel->getNumberOfElements());
}
}
bool ListBox::isWrappingEnabled() const
{
return mWrappingEnabled;
}
void ListBox::setWrappingEnabled(bool wrappingEnabled)
{
mWrappingEnabled = wrappingEnabled;
}
void ListBox::addSelectionListener(SelectionListener* selectionListener)
{
mSelectionListeners.push_back(selectionListener);
}
void ListBox::removeSelectionListener(SelectionListener* selectionListener)
{
mSelectionListeners.remove(selectionListener);
}
void ListBox::distributeValueChangedEvent()
{
SelectionListenerIterator iter;
for (iter = mSelectionListeners.begin(); iter != mSelectionListeners.end(); ++iter)
{
SelectionEvent event(this);
(*iter)->valueChanged(event);
}
}
}
<|endoftext|> |
<commit_before>/* _______ __ __ __ ______ __ __ _______ __ __
* / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\
* / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / /
* / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / /
* / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / /
* /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ /
* \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/
*
* Copyright (c) 2004, 2005, 2006 Olof Naessn and Per Larsson
*
* Js_./
* Per Larsson a.k.a finalman _RqZ{a<^_aa
* Olof Naessn a.k.a jansem/yakslem _asww7!uY`> )\a//
* _Qhm`] _f "'c 1!5m
* Visit: http://guichan.darkbits.org )Qk<P ` _: :+' .' "{[
* .)j(] .d_/ '-( P . S
* License: (BSD) <Td/Z <fP"5(\"??"\a. .L
* Redistribution and use in source and _dV>ws?a-?' ._/L #'
* binary forms, with or without )4d[#7r, . ' )d`)[
* modification, are permitted provided _Q-5'5W..j/?' -?!\)cam'
* that the following conditions are met: j<<WP+k/);. _W=j f
* 1. Redistributions of source code must .$%w\/]Q . ."' . mj$
* retain the above copyright notice, ]E.pYY(Q]>. a J@\
* this list of conditions and the j(]1u<sE"L,. . ./^ ]{a
* following disclaimer. 4'_uomm\. )L);-4 (3=
* 2. Redistributions in binary form must )_]X{Z('a_"a7'<a"a, ]"[
* reproduce the above copyright notice, #}<]m7`Za??4,P-"'7. ).m
* this list of conditions and the ]d2e)Q(<Q( ?94 b- LQ/
* following disclaimer in the <B!</]C)d_, '(<' .f. =C+m
* documentation and/or other materials .Z!=J ]e []('-4f _ ) -.)m]'
* provided with the distribution. .w[5]' _[ /.)_-"+? _/ <W"
* 3. Neither the name of Guichan nor the :$we` _! + _/ . j?
* names of its contributors may be used =3)= _f (_yQmWW$#( "
* to endorse or promote products derived - W, sQQQQmZQ#Wwa]..
* from this software without specific (js, \[QQW$QWW#?!V"".
* prior written permission. ]y:.<\.. .
* -]n w/ ' [.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT )/ )/ !
* HOLDERS AND CONTRIBUTORS "AS IS" AND ANY < (; sac , '
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ]^ .- %
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF c < r
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR aga< <La
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 5% )P'-3L
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR _bQf` y`..)a
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ,J?4P'.P"_(\?d'.,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES _Pa,)!f/<[]/ ?"
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT _2-..:. .r+_,.. .
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ?a.<%"' " -'.a_ _,
* 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.
*/
/*
* For comments regarding functions please see the header file.
*/
#include "guichan/widgets/listbox.hpp"
#include "guichan/basiccontainer.hpp"
#include "guichan/font.hpp"
#include "guichan/graphics.hpp"
#include "guichan/key.hpp"
#include "guichan/listmodel.hpp"
#include "guichan/mouseinput.hpp"
namespace gcn
{
ListBox::ListBox()
{
mSelected = -1;
mListModel = NULL;
mWrappingKeyboardSelection = false;
setWidth(100);
setFocusable(true);
addMouseListener(this);
addKeyListener(this);
}
ListBox::ListBox(ListModel *listModel)
{
mSelected = -1;
mWrappingKeyboardSelection = false;
setWidth(100);
setListModel(listModel);
setFocusable(true);
addMouseListener(this);
addKeyListener(this);
}
void ListBox::draw(Graphics* graphics)
{
graphics->setColor(getBackgroundColor());
graphics->fillRectangle(Rectangle(0, 0, getWidth(), getHeight()));
if (mListModel == NULL)
{
return;
}
graphics->setColor(getForegroundColor());
graphics->setFont(getFont());
int i, fontHeight;
int y = 0;
fontHeight = getFont()->getHeight();
/**
* @todo Check cliprects so we do not have to iterate over elements in the list model
*/
for (i = 0; i < mListModel->getNumberOfElements(); ++i)
{
if (i == mSelected)
{
graphics->drawRectangle(Rectangle(0, y, getWidth(), fontHeight));
}
graphics->drawText(mListModel->getElementAt(i), 1, y);
y += fontHeight;
}
}
void ListBox::drawBorder(Graphics* graphics)
{
Color faceColor = getBaseColor();
Color highlightColor, shadowColor;
int alpha = getBaseColor().a;
int width = getWidth() + getBorderSize() * 2 - 1;
int height = getHeight() + getBorderSize() * 2 - 1;
highlightColor = faceColor + 0x303030;
highlightColor.a = alpha;
shadowColor = faceColor - 0x303030;
shadowColor.a = alpha;
unsigned int i;
for (i = 0; i < getBorderSize(); ++i)
{
graphics->setColor(shadowColor);
graphics->drawLine(i,i, width - i, i);
graphics->drawLine(i,i + 1, i, height - i - 1);
graphics->setColor(highlightColor);
graphics->drawLine(width - i,i + 1, width - i, height - i);
graphics->drawLine(i,height - i, width - i - 1, height - i);
}
}
void ListBox::logic()
{
adjustSize();
}
int ListBox::getSelected()
{
return mSelected;
}
void ListBox::setSelected(int selected)
{
if (mListModel == NULL)
{
mSelected = -1;
}
else
{
if (selected < 0)
{
mSelected = -1;
}
else if (selected >= mListModel->getNumberOfElements())
{
mSelected = mListModel->getNumberOfElements() - 1;
}
else
{
mSelected = selected;
}
BasicContainer *par = getParent();
if (par == NULL)
{
return;
}
Rectangle scroll;
if (mSelected < 0)
{
scroll.y = 0;
}
else
{
scroll.y = getFont()->getHeight() * mSelected;
}
scroll.y = getFont()->getHeight() * mSelected;
scroll.height = getFont()->getHeight();
par->showWidgetPart(this, scroll);
}
}
void ListBox::keyPress(const Key& key)
{
if (key.getValue() == Key::ENTER || key.getValue() == Key::SPACE)
{
generateAction();
}
else if (key.getValue() == Key::UP)
{
setSelected(mSelected - 1);
if (mSelected == -1)
{
if (isWrappingKeyboardSelection())
{
setSelected(getListModel()->getNumberOfElements() - 1);
}
else
{
setSelected(0);
}
}
}
else if (key.getValue() == Key::DOWN)
{
if (isWrappingKeyboardSelection()
&& getSelected() == getListModel()->getNumberOfElements() - 1)
{
setSelected(0);
}
else
{
setSelected(getSelected() + 1);
}
}
}
void ListBox::mousePress(int x, int y, int button)
{
if (button == MouseInput::LEFT && hasMouse())
{
setSelected(y / getFont()->getHeight());
generateAction();
}
}
void ListBox::setListModel(ListModel *listModel)
{
mSelected = -1;
mListModel = listModel;
adjustSize();
}
ListModel* ListBox::getListModel()
{
return mListModel;
}
void ListBox::adjustSize()
{
if (mListModel != NULL)
{
setHeight(getFont()->getHeight() * mListModel->getNumberOfElements());
}
}
bool ListBox::isWrappingKeyboardSelection()
{
return mWrappingKeyboardSelection;
}
void ListBox::setWrappingKeyboardSelection(bool wrapping)
{
mWrappingKeyboardSelection = wrapping;
}
}
<commit_msg>A bug with using Container::showWidgetPart incorrectly has been fixed.<commit_after>/* _______ __ __ __ ______ __ __ _______ __ __
* / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\
* / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / /
* / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / /
* / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / /
* /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ /
* \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/
*
* Copyright (c) 2004, 2005, 2006 Olof Naessn and Per Larsson
*
* Js_./
* Per Larsson a.k.a finalman _RqZ{a<^_aa
* Olof Naessn a.k.a jansem/yakslem _asww7!uY`> )\a//
* _Qhm`] _f "'c 1!5m
* Visit: http://guichan.darkbits.org )Qk<P ` _: :+' .' "{[
* .)j(] .d_/ '-( P . S
* License: (BSD) <Td/Z <fP"5(\"??"\a. .L
* Redistribution and use in source and _dV>ws?a-?' ._/L #'
* binary forms, with or without )4d[#7r, . ' )d`)[
* modification, are permitted provided _Q-5'5W..j/?' -?!\)cam'
* that the following conditions are met: j<<WP+k/);. _W=j f
* 1. Redistributions of source code must .$%w\/]Q . ."' . mj$
* retain the above copyright notice, ]E.pYY(Q]>. a J@\
* this list of conditions and the j(]1u<sE"L,. . ./^ ]{a
* following disclaimer. 4'_uomm\. )L);-4 (3=
* 2. Redistributions in binary form must )_]X{Z('a_"a7'<a"a, ]"[
* reproduce the above copyright notice, #}<]m7`Za??4,P-"'7. ).m
* this list of conditions and the ]d2e)Q(<Q( ?94 b- LQ/
* following disclaimer in the <B!</]C)d_, '(<' .f. =C+m
* documentation and/or other materials .Z!=J ]e []('-4f _ ) -.)m]'
* provided with the distribution. .w[5]' _[ /.)_-"+? _/ <W"
* 3. Neither the name of Guichan nor the :$we` _! + _/ . j?
* names of its contributors may be used =3)= _f (_yQmWW$#( "
* to endorse or promote products derived - W, sQQQQmZQ#Wwa]..
* from this software without specific (js, \[QQW$QWW#?!V"".
* prior written permission. ]y:.<\.. .
* -]n w/ ' [.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT )/ )/ !
* HOLDERS AND CONTRIBUTORS "AS IS" AND ANY < (; sac , '
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ]^ .- %
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF c < r
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR aga< <La
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 5% )P'-3L
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR _bQf` y`..)a
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ,J?4P'.P"_(\?d'.,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES _Pa,)!f/<[]/ ?"
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT _2-..:. .r+_,.. .
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ?a.<%"' " -'.a_ _,
* 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.
*/
/*
* For comments regarding functions please see the header file.
*/
#include "guichan/widgets/listbox.hpp"
#include "guichan/basiccontainer.hpp"
#include "guichan/font.hpp"
#include "guichan/graphics.hpp"
#include "guichan/key.hpp"
#include "guichan/listmodel.hpp"
#include "guichan/mouseinput.hpp"
namespace gcn
{
ListBox::ListBox()
{
mSelected = -1;
mListModel = NULL;
mWrappingKeyboardSelection = false;
setWidth(100);
setFocusable(true);
addMouseListener(this);
addKeyListener(this);
}
ListBox::ListBox(ListModel *listModel)
{
mSelected = -1;
mWrappingKeyboardSelection = false;
setWidth(100);
setListModel(listModel);
setFocusable(true);
addMouseListener(this);
addKeyListener(this);
}
void ListBox::draw(Graphics* graphics)
{
graphics->setColor(getBackgroundColor());
graphics->fillRectangle(Rectangle(0, 0, getWidth(), getHeight()));
if (mListModel == NULL)
{
return;
}
graphics->setColor(getForegroundColor());
graphics->setFont(getFont());
int i, fontHeight;
int y = 0;
fontHeight = getFont()->getHeight();
/**
* @todo Check cliprects so we do not have to iterate over elements in the list model
*/
for (i = 0; i < mListModel->getNumberOfElements(); ++i)
{
if (i == mSelected)
{
graphics->drawRectangle(Rectangle(0, y, getWidth(), fontHeight));
}
graphics->drawText(mListModel->getElementAt(i), 1, y);
y += fontHeight;
}
}
void ListBox::drawBorder(Graphics* graphics)
{
Color faceColor = getBaseColor();
Color highlightColor, shadowColor;
int alpha = getBaseColor().a;
int width = getWidth() + getBorderSize() * 2 - 1;
int height = getHeight() + getBorderSize() * 2 - 1;
highlightColor = faceColor + 0x303030;
highlightColor.a = alpha;
shadowColor = faceColor - 0x303030;
shadowColor.a = alpha;
unsigned int i;
for (i = 0; i < getBorderSize(); ++i)
{
graphics->setColor(shadowColor);
graphics->drawLine(i,i, width - i, i);
graphics->drawLine(i,i + 1, i, height - i - 1);
graphics->setColor(highlightColor);
graphics->drawLine(width - i,i + 1, width - i, height - i);
graphics->drawLine(i,height - i, width - i - 1, height - i);
}
}
void ListBox::logic()
{
adjustSize();
}
int ListBox::getSelected()
{
return mSelected;
}
void ListBox::setSelected(int selected)
{
if (mListModel == NULL)
{
mSelected = -1;
}
else
{
if (selected < 0)
{
mSelected = -1;
}
else if (selected >= mListModel->getNumberOfElements())
{
mSelected = mListModel->getNumberOfElements() - 1;
}
else
{
mSelected = selected;
}
BasicContainer *par = getParent();
if (par == NULL)
{
return;
}
Rectangle scroll;
if (mSelected < 0)
{
scroll.y = 0;
}
else
{
scroll.y = getFont()->getHeight() * mSelected;
}
scroll.height = getFont()->getHeight();
par->showWidgetPart(this, scroll);
}
}
void ListBox::keyPress(const Key& key)
{
if (key.getValue() == Key::ENTER || key.getValue() == Key::SPACE)
{
generateAction();
}
else if (key.getValue() == Key::UP)
{
setSelected(mSelected - 1);
if (mSelected == -1)
{
if (isWrappingKeyboardSelection())
{
setSelected(getListModel()->getNumberOfElements() - 1);
}
else
{
setSelected(0);
}
}
}
else if (key.getValue() == Key::DOWN)
{
if (isWrappingKeyboardSelection()
&& getSelected() == getListModel()->getNumberOfElements() - 1)
{
setSelected(0);
}
else
{
setSelected(getSelected() + 1);
}
}
}
void ListBox::mousePress(int x, int y, int button)
{
if (button == MouseInput::LEFT && hasMouse())
{
setSelected(y / getFont()->getHeight());
generateAction();
}
}
void ListBox::setListModel(ListModel *listModel)
{
mSelected = -1;
mListModel = listModel;
adjustSize();
}
ListModel* ListBox::getListModel()
{
return mListModel;
}
void ListBox::adjustSize()
{
if (mListModel != NULL)
{
setHeight(getFont()->getHeight() * mListModel->getNumberOfElements());
}
}
bool ListBox::isWrappingKeyboardSelection()
{
return mWrappingKeyboardSelection;
}
void ListBox::setWrappingKeyboardSelection(bool wrapping)
{
mWrappingKeyboardSelection = wrapping;
}
}
<|endoftext|> |
<commit_before>// Copyright (C) 2012, Chris J. Foster and the other authors and contributors
// 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 software's owners 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.
//
// (This is the BSD 3-clause license)
#include "hcloudview.h"
#include "hcloud.h"
#include "glutil.h"
#include "qtlogger.h"
#include "shader.h"
#include "util.h"
//------------------------------------------------------------------------------
struct HCloudNode
{
HCloudNode* children[8]; ///< Child nodes - order (x + 2*y + 4*z)
Imath::Box3f bbox; ///< Bounding box of node
uint64_t dataOffset;
uint16_t numOccupiedVoxels;
uint16_t numLeafPoints;
// List of non-empty voxels inside the node
std::unique_ptr<float[]> position;
std::unique_ptr<float[]> intensity;
std::unique_ptr<float[]> coverage;
HCloudNode(const Box3f& bbox)
: bbox(bbox),
dataOffset(0), numOccupiedVoxels(0), numLeafPoints(0)
{
for (int i = 0; i < 8; ++i)
children[i] = 0;
}
~HCloudNode()
{
for (int i = 0; i < 8; ++i)
delete children[i];
}
bool isLeaf() const { return numLeafPoints != 0; }
bool isCached() const { return position.get() != 0; }
//bool isChildrenCached() const { return position; }
float radius() const { return bbox.max.x - bbox.min.x; }
/// Allocate arrays for storing point data
///
/// (TODO: need some sort of LRU cache)
void allocateArrays()
{
position.reset(new float[3*numOccupiedVoxels]);
intensity.reset(new float[numOccupiedVoxels]);
coverage.reset(new float[numOccupiedVoxels]);
}
};
static HCloudNode* readHCloudIndex(std::istream& in, const Box3f& bbox)
{
HCloudNode* node = new HCloudNode(bbox);
uint8_t childNodeMask = readLE<uint8_t>(in);
node->dataOffset = readLE<uint64_t>(in);
node->numOccupiedVoxels = readLE<uint16_t>(in);
node->numLeafPoints = readLE<uint16_t>(in);
V3f center = bbox.center();
for (int i = 0; i < 8; ++i)
{
if (!((childNodeMask >> i) & 1))
continue;
Box3f b = bbox;
if (i % 2 == 0)
b.max.x = center.x;
else
b.min.x = center.x;
if ((i/2) % 2 == 0)
b.max.y = center.y;
else
b.min.y = center.y;
if ((i/4) % 2 == 0)
b.max.z = center.z;
else
b.min.z = center.z;
// tfm::printf("Read %d: %.3f - %.3f\n", childNodeMask, b.min, b.max);
node->children[i] = readHCloudIndex(in, b);
}
return node;
}
HCloudView::HCloudView() { }
HCloudView::~HCloudView() { }
bool HCloudView::loadFile(QString fileName, size_t maxVertexCount)
{
m_input.open(fileName.toUtf8(), std::ios::binary);
m_header.read(m_input);
g_logger.info("Header:\n%s", m_header);
Box3f offsetBox(m_header.boundingBox.min - m_header.offset,
m_header.boundingBox.max - m_header.offset);
m_rootNode.reset(readHCloudIndex(m_input, offsetBox));
// fields.push_back(GeomField(TypeSpec::vec3float32(), "position", npoints));
// fields.push_back(GeomField(TypeSpec::float32(), "intensity", npoints));
// V3f* position = (V3f*)fields[0].as<float>();
// float* intensity = fields[0].as<float>();
setFileName(fileName);
setBoundingBox(m_header.boundingBox);
setOffset(m_header.offset);
setCentroid(m_header.boundingBox.center());
return true;
}
void HCloudView::initializeGL()
{
m_shader.reset(new ShaderProgram(QGLContext::currentContext()));
m_shader->setShaderFromSourceFile("shaders:las_points_lod.glsl");
}
void drawBounds(HCloudNode* node, const TransformState& transState)
{
drawBoundingBox(transState, node->bbox, Imath::C3f(1));
for (int i = 0; i < 8; ++i)
{
if (node->children[i])
drawBounds(node->children[i], transState);
}
}
void HCloudView::draw(const TransformState& transStateIn, double quality)
{
g_logger.info("hcloud MBytes = %.2f", m_sizeBytes/1e6);
TransformState transState = transStateIn.translate(offset());
//drawBounds(m_rootNode.get(), transState);
V3f cameraPos = V3d(0) * transState.modelViewMatrix.inverse();
QGLShaderProgram& prog = m_shader->shaderProgram();
prog.bind();
glEnable(GL_POINT_SPRITE);
glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);
transState.setUniforms(prog.programId());
prog.enableAttributeArray("position");
prog.enableAttributeArray("coverage");
prog.enableAttributeArray("intensity");
prog.enableAttributeArray("simplifyThreshold");
prog.setUniformValue("pointPixelScale", (GLfloat)(0.5 * transState.viewSize.x *
transState.projMatrix[0][0]));
// TODO: Ultimately should scale sizeRatioLimit with the quality, something
// like this:
// const double sizeRatioLimit = 0.01/std::min(1.0, quality);
// g_logger.info("quality = %f", quality);
const double sizeRatioLimit = 0.01;
std::vector<HCloudNode*> nodeStack;
nodeStack.push_back(m_rootNode.get());
while (!nodeStack.empty())
{
HCloudNode* node = nodeStack.back();
nodeStack.pop_back();
double sizeRatio = node->radius()/(node->bbox.center() - cameraPos).length();
if (sizeRatio < sizeRatioLimit || node->isLeaf())
{
if (!node->isCached())
{
// Read node from disk on demand. This causes a lot of seeking
// and stuttering - should generate and optimize a read plan as
// a first step, and do it lazily in a separate thread as well.
node->allocateArrays();
m_input.seekg(m_header.dataOffset() + node->dataOffset);
if (!m_input)
g_logger.error("Bad seek");
int nvox = node->numOccupiedVoxels;
m_input.read((char*)node->position.get(), 3*sizeof(float)*nvox);
m_input.read((char*)node->coverage.get(), sizeof(float)*nvox);
m_input.read((char*)node->intensity.get(), sizeof(float)*nvox);
m_sizeBytes += 5*sizeof(float)*nvox;
// Ensure large enough array of simplification thresholds
//
// Nvidia cards seem to clamp the minimum gl_PointSize to 1, so
// tiny points get too much emphasis. We can avoid this
// problem by randomly removing such points according to the
// correct probability. This needs to happen coherently
// between frames to avoid shimmer, so generate a single array
// for it and reuse it every time.
int nsimp = (int)m_simplifyThreshold.size();
if (nvox > nsimp)
{
m_simplifyThreshold.resize(nvox);
for (int i = nsimp; i < nvox; ++i)
m_simplifyThreshold[i] = float(rand())/RAND_MAX;
}
}
// We draw points as billboards (not spheres) when drawing MIP
// levels: the point radius represents a screen coverage in this
// case, with no sensible interpreation as a radius toward the
// camera. If we don't do this, we get problems for multi layer
// surfaces where the more distant layer can cover the nearer one.
prog.setUniformValue("markerShape", GLint(0));
prog.setUniformValue("lodMultiplier", GLfloat(node->radius()/m_header.brickSize));
prog.setAttributeArray("position", node->position.get(), 3);
prog.setAttributeArray("intensity", node->intensity.get(), 1);
prog.setAttributeArray("coverage", node->coverage.get(), 1);
prog.setAttributeArray("simplifyThreshold", m_simplifyThreshold.data(), 1);
glDrawArrays(GL_POINTS, 0, node->numOccupiedVoxels);
}
else
{
for (int i = 0; i < 8; ++i)
{
HCloudNode* n = node->children[i];
if (n)
nodeStack.push_back(n);
}
}
}
prog.disableAttributeArray("position");
prog.disableAttributeArray("coverage");
prog.disableAttributeArray("intensity");
prog.disableAttributeArray("simplifyThreshold");
glDisable(GL_POINT_SPRITE);
glDisable(GL_VERTEX_PROGRAM_POINT_SIZE);
prog.release();
}
size_t HCloudView::pointCount() const
{
// FIXME
return 0;
}
size_t HCloudView::simplifiedPointCount(const V3d& cameraPos,
bool incrementalDraw) const
{
// FIXME
return 0;
}
V3d HCloudView::pickVertex(const V3d& rayOrigin, const V3d& rayDirection,
double longitudinalScale, double* distance) const
{
// FIXME
return V3d(0,0,0);
}
<commit_msg>Limit number of bricks loaded in a frame<commit_after>// Copyright (C) 2012, Chris J. Foster and the other authors and contributors
// 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 software's owners 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.
//
// (This is the BSD 3-clause license)
#include "hcloudview.h"
#include "hcloud.h"
#include "glutil.h"
#include "qtlogger.h"
#include "shader.h"
#include "util.h"
#include <queue>
//------------------------------------------------------------------------------
struct HCloudNode
{
HCloudNode* children[8]; ///< Child nodes - order (x + 2*y + 4*z)
Imath::Box3f bbox; ///< Bounding box of node
uint64_t dataOffset;
uint16_t numOccupiedVoxels;
uint16_t numLeafPoints;
// List of non-empty voxels inside the node
std::unique_ptr<float[]> position;
std::unique_ptr<float[]> intensity;
std::unique_ptr<float[]> coverage;
HCloudNode(const Box3f& bbox)
: bbox(bbox),
dataOffset(0), numOccupiedVoxels(0), numLeafPoints(0)
{
for (int i = 0; i < 8; ++i)
children[i] = 0;
}
~HCloudNode()
{
for (int i = 0; i < 8; ++i)
delete children[i];
}
bool isLeaf() const { return numLeafPoints != 0; }
bool isCached() const { return position.get() != 0; }
//bool isChildrenCached() const { return position; }
float radius() const { return bbox.max.x - bbox.min.x; }
/// Allocate arrays for storing point data
///
/// (TODO: need some sort of LRU cache)
void allocateArrays()
{
position.reset(new float[3*numOccupiedVoxels]);
intensity.reset(new float[numOccupiedVoxels]);
coverage.reset(new float[numOccupiedVoxels]);
}
};
static HCloudNode* readHCloudIndex(std::istream& in, const Box3f& bbox)
{
HCloudNode* node = new HCloudNode(bbox);
uint8_t childNodeMask = readLE<uint8_t>(in);
node->dataOffset = readLE<uint64_t>(in);
node->numOccupiedVoxels = readLE<uint16_t>(in);
node->numLeafPoints = readLE<uint16_t>(in);
V3f center = bbox.center();
for (int i = 0; i < 8; ++i)
{
if (!((childNodeMask >> i) & 1))
continue;
Box3f b = bbox;
if (i % 2 == 0)
b.max.x = center.x;
else
b.min.x = center.x;
if ((i/2) % 2 == 0)
b.max.y = center.y;
else
b.min.y = center.y;
if ((i/4) % 2 == 0)
b.max.z = center.z;
else
b.min.z = center.z;
// tfm::printf("Read %d: %.3f - %.3f\n", childNodeMask, b.min, b.max);
node->children[i] = readHCloudIndex(in, b);
}
return node;
}
HCloudView::HCloudView() { }
HCloudView::~HCloudView() { }
bool HCloudView::loadFile(QString fileName, size_t maxVertexCount)
{
m_input.open(fileName.toUtf8(), std::ios::binary);
m_header.read(m_input);
g_logger.info("Header:\n%s", m_header);
Box3f offsetBox(m_header.boundingBox.min - m_header.offset,
m_header.boundingBox.max - m_header.offset);
m_rootNode.reset(readHCloudIndex(m_input, offsetBox));
// fields.push_back(GeomField(TypeSpec::vec3float32(), "position", npoints));
// fields.push_back(GeomField(TypeSpec::float32(), "intensity", npoints));
// V3f* position = (V3f*)fields[0].as<float>();
// float* intensity = fields[0].as<float>();
setFileName(fileName);
setBoundingBox(m_header.boundingBox);
setOffset(m_header.offset);
setCentroid(m_header.boundingBox.center());
return true;
}
void HCloudView::initializeGL()
{
m_shader.reset(new ShaderProgram(QGLContext::currentContext()));
m_shader->setShaderFromSourceFile("shaders:las_points_lod.glsl");
}
void drawBounds(HCloudNode* node, const TransformState& transState)
{
drawBoundingBox(transState, node->bbox, Imath::C3f(1));
for (int i = 0; i < 8; ++i)
{
if (node->children[i])
drawBounds(node->children[i], transState);
}
}
void HCloudView::draw(const TransformState& transStateIn, double quality)
{
TransformState transState = transStateIn.translate(offset());
//drawBounds(m_rootNode.get(), transState);
V3f cameraPos = V3d(0) * transState.modelViewMatrix.inverse();
QGLShaderProgram& prog = m_shader->shaderProgram();
prog.bind();
glEnable(GL_POINT_SPRITE);
glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);
transState.setUniforms(prog.programId());
prog.enableAttributeArray("position");
prog.enableAttributeArray("coverage");
prog.enableAttributeArray("intensity");
prog.enableAttributeArray("simplifyThreshold");
prog.setUniformValue("pointPixelScale", (GLfloat)(0.5 * transState.viewSize.x *
transState.projMatrix[0][0]));
// TODO: Ultimately should scale sizeRatioLimit with the quality, something
// like this:
// const double sizeRatioLimit = 0.01/std::min(1.0, quality);
// g_logger.info("quality = %f", quality);
const double sizeRatioLimit = 0.01;
size_t nodesRendered = 0;
size_t voxelsRendered = 0;
int loadQuota = 1000;
std::queue<HCloudNode*> nodeQueue;
nodeQueue.push(m_rootNode.get());
while (!nodeQueue.empty())
{
HCloudNode* node = nodeQueue.front();
nodeQueue.pop();
if (!node->isCached())
{
// Read node from disk on demand. This causes a lot of seeking
// and stuttering - should generate and optimize a read plan as
// a first step, and do it lazily in a separate thread as well.
//
// Note that this caches all the parent nodes of the nodes we
// actually want to draw, but that's not all that many because the
// octree is only O(log(N)) deep.
node->allocateArrays();
m_input.seekg(m_header.dataOffset() + node->dataOffset);
assert(m_input);
int nvox = node->numOccupiedVoxels;
m_input.read((char*)node->position.get(), 3*sizeof(float)*nvox);
m_input.read((char*)node->coverage.get(), sizeof(float)*nvox);
m_input.read((char*)node->intensity.get(), sizeof(float)*nvox);
m_sizeBytes += 5*sizeof(float)*nvox;
// Ensure large enough array of simplification thresholds
//
// Nvidia cards seem to clamp the minimum gl_PointSize to 1, so
// tiny points get too much emphasis. We can avoid this
// problem by randomly removing such points according to the
// correct probability. This needs to happen coherently
// between frames to avoid shimmer, so generate a single array
// for it and reuse it every time.
int nsimp = (int)m_simplifyThreshold.size();
if (nvox > nsimp)
{
m_simplifyThreshold.resize(nvox);
for (int i = nsimp; i < nvox; ++i)
m_simplifyThreshold[i] = float(rand())/RAND_MAX;
}
}
double sizeRatio = node->radius()/(node->bbox.center() - cameraPos).length();
if (sizeRatio < sizeRatioLimit || node->isLeaf() || loadQuota <= 0)
{
// We draw points as billboards (not spheres) when drawing MIP
// levels: the point radius represents a screen coverage in this
// case, with no sensible interpreation as a radius toward the
// camera. If we don't do this, we get problems for multi layer
// surfaces where the more distant layer can cover the nearer one.
prog.setUniformValue("markerShape", GLint(0));
prog.setUniformValue("lodMultiplier", GLfloat(node->radius()/m_header.brickSize));
prog.setAttributeArray("position", node->position.get(), 3);
prog.setAttributeArray("intensity", node->intensity.get(), 1);
prog.setAttributeArray("coverage", node->coverage.get(), 1);
prog.setAttributeArray("simplifyThreshold", m_simplifyThreshold.data(), 1);
glDrawArrays(GL_POINTS, 0, node->numOccupiedVoxels);
nodesRendered++;
voxelsRendered += node->numOccupiedVoxels;
}
else
{
for (int i = 0; i < 8; ++i)
{
HCloudNode* n = node->children[i];
if (n)
{
// Count newly pending uncached toward the load quota
if (!n->isCached())
--loadQuota;
nodeQueue.push(n);
}
}
}
}
prog.disableAttributeArray("position");
prog.disableAttributeArray("coverage");
prog.disableAttributeArray("intensity");
prog.disableAttributeArray("simplifyThreshold");
glDisable(GL_POINT_SPRITE);
glDisable(GL_VERTEX_PROGRAM_POINT_SIZE);
prog.release();
g_logger.info("hcloud: %.1fMB, #nodes = %d, load quota = %d, mean voxel size = %.0f",
m_sizeBytes/1e6, nodesRendered, loadQuota,
double(voxelsRendered)/nodesRendered);
}
size_t HCloudView::pointCount() const
{
// FIXME
return 0;
}
size_t HCloudView::simplifiedPointCount(const V3d& cameraPos,
bool incrementalDraw) const
{
// FIXME
return 0;
}
V3d HCloudView::pickVertex(const V3d& rayOrigin, const V3d& rayDirection,
double longitudinalScale, double* distance) const
{
// FIXME
return V3d(0,0,0);
}
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named LICENSE that should have accompanied this file.
*
* THIS PACKAGE 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.
*/
// Provide BZFS with a list server connection
/* class header */
#include "ListServerConnection.h"
/* system implementation headers */
#include <string.h>
#include <string>
#include <math.h>
#include <errno.h>
/* common implementation headers */
#include "bzfio.h"
#include "version.h"
#include "TextUtils.h"
#include "Protocol.h"
extern Address serverAddress;
extern PingPacket getTeamCounts();
ListServerLink::ListServerLink(std::string listServerURL, std::string publicizedAddress, std::string publicizedTitle)
{
// parse url
std::string protocol, hostname, pathname;
int port = 80;
bool useDefault = false;
// use default if it can't be parsed
if (!BzfNetwork::parseURL(listServerURL, protocol, hostname, port, pathname))
useDefault = true;
// use default if wrong protocol or invalid port
if ((protocol != "http") || (port < 1) || (port > 65535))
useDefault = true;
// use default if bad address
Address address = Address::getHostAddress(hostname);
if (address.isAny())
useDefault = true;
// parse default list server URL if we need to; assume default works
if (useDefault) {
BzfNetwork::parseURL(DefaultListServerURL, protocol, hostname, port, pathname);
DEBUG1("Provided list server URL (%s) is invalid. Using default of %s.\n", listServerURL.c_str(), DefaultListServerURL);
}
// add to list
this->address = address;
this->port = port;
this->pathname = pathname;
this->hostname = hostname;
this->linkSocket = NotConnected;
this->publicizeAddress = publicizedAddress;
this->publicizeDescription = publicizedTitle;
this->publicizeServer = true; //if this c'tor is called, it's safe to publicize
// schedule initial ADD message
queueMessage(ListServerLink::ADD);
}
ListServerLink::ListServerLink()
{
// does not create a usable link, so checks should be placed
// in all public member functions to ensure that nothing tries
// to happen if publicizeServer is false
this->linkSocket = NotConnected;
this->publicizeServer = false;
}
ListServerLink::~ListServerLink()
{
// now tell the list server that we're going away. this can
// take some time but we don't want to wait too long. we do
// our own multiplexing loop and wait for a maximum of 3 seconds
// total.
// if we aren't supposed to be publicizing, skip the whole thing
// and don't waste 3 seconds.
if (!publicizeServer)
return;
queueMessage(ListServerLink::REMOVE);
TimeKeeper start = TimeKeeper::getCurrent();
do {
// compute timeout
float waitTime = 3.0f - (TimeKeeper::getCurrent() - start);
if (waitTime <= 0.0f)
break;
if (!isConnected()) //queueMessage should have connected us
break;
// check for list server socket connection
int fdMax = -1;
fd_set write_set;
fd_set read_set;
FD_ZERO(&write_set);
FD_ZERO(&read_set);
if (phase == ListServerLink::CONNECTING)
_FD_SET(linkSocket, &write_set);
else
_FD_SET(linkSocket, &read_set);
fdMax = linkSocket;
// wait for socket to connect or timeout
struct timeval timeout;
timeout.tv_sec = long(floorf(waitTime));
timeout.tv_usec = long(1.0e+6f * (waitTime - floorf(waitTime)));
int nfound = select(fdMax + 1, (fd_set*)&read_set, (fd_set*)&write_set,
0, &timeout);
if (nfound == 0)
// Time has gone, close and go
break;
// check for connection to list server
if (FD_ISSET(linkSocket, &write_set))
sendQueuedMessages();
else if (FD_ISSET(linkSocket, &read_set))
read();
} while (true);
// stop list server communication
closeLink();
}
void ListServerLink::closeLink()
{
if (isConnected()) {
close(linkSocket);
DEBUG4("Closing List Server\n");
linkSocket = NotConnected;
}
}
void ListServerLink::read()
{
if (isConnected()) {
char buf[256];
recv(linkSocket, buf, sizeof(buf), 0);
closeLink();
if (nextMessageType != ListServerLink::NONE)
// There was a pending request arrived after we write:
// we should redo all the stuff
openLink();
}
}
void ListServerLink::openLink()
{
// start opening connection if not already doing so
if (!isConnected()) {
linkSocket = socket(AF_INET, SOCK_STREAM, 0);
DEBUG4("Opening List Server\n");
if (!isConnected()) {
return;
}
// set to non-blocking for connect
if (BzfNetwork::setNonBlocking(linkSocket) < 0) {
closeLink();
return;
}
// Make our connection come from our serverAddress in case we have
// multiple/masked IPs so the list server can verify us.
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr = serverAddress;
// assign the address to the socket
if (bind(linkSocket, (CNCTType*)&addr, sizeof(addr)) < 0) {
closeLink();
return;
}
// connect. this should fail with EINPROGRESS but check for
// success just in case.
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr = address;
if (connect(linkSocket, (CNCTType*)&addr, sizeof(addr)) < 0) {
#if defined(_WIN32)
#undef EINPROGRESS
#define EINPROGRESS EWOULDBLOCK
#endif
if (getErrno() != EINPROGRESS) {
nerror("connecting to list server");
// try to lookup dns name again in case it moved
this->address = Address::getHostAddress(this->hostname);
closeLink();
} else {
phase = CONNECTING;
}
} else {
// shouldn't arrive here. Just in case, clean
closeLink();
}
}
}
void ListServerLink::queueMessage(MessageType type)
{
// ignore if the server is not public
if (!publicizeServer) return;
// Open network connection only if closed
if (!isConnected()) openLink();
// record next message to send.
nextMessageType = type;
}
void ListServerLink::sendQueuedMessages()
{
if (!isConnected())
return;
if (nextMessageType == ListServerLink::ADD) {
DEBUG3("Queuing ADD message to list server\n");
addMe(getTeamCounts(), publicizeAddress, TextUtils::url_encode(publicizeDescription));
lastAddTime = TimeKeeper::getCurrent();
} else if (nextMessageType == ListServerLink::REMOVE) {
DEBUG3("Queuing REMOVE message to list server\n");
removeMe(publicizeAddress);
}
}
void ListServerLink::addMe(PingPacket pingInfo,
std::string publicizedAddress,
std::string publicizedTitle)
{
std::string msg;
// encode ping reply as ascii hex digits plus NULL
char gameInfo[PingPacketHexPackedSize + 1];
pingInfo.packHex(gameInfo);
// send ADD message (must send blank line)
msg = TextUtils::format("GET %s?action=ADD&nameport=%s&version=%s&gameinfo=%s&build=%s&title=%s HTTP/1.1\r\n"
"Host: %s\r\nCache-Control: no-cache\r\n\r\n",
pathname.c_str(), publicizedAddress.c_str(),
getServerVersion(), gameInfo,
getAppVersion(),
publicizedTitle.c_str(),
hostname.c_str());
sendMessage(msg);
}
void ListServerLink::removeMe(std::string publicizedAddress)
{
std::string msg;
// send REMOVE (must send blank line)
msg = TextUtils::format("GET %s?action=REMOVE&nameport=%s HTTP/1.1\r\n"
"Host: %s\r\nCache-Control: no-cache\r\n\r\n",
pathname.c_str(),
publicizedAddress.c_str(),
hostname.c_str());
sendMessage(msg);
}
void ListServerLink::sendMessage(std::string message)
{
const int bufsize = 4096;
char msg[bufsize];
strncpy(msg, message.c_str(), bufsize);
msg[bufsize - 1] = 0;
if (strlen(msg) > 0) {
DEBUG3("%s\n", msg);
if (send(linkSocket, msg, strlen(msg), 0) == -1) {
perror("List server send failed");
DEBUG3("Unable to send to the list server!\n");
closeLink();
} else {
nextMessageType = ListServerLink::NONE;
phase = ListServerLink::WRITTEN;
}
} else {
closeLink();
}
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>comments on next steps for authentication<commit_after>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named LICENSE that should have accompanied this file.
*
* THIS PACKAGE 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.
*/
// Provide BZFS with a list server connection
/* class header */
#include "ListServerConnection.h"
/* system implementation headers */
#include <string.h>
#include <string>
#include <math.h>
#include <errno.h>
/* common implementation headers */
#include "bzfio.h"
#include "version.h"
#include "TextUtils.h"
#include "Protocol.h"
extern Address serverAddress;
extern PingPacket getTeamCounts();
ListServerLink::ListServerLink(std::string listServerURL, std::string publicizedAddress, std::string publicizedTitle)
{
// parse url
std::string protocol, hostname, pathname;
int port = 80;
bool useDefault = false;
// use default if it can't be parsed
if (!BzfNetwork::parseURL(listServerURL, protocol, hostname, port, pathname))
useDefault = true;
// use default if wrong protocol or invalid port
if ((protocol != "http") || (port < 1) || (port > 65535))
useDefault = true;
// use default if bad address
Address address = Address::getHostAddress(hostname);
if (address.isAny())
useDefault = true;
// parse default list server URL if we need to; assume default works
if (useDefault) {
BzfNetwork::parseURL(DefaultListServerURL, protocol, hostname, port, pathname);
DEBUG1("Provided list server URL (%s) is invalid. Using default of %s.\n", listServerURL.c_str(), DefaultListServerURL);
}
// add to list
this->address = address;
this->port = port;
this->pathname = pathname;
this->hostname = hostname;
this->linkSocket = NotConnected;
this->publicizeAddress = publicizedAddress;
this->publicizeDescription = publicizedTitle;
this->publicizeServer = true; //if this c'tor is called, it's safe to publicize
// schedule initial ADD message
queueMessage(ListServerLink::ADD);
}
ListServerLink::ListServerLink()
{
// does not create a usable link, so checks should be placed
// in all public member functions to ensure that nothing tries
// to happen if publicizeServer is false
this->linkSocket = NotConnected;
this->publicizeServer = false;
}
ListServerLink::~ListServerLink()
{
// now tell the list server that we're going away. this can
// take some time but we don't want to wait too long. we do
// our own multiplexing loop and wait for a maximum of 3 seconds
// total.
// if we aren't supposed to be publicizing, skip the whole thing
// and don't waste 3 seconds.
if (!publicizeServer)
return;
queueMessage(ListServerLink::REMOVE);
TimeKeeper start = TimeKeeper::getCurrent();
do {
// compute timeout
float waitTime = 3.0f - (TimeKeeper::getCurrent() - start);
if (waitTime <= 0.0f)
break;
if (!isConnected()) //queueMessage should have connected us
break;
// check for list server socket connection
int fdMax = -1;
fd_set write_set;
fd_set read_set;
FD_ZERO(&write_set);
FD_ZERO(&read_set);
if (phase == ListServerLink::CONNECTING)
_FD_SET(linkSocket, &write_set);
else
_FD_SET(linkSocket, &read_set);
fdMax = linkSocket;
// wait for socket to connect or timeout
struct timeval timeout;
timeout.tv_sec = long(floorf(waitTime));
timeout.tv_usec = long(1.0e+6f * (waitTime - floorf(waitTime)));
int nfound = select(fdMax + 1, (fd_set*)&read_set, (fd_set*)&write_set,
0, &timeout);
if (nfound == 0)
// Time has gone, close and go
break;
// check for connection to list server
if (FD_ISSET(linkSocket, &write_set))
sendQueuedMessages();
else if (FD_ISSET(linkSocket, &read_set))
read();
} while (true);
// stop list server communication
closeLink();
}
void ListServerLink::closeLink()
{
if (isConnected()) {
close(linkSocket);
DEBUG4("Closing List Server\n");
linkSocket = NotConnected;
}
}
void ListServerLink::read()
{
if (isConnected()) {
char buf[256];
recv(linkSocket, buf, sizeof(buf), 0);
closeLink();
if (nextMessageType != ListServerLink::NONE)
// There was a pending request arrived after we write:
// we should redo all the stuff
openLink();
}
}
void ListServerLink::openLink()
{
// start opening connection if not already doing so
if (!isConnected()) {
linkSocket = socket(AF_INET, SOCK_STREAM, 0);
DEBUG4("Opening List Server\n");
if (!isConnected()) {
return;
}
// set to non-blocking for connect
if (BzfNetwork::setNonBlocking(linkSocket) < 0) {
closeLink();
return;
}
// Make our connection come from our serverAddress in case we have
// multiple/masked IPs so the list server can verify us.
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr = serverAddress;
// assign the address to the socket
if (bind(linkSocket, (CNCTType*)&addr, sizeof(addr)) < 0) {
closeLink();
return;
}
// connect. this should fail with EINPROGRESS but check for
// success just in case.
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr = address;
if (connect(linkSocket, (CNCTType*)&addr, sizeof(addr)) < 0) {
#if defined(_WIN32)
#undef EINPROGRESS
#define EINPROGRESS EWOULDBLOCK
#endif
if (getErrno() != EINPROGRESS) {
nerror("connecting to list server");
// try to lookup dns name again in case it moved
this->address = Address::getHostAddress(this->hostname);
closeLink();
} else {
phase = CONNECTING;
}
} else {
// shouldn't arrive here. Just in case, clean
closeLink();
}
}
}
void ListServerLink::queueMessage(MessageType type)
{
// ignore if the server is not public
if (!publicizeServer) return;
// Open network connection only if closed
if (!isConnected()) openLink();
// record next message to send.
nextMessageType = type;
}
void ListServerLink::sendQueuedMessages()
{
if (!isConnected())
return;
if (nextMessageType == ListServerLink::ADD) {
DEBUG3("Queuing ADD message to list server\n");
addMe(getTeamCounts(), publicizeAddress, TextUtils::url_encode(publicizeDescription));
lastAddTime = TimeKeeper::getCurrent();
} else if (nextMessageType == ListServerLink::REMOVE) {
DEBUG3("Queuing REMOVE message to list server\n");
removeMe(publicizeAddress);
}
}
void ListServerLink::addMe(PingPacket pingInfo,
std::string publicizedAddress,
std::string publicizedTitle)
{
std::string msg;
// encode ping reply as ascii hex digits plus NULL
char gameInfo[PingPacketHexPackedSize + 1];
pingInfo.packHex(gameInfo);
// TODO loop through and send any player tokens that need approval
// TODO loop through groups we are interested and request those too
// TODO we probably should convert to a POST instead. List server now allows either
// send ADD message (must send blank line)
msg = TextUtils::format("GET %s?action=ADD&nameport=%s&version=%s&gameinfo=%s&build=%s&title=%s HTTP/1.1\r\n"
"Host: %s\r\nCache-Control: no-cache\r\n\r\n",
pathname.c_str(), publicizedAddress.c_str(),
getServerVersion(), gameInfo,
getAppVersion(),
publicizedTitle.c_str(),
hostname.c_str());
// TODO need to listen for user info replies and setup callsign for isAllowedToEnter()
sendMessage(msg);
}
void ListServerLink::removeMe(std::string publicizedAddress)
{
std::string msg;
// send REMOVE (must send blank line)
msg = TextUtils::format("GET %s?action=REMOVE&nameport=%s HTTP/1.1\r\n"
"Host: %s\r\nCache-Control: no-cache\r\n\r\n",
pathname.c_str(),
publicizedAddress.c_str(),
hostname.c_str());
sendMessage(msg);
}
void ListServerLink::sendMessage(std::string message)
{
const int bufsize = 4096;
char msg[bufsize];
strncpy(msg, message.c_str(), bufsize);
msg[bufsize - 1] = 0;
if (strlen(msg) > 0) {
DEBUG3("%s\n", msg);
if (send(linkSocket, msg, strlen(msg), 0) == -1) {
perror("List server send failed");
DEBUG3("Unable to send to the list server!\n");
closeLink();
} else {
nextMessageType = ListServerLink::NONE;
phase = ListServerLink::WRITTEN;
}
} else {
closeLink();
}
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993-2013 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
// Provide BZFS with a list server connection
/* class header */
#include "ListServerConnection.h"
/* system implementation headers */
#include <string.h>
#include <string>
#include <math.h>
#include <errno.h>
#include <set>
/* common implementation headers */
#include "bzfio.h"
#include "version.h"
#include "TextUtils.h"
#include "Protocol.h"
#include "bzfsAPI.h"
#include "WorldEventManager.h"
/* local implementation headers */
#include "bzfs.h"
const int ListServerLink::NotConnected = -1;
ListServerLink::ListServerLink(std::string listServerURL,
std::string publicizedAddress,
std::string publicizedTitle,
std::string _advertiseGroups,
float dnsCache)
{
std::string bzfsUserAgent = "bzfs ";
bzfsUserAgent += getAppVersion();
setURLwithNonce(listServerURL);
setUserAgent(bzfsUserAgent);
setDNSCachingTime((long)ceilf(dnsCache));
setTimeout(10);
publiclyDisconnected = false;
if (clOptions->pingInterface != "")
setInterface(clOptions->pingInterface);
publicizeAddress = publicizedAddress;
publicizeDescription = publicizedTitle;
advertiseGroups = _advertiseGroups;
//if this c'tor is called, it's safe to publicize
publicizeServer = true;
queuedRequest = false;
// schedule initial ADD message
queueMessage(ListServerLink::ADD);
}
ListServerLink::ListServerLink(): nextMessageType(), port(0), queuedRequest(0)
{
// does not create a usable link, so checks should be placed
// in all public member functions to ensure that nothing tries
// to happen if publicizeServer is false
publicizeServer = false;
}
ListServerLink::~ListServerLink()
{
// now tell the list server that we're going away. this can
// take some time but we don't want to wait too long. we do
// our own multiplexing loop and wait for a maximum of 3 seconds
// total.
// if we aren't supposed to be publicizing, skip the whole thing
// and don't waste 3 seconds.
if (!publicizeServer)
return;
queueMessage(ListServerLink::REMOVE);
for (int i = 0; i < 12; i++) {
cURLManager::perform();
if (!queuedRequest)
break;
TimeKeeper::sleep(0.25f);
}
}
void ListServerLink::finalization(char *data, unsigned int length, bool good)
{
publiclyDisconnected = !good;
GameKeeper::Player *playerData = NULL;
queuedRequest = false;
if (good && (length < 2048)) {
char buf[2048];
memcpy(buf, data, length);
int bytes = length;
buf[bytes]=0;
char* base = buf;
const char tokGoodIdentifier[] = "TOKGOOD: ";
const char tokBadIdentifier[] = "TOKBAD: ";
const char unknownPlayer[] = "UNK: ";
const char bzIdentifier[] = "BZID: ";
const char ownerIdentifier[] = "OWNER: ";
// walks entire reply including HTTP headers
while (*base) {
// find next newline
char* scan = base;
while (*scan && *scan != '\r' && *scan != '\n') scan++;
// if no newline then no more complete replies
if (*scan != '\r' && *scan != '\n') break;
while (*scan && (*scan == '\r' || *scan == '\n')) *scan++ = '\0';
logDebugMessage(4,"Got line: \"%s\"\n", base);
// TODO don't do this if we don't want central logins
// is player globally registered ?
bool registered = false;
// is player authenticated ?
bool verified = false;
// this is a reply to an authentication request ?
bool authReply = false;
char *callsign;
if (strncmp(base, tokGoodIdentifier, strlen(tokGoodIdentifier)) == 0) {
callsign = base + strlen(tokGoodIdentifier);
registered = true;
verified = true;
authReply = true;
} else if (!strncmp(base, tokBadIdentifier, strlen(tokBadIdentifier))) {
callsign = base + strlen(tokBadIdentifier);
registered = true;
authReply = true;
} else if (!strncmp(base, unknownPlayer, strlen(unknownPlayer))) {
callsign = base + strlen(unknownPlayer);
authReply = true;
} else if (!strncmp(base, ownerIdentifier, strlen(ownerIdentifier))){
setPublicOwner(base + strlen(ownerIdentifier));
} else if (!strncmp(base, bzIdentifier, strlen(bzIdentifier))) {
std::string line = base;
std::vector<std::string> args = TextUtils::tokenize(line, " \t", 3, true);
if (args.size() < 3) {
logDebugMessage(3,"Bad BZID string: %s\n", line.c_str());
} else {
const std::string& bzId = args[1];
const std::string& nick = args[2];
logDebugMessage(4,"Got BZID: \"%s\" || \"%s\"\n", bzId.c_str(), nick.c_str());
for (int i = 0; i < curMaxPlayers; i++) {
GameKeeper::Player* gkp = GameKeeper::Player::getPlayerByIndex(i);
if ((gkp != NULL) &&
(strcasecmp(gkp->player.getCallSign(), nick.c_str()) == 0) &&
(gkp->_LSAState == GameKeeper::Player::verified)) {
gkp->setBzIdentifier(bzId);
logDebugMessage(3,"Set player (%s [%i]) bzId to (%s)\n",
nick.c_str(), i, bzId.c_str());
break;
}
}
}
}
/*
char* start = base + strlen(bzIdentifier);
// skip leading white
while ((*start != '\0') && isspace(*start)) start++;
const bool useQuotes = (*start == '"');
if (useQuotes) start++; // ditch the '"'
char* end = start;
// skip until the end of the id
if (useQuotes) {
while ((*end != '\0') && (*end != '"')) end++;
} else {
while ((*end != '\0') && !isspace(*end)) end++;
}
if ((*end != '\0') && (useQuotes && (*end != '"'))) {
if (useQuotes) {
callsign = end + 1;
end--; // ditch the '"'
} else {
callsign = end;
}
// skip leading white
while ((*callsign != '\0') && isspace(*callsign)) callsign++;
if (*callsign != '\0') {
bzId = start;
bzId = bzId.substr(end - start);
if ((bzId.size() > 0) && (strlen(callsign) > 0)) {
bzIdInfo = true;
}
}
}
}
if (bzIdInfo == true) {
logDebugMessage(3,"Got BZID: %s", base);
for (int i = 0; i < curMaxPlayers; i++) {
GameKeeper::Player* gkp = GameKeeper::Player::getPlayerByIndex(i);
if ((gkp != NULL) &&
(strcasecmp(gkp->player.getCallSign(), callsign) == 0)) {
gkp->setBzIdentifier(bzId);
logDebugMessage(3,"Set player (%s [%i]) bzId to (%s)\n", callsign, i, bzId.c_str());
break;
}
}
}
*/
if (authReply) {
logDebugMessage(3,"Got: %s", base);
char *group = (char *)NULL;
// Isolate callsign from groups
if (verified) {
group = callsign;
if (group) {
while (*group && (*group != ':')) group++;
while (*group && (*group == ':')) *group++ = 0;
}
}
playerData = NULL;
int playerIndex;
for (playerIndex = 0; playerIndex < curMaxPlayers; playerIndex++) {
playerData = GameKeeper::Player::getPlayerByIndex(playerIndex);
if (!playerData)
continue;
if (playerData->_LSAState != GameKeeper::Player::checking)
continue;
if (!TextUtils::compare_nocase(playerData->player.getCallSign(),
callsign))
break;
}
logDebugMessage(3,"[%d]\n", playerIndex);
if (playerIndex < curMaxPlayers) {
if (registered) {
// don't accept the global auth if there's a local account
// of the same name and the local account is not marked as
// being the same as the global account
if (!playerData->accessInfo.hasRealPassword()
|| playerData->accessInfo.getUserInfo(callsign)
.hasGroup("LOCAL.GLOBAL")) {
if (!playerData->accessInfo.isRegistered())
// Create an entry on the user database even if
// authentication wenk ko. Make the "isRegistered"
// things work
playerData->accessInfo.storeInfo(NULL);
if (verified) {
playerData->_LSAState = GameKeeper::Player::verified;
playerData->accessInfo.setPermissionRights();
while (group && *group) {
char *nextgroup = group;
if (nextgroup) {
while (*nextgroup && (*nextgroup != ':')) nextgroup++;
while (*nextgroup && (*nextgroup == ':')) *nextgroup++ = 0;
}
playerData->accessInfo.addGroup(group);
group = nextgroup;
}
playerData->authentication.global(true);
sendMessage(ServerPlayer, playerIndex,
"Global login approved!");
} else {
playerData->_LSAState = GameKeeper::Player::failed;
sendMessage(ServerPlayer, playerIndex,
"Global login rejected, bad token.");
}
} else {
playerData->_LSAState = GameKeeper::Player::failed;
sendMessage(ServerPlayer, playerIndex, "Global login rejected. ");
}
} else {
playerData->_LSAState = GameKeeper::Player::notRequired;
if (!playerData->player.isBot()) {
sendMessage(ServerPlayer, playerIndex,
"This callsign is not registered.");
sendMessage(ServerPlayer, playerIndex,
"You can register it at http://forums.bzflag.org/");
}
}
playerData->player.clearToken();
}
}
// next reply
base = scan;
}
}
if (playerData != NULL){
// tell the API that auth is complete
bz_AuthenticationCompleteData_V1 eventData;
eventData.player = bz_getPlayerByIndex(playerData->getIndex());
worldEventManager.callEvents(eventData);
}
for (int i = 0; i < curMaxPlayers; i++) {
GameKeeper::Player *playerData = GameKeeper::Player::getPlayerByIndex(i);
if (!playerData)
continue;
if (playerData->_LSAState != GameKeeper::Player::checking)
continue;
playerData->_LSAState = GameKeeper::Player::timedOut;
}
if (nextMessageType != ListServerLink::NONE) {
// There was a pending request arrived after we write:
// we should redo all the stuff
sendQueuedMessages();
}
}
void ListServerLink::queueMessage(MessageType type)
{
// ignore if the server is not public
if (!publicizeServer) return;
// record next message to send.
nextMessageType = type;
if (!queuedRequest)
sendQueuedMessages();
else
logDebugMessage(3,"There is a message already queued to the list server: not sending this one yet.\n");
}
void ListServerLink::sendQueuedMessages()
{
queuedRequest = true;
if (nextMessageType == ListServerLink::ADD) {
logDebugMessage(3,"Queuing ADD message to list server\n");
bz_ListServerUpdateEvent_V1 updateEvent;
updateEvent.address = publicizeAddress;
updateEvent.description = publicizeDescription;
updateEvent.groups = advertiseGroups;
worldEventManager.callEvents(bz_eListServerUpdateEvent,&updateEvent);
addMe(getTeamCounts(), std::string(updateEvent.address.c_str()), std::string(updateEvent.description.c_str()), std::string(updateEvent.groups.c_str()));
lastAddTime = TimeKeeper::getCurrent();
} else if (nextMessageType == ListServerLink::REMOVE) {
logDebugMessage(3,"Queuing REMOVE message to list server\n");
removeMe(publicizeAddress);
}
nextMessageType = ListServerLink::NONE;
}
void ListServerLink::addMe(PingPacket pingInfo,
std::string publicizedAddress,
std::string publicizedTitle,
std::string _advertiseGroups)
{
std::string msg;
// encode ping reply as ascii hex digits plus NULL
char gameInfo[PingPacketHexPackedSize + 1];
pingInfo.packHex(gameInfo);
// send ADD message (must send blank line)
msg = "action=ADD&nameport=";
msg += publicizedAddress;
msg += "&version=";
msg += getServerVersion();
msg += "&gameinfo=";
msg += gameInfo;
msg += "&build=";
msg += getAppVersion();
msg += "&checktokens=";
std::set<std::string> callSigns;
// callsign1@ip1=token1%0D%0Acallsign2@ip2=token2%0D%0A
for (int i = 0; i < curMaxPlayers; i++) {
GameKeeper::Player *playerData = GameKeeper::Player::getPlayerByIndex(i);
if (!playerData)
continue;
if ((playerData->_LSAState != GameKeeper::Player::required)
&& (playerData->_LSAState != GameKeeper::Player::requesting))
continue;
if (callSigns.count(playerData->player.getCallSign()))
continue;
callSigns.insert(playerData->player.getCallSign());
playerData->_LSAState = GameKeeper::Player::checking;
NetHandler *handler = playerData->netHandler;
msg += TextUtils::url_encode(playerData->player.getCallSign());
Address addr = handler->getIPAddress();
if (!addr.isPrivate()) {
msg += "@";
msg += handler->getTargetIP();
}
msg += "=";
msg += playerData->player.getToken();
msg += "%0D%0A";
}
msg += "&groups=";
// *groups=GROUP0%0D%0AGROUP1%0D%0A
PlayerAccessMap::iterator itr = groupAccess.begin();
for ( ; itr != groupAccess.end(); ++itr) {
if (itr->first.substr(0, 6) != "LOCAL.") {
msg += itr->first.c_str();
msg += "%0D%0A";
}
}
if (clOptions && !clOptions->publicizedKey.empty()) {
msg += "&key=" + clOptions->publicizedKey;
}
msg += "&advertgroups=";
msg += TextUtils::url_encode(_advertiseGroups);
msg += "&title=";
msg += TextUtils::url_encode(publicizedTitle);
setPostMode(msg);
addHandle();
}
void ListServerLink::removeMe(std::string publicizedAddress)
{
std::string msg;
msg = "action=REMOVE&nameport=";
msg += publicizedAddress;
setPostMode(msg);
addHandle();
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>Reuse the existing playerData variable rather than shadow it with another.<commit_after>/* bzflag
* Copyright (c) 1993-2013 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
// Provide BZFS with a list server connection
/* class header */
#include "ListServerConnection.h"
/* system implementation headers */
#include <string.h>
#include <string>
#include <math.h>
#include <errno.h>
#include <set>
/* common implementation headers */
#include "bzfio.h"
#include "version.h"
#include "TextUtils.h"
#include "Protocol.h"
#include "bzfsAPI.h"
#include "WorldEventManager.h"
/* local implementation headers */
#include "bzfs.h"
const int ListServerLink::NotConnected = -1;
ListServerLink::ListServerLink(std::string listServerURL,
std::string publicizedAddress,
std::string publicizedTitle,
std::string _advertiseGroups,
float dnsCache)
{
std::string bzfsUserAgent = "bzfs ";
bzfsUserAgent += getAppVersion();
setURLwithNonce(listServerURL);
setUserAgent(bzfsUserAgent);
setDNSCachingTime((long)ceilf(dnsCache));
setTimeout(10);
publiclyDisconnected = false;
if (clOptions->pingInterface != "")
setInterface(clOptions->pingInterface);
publicizeAddress = publicizedAddress;
publicizeDescription = publicizedTitle;
advertiseGroups = _advertiseGroups;
//if this c'tor is called, it's safe to publicize
publicizeServer = true;
queuedRequest = false;
// schedule initial ADD message
queueMessage(ListServerLink::ADD);
}
ListServerLink::ListServerLink(): nextMessageType(), port(0), queuedRequest(0)
{
// does not create a usable link, so checks should be placed
// in all public member functions to ensure that nothing tries
// to happen if publicizeServer is false
publicizeServer = false;
}
ListServerLink::~ListServerLink()
{
// now tell the list server that we're going away. this can
// take some time but we don't want to wait too long. we do
// our own multiplexing loop and wait for a maximum of 3 seconds
// total.
// if we aren't supposed to be publicizing, skip the whole thing
// and don't waste 3 seconds.
if (!publicizeServer)
return;
queueMessage(ListServerLink::REMOVE);
for (int i = 0; i < 12; i++) {
cURLManager::perform();
if (!queuedRequest)
break;
TimeKeeper::sleep(0.25f);
}
}
void ListServerLink::finalization(char *data, unsigned int length, bool good)
{
publiclyDisconnected = !good;
GameKeeper::Player *playerData = NULL;
queuedRequest = false;
if (good && (length < 2048)) {
char buf[2048];
memcpy(buf, data, length);
int bytes = length;
buf[bytes]=0;
char* base = buf;
const char tokGoodIdentifier[] = "TOKGOOD: ";
const char tokBadIdentifier[] = "TOKBAD: ";
const char unknownPlayer[] = "UNK: ";
const char bzIdentifier[] = "BZID: ";
const char ownerIdentifier[] = "OWNER: ";
// walks entire reply including HTTP headers
while (*base) {
// find next newline
char* scan = base;
while (*scan && *scan != '\r' && *scan != '\n') scan++;
// if no newline then no more complete replies
if (*scan != '\r' && *scan != '\n') break;
while (*scan && (*scan == '\r' || *scan == '\n')) *scan++ = '\0';
logDebugMessage(4,"Got line: \"%s\"\n", base);
// TODO don't do this if we don't want central logins
// is player globally registered ?
bool registered = false;
// is player authenticated ?
bool verified = false;
// this is a reply to an authentication request ?
bool authReply = false;
char *callsign;
if (strncmp(base, tokGoodIdentifier, strlen(tokGoodIdentifier)) == 0) {
callsign = base + strlen(tokGoodIdentifier);
registered = true;
verified = true;
authReply = true;
} else if (!strncmp(base, tokBadIdentifier, strlen(tokBadIdentifier))) {
callsign = base + strlen(tokBadIdentifier);
registered = true;
authReply = true;
} else if (!strncmp(base, unknownPlayer, strlen(unknownPlayer))) {
callsign = base + strlen(unknownPlayer);
authReply = true;
} else if (!strncmp(base, ownerIdentifier, strlen(ownerIdentifier))){
setPublicOwner(base + strlen(ownerIdentifier));
} else if (!strncmp(base, bzIdentifier, strlen(bzIdentifier))) {
std::string line = base;
std::vector<std::string> args = TextUtils::tokenize(line, " \t", 3, true);
if (args.size() < 3) {
logDebugMessage(3,"Bad BZID string: %s\n", line.c_str());
} else {
const std::string& bzId = args[1];
const std::string& nick = args[2];
logDebugMessage(4,"Got BZID: \"%s\" || \"%s\"\n", bzId.c_str(), nick.c_str());
for (int i = 0; i < curMaxPlayers; i++) {
GameKeeper::Player* gkp = GameKeeper::Player::getPlayerByIndex(i);
if ((gkp != NULL) &&
(strcasecmp(gkp->player.getCallSign(), nick.c_str()) == 0) &&
(gkp->_LSAState == GameKeeper::Player::verified)) {
gkp->setBzIdentifier(bzId);
logDebugMessage(3,"Set player (%s [%i]) bzId to (%s)\n",
nick.c_str(), i, bzId.c_str());
break;
}
}
}
}
/*
char* start = base + strlen(bzIdentifier);
// skip leading white
while ((*start != '\0') && isspace(*start)) start++;
const bool useQuotes = (*start == '"');
if (useQuotes) start++; // ditch the '"'
char* end = start;
// skip until the end of the id
if (useQuotes) {
while ((*end != '\0') && (*end != '"')) end++;
} else {
while ((*end != '\0') && !isspace(*end)) end++;
}
if ((*end != '\0') && (useQuotes && (*end != '"'))) {
if (useQuotes) {
callsign = end + 1;
end--; // ditch the '"'
} else {
callsign = end;
}
// skip leading white
while ((*callsign != '\0') && isspace(*callsign)) callsign++;
if (*callsign != '\0') {
bzId = start;
bzId = bzId.substr(end - start);
if ((bzId.size() > 0) && (strlen(callsign) > 0)) {
bzIdInfo = true;
}
}
}
}
if (bzIdInfo == true) {
logDebugMessage(3,"Got BZID: %s", base);
for (int i = 0; i < curMaxPlayers; i++) {
GameKeeper::Player* gkp = GameKeeper::Player::getPlayerByIndex(i);
if ((gkp != NULL) &&
(strcasecmp(gkp->player.getCallSign(), callsign) == 0)) {
gkp->setBzIdentifier(bzId);
logDebugMessage(3,"Set player (%s [%i]) bzId to (%s)\n", callsign, i, bzId.c_str());
break;
}
}
}
*/
if (authReply) {
logDebugMessage(3,"Got: %s", base);
char *group = (char *)NULL;
// Isolate callsign from groups
if (verified) {
group = callsign;
if (group) {
while (*group && (*group != ':')) group++;
while (*group && (*group == ':')) *group++ = 0;
}
}
playerData = NULL;
int playerIndex;
for (playerIndex = 0; playerIndex < curMaxPlayers; playerIndex++) {
playerData = GameKeeper::Player::getPlayerByIndex(playerIndex);
if (!playerData)
continue;
if (playerData->_LSAState != GameKeeper::Player::checking)
continue;
if (!TextUtils::compare_nocase(playerData->player.getCallSign(),
callsign))
break;
}
logDebugMessage(3,"[%d]\n", playerIndex);
if (playerIndex < curMaxPlayers) {
if (registered) {
// don't accept the global auth if there's a local account
// of the same name and the local account is not marked as
// being the same as the global account
if (!playerData->accessInfo.hasRealPassword()
|| playerData->accessInfo.getUserInfo(callsign)
.hasGroup("LOCAL.GLOBAL")) {
if (!playerData->accessInfo.isRegistered())
// Create an entry on the user database even if
// authentication wenk ko. Make the "isRegistered"
// things work
playerData->accessInfo.storeInfo(NULL);
if (verified) {
playerData->_LSAState = GameKeeper::Player::verified;
playerData->accessInfo.setPermissionRights();
while (group && *group) {
char *nextgroup = group;
if (nextgroup) {
while (*nextgroup && (*nextgroup != ':')) nextgroup++;
while (*nextgroup && (*nextgroup == ':')) *nextgroup++ = 0;
}
playerData->accessInfo.addGroup(group);
group = nextgroup;
}
playerData->authentication.global(true);
sendMessage(ServerPlayer, playerIndex,
"Global login approved!");
} else {
playerData->_LSAState = GameKeeper::Player::failed;
sendMessage(ServerPlayer, playerIndex,
"Global login rejected, bad token.");
}
} else {
playerData->_LSAState = GameKeeper::Player::failed;
sendMessage(ServerPlayer, playerIndex, "Global login rejected. ");
}
} else {
playerData->_LSAState = GameKeeper::Player::notRequired;
if (!playerData->player.isBot()) {
sendMessage(ServerPlayer, playerIndex,
"This callsign is not registered.");
sendMessage(ServerPlayer, playerIndex,
"You can register it at http://forums.bzflag.org/");
}
}
playerData->player.clearToken();
}
}
// next reply
base = scan;
}
}
if (playerData != NULL){
// tell the API that auth is complete
bz_AuthenticationCompleteData_V1 eventData;
eventData.player = bz_getPlayerByIndex(playerData->getIndex());
worldEventManager.callEvents(eventData);
}
for (int i = 0; i < curMaxPlayers; i++) {
playerData = GameKeeper::Player::getPlayerByIndex(i);
if (!playerData)
continue;
if (playerData->_LSAState != GameKeeper::Player::checking)
continue;
playerData->_LSAState = GameKeeper::Player::timedOut;
}
if (nextMessageType != ListServerLink::NONE) {
// There was a pending request arrived after we write:
// we should redo all the stuff
sendQueuedMessages();
}
}
void ListServerLink::queueMessage(MessageType type)
{
// ignore if the server is not public
if (!publicizeServer) return;
// record next message to send.
nextMessageType = type;
if (!queuedRequest)
sendQueuedMessages();
else
logDebugMessage(3,"There is a message already queued to the list server: not sending this one yet.\n");
}
void ListServerLink::sendQueuedMessages()
{
queuedRequest = true;
if (nextMessageType == ListServerLink::ADD) {
logDebugMessage(3,"Queuing ADD message to list server\n");
bz_ListServerUpdateEvent_V1 updateEvent;
updateEvent.address = publicizeAddress;
updateEvent.description = publicizeDescription;
updateEvent.groups = advertiseGroups;
worldEventManager.callEvents(bz_eListServerUpdateEvent,&updateEvent);
addMe(getTeamCounts(), std::string(updateEvent.address.c_str()), std::string(updateEvent.description.c_str()), std::string(updateEvent.groups.c_str()));
lastAddTime = TimeKeeper::getCurrent();
} else if (nextMessageType == ListServerLink::REMOVE) {
logDebugMessage(3,"Queuing REMOVE message to list server\n");
removeMe(publicizeAddress);
}
nextMessageType = ListServerLink::NONE;
}
void ListServerLink::addMe(PingPacket pingInfo,
std::string publicizedAddress,
std::string publicizedTitle,
std::string _advertiseGroups)
{
std::string msg;
// encode ping reply as ascii hex digits plus NULL
char gameInfo[PingPacketHexPackedSize + 1];
pingInfo.packHex(gameInfo);
// send ADD message (must send blank line)
msg = "action=ADD&nameport=";
msg += publicizedAddress;
msg += "&version=";
msg += getServerVersion();
msg += "&gameinfo=";
msg += gameInfo;
msg += "&build=";
msg += getAppVersion();
msg += "&checktokens=";
std::set<std::string> callSigns;
// callsign1@ip1=token1%0D%0Acallsign2@ip2=token2%0D%0A
for (int i = 0; i < curMaxPlayers; i++) {
GameKeeper::Player *playerData = GameKeeper::Player::getPlayerByIndex(i);
if (!playerData)
continue;
if ((playerData->_LSAState != GameKeeper::Player::required)
&& (playerData->_LSAState != GameKeeper::Player::requesting))
continue;
if (callSigns.count(playerData->player.getCallSign()))
continue;
callSigns.insert(playerData->player.getCallSign());
playerData->_LSAState = GameKeeper::Player::checking;
NetHandler *handler = playerData->netHandler;
msg += TextUtils::url_encode(playerData->player.getCallSign());
Address addr = handler->getIPAddress();
if (!addr.isPrivate()) {
msg += "@";
msg += handler->getTargetIP();
}
msg += "=";
msg += playerData->player.getToken();
msg += "%0D%0A";
}
msg += "&groups=";
// *groups=GROUP0%0D%0AGROUP1%0D%0A
PlayerAccessMap::iterator itr = groupAccess.begin();
for ( ; itr != groupAccess.end(); ++itr) {
if (itr->first.substr(0, 6) != "LOCAL.") {
msg += itr->first.c_str();
msg += "%0D%0A";
}
}
if (clOptions && !clOptions->publicizedKey.empty()) {
msg += "&key=" + clOptions->publicizedKey;
}
msg += "&advertgroups=";
msg += TextUtils::url_encode(_advertiseGroups);
msg += "&title=";
msg += TextUtils::url_encode(publicizedTitle);
setPostMode(msg);
addHandle();
}
void ListServerLink::removeMe(std::string publicizedAddress)
{
std::string msg;
msg = "action=REMOVE&nameport=";
msg += publicizedAddress;
setPostMode(msg);
addHandle();
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>#include <algorithm>
#include <cstring>
#include <vector>
#include "gtest/gtest.h"
#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/filler.hpp"
#include "caffe/vision_layers.hpp"
#include "caffe/test/test_caffe_main.hpp"
#include "caffe/test/test_gradient_check_util.hpp"
using std::min;
using std::max;
namespace caffe {
template <typename TypeParam>
class LRNLayerTest : public MultiDeviceTest<TypeParam> {
typedef typename TypeParam::Dtype Dtype;
protected:
LRNLayerTest()
: epsilon_(Dtype(1e-5)),
blob_bottom_(new Blob<Dtype>()),
blob_top_(new Blob<Dtype>()) {}
virtual void SetUp() {
Caffe::set_random_seed(1701);
blob_bottom_->Reshape(2, 7, 3, 3);
// fill the values
FillerParameter filler_param;
GaussianFiller<Dtype> filler(filler_param);
filler.Fill(this->blob_bottom_);
blob_bottom_vec_.push_back(blob_bottom_);
blob_top_vec_.push_back(blob_top_);
}
virtual ~LRNLayerTest() { delete blob_bottom_; delete blob_top_; }
void ReferenceLRNForward(const Blob<Dtype>& blob_bottom,
const LayerParameter& layer_param, Blob<Dtype>* blob_top);
Dtype epsilon_;
Blob<Dtype>* const blob_bottom_;
Blob<Dtype>* const blob_top_;
vector<Blob<Dtype>*> blob_bottom_vec_;
vector<Blob<Dtype>*> blob_top_vec_;
};
template <typename TypeParam>
void LRNLayerTest<TypeParam>::ReferenceLRNForward(
const Blob<Dtype>& blob_bottom, const LayerParameter& layer_param,
Blob<Dtype>* blob_top) {
typedef typename TypeParam::Dtype Dtype;
blob_top->Reshape(blob_bottom.num(), blob_bottom.channels(),
blob_bottom.height(), blob_bottom.width());
Dtype* top_data = blob_top->mutable_cpu_data();
LRNParameter lrn_param = layer_param.lrn_param();
Dtype alpha = lrn_param.alpha();
Dtype beta = lrn_param.beta();
int size = lrn_param.local_size();
switch (lrn_param.norm_region()) {
case LRNParameter_NormRegion_ACROSS_CHANNELS:
for (int n = 0; n < blob_bottom.num(); ++n) {
for (int c = 0; c < blob_bottom.channels(); ++c) {
for (int h = 0; h < blob_bottom.height(); ++h) {
for (int w = 0; w < blob_bottom.width(); ++w) {
int c_start = c - (size - 1) / 2;
int c_end = min(c_start + size, blob_bottom.channels());
c_start = max(c_start, 0);
Dtype scale = 1.;
for (int i = c_start; i < c_end; ++i) {
Dtype value = blob_bottom.data_at(n, i, h, w);
scale += value * value * alpha / size;
}
*(top_data + blob_top->offset(n, c, h, w)) =
blob_bottom.data_at(n, c, h, w) / pow(scale, beta);
}
}
}
}
break;
case LRNParameter_NormRegion_WITHIN_CHANNEL:
for (int n = 0; n < blob_bottom.num(); ++n) {
for (int c = 0; c < blob_bottom.channels(); ++c) {
for (int h = 0; h < blob_bottom.height(); ++h) {
int h_start = h - (size - 1) / 2;
int h_end = min(h_start + size, blob_bottom.height());
h_start = max(h_start, 0);
for (int w = 0; w < blob_bottom.width(); ++w) {
Dtype scale = 1.;
int w_start = w - (size - 1) / 2;
int w_end = min(w_start + size, blob_bottom.width());
w_start = max(w_start, 0);
for (int nh = h_start; nh < h_end; ++nh) {
for (int nw = w_start; nw < w_end; ++nw) {
Dtype value = blob_bottom.data_at(n, c, nh, nw);
scale += value * value * alpha / (size * size);
}
}
*(top_data + blob_top->offset(n, c, h, w)) =
blob_bottom.data_at(n, c, h, w) / pow(scale, beta);
}
}
}
}
break;
default:
LOG(FATAL) << "Unknown normalization region.";
}
}
TYPED_TEST_CASE(LRNLayerTest, TestDtypesAndDevices);
TYPED_TEST(LRNLayerTest, TestSetupAcrossChannels) {
typedef typename TypeParam::Dtype Dtype;
LayerParameter layer_param;
LRNLayer<Dtype> layer(layer_param);
layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_);
EXPECT_EQ(this->blob_top_->num(), 2);
EXPECT_EQ(this->blob_top_->channels(), 7);
EXPECT_EQ(this->blob_top_->height(), 3);
EXPECT_EQ(this->blob_top_->width(), 3);
}
TYPED_TEST(LRNLayerTest, TestForwardAcrossChannels) {
typedef typename TypeParam::Dtype Dtype;
LayerParameter layer_param;
LRNLayer<Dtype> layer(layer_param);
layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_);
layer.Forward(this->blob_bottom_vec_, this->blob_top_vec_);
Blob<Dtype> top_reference;
this->ReferenceLRNForward(*(this->blob_bottom_), layer_param,
&top_reference);
for (int i = 0; i < this->blob_bottom_->count(); ++i) {
EXPECT_NEAR(this->blob_top_->cpu_data()[i], top_reference.cpu_data()[i],
this->epsilon_);
}
}
TYPED_TEST(LRNLayerTest, TestGradientAcrossChannels) {
typedef typename TypeParam::Dtype Dtype;
LayerParameter layer_param;
LRNLayer<Dtype> layer(layer_param);
GradientChecker<Dtype> checker(1e-2, 1e-2);
layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_);
layer.Forward(this->blob_bottom_vec_, this->blob_top_vec_);
for (int i = 0; i < this->blob_top_->count(); ++i) {
this->blob_top_->mutable_cpu_diff()[i] = 1.;
}
vector<bool> propagate_down(this->blob_bottom_vec_.size(), true);
layer.Backward(this->blob_top_vec_, propagate_down,
this->blob_bottom_vec_);
// for (int i = 0; i < this->blob_bottom_->count(); ++i) {
// std::cout << "CPU diff " << this->blob_bottom_->cpu_diff()[i]
// << std::endl;
// }
checker.CheckGradientExhaustive(&layer, this->blob_bottom_vec_,
this->blob_top_vec_);
}
TYPED_TEST(LRNLayerTest, TestSetupWithinChannel) {
typedef typename TypeParam::Dtype Dtype;
LayerParameter layer_param;
layer_param.mutable_lrn_param()->set_norm_region(
LRNParameter_NormRegion_WITHIN_CHANNEL);
layer_param.mutable_lrn_param()->set_local_size(3);
LRNLayer<Dtype> layer(layer_param);
layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_);
EXPECT_EQ(this->blob_top_->num(), 2);
EXPECT_EQ(this->blob_top_->channels(), 7);
EXPECT_EQ(this->blob_top_->height(), 3);
EXPECT_EQ(this->blob_top_->width(), 3);
}
TYPED_TEST(LRNLayerTest, TestForwardWithinChannel) {
typedef typename TypeParam::Dtype Dtype;
LayerParameter layer_param;
layer_param.mutable_lrn_param()->set_norm_region(
LRNParameter_NormRegion_WITHIN_CHANNEL);
layer_param.mutable_lrn_param()->set_local_size(3);
LRNLayer<Dtype> layer(layer_param);
layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_);
layer.Forward(this->blob_bottom_vec_, this->blob_top_vec_);
Blob<Dtype> top_reference;
this->ReferenceLRNForward(*(this->blob_bottom_), layer_param,
&top_reference);
for (int i = 0; i < this->blob_bottom_->count(); ++i) {
EXPECT_NEAR(this->blob_top_->cpu_data()[i], top_reference.cpu_data()[i],
this->epsilon_);
}
}
TYPED_TEST(LRNLayerTest, TestGradientWithinChannel) {
typedef typename TypeParam::Dtype Dtype;
LayerParameter layer_param;
layer_param.mutable_lrn_param()->set_norm_region(
LRNParameter_NormRegion_WITHIN_CHANNEL);
layer_param.mutable_lrn_param()->set_local_size(3);
LRNLayer<Dtype> layer(layer_param);
GradientChecker<Dtype> checker(1e-2, 1e-2);
layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_);
layer.Forward(this->blob_bottom_vec_, this->blob_top_vec_);
for (int i = 0; i < this->blob_top_->count(); ++i) {
this->blob_top_->mutable_cpu_diff()[i] = 1.;
}
checker.CheckGradientExhaustive(&layer, this->blob_bottom_vec_,
this->blob_top_vec_);
}
} // namespace caffe
<commit_msg>Add failing tests for LRNLayer due to large local region<commit_after>#include <algorithm>
#include <cstring>
#include <vector>
#include "gtest/gtest.h"
#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/filler.hpp"
#include "caffe/vision_layers.hpp"
#include "caffe/test/test_caffe_main.hpp"
#include "caffe/test/test_gradient_check_util.hpp"
using std::min;
using std::max;
namespace caffe {
template <typename TypeParam>
class LRNLayerTest : public MultiDeviceTest<TypeParam> {
typedef typename TypeParam::Dtype Dtype;
protected:
LRNLayerTest()
: epsilon_(Dtype(1e-5)),
blob_bottom_(new Blob<Dtype>()),
blob_top_(new Blob<Dtype>()) {}
virtual void SetUp() {
Caffe::set_random_seed(1701);
blob_bottom_->Reshape(2, 7, 3, 3);
// fill the values
FillerParameter filler_param;
GaussianFiller<Dtype> filler(filler_param);
filler.Fill(this->blob_bottom_);
blob_bottom_vec_.push_back(blob_bottom_);
blob_top_vec_.push_back(blob_top_);
}
virtual ~LRNLayerTest() { delete blob_bottom_; delete blob_top_; }
void ReferenceLRNForward(const Blob<Dtype>& blob_bottom,
const LayerParameter& layer_param, Blob<Dtype>* blob_top);
Dtype epsilon_;
Blob<Dtype>* const blob_bottom_;
Blob<Dtype>* const blob_top_;
vector<Blob<Dtype>*> blob_bottom_vec_;
vector<Blob<Dtype>*> blob_top_vec_;
};
template <typename TypeParam>
void LRNLayerTest<TypeParam>::ReferenceLRNForward(
const Blob<Dtype>& blob_bottom, const LayerParameter& layer_param,
Blob<Dtype>* blob_top) {
typedef typename TypeParam::Dtype Dtype;
blob_top->Reshape(blob_bottom.num(), blob_bottom.channels(),
blob_bottom.height(), blob_bottom.width());
Dtype* top_data = blob_top->mutable_cpu_data();
LRNParameter lrn_param = layer_param.lrn_param();
Dtype alpha = lrn_param.alpha();
Dtype beta = lrn_param.beta();
int size = lrn_param.local_size();
switch (lrn_param.norm_region()) {
case LRNParameter_NormRegion_ACROSS_CHANNELS:
for (int n = 0; n < blob_bottom.num(); ++n) {
for (int c = 0; c < blob_bottom.channels(); ++c) {
for (int h = 0; h < blob_bottom.height(); ++h) {
for (int w = 0; w < blob_bottom.width(); ++w) {
int c_start = c - (size - 1) / 2;
int c_end = min(c_start + size, blob_bottom.channels());
c_start = max(c_start, 0);
Dtype scale = 1.;
for (int i = c_start; i < c_end; ++i) {
Dtype value = blob_bottom.data_at(n, i, h, w);
scale += value * value * alpha / size;
}
*(top_data + blob_top->offset(n, c, h, w)) =
blob_bottom.data_at(n, c, h, w) / pow(scale, beta);
}
}
}
}
break;
case LRNParameter_NormRegion_WITHIN_CHANNEL:
for (int n = 0; n < blob_bottom.num(); ++n) {
for (int c = 0; c < blob_bottom.channels(); ++c) {
for (int h = 0; h < blob_bottom.height(); ++h) {
int h_start = h - (size - 1) / 2;
int h_end = min(h_start + size, blob_bottom.height());
h_start = max(h_start, 0);
for (int w = 0; w < blob_bottom.width(); ++w) {
Dtype scale = 1.;
int w_start = w - (size - 1) / 2;
int w_end = min(w_start + size, blob_bottom.width());
w_start = max(w_start, 0);
for (int nh = h_start; nh < h_end; ++nh) {
for (int nw = w_start; nw < w_end; ++nw) {
Dtype value = blob_bottom.data_at(n, c, nh, nw);
scale += value * value * alpha / (size * size);
}
}
*(top_data + blob_top->offset(n, c, h, w)) =
blob_bottom.data_at(n, c, h, w) / pow(scale, beta);
}
}
}
}
break;
default:
LOG(FATAL) << "Unknown normalization region.";
}
}
TYPED_TEST_CASE(LRNLayerTest, TestDtypesAndDevices);
TYPED_TEST(LRNLayerTest, TestSetupAcrossChannels) {
typedef typename TypeParam::Dtype Dtype;
LayerParameter layer_param;
LRNLayer<Dtype> layer(layer_param);
layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_);
EXPECT_EQ(this->blob_top_->num(), 2);
EXPECT_EQ(this->blob_top_->channels(), 7);
EXPECT_EQ(this->blob_top_->height(), 3);
EXPECT_EQ(this->blob_top_->width(), 3);
}
TYPED_TEST(LRNLayerTest, TestForwardAcrossChannels) {
typedef typename TypeParam::Dtype Dtype;
LayerParameter layer_param;
LRNLayer<Dtype> layer(layer_param);
layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_);
layer.Forward(this->blob_bottom_vec_, this->blob_top_vec_);
Blob<Dtype> top_reference;
this->ReferenceLRNForward(*(this->blob_bottom_), layer_param,
&top_reference);
for (int i = 0; i < this->blob_bottom_->count(); ++i) {
EXPECT_NEAR(this->blob_top_->cpu_data()[i], top_reference.cpu_data()[i],
this->epsilon_);
}
}
TYPED_TEST(LRNLayerTest, TestForwardAcrossChannelsLargeRegion) {
typedef typename TypeParam::Dtype Dtype;
LayerParameter layer_param;
layer_param.mutable_lrn_param()->set_local_size(15);
LRNLayer<Dtype> layer(layer_param);
layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_);
layer.Forward(this->blob_bottom_vec_, this->blob_top_vec_);
Blob<Dtype> top_reference;
this->ReferenceLRNForward(*(this->blob_bottom_), layer_param,
&top_reference);
for (int i = 0; i < this->blob_bottom_->count(); ++i) {
EXPECT_NEAR(this->blob_top_->cpu_data()[i], top_reference.cpu_data()[i],
this->epsilon_);
}
}
TYPED_TEST(LRNLayerTest, TestGradientAcrossChannels) {
typedef typename TypeParam::Dtype Dtype;
LayerParameter layer_param;
LRNLayer<Dtype> layer(layer_param);
GradientChecker<Dtype> checker(1e-2, 1e-2);
layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_);
layer.Forward(this->blob_bottom_vec_, this->blob_top_vec_);
for (int i = 0; i < this->blob_top_->count(); ++i) {
this->blob_top_->mutable_cpu_diff()[i] = 1.;
}
vector<bool> propagate_down(this->blob_bottom_vec_.size(), true);
layer.Backward(this->blob_top_vec_, propagate_down,
this->blob_bottom_vec_);
// for (int i = 0; i < this->blob_bottom_->count(); ++i) {
// std::cout << "CPU diff " << this->blob_bottom_->cpu_diff()[i]
// << std::endl;
// }
checker.CheckGradientExhaustive(&layer, this->blob_bottom_vec_,
this->blob_top_vec_);
}
TYPED_TEST(LRNLayerTest, TestGradientAcrossChannelsLargeRegion) {
typedef typename TypeParam::Dtype Dtype;
LayerParameter layer_param;
layer_param.mutable_lrn_param()->set_local_size(15);
LRNLayer<Dtype> layer(layer_param);
GradientChecker<Dtype> checker(1e-2, 1e-2);
layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_);
layer.Forward(this->blob_bottom_vec_, this->blob_top_vec_);
for (int i = 0; i < this->blob_top_->count(); ++i) {
this->blob_top_->mutable_cpu_diff()[i] = 1.;
}
vector<bool> propagate_down(this->blob_bottom_vec_.size(), true);
layer.Backward(this->blob_top_vec_, propagate_down,
this->blob_bottom_vec_);
// for (int i = 0; i < this->blob_bottom_->count(); ++i) {
// std::cout << "CPU diff " << this->blob_bottom_->cpu_diff()[i]
// << std::endl;
// }
checker.CheckGradientExhaustive(&layer, this->blob_bottom_vec_,
this->blob_top_vec_);
}
TYPED_TEST(LRNLayerTest, TestSetupWithinChannel) {
typedef typename TypeParam::Dtype Dtype;
LayerParameter layer_param;
layer_param.mutable_lrn_param()->set_norm_region(
LRNParameter_NormRegion_WITHIN_CHANNEL);
layer_param.mutable_lrn_param()->set_local_size(3);
LRNLayer<Dtype> layer(layer_param);
layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_);
EXPECT_EQ(this->blob_top_->num(), 2);
EXPECT_EQ(this->blob_top_->channels(), 7);
EXPECT_EQ(this->blob_top_->height(), 3);
EXPECT_EQ(this->blob_top_->width(), 3);
}
TYPED_TEST(LRNLayerTest, TestForwardWithinChannel) {
typedef typename TypeParam::Dtype Dtype;
LayerParameter layer_param;
layer_param.mutable_lrn_param()->set_norm_region(
LRNParameter_NormRegion_WITHIN_CHANNEL);
layer_param.mutable_lrn_param()->set_local_size(3);
LRNLayer<Dtype> layer(layer_param);
layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_);
layer.Forward(this->blob_bottom_vec_, this->blob_top_vec_);
Blob<Dtype> top_reference;
this->ReferenceLRNForward(*(this->blob_bottom_), layer_param,
&top_reference);
for (int i = 0; i < this->blob_bottom_->count(); ++i) {
EXPECT_NEAR(this->blob_top_->cpu_data()[i], top_reference.cpu_data()[i],
this->epsilon_);
}
}
TYPED_TEST(LRNLayerTest, TestGradientWithinChannel) {
typedef typename TypeParam::Dtype Dtype;
LayerParameter layer_param;
layer_param.mutable_lrn_param()->set_norm_region(
LRNParameter_NormRegion_WITHIN_CHANNEL);
layer_param.mutable_lrn_param()->set_local_size(3);
LRNLayer<Dtype> layer(layer_param);
GradientChecker<Dtype> checker(1e-2, 1e-2);
layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_);
layer.Forward(this->blob_bottom_vec_, this->blob_top_vec_);
for (int i = 0; i < this->blob_top_->count(); ++i) {
this->blob_top_->mutable_cpu_diff()[i] = 1.;
}
checker.CheckGradientExhaustive(&layer, this->blob_bottom_vec_,
this->blob_top_vec_);
}
} // namespace caffe
<|endoftext|> |
<commit_before>#include "dds_stream.hpp"
#include "gl_util.hpp"
#include "thirdparty/shaun/sweeper.hpp"
#include "thirdparty/shaun/parser.hpp"
#include <iostream>
#include <fstream>
#include <algorithm>
#include <cmath>
using namespace std;
GLenum DDSFormatToGL(DDSLoader::Format format)
{
switch (format)
{
case DDSLoader::Format::BC1: return GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
case DDSLoader::Format::BC1_SRGB: return GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
case DDSLoader::Format::BC2: return GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
case DDSLoader::Format::BC2_SRGB: return GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
case DDSLoader::Format::BC3: return GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
case DDSLoader::Format::BC3_SRGB: return GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
case DDSLoader::Format::BC4: return GL_COMPRESSED_RED_RGTC1;
case DDSLoader::Format::BC4_SIGNED:return GL_COMPRESSED_SIGNED_RED_RGTC1;
case DDSLoader::Format::BC5: return GL_COMPRESSED_RG_RGTC2;
case DDSLoader::Format::BC5_SIGNED:return GL_COMPRESSED_SIGNED_RG_RGTC2;
case DDSLoader::Format::BC6: return GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT;
case DDSLoader::Format::BC6_SIGNED:return GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT;
case DDSLoader::Format::BC7: return GL_COMPRESSED_RGBA_BPTC_UNORM;
case DDSLoader::Format::BC7_SRGB: return GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM;
}
return 0;
}
void DDSStreamer::init(int pageSize, int numPages, int maxSize)
{
_maxSize = maxSize;
_pageSize = pageSize;
_numPages = numPages;
int pboSize = pageSize*numPages;
glCreateBuffers(1, &_pbo);
GLbitfield storageFlags = GL_MAP_WRITE_BIT|GL_MAP_PERSISTENT_BIT;
#ifdef USE_COHERENT_MAPPING
storageFlags = storageFlags | GL_MAP_COHERENT_BIT;
#endif
glNamedBufferStorage(_pbo, pboSize, nullptr, storageFlags);
GLbitfield mapFlags = storageFlags;
#ifndef USE_COHERENT_MAPPING
mapFlags = mapFlags | GL_MAP_FLUSH_EXPLICIT_BIT;
#endif
_pboPtr = glMapNamedBufferRange(
_pbo, 0, pboSize, mapFlags);
_usedPages.resize(numPages, false);
_pageFences.resize(numPages);
_t = thread([this]{
while (true)
{
LoadInfo info{};
{
unique_lock<mutex> lk(_mtx);
_cond.wait(lk, [this]{ return _killThread || !_loadInfoQueue.empty();});
if (_killThread) return;
info = _loadInfoQueue[0];
_loadInfoQueue.erase(_loadInfoQueue.begin());
}
LoadData data = load(info);
{
lock_guard<mutex> lk(_dataMtx);
_loadData.push_back(data);
}
}
});
}
DDSStreamer::~DDSStreamer()
{
if (_pbo)
{
glUnmapNamedBuffer(_pbo);
glDeleteBuffers(1, &_pbo);
}
if (_t.joinable())
{
{
lock_guard<mutex> lk(_mtx);
_killThread = true;
}
_cond.notify_one();
_t.join();
}
}
struct TexInfo
{
int size = 0;
int levels = 0;
string prefix = "";
string separator = "";
string suffix = "";
bool rowColumnOrder = false;
};
TexInfo parseInfoFile(const string &filename, int maxSize)
{
ifstream in(filename.c_str(), ios::in | ios::binary);
if (!in) return {};
string contents;
in.seekg(0, ios::end);
contents.resize(in.tellg());
in.seekg(0, ios::beg);
in.read(&contents[0], contents.size());
try
{
shaun::parser p{};
shaun::object obj = p.parse(contents.c_str());
shaun::sweeper swp(&obj);
TexInfo info{};
info.size = swp("size").value<shaun::number>();
info.levels = swp("levels").value<shaun::number>();
info.prefix = (string)swp("prefix").value<shaun::string>();
info.separator = (string)swp("separator").value<shaun::string>();
info.suffix = (string)swp("suffix").value<shaun::string>();
info.rowColumnOrder = swp("row_column_order").value<shaun::boolean>();
if (maxSize)
{
int maxRows = maxSize/(info.size*2);
int maxLevel = (int)floor(log2(maxRows))+1;
info.levels = max(1,min(info.levels, maxLevel));
}
return info;
}
catch (shaun::parse_error &e)
{
cout << e << endl;
return {};
}
}
DDSStreamer::Handle DDSStreamer::createTex(const string &filename)
{
// Get info file
TexInfo info = parseInfoFile(filename + "/info.sn", _maxSize);
// Check if file exists or is valid
if (info.levels == 0) return 0;
const string tailFile = "/level0/" + info.prefix + "0" + info.separator + "0" + info.suffix;
// Gen texture
const Handle h = genHandle();
GLuint id;
glCreateTextures(GL_TEXTURE_2D, 1, &id);
_texs.insert(make_pair(h, StreamTexture(id)));
// Tail loader
DDSLoader tailLoader = DDSLoader(filename+tailFile);
// Storage
const int width = info.size<<(info.levels-1);
const int height = width/2;
const GLenum format = DDSFormatToGL(tailLoader.getFormat());
glTextureStorage2D(id, mipmapCount(width), format, width, height);
// Gen jobs
vector<LoadInfo> jobs;
// Tail mipmaps (level0)
const int tailMips = mipmapCount(info.size);
for (int i=tailMips-1;i>=0;--i)
{
LoadInfo tailInfo{};
tailInfo.handle = h;
tailInfo.loader = tailLoader;
tailInfo.fileLevel = i;
tailInfo.offsetX = 0;
tailInfo.offsetY = 0;
tailInfo.level = info.levels-1+i;
tailInfo.imageSize = tailLoader.getImageSize(i);
jobs.push_back(tailInfo);
}
for (int i=1;i<info.levels;++i)
{
const string levelFolder = filename + "/level" + to_string(i) + "/";
const int rows = 1<<(i-1);
const int columns = 2*rows;
for (int x=0;x<columns;++x)
{
for (int y=0;y<rows;++y)
{
const string ddsFile =
info.prefix+
to_string(info.rowColumnOrder?y:x)+
info.separator+
to_string(info.rowColumnOrder?x:y)+
info.suffix;
const string fullFilename = levelFolder+ddsFile;
const DDSLoader loader(fullFilename);
const int fileLevel = 0;
const int imageSize = loader.getImageSize(fileLevel);
LoadInfo loadInfo{};
loadInfo.handle = h;
loadInfo.loader = std::move(loader);
loadInfo.fileLevel = fileLevel;
loadInfo.offsetX = x*info.size;
loadInfo.offsetY = y*info.size;
loadInfo.level = info.levels-i-1;
loadInfo.imageSize = imageSize;
jobs.push_back(loadInfo);
}
}
}
_loadInfoWaiting.insert(_loadInfoWaiting.end(), jobs.begin(), jobs.end());
return h;
}
const StreamTexture &DDSStreamer::getTex(Handle handle)
{
if (!handle) return _nullTex;
auto it = _texs.find(handle);
if (it == _texs.end()) return _nullTex;
return it->second;
}
void DDSStreamer::deleteTex(Handle handle)
{
_texDeleted.push_back(handle);
_texs.erase(handle);
}
void DDSStreamer::update()
{
// Invalidate deleted textures from pre-queue
auto isDeleted = [this](const LoadInfo &info)
{
for (Handle h : _texDeleted)
{
if (h == info.handle)
{
if (info.ptrOffset != -1) releasePages(info.ptrOffset, info.imageSize);
return true;
}
}
return false;
};
remove_if(_loadInfoWaiting.begin(), _loadInfoWaiting.end(), isDeleted);
// Assign offsets
std::vector<LoadInfo> assigned;
std::vector<LoadInfo> nonAssigned;
for_each(_loadInfoWaiting.begin(), _loadInfoWaiting.end(),
[&assigned, &nonAssigned, this](const LoadInfo &info) {
int ptrOffset = acquirePages(info.imageSize);
if (ptrOffset == -1)
{
nonAssigned.push_back(info);
}
else
{
LoadInfo s = info;
s.ptrOffset = ptrOffset;
assigned.push_back(s);
}
});
{
lock_guard<mutex> lk(_mtx);
// Invalidate deleted textures from queue
remove_if(_loadInfoQueue.begin(), _loadInfoQueue.end(), isDeleted);
// Submit created textures
_loadInfoQueue.insert(
_loadInfoQueue.end(),
assigned.begin(),
assigned.end());
}
_cond.notify_one();
_loadInfoWaiting = nonAssigned;
_texDeleted.clear();
// Get loaded slices
vector<LoadData> data;
{
lock_guard<mutex> lk(_dataMtx);
data = _loadData;
_loadData.clear();
}
// Update
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, _pbo);
for (LoadData d : data)
{
#ifndef USE_COHERENT_MAPPING
glFlushMappedNamedBufferRange(_pbo, d.ptrOffset, d.imageSize);
#endif
auto it = _texs.find(d.handle);
if (it != _texs.end())
{
glCompressedTextureSubImage2D(it->second.getId(),
d.level,
d.offsetX,
d.offsetY,
d.width,
d.height,
d.format,
d.imageSize,
(void*)(intptr_t)d.ptrOffset);
}
releasePages(d.ptrOffset, d.imageSize);
}
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
}
int DDSStreamer::acquirePages(int size)
{
const int pages = ((size-1)/_pageSize)+1;
if (pages > _numPages)
{
throw runtime_error("Not enough pages");
}
int start = 0;
for (int i=0;i<_usedPages.size();++i)
{
if (_usedPages[i] || !_pageFences[i].waitClient(1000))
{
start = i+1;
}
else
{
if (i-start+1 == pages)
{
for (int j=start;j<start+pages;++j)
{
_usedPages[j] = true;
}
return start*_pageSize;
}
}
}
return -1;
}
void DDSStreamer::releasePages(int offset, int size)
{
const int pageStart = offset/_pageSize;
const int pages = ((size-1)/_pageSize)+1;
for (int i=pageStart;i<pageStart+pages;++i)
{
_pageFences[i].lock();
_usedPages[i] = false;
}
}
DDSStreamer::LoadData DDSStreamer::load(const LoadInfo &info)
{
LoadData s{};
int level = info.fileLevel;
int ptrOffset = info.ptrOffset;
s.handle = info.handle;
s.level = info.level;
s.offsetX = info.offsetX;
s.offsetY = info.offsetY;
s.width = info.loader.getWidth(level);
s.height = info.loader.getHeight(level);
s.format = DDSFormatToGL(info.loader.getFormat());
s.imageSize = info.imageSize;
s.ptrOffset = ptrOffset;
info.loader.writeImageData(level, (char*)_pboPtr+ptrOffset);
return s;
}
DDSStreamer::Handle DDSStreamer::genHandle()
{
static Handle h=0;
++h;
if (h == 0) ++h;
return h;
}
StreamTexture::StreamTexture(GLuint id) :_id{id}
{
}
StreamTexture::StreamTexture(StreamTexture &&tex) : _id{tex._id}
{
tex._id = 0;
}
StreamTexture &StreamTexture::operator=(StreamTexture &&tex)
{
if (tex._id != _id) glDeleteTextures(1, &_id);
_id = tex._id;
tex._id = 0;
return *this;
}
StreamTexture::~StreamTexture()
{
if (_id) glDeleteTextures(1, &_id);
}
GLuint StreamTexture::getId(GLuint def) const
{
if (_id) return _id;
return def;
}<commit_msg>Better DDS max size<commit_after>#include "dds_stream.hpp"
#include "gl_util.hpp"
#include "thirdparty/shaun/sweeper.hpp"
#include "thirdparty/shaun/parser.hpp"
#include <iostream>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <limits>
using namespace std;
GLenum DDSFormatToGL(DDSLoader::Format format)
{
switch (format)
{
case DDSLoader::Format::BC1: return GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
case DDSLoader::Format::BC1_SRGB: return GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
case DDSLoader::Format::BC2: return GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
case DDSLoader::Format::BC2_SRGB: return GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
case DDSLoader::Format::BC3: return GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
case DDSLoader::Format::BC3_SRGB: return GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
case DDSLoader::Format::BC4: return GL_COMPRESSED_RED_RGTC1;
case DDSLoader::Format::BC4_SIGNED:return GL_COMPRESSED_SIGNED_RED_RGTC1;
case DDSLoader::Format::BC5: return GL_COMPRESSED_RG_RGTC2;
case DDSLoader::Format::BC5_SIGNED:return GL_COMPRESSED_SIGNED_RG_RGTC2;
case DDSLoader::Format::BC6: return GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT;
case DDSLoader::Format::BC6_SIGNED:return GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT;
case DDSLoader::Format::BC7: return GL_COMPRESSED_RGBA_BPTC_UNORM;
case DDSLoader::Format::BC7_SRGB: return GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM;
}
return 0;
}
void DDSStreamer::init(int pageSize, int numPages, int maxSize)
{
_maxSize = (maxSize>0)?maxSize:numeric_limits<int>::max();
_pageSize = pageSize;
_numPages = numPages;
int pboSize = pageSize*numPages;
glCreateBuffers(1, &_pbo);
GLbitfield storageFlags = GL_MAP_WRITE_BIT|GL_MAP_PERSISTENT_BIT;
#ifdef USE_COHERENT_MAPPING
storageFlags = storageFlags | GL_MAP_COHERENT_BIT;
#endif
glNamedBufferStorage(_pbo, pboSize, nullptr, storageFlags);
GLbitfield mapFlags = storageFlags;
#ifndef USE_COHERENT_MAPPING
mapFlags = mapFlags | GL_MAP_FLUSH_EXPLICIT_BIT;
#endif
_pboPtr = glMapNamedBufferRange(
_pbo, 0, pboSize, mapFlags);
_usedPages.resize(numPages, false);
_pageFences.resize(numPages);
_t = thread([this]{
while (true)
{
LoadInfo info{};
{
unique_lock<mutex> lk(_mtx);
_cond.wait(lk, [this]{ return _killThread || !_loadInfoQueue.empty();});
if (_killThread) return;
info = _loadInfoQueue[0];
_loadInfoQueue.erase(_loadInfoQueue.begin());
}
LoadData data = load(info);
{
lock_guard<mutex> lk(_dataMtx);
_loadData.push_back(data);
}
}
});
}
DDSStreamer::~DDSStreamer()
{
if (_pbo)
{
glUnmapNamedBuffer(_pbo);
glDeleteBuffers(1, &_pbo);
}
if (_t.joinable())
{
{
lock_guard<mutex> lk(_mtx);
_killThread = true;
}
_cond.notify_one();
_t.join();
}
}
struct TexInfo
{
int size = 0;
int levels = 0;
string prefix = "";
string separator = "";
string suffix = "";
bool rowColumnOrder = false;
};
TexInfo parseInfoFile(const string &filename, int maxSize)
{
ifstream in(filename.c_str(), ios::in | ios::binary);
if (!in) return {};
string contents;
in.seekg(0, ios::end);
contents.resize(in.tellg());
in.seekg(0, ios::beg);
in.read(&contents[0], contents.size());
try
{
shaun::parser p{};
shaun::object obj = p.parse(contents.c_str());
shaun::sweeper swp(&obj);
TexInfo info{};
info.size = swp("size").value<shaun::number>();
info.levels = swp("levels").value<shaun::number>();
info.prefix = (string)swp("prefix").value<shaun::string>();
info.separator = (string)swp("separator").value<shaun::string>();
info.suffix = (string)swp("suffix").value<shaun::string>();
info.rowColumnOrder = swp("row_column_order").value<shaun::boolean>();
int maxRows = maxSize/(info.size*2);
int maxLevel = (int)floor(log2(maxRows))+1;
info.levels = max(1,min(info.levels, maxLevel));
return info;
}
catch (shaun::parse_error &e)
{
cout << e << endl;
return {};
}
}
DDSStreamer::Handle DDSStreamer::createTex(const string &filename)
{
// Get info file
TexInfo info = parseInfoFile(filename + "/info.sn", _maxSize);
// Check if file exists or is valid
if (info.levels == 0) return 0;
const string tailFile = "/level0/" + info.prefix + "0" + info.separator + "0" + info.suffix;
// Gen texture
const Handle h = genHandle();
GLuint id;
glCreateTextures(GL_TEXTURE_2D, 1, &id);
_texs.insert(make_pair(h, StreamTexture(id)));
// Tail loader
DDSLoader tailLoader = DDSLoader(filename+tailFile);
// Storage
const int width = min(_maxSize,info.size<<(info.levels-1));
const int height = width/2;
const GLenum format = DDSFormatToGL(tailLoader.getFormat());
glTextureStorage2D(id, mipmapCount(width), format, width, height);
// Gen jobs
vector<LoadInfo> jobs;
// Tail mipmaps (level0)
const int tailMipsFile = mipmapCount(info.size);
const int tailMips = mipmapCount(min(_maxSize,info.size));
const int skipMips = tailMipsFile - tailMips;
for (int i=tailMips-1;i>=0;--i)
{
LoadInfo tailInfo{};
tailInfo.handle = h;
tailInfo.loader = tailLoader;
tailInfo.fileLevel = i+skipMips;
tailInfo.offsetX = 0;
tailInfo.offsetY = 0;
tailInfo.level = info.levels-1+i;
tailInfo.imageSize = tailLoader.getImageSize(tailInfo.fileLevel);
jobs.push_back(tailInfo);
}
for (int i=1;i<info.levels;++i)
{
const string levelFolder = filename + "/level" + to_string(i) + "/";
const int rows = 1<<(i-1);
const int columns = 2*rows;
for (int x=0;x<columns;++x)
{
for (int y=0;y<rows;++y)
{
const string ddsFile =
info.prefix+
to_string(info.rowColumnOrder?y:x)+
info.separator+
to_string(info.rowColumnOrder?x:y)+
info.suffix;
const string fullFilename = levelFolder+ddsFile;
const DDSLoader loader(fullFilename);
const int fileLevel = 0;
const int imageSize = loader.getImageSize(fileLevel);
LoadInfo loadInfo{};
loadInfo.handle = h;
loadInfo.loader = std::move(loader);
loadInfo.fileLevel = fileLevel;
loadInfo.offsetX = x*info.size;
loadInfo.offsetY = y*info.size;
loadInfo.level = info.levels-i-1;
loadInfo.imageSize = imageSize;
jobs.push_back(loadInfo);
}
}
}
_loadInfoWaiting.insert(_loadInfoWaiting.end(), jobs.begin(), jobs.end());
return h;
}
const StreamTexture &DDSStreamer::getTex(Handle handle)
{
if (!handle) return _nullTex;
auto it = _texs.find(handle);
if (it == _texs.end()) return _nullTex;
return it->second;
}
void DDSStreamer::deleteTex(Handle handle)
{
_texDeleted.push_back(handle);
_texs.erase(handle);
}
void DDSStreamer::update()
{
// Invalidate deleted textures from pre-queue
auto isDeleted = [this](const LoadInfo &info)
{
for (Handle h : _texDeleted)
{
if (h == info.handle)
{
if (info.ptrOffset != -1) releasePages(info.ptrOffset, info.imageSize);
return true;
}
}
return false;
};
remove_if(_loadInfoWaiting.begin(), _loadInfoWaiting.end(), isDeleted);
// Assign offsets
std::vector<LoadInfo> assigned;
std::vector<LoadInfo> nonAssigned;
for_each(_loadInfoWaiting.begin(), _loadInfoWaiting.end(),
[&assigned, &nonAssigned, this](const LoadInfo &info) {
int ptrOffset = acquirePages(info.imageSize);
if (ptrOffset == -1)
{
nonAssigned.push_back(info);
}
else
{
LoadInfo s = info;
s.ptrOffset = ptrOffset;
assigned.push_back(s);
}
});
{
lock_guard<mutex> lk(_mtx);
// Invalidate deleted textures from queue
remove_if(_loadInfoQueue.begin(), _loadInfoQueue.end(), isDeleted);
// Submit created textures
_loadInfoQueue.insert(
_loadInfoQueue.end(),
assigned.begin(),
assigned.end());
}
_cond.notify_one();
_loadInfoWaiting = nonAssigned;
_texDeleted.clear();
// Get loaded slices
vector<LoadData> data;
{
lock_guard<mutex> lk(_dataMtx);
data = _loadData;
_loadData.clear();
}
// Update
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, _pbo);
for (LoadData d : data)
{
#ifndef USE_COHERENT_MAPPING
glFlushMappedNamedBufferRange(_pbo, d.ptrOffset, d.imageSize);
#endif
auto it = _texs.find(d.handle);
if (it != _texs.end())
{
glCompressedTextureSubImage2D(it->second.getId(),
d.level,
d.offsetX,
d.offsetY,
d.width,
d.height,
d.format,
d.imageSize,
(void*)(intptr_t)d.ptrOffset);
}
releasePages(d.ptrOffset, d.imageSize);
}
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
}
int DDSStreamer::acquirePages(int size)
{
const int pages = ((size-1)/_pageSize)+1;
if (pages > _numPages)
{
throw runtime_error("Not enough pages");
}
int start = 0;
for (int i=0;i<_usedPages.size();++i)
{
if (_usedPages[i] || !_pageFences[i].waitClient(1000))
{
start = i+1;
}
else
{
if (i-start+1 == pages)
{
for (int j=start;j<start+pages;++j)
{
_usedPages[j] = true;
}
return start*_pageSize;
}
}
}
return -1;
}
void DDSStreamer::releasePages(int offset, int size)
{
const int pageStart = offset/_pageSize;
const int pages = ((size-1)/_pageSize)+1;
for (int i=pageStart;i<pageStart+pages;++i)
{
_pageFences[i].lock();
_usedPages[i] = false;
}
}
DDSStreamer::LoadData DDSStreamer::load(const LoadInfo &info)
{
LoadData s{};
int level = info.fileLevel;
int ptrOffset = info.ptrOffset;
s.handle = info.handle;
s.level = info.level;
s.offsetX = info.offsetX;
s.offsetY = info.offsetY;
s.width = info.loader.getWidth(level);
s.height = info.loader.getHeight(level);
s.format = DDSFormatToGL(info.loader.getFormat());
s.imageSize = info.imageSize;
s.ptrOffset = ptrOffset;
info.loader.writeImageData(level, (char*)_pboPtr+ptrOffset);
return s;
}
DDSStreamer::Handle DDSStreamer::genHandle()
{
static Handle h=0;
++h;
if (h == 0) ++h;
return h;
}
StreamTexture::StreamTexture(GLuint id) :_id{id}
{
}
StreamTexture::StreamTexture(StreamTexture &&tex) : _id{tex._id}
{
tex._id = 0;
}
StreamTexture &StreamTexture::operator=(StreamTexture &&tex)
{
if (tex._id != _id) glDeleteTextures(1, &_id);
_id = tex._id;
tex._id = 0;
return *this;
}
StreamTexture::~StreamTexture()
{
if (_id) glDeleteTextures(1, &_id);
}
GLuint StreamTexture::getId(GLuint def) const
{
if (_id) return _id;
return def;
}<|endoftext|> |
<commit_before>#include <string.h>
#include <stdio.h>
#include "httpServer.h"
#include "logging.h"
HttpServer::HttpServer(int portNr)
{
listenSocket.listen(portNr);
selector.add(listenSocket);
}
HttpServer::~HttpServer()
{
listenSocket.close();
for(unsigned int n=0; n<connections.size(); n++)
delete connections[n];
for(unsigned int n=0; n<handlers.size(); n++)
delete handlers[n];
}
void HttpServer::update(float delta)
{
if (selector.wait(sf::microseconds(1)))
{
if (selector.isReady(listenSocket))
{
HttpServerConnection* connection = new HttpServerConnection(this);
if (listenSocket.accept(connection->socket) == sf::Socket::Done)
{
connections.push_back(connection);
selector.add(connection->socket);
}else{
delete connection;
}
}
for(unsigned int n=0; n<connections.size(); n++)
{
if (selector.isReady(connections[n]->socket))
{
if (!connections[n]->read())
{
selector.remove(connections[n]->socket);
delete connections[n];
connections.erase(connections.begin() + n);
}
}
}
}
}
HttpServerConnection::HttpServerConnection(HttpServer* server)
: server(server)
{
recvBufferCount = 0;
status = METHOD;
}
bool HttpServerConnection::read()
{
char buffer[1024];
size_t size;
if (socket.receive(buffer, sizeof(buffer), size) != sf::Socket::Done)
return false;
if (recvBufferCount + size > recvBufferSize)
size = recvBufferSize - recvBufferCount;
if (size < 1)
return false;
memcpy(recvBuffer + recvBufferCount, buffer, size);
recvBufferCount += size;
while(true)
{
char* ptr = (char*)memchr(recvBuffer, '\n', recvBufferCount);
if (!ptr)
break;
*ptr = '\0';
string line(recvBuffer);
ptr++;
size_t len = ptr - recvBuffer;
recvBufferCount -= len;
memmove(recvBuffer, ptr, recvBufferCount);
if (line.endswith("\r"))
line = line.substr(0, -1);
if (!handleLine(line))
return false;
}
return true;
}
/** \brief Decode a percent-encoded URI
* Uri decoding according to RFC1630, RFC1738, RFC2396
* Credits: Jin Qing
* \param sSrc const string& Percent-encoded URI
* \return string Decoded URI-string
*
*/
string HttpServerConnection::UriDecode(const string & sSrc)
{
// Note from RFC1630: "Sequences which start with a percent
// sign but are not followed by two hexadecimal characters
// (0-9, A-F) are reserved for future extension"
const unsigned char * pSrc = (const unsigned char *)sSrc.c_str();
const int SRC_LEN = sSrc.length();
const unsigned char * const SRC_END = pSrc + SRC_LEN;
// last decodable '%'
const unsigned char * const SRC_LAST_DEC = SRC_END - 2;
char * const pStart = new char[SRC_LEN];
char * pEnd = pStart;
while (pSrc < SRC_LAST_DEC)
{
if (*pSrc == '%')
{
char dec1, dec2;
if (-1 != (dec1 = HEX2DEC[*(pSrc + 1)])
&& -1 != (dec2 = HEX2DEC[*(pSrc + 2)]))
{
*pEnd++ = (dec1 << 4) + dec2;
pSrc += 3;
continue;
}
}
*pEnd++ = *pSrc++;
}
// the last 2- chars
while (pSrc < SRC_END)
*pEnd++ = *pSrc++;
std::string sResult(pStart, pEnd);
delete [] pStart;
return (string) sResult;
}
/**< Map to convert between character encodings */
const char HttpServerConnection::HEX2DEC[256] =
{
/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
/* 0 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* 1 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* 2 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* 3 */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1, -1,-1,-1,-1,
/* 4 */ -1,10,11,12, 13,14,15,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* 5 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* 6 */ -1,10,11,12, 13,14,15,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* 7 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* 8 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* 9 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* A */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* B */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* C */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* D */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* E */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* F */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1
};
/** \brief Parse a URL, splitting it in its part and optional parameters
*
* \param sSrc const string& URL
* \return void
*
*/
void HttpServerConnection::parseUri(const string & sSrc)
{
string uri = UriDecode(sSrc);
std::size_t found = uri.find('?');
if (found==std::string::npos)
{
request.path = uri;
return;
}
else
{
std::vector<string> parts = uri.split("?", 1);
request.path = parts[0];
std::vector<string> parameters = parts[1].split("&");
for (unsigned int n=0; n<parameters.size(); n++)
{
string param = parameters[n];
std::size_t found = param.find('=');
if (found==std::string::npos)
{
request.parameters[param] = sFALSE;
LOG(DEBUG) << "HTTP Parameter: " << param;
}
else
{
if (param.endswith('='))
{
request.parameters[param.substr(0, param.length()-1)] = sFALSE;
LOG(DEBUG) << "HTTP Parameter: " << param.substr(0, param.length()-1);
}
else
{
std::vector<string> items = param.split("=", 1);
request.parameters[items[0]] = items[1];
LOG(DEBUG) << "HTTP Parameter: " << items[0] << " = " << items[1];
}
}
}
}
LOG(DEBUG) << "HTTP Path: " << request.path;
}
bool HttpServerConnection::handleLine(string line)
{
switch(status)
{
case METHOD:{
std::vector<string> parts = line.split();
if (parts.size() != 3)
return false;
request.method = parts[0];
parseUri(parts[1]);
//request.path = parts[1];
status = HEADERS;
}break;
case HEADERS:
if (line.length() == 0)
{
request.post_data = "";
if (request.method == "POST")
{
if (request.headers.find("content-length") != request.headers.end())
{
unsigned int body_length = request.headers["content-length"].toInt();
if (body_length > recvBufferSize)
return false;
while (body_length > recvBufferCount)
{
size_t received;
if (socket.receive(recvBuffer + recvBufferCount, body_length - recvBufferCount, received) != sf::Socket::Done)
return false;
recvBufferCount += received;
}
request.post_data = string(recvBuffer, body_length);
recvBufferCount -= body_length;
memmove(recvBuffer, recvBuffer + body_length, recvBufferCount);
}
}
status = METHOD;
#ifdef DEBUG
for (std::map<string, string>::iterator iter = request.headers.begin(); iter != request.headers.end(); iter++)
{
string key=iter->first;
string value=iter->second;
LOG(DEBUG) << "HTTP header: (" << key << ", " << value << ")";
}
#endif // DEBUG
handleRequest();
}else{
std::vector<string> parts = line.split(":", 1);
if (parts.size() != 2)
LOG(WARNING) << "Invalid HTTP header: " << line;
else
request.headers[parts[0].strip().lower()] = parts[1];
}
break;
}
return true;
}
void HttpServerConnection::handleRequest()
{
reply_code = 200;
headers_send = false;
for(unsigned int n=0; n<server->handlers.size(); n++)
{
if (server->handlers[n]->handleRequest(request, this))
break;
if (headers_send)
break;
}
if (!headers_send)
{
reply_code = 404;
string replyData = "File not found";
sendData(replyData.c_str(), replyData.size());
}
string end_chunk = "0\r\n\r\n";
socket.send(end_chunk.c_str(), end_chunk.size());
request.parameters.clear();
}
void HttpServerConnection::sendHeaders()
{
string reply = string("HTTP/1.1 ") + string(reply_code) + " OK\r\n";
reply += "Content-type: text/html\r\n";
reply += "Connection: Keep-Alive\r\n";
reply += "Transfer-Encoding: chunked\r\n";
reply += "\r\n";
socket.send(reply.c_str(), reply.size());
headers_send = true;
}
void HttpServerConnection::sendData(const char* data, size_t data_length)
{
if (!headers_send)
sendHeaders();
if (data_length < 1)
return;
string chunk_len_string = string::hex(data_length) + "\r\n";
socket.send(chunk_len_string.c_str(), chunk_len_string.size());
socket.send(data, data_length);
socket.send("\r\n", 2);
}
bool HttpRequestFileHandler::handleRequest(HttpRequest& request, HttpServerConnection* connection)
{
string replyData = "";
FILE* f = NULL;
if (request.path == "/")
request.path = "/index.html";
if (request.path.find("..") != -1)
return false;
string fullPath = base_path + request.path;
f = fopen(fullPath.c_str(), "rb");
if (!f)
return false;
while(true)
{
char buffer[1024];
size_t n = fread(buffer, 1, sizeof(buffer), f);
if (n < 1)
break;
connection->sendData(buffer, n);
}
fclose(f);
return true;
}
<commit_msg>Removed junk comment<commit_after>#include <string.h>
#include <stdio.h>
#include "httpServer.h"
#include "logging.h"
HttpServer::HttpServer(int portNr)
{
listenSocket.listen(portNr);
selector.add(listenSocket);
}
HttpServer::~HttpServer()
{
listenSocket.close();
for(unsigned int n=0; n<connections.size(); n++)
delete connections[n];
for(unsigned int n=0; n<handlers.size(); n++)
delete handlers[n];
}
void HttpServer::update(float delta)
{
if (selector.wait(sf::microseconds(1)))
{
if (selector.isReady(listenSocket))
{
HttpServerConnection* connection = new HttpServerConnection(this);
if (listenSocket.accept(connection->socket) == sf::Socket::Done)
{
connections.push_back(connection);
selector.add(connection->socket);
}else{
delete connection;
}
}
for(unsigned int n=0; n<connections.size(); n++)
{
if (selector.isReady(connections[n]->socket))
{
if (!connections[n]->read())
{
selector.remove(connections[n]->socket);
delete connections[n];
connections.erase(connections.begin() + n);
}
}
}
}
}
HttpServerConnection::HttpServerConnection(HttpServer* server)
: server(server)
{
recvBufferCount = 0;
status = METHOD;
}
bool HttpServerConnection::read()
{
char buffer[1024];
size_t size;
if (socket.receive(buffer, sizeof(buffer), size) != sf::Socket::Done)
return false;
if (recvBufferCount + size > recvBufferSize)
size = recvBufferSize - recvBufferCount;
if (size < 1)
return false;
memcpy(recvBuffer + recvBufferCount, buffer, size);
recvBufferCount += size;
while(true)
{
char* ptr = (char*)memchr(recvBuffer, '\n', recvBufferCount);
if (!ptr)
break;
*ptr = '\0';
string line(recvBuffer);
ptr++;
size_t len = ptr - recvBuffer;
recvBufferCount -= len;
memmove(recvBuffer, ptr, recvBufferCount);
if (line.endswith("\r"))
line = line.substr(0, -1);
if (!handleLine(line))
return false;
}
return true;
}
/** \brief Decode a percent-encoded URI
* Uri decoding according to RFC1630, RFC1738, RFC2396
* Credits: Jin Qing
* \param sSrc const string& Percent-encoded URI
* \return string Decoded URI-string
*
*/
string HttpServerConnection::UriDecode(const string & sSrc)
{
// Note from RFC1630: "Sequences which start with a percent
// sign but are not followed by two hexadecimal characters
// (0-9, A-F) are reserved for future extension"
const unsigned char * pSrc = (const unsigned char *)sSrc.c_str();
const int SRC_LEN = sSrc.length();
const unsigned char * const SRC_END = pSrc + SRC_LEN;
// last decodable '%'
const unsigned char * const SRC_LAST_DEC = SRC_END - 2;
char * const pStart = new char[SRC_LEN];
char * pEnd = pStart;
while (pSrc < SRC_LAST_DEC)
{
if (*pSrc == '%')
{
char dec1, dec2;
if (-1 != (dec1 = HEX2DEC[*(pSrc + 1)])
&& -1 != (dec2 = HEX2DEC[*(pSrc + 2)]))
{
*pEnd++ = (dec1 << 4) + dec2;
pSrc += 3;
continue;
}
}
*pEnd++ = *pSrc++;
}
// the last 2- chars
while (pSrc < SRC_END)
*pEnd++ = *pSrc++;
std::string sResult(pStart, pEnd);
delete [] pStart;
return (string) sResult;
}
/**< Map to convert between character encodings */
const char HttpServerConnection::HEX2DEC[256] =
{
/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
/* 0 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* 1 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* 2 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* 3 */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1, -1,-1,-1,-1,
/* 4 */ -1,10,11,12, 13,14,15,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* 5 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* 6 */ -1,10,11,12, 13,14,15,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* 7 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* 8 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* 9 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* A */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* B */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* C */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* D */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* E */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* F */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1
};
/** \brief Parse a URL, splitting it in its part and optional parameters
*
* \param sSrc const string& URL
* \return void
*
*/
void HttpServerConnection::parseUri(const string & sSrc)
{
string uri = UriDecode(sSrc);
std::size_t found = uri.find('?');
if (found==std::string::npos)
{
request.path = uri;
return;
}
else
{
std::vector<string> parts = uri.split("?", 1);
request.path = parts[0];
std::vector<string> parameters = parts[1].split("&");
for (unsigned int n=0; n<parameters.size(); n++)
{
string param = parameters[n];
std::size_t found = param.find('=');
if (found==std::string::npos)
{
request.parameters[param] = sFALSE;
LOG(DEBUG) << "HTTP Parameter: " << param;
}
else
{
if (param.endswith('='))
{
request.parameters[param.substr(0, param.length()-1)] = sFALSE;
LOG(DEBUG) << "HTTP Parameter: " << param.substr(0, param.length()-1);
}
else
{
std::vector<string> items = param.split("=", 1);
request.parameters[items[0]] = items[1];
LOG(DEBUG) << "HTTP Parameter: " << items[0] << " = " << items[1];
}
}
}
}
LOG(DEBUG) << "HTTP Path: " << request.path;
}
bool HttpServerConnection::handleLine(string line)
{
switch(status)
{
case METHOD:{
std::vector<string> parts = line.split();
if (parts.size() != 3)
return false;
request.method = parts[0];
parseUri(parts[1]);
status = HEADERS;
}break;
case HEADERS:
if (line.length() == 0)
{
request.post_data = "";
if (request.method == "POST")
{
if (request.headers.find("content-length") != request.headers.end())
{
unsigned int body_length = request.headers["content-length"].toInt();
if (body_length > recvBufferSize)
return false;
while (body_length > recvBufferCount)
{
size_t received;
if (socket.receive(recvBuffer + recvBufferCount, body_length - recvBufferCount, received) != sf::Socket::Done)
return false;
recvBufferCount += received;
}
request.post_data = string(recvBuffer, body_length);
recvBufferCount -= body_length;
memmove(recvBuffer, recvBuffer + body_length, recvBufferCount);
}
}
status = METHOD;
#ifdef DEBUG
for (std::map<string, string>::iterator iter = request.headers.begin(); iter != request.headers.end(); iter++)
{
string key=iter->first;
string value=iter->second;
LOG(DEBUG) << "HTTP header: (" << key << ", " << value << ")";
}
#endif // DEBUG
handleRequest();
}else{
std::vector<string> parts = line.split(":", 1);
if (parts.size() != 2)
LOG(WARNING) << "Invalid HTTP header: " << line;
else
request.headers[parts[0].strip().lower()] = parts[1];
}
break;
}
return true;
}
void HttpServerConnection::handleRequest()
{
reply_code = 200;
headers_send = false;
for(unsigned int n=0; n<server->handlers.size(); n++)
{
if (server->handlers[n]->handleRequest(request, this))
break;
if (headers_send)
break;
}
if (!headers_send)
{
reply_code = 404;
string replyData = "File not found";
sendData(replyData.c_str(), replyData.size());
}
string end_chunk = "0\r\n\r\n";
socket.send(end_chunk.c_str(), end_chunk.size());
request.parameters.clear();
}
void HttpServerConnection::sendHeaders()
{
string reply = string("HTTP/1.1 ") + string(reply_code) + " OK\r\n";
reply += "Content-type: text/html\r\n";
reply += "Connection: Keep-Alive\r\n";
reply += "Transfer-Encoding: chunked\r\n";
reply += "\r\n";
socket.send(reply.c_str(), reply.size());
headers_send = true;
}
void HttpServerConnection::sendData(const char* data, size_t data_length)
{
if (!headers_send)
sendHeaders();
if (data_length < 1)
return;
string chunk_len_string = string::hex(data_length) + "\r\n";
socket.send(chunk_len_string.c_str(), chunk_len_string.size());
socket.send(data, data_length);
socket.send("\r\n", 2);
}
bool HttpRequestFileHandler::handleRequest(HttpRequest& request, HttpServerConnection* connection)
{
string replyData = "";
FILE* f = NULL;
if (request.path == "/")
request.path = "/index.html";
if (request.path.find("..") != -1)
return false;
string fullPath = base_path + request.path;
f = fopen(fullPath.c_str(), "rb");
if (!f)
return false;
while(true)
{
char buffer[1024];
size_t n = fread(buffer, 1, sizeof(buffer), f);
if (n < 1)
break;
connection->sendData(buffer, n);
}
fclose(f);
return true;
}
<|endoftext|> |
<commit_before>#include <kaction.h>
#include <klocale.h>
#include "kopete.h"
#include "kopetestdaction.h"
#include "kopetestdaction.moc"
#include "contactlist.h"
/** KopeteGroupList **/
KopeteGroupList::KopeteGroupList(const QString& text, const QString& pix, const KShortcut& cut, const QObject* receiver, const char* slot, QObject* parent, const char* name)
: KListAction(text, pix, cut, receiver, slot, parent, name)
{
connect(kopeteapp->contactList(), SIGNAL(groupAdded(const QString &)), this, SLOT(slotUpdateList()));
connect(kopeteapp->contactList(), SIGNAL(groupRemoved(const QString &)), this, SLOT(slotUpdateList()));
slotUpdateList();
}
KopeteGroupList::~KopeteGroupList()
{
}
void KopeteGroupList::slotUpdateList()
{
setItems(kopeteapp->contactList()->groups());
}
KAction* KopeteStdAction::chat( const QObject *recvr, const char *slot,
QObject* parent, const char *name )
{
return new KAction( "&Chat...", "mail_generic", 0, recvr, slot, parent,
name );
}
KAction* KopeteStdAction::sendMessage(const QObject *recvr, const char *slot, QObject* parent, const char *name)
{
return new KAction( "&Send Message...", "mail_generic", 0, recvr, slot,
parent, name );
}
KAction* KopeteStdAction::contactInfo(const QObject *recvr, const char *slot, QObject* parent, const char *name)
{
return new KAction( "User &Info...", "identity", 0, recvr, slot, parent,
name );
}
KAction* KopeteStdAction::viewHistory(const QObject *recvr, const char *slot, QObject* parent, const char *name)
{
return new KAction( "View &History...", "history", 0, recvr, slot, parent,
name );
}
KAction* KopeteStdAction::addGroup(const QObject *recvr, const char *slot, QObject* parent, const char *name)
{
return new KAction( "&Add Group...", "folder", 0, recvr, slot, parent,
name );
}
KListAction *KopeteStdAction::moveContact(const QObject *recvr, const char *slot, QObject* parent, const char *name)
{
return new KopeteGroupList( "&Move Contact", "editcut", 0, recvr, slot,
parent, name );
}
KListAction *KopeteStdAction::copyContact( const QObject *recvr,
const char *slot, QObject* parent, const char *name )
{
return new KopeteGroupList( "&Copy Contact", "editcopy", 0, recvr, slot,
parent, name );
}
KAction* KopeteStdAction::deleteContact(const QObject *recvr, const char *slot, QObject* parent, const char *name)
{
return new KAction( "&Delete Contact...", "edittrash", 0, recvr, slot,
parent, name );
}
// vim: set noet ts=4 sts=4 sw=4:
<commit_msg>Fixlets<commit_after>#include <kaction.h>
#include <klocale.h>
#include "kopete.h"
#include "kopetestdaction.h"
#include "kopetestdaction.moc"
#include "contactlist.h"
/** KopeteGroupList **/
KopeteGroupList::KopeteGroupList(const QString& text, const QString& pix, const KShortcut& cut, const QObject* receiver, const char* slot, QObject* parent, const char* name)
: KListAction(text, pix, cut, receiver, slot, parent, name)
{
connect(kopeteapp->contactList(), SIGNAL(groupAdded(const QString &)), this, SLOT(slotUpdateList()));
connect(kopeteapp->contactList(), SIGNAL(groupRemoved(const QString &)), this, SLOT(slotUpdateList()));
slotUpdateList();
}
KopeteGroupList::~KopeteGroupList()
{
}
void KopeteGroupList::slotUpdateList()
{
setItems(kopeteapp->contactList()->groups());
}
KAction* KopeteStdAction::chat( const QObject *recvr, const char *slot,
QObject* parent, const char *name )
{
return new KAction( "Start &Chat...", "mail_generic", 0, recvr, slot, parent,
name );
}
KAction* KopeteStdAction::sendMessage(const QObject *recvr, const char *slot, QObject* parent, const char *name)
{
return new KAction( "&Send Message...", "mail_generic", 0, recvr, slot,
parent, name );
}
KAction* KopeteStdAction::contactInfo(const QObject *recvr, const char *slot, QObject* parent, const char *name)
{
return new KAction( "User &Info...", "identity", 0, recvr, slot, parent,
name );
}
KAction* KopeteStdAction::viewHistory(const QObject *recvr, const char *slot, QObject* parent, const char *name)
{
return new KAction( "View &History...", "history", 0, recvr, slot, parent,
name );
}
KAction* KopeteStdAction::addGroup(const QObject *recvr, const char *slot, QObject* parent, const char *name)
{
return new KAction( "&Add Group...", "folder", 0, recvr, slot, parent,
name );
}
KListAction *KopeteStdAction::moveContact(const QObject *recvr, const char *slot, QObject* parent, const char *name)
{
return new KopeteGroupList( "&Move Contact", "editcut", 0, recvr, slot,
parent, name );
}
KListAction *KopeteStdAction::copyContact( const QObject *recvr,
const char *slot, QObject* parent, const char *name )
{
return new KopeteGroupList( "Cop&y Contact", "editcopy", 0, recvr, slot,
parent, name );
}
KAction* KopeteStdAction::deleteContact(const QObject *recvr, const char *slot, QObject* parent, const char *name)
{
return new KAction( "&Delete Contact...", "edittrash", 0, recvr, slot,
parent, name );
}
// vim: set noet ts=4 sts=4 sw=4:
<|endoftext|> |
<commit_before>#include <phypp.hpp>
void print_help();
int main(int argc, char* argv[]) {
uint_t id = npos;
std::string component, sed, out;
read_args(argc, argv, arg_list(seds, out, id, component));
if (seds.empty() || id == npos || component.empty()) {
print_help();
return 0;
}
if (out.empty()) {
out = file::remove_extension(seds)+"-"+component+"-"+strn(id)+".fits"
} else {
file::mkdir(file::get_directory(out));
}
vec1u tstart, tnbyte;
fits::read_table(file::remove_extension(seds)+"-header.fits",
component+"_start", tstart, component+"_nbyte", tnbyte
);
uint_t start = tstart[id], nbyte = tnbyte[id], npt = nbyte/sizeof(float);
vec1f lambda(npt), flux(npt);
std::ifstream file(seds);
file.seekg(start);
file.read(reinterpret_cast<char*>(lambda.data.data()), nbyte/2);
file.read(reinterpret_cast<char*>(flux.data.data()), nbyte/2);
fits::write_table(out, ftable(lambda, flux));
return 0;
}
void print_help() {
using namespace format;
auto argdoc = [](const std::string& name, const std::string& type,
const std::string& desc) {
std::string header = " - "+name+" "+type;
print(header);
std::string indent = " ";
vec1s w = wrap(indent+desc, 80, indent);
for (auto& s : w) {
print(s);
}
};
print("egg-getsed v1.0rc1");
print("usage: egg-getsed [options]\n");
print("List of options:");
argdoc("sed", "[string]", "file containing the SEDs (mandatory)");
argdoc("id", "[uint]", "ID of the galaxy to extract (zero-based and mandatory) ");
argdoc("component", "[string]", "name of the galaxy component to extract (disk or bulge, "
"mandatory)");
argdoc("out", "[string]", "FITS file in which the SED will be extracted (default: "
"[out]-[component]-[id].fits)");
print("");
}
<commit_msg>Fixed compiler error<commit_after>#include <phypp.hpp>
void print_help();
int main(int argc, char* argv[]) {
uint_t id = npos;
std::string component, seds, out;
read_args(argc, argv, arg_list(seds, out, id, component));
if (seds.empty() || id == npos || component.empty()) {
print_help();
return 0;
}
if (out.empty()) {
out = file::remove_extension(seds)+"-"+component+"-"+strn(id)+".fits";
} else {
file::mkdir(file::get_directory(out));
}
vec1u tstart, tnbyte;
fits::read_table(file::remove_extension(seds)+"-header.fits",
component+"_start", tstart, component+"_nbyte", tnbyte
);
uint_t start = tstart[id], nbyte = tnbyte[id], npt = nbyte/sizeof(float);
vec1f lambda(npt), flux(npt);
std::ifstream file(seds);
file.seekg(start);
file.read(reinterpret_cast<char*>(lambda.data.data()), nbyte/2);
file.read(reinterpret_cast<char*>(flux.data.data()), nbyte/2);
fits::write_table(out, ftable(lambda, flux));
return 0;
}
void print_help() {
using namespace format;
auto argdoc = [](const std::string& name, const std::string& type,
const std::string& desc) {
std::string header = " - "+name+" "+type;
print(header);
std::string indent = " ";
vec1s w = wrap(indent+desc, 80, indent);
for (auto& s : w) {
print(s);
}
};
print("egg-getsed v1.0rc1");
print("usage: egg-getsed [options]\n");
print("List of options:");
argdoc("seds", "[string]", "file containing the SEDs (mandatory)");
argdoc("id", "[uint]", "ID of the galaxy to extract (zero-based and mandatory) ");
argdoc("component", "[string]", "name of the galaxy component to extract (disk or bulge, "
"mandatory)");
argdoc("out", "[string]", "FITS file in which the SED will be extracted (default: "
"[out]-[component]-[id].fits)");
print("");
}
<|endoftext|> |
<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include <ncurses.h>
#include "concat_c.hh"
#include "configuration.hh"
#include "contents.hh"
#include "file_contents.hh"
#include "../lib.hh"
#include "key_aliases.hh"
#include "show_message.hh"
#include "vick-move/lib.hh"
#include "print_contents.hh"
namespace vick {
namespace insert_mode {
struct insert_c : public change {
const std::string track;
const move_t y, x;
insert_c(const std::string& track, move_t y, move_t x)
: track(track)
, y(y)
, x(x) {}
virtual bool is_overriding() const noexcept override {
return true;
}
virtual void undo(contents& contents) override {
contents.cont[y] = contents.cont[y].substr(0, x) +
contents.cont[y].substr(x + track.size());
contents.y = y;
contents.x = x;
if (contents.x and contents.x >= contents.cont[y].size())
contents.x = contents.cont[y].size() - 1;
}
virtual void redo(contents& contents) override {
contents.cont[y] = contents.cont[y].substr(0, x) + track +
contents.cont[y].substr(x);
contents.y = y;
contents.x = x + track.size();
if (contents.x >= contents.cont[y].size())
contents.x = contents.cont[y].size() - 1;
}
virtual std::shared_ptr<change>
regenerate(const contents& contents) const override {
return std::make_shared<insert_c>(track, contents.y,
contents.x);
}
};
struct newline_c : public change {
const std::string first, second;
const move_t y;
newline_c(const contents& contents)
: first(contents.cont[contents.y].substr(0, contents.x))
, second(contents.cont[contents.y].substr(contents.x))
, y(contents.y) {}
virtual bool is_overriding() const noexcept override {
return true;
}
virtual void undo(contents& contents) override {
contents.cont[y] = first + second;
contents.cont.erase(contents.cont.begin() + y + 1);
contents.y = y;
contents.x = first.size();
}
virtual void redo(contents& contents) override {
contents.cont[y] = first;
contents.cont.insert(contents.cont.begin() + y + 1, second);
contents.y = y + 1;
contents.x = 0;
}
virtual std::shared_ptr<change>
regenerate(const contents& contents) const override {
return std::make_shared<newline_c>(contents);
}
};
boost::optional<std::shared_ptr<change> >
enter_insert_mode(contents& contents, boost::optional<int> pref) {
std::string track;
auto x = contents.x;
char ch;
show_message("--INSERT--");
contents.is_inserting = true;
if (contents.refresh) {
print_contents(contents);
show_message("--INSERT--");
}
while ((ch = getch()) != QUIT_KEY) {
if (ch == '\n') {
std::vector<std::shared_ptr<change> > changes;
changes.reserve(3);
if (track.size())
changes.push_back(
std::make_shared<insert_c>(track, contents.y, x));
changes.push_back(std::make_shared<newline_c>(contents));
changes.back()->redo(contents);
auto recursed = enter_insert_mode(contents, pref);
if (recursed)
changes.push_back(recursed.get());
return boost::optional<std::shared_ptr<change> >(
std::make_shared<concat_c>(changes));
}
if (contents.x >= contents.cont[contents.y].size()) {
contents.cont[contents.y].push_back(ch);
contents.x = contents.cont[contents.y].size();
track += ch;
} else {
contents.cont[contents.y].insert(contents.x, 1, ch);
contents.x++;
track += ch;
}
if (contents.refresh) {
print_contents(contents);
show_message("--INSERT--");
}
}
contents.is_inserting = false;
showing_message = false;
return boost::optional<std::shared_ptr<change> >(
std::make_shared<insert_c>(track, contents.y, x));
}
struct replace_c : public change {
const std::string o, n;
const move_t y, x;
replace_c(const std::string& o, const std::string& n, move_t y,
move_t x)
: o(o)
, n(n)
, y(y)
, x(x) {}
virtual bool is_overriding() const noexcept override {
return true;
}
virtual void undo(contents& contents) override {
contents.cont[y] = contents.cont[y].substr(0, x) + o +
contents.cont[y].substr(x + o.size());
}
virtual void redo(contents& contents) override {
contents.cont[y] = contents.cont[y].substr(0, x) + n +
contents.cont[y].substr(x + n.size());
}
virtual std::shared_ptr<change>
regenerate(const contents& contents) const override {
return std::make_shared<replace_c>(contents.cont[contents.y]
.substr(contents.x,
n.size()),
n, contents.y, contents.x);
}
};
boost::optional<std::shared_ptr<change> >
enter_replace_mode(contents& contents, boost::optional<int> pref) {
std::string o, n;
auto x = contents.x;
char ch;
show_message("--INSERT (REPLACE)--");
contents.is_inserting = true;
if (get_contents().refresh) {
print_contents(get_contents());
show_message("--INSERT (REPLACE)--");
}
while ((ch = getch()) != QUIT_KEY) {
if (ch == '\n') {
o = contents.cont[contents.y][contents.x];
std::vector<std::shared_ptr<change> > changes;
changes.reserve(3);
if (o.size())
changes.push_back(
std::make_shared<replace_c>(o, n, contents.y, x));
changes.push_back(std::make_shared<newline_c>(contents));
changes.back()->redo(contents);
auto recursed = enter_replace_mode(contents, pref);
if (recursed)
changes.push_back(recursed.get());
return boost::optional<std::shared_ptr<change> >(
std::make_shared<concat_c>(changes));
}
if (contents.x >= contents.cont[contents.y].size()) {
contents.cont[contents.y].push_back(ch);
contents.x = contents.cont[contents.y].size();
n += ch;
} else {
o += contents.cont[contents.y][contents.x];
n += ch;
contents.cont[contents.y][contents.x] = ch;
contents.x++;
}
if (get_contents().refresh) {
print_contents(get_contents());
show_message("--INSERT (REPLACE)--");
}
}
contents.is_inserting = false;
showing_message = false;
return boost::optional<std::shared_ptr<change> >(
std::make_shared<replace_c>(o, n, contents.y, x));
}
struct append_c : public change {
const std::string track;
const move_t y, x;
append_c(const std::string& track, move_t y, move_t x)
: track(track)
, y(y)
, x(x) {}
virtual bool is_overriding() const noexcept override {
return true;
}
virtual void undo(contents& contents) override {
contents.cont[y] = contents.cont[y].substr(0, x) +
contents.cont[y].substr(x + track.size());
contents.y = y;
contents.x = x;
if (contents.x and contents.x >= contents.cont[y].size())
contents.x = contents.cont[y].size() - 1;
}
virtual void redo(contents& contents) override {
contents.cont[y] = contents.cont[y].substr(0, x) + track +
contents.cont[y].substr(x);
contents.y = y;
contents.x = x + track.size();
if (contents.x >= contents.cont[y].size())
contents.x = contents.cont[y].size() - 1;
}
virtual std::shared_ptr<change>
regenerate(const contents& contents) const override {
return std::make_shared<append_c>(track, contents.y,
contents.x + 1);
}
};
boost::optional<std::shared_ptr<change> >
enter_append_mode(contents& contents, boost::optional<int> pref) {
if (contents.cont[contents.y].empty())
return enter_insert_mode(contents, pref);
contents.x++;
std::string track;
auto x = contents.x;
char ch;
show_message("--INSERT--");
contents.is_inserting = true;
if (get_contents().refresh) {
print_contents(get_contents());
show_message("--INSERT--");
}
while ((ch = getch()) != QUIT_KEY) {
if (ch == '\n') {
std::vector<std::shared_ptr<change> > changes;
changes.reserve(3);
if (track.size())
changes.push_back(
std::make_shared<insert_c>(track, contents.y, x));
changes.push_back(std::make_shared<newline_c>(contents));
changes.back()->redo(contents);
auto recursed = enter_insert_mode(contents, pref);
if (recursed)
changes.push_back(recursed.get());
return boost::optional<std::shared_ptr<change> >(
std::make_shared<concat_c>(changes));
}
if (contents.x >= contents.cont[contents.y].size()) {
contents.cont[contents.y].push_back(ch);
contents.x = contents.cont[contents.y].size();
track += ch;
} else {
contents.cont[contents.y].insert(contents.x, 1, ch);
contents.x++;
track += ch;
}
if (get_contents().refresh) {
print_contents(get_contents());
show_message("--INSERT--");
}
}
contents.is_inserting = false;
showing_message = false;
// cancel out ++ from beginning
if (contents.x != 0)
contents.x--;
return boost::optional<std::shared_ptr<change> >(
std::make_shared<append_c>(track, contents.y, x));
}
}
}
<commit_msg>Remove references to `contents::is_inserting`<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include <ncurses.h>
#include "concat_c.hh"
#include "configuration.hh"
#include "contents.hh"
#include "file_contents.hh"
#include "../lib.hh"
#include "key_aliases.hh"
#include "show_message.hh"
#include "vick-move/lib.hh"
#include "print_contents.hh"
namespace vick {
namespace insert_mode {
struct insert_c : public change {
const std::string track;
const move_t y, x;
insert_c(const std::string& track, move_t y, move_t x)
: track(track)
, y(y)
, x(x) {}
virtual bool is_overriding() const noexcept override {
return true;
}
virtual void undo(contents& contents) override {
contents.cont[y] = contents.cont[y].substr(0, x) +
contents.cont[y].substr(x + track.size());
contents.y = y;
contents.x = x;
if (contents.x and contents.x >= contents.cont[y].size())
contents.x = contents.cont[y].size() - 1;
}
virtual void redo(contents& contents) override {
contents.cont[y] = contents.cont[y].substr(0, x) + track +
contents.cont[y].substr(x);
contents.y = y;
contents.x = x + track.size();
if (contents.x >= contents.cont[y].size())
contents.x = contents.cont[y].size() - 1;
}
virtual std::shared_ptr<change>
regenerate(const contents& contents) const override {
return std::make_shared<insert_c>(track, contents.y,
contents.x);
}
};
struct newline_c : public change {
const std::string first, second;
const move_t y;
newline_c(const contents& contents)
: first(contents.cont[contents.y].substr(0, contents.x))
, second(contents.cont[contents.y].substr(contents.x))
, y(contents.y) {}
virtual bool is_overriding() const noexcept override {
return true;
}
virtual void undo(contents& contents) override {
contents.cont[y] = first + second;
contents.cont.erase(contents.cont.begin() + y + 1);
contents.y = y;
contents.x = first.size();
}
virtual void redo(contents& contents) override {
contents.cont[y] = first;
contents.cont.insert(contents.cont.begin() + y + 1, second);
contents.y = y + 1;
contents.x = 0;
}
virtual std::shared_ptr<change>
regenerate(const contents& contents) const override {
return std::make_shared<newline_c>(contents);
}
};
boost::optional<std::shared_ptr<change> >
enter_insert_mode(contents& contents, boost::optional<int> pref) {
std::string track;
auto x = contents.x;
char ch;
show_message("--INSERT--");
if (contents.refresh) {
print_contents(contents);
show_message("--INSERT--");
}
while ((ch = getch()) != QUIT_KEY) {
if (ch == '\n') {
std::vector<std::shared_ptr<change> > changes;
changes.reserve(3);
if (track.size())
changes.push_back(
std::make_shared<insert_c>(track, contents.y, x));
changes.push_back(std::make_shared<newline_c>(contents));
changes.back()->redo(contents);
auto recursed = enter_insert_mode(contents, pref);
if (recursed)
changes.push_back(recursed.get());
return boost::optional<std::shared_ptr<change> >(
std::make_shared<concat_c>(changes));
}
if (contents.x >= contents.cont[contents.y].size()) {
contents.cont[contents.y].push_back(ch);
contents.x = contents.cont[contents.y].size();
track += ch;
} else {
contents.cont[contents.y].insert(contents.x, 1, ch);
contents.x++;
track += ch;
}
if (contents.refresh) {
print_contents(contents);
show_message("--INSERT--");
}
}
showing_message = false;
return boost::optional<std::shared_ptr<change> >(
std::make_shared<insert_c>(track, contents.y, x));
}
struct replace_c : public change {
const std::string o, n;
const move_t y, x;
replace_c(const std::string& o, const std::string& n, move_t y,
move_t x)
: o(o)
, n(n)
, y(y)
, x(x) {}
virtual bool is_overriding() const noexcept override {
return true;
}
virtual void undo(contents& contents) override {
contents.cont[y] = contents.cont[y].substr(0, x) + o +
contents.cont[y].substr(x + o.size());
}
virtual void redo(contents& contents) override {
contents.cont[y] = contents.cont[y].substr(0, x) + n +
contents.cont[y].substr(x + n.size());
}
virtual std::shared_ptr<change>
regenerate(const contents& contents) const override {
return std::make_shared<replace_c>(contents.cont[contents.y]
.substr(contents.x,
n.size()),
n, contents.y, contents.x);
}
};
boost::optional<std::shared_ptr<change> >
enter_replace_mode(contents& contents, boost::optional<int> pref) {
std::string o, n;
auto x = contents.x;
char ch;
show_message("--INSERT (REPLACE)--");
if (get_contents().refresh) {
print_contents(get_contents());
show_message("--INSERT (REPLACE)--");
}
while ((ch = getch()) != QUIT_KEY) {
if (ch == '\n') {
o = contents.cont[contents.y][contents.x];
std::vector<std::shared_ptr<change> > changes;
changes.reserve(3);
if (o.size())
changes.push_back(
std::make_shared<replace_c>(o, n, contents.y, x));
changes.push_back(std::make_shared<newline_c>(contents));
changes.back()->redo(contents);
auto recursed = enter_replace_mode(contents, pref);
if (recursed)
changes.push_back(recursed.get());
return boost::optional<std::shared_ptr<change> >(
std::make_shared<concat_c>(changes));
}
if (contents.x >= contents.cont[contents.y].size()) {
contents.cont[contents.y].push_back(ch);
contents.x = contents.cont[contents.y].size();
n += ch;
} else {
o += contents.cont[contents.y][contents.x];
n += ch;
contents.cont[contents.y][contents.x] = ch;
contents.x++;
}
if (get_contents().refresh) {
print_contents(get_contents());
show_message("--INSERT (REPLACE)--");
}
}
showing_message = false;
return boost::optional<std::shared_ptr<change> >(
std::make_shared<replace_c>(o, n, contents.y, x));
}
struct append_c : public change {
const std::string track;
const move_t y, x;
append_c(const std::string& track, move_t y, move_t x)
: track(track)
, y(y)
, x(x) {}
virtual bool is_overriding() const noexcept override {
return true;
}
virtual void undo(contents& contents) override {
contents.cont[y] = contents.cont[y].substr(0, x) +
contents.cont[y].substr(x + track.size());
contents.y = y;
contents.x = x;
if (contents.x and contents.x >= contents.cont[y].size())
contents.x = contents.cont[y].size() - 1;
}
virtual void redo(contents& contents) override {
contents.cont[y] = contents.cont[y].substr(0, x) + track +
contents.cont[y].substr(x);
contents.y = y;
contents.x = x + track.size();
if (contents.x >= contents.cont[y].size())
contents.x = contents.cont[y].size() - 1;
}
virtual std::shared_ptr<change>
regenerate(const contents& contents) const override {
return std::make_shared<append_c>(track, contents.y,
contents.x + 1);
}
};
boost::optional<std::shared_ptr<change> >
enter_append_mode(contents& contents, boost::optional<int> pref) {
if (contents.cont[contents.y].empty())
return enter_insert_mode(contents, pref);
contents.x++;
std::string track;
auto x = contents.x;
char ch;
show_message("--INSERT--");
if (get_contents().refresh) {
print_contents(get_contents());
show_message("--INSERT--");
}
while ((ch = getch()) != QUIT_KEY) {
if (ch == '\n') {
std::vector<std::shared_ptr<change> > changes;
changes.reserve(3);
if (track.size())
changes.push_back(
std::make_shared<insert_c>(track, contents.y, x));
changes.push_back(std::make_shared<newline_c>(contents));
changes.back()->redo(contents);
auto recursed = enter_insert_mode(contents, pref);
if (recursed)
changes.push_back(recursed.get());
return boost::optional<std::shared_ptr<change> >(
std::make_shared<concat_c>(changes));
}
if (contents.x >= contents.cont[contents.y].size()) {
contents.cont[contents.y].push_back(ch);
contents.x = contents.cont[contents.y].size();
track += ch;
} else {
contents.cont[contents.y].insert(contents.x, 1, ch);
contents.x++;
track += ch;
}
if (get_contents().refresh) {
print_contents(get_contents());
show_message("--INSERT--");
}
}
showing_message = false;
// cancel out ++ from beginning
if (contents.x != 0)
contents.x--;
return boost::optional<std::shared_ptr<change> >(
std::make_shared<append_c>(track, contents.y, x));
}
}
}
<|endoftext|> |
<commit_before>#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include <thread>
using std::thread;
#include <instruments.h>
#include <instruments_private.h>
#include "strategy.h"
#include "estimator.h"
#include "external_estimator.h"
#include "estimator_registry.h"
#include "strategy_evaluator.h"
#include "strategy_evaluation_context.h"
#include "continuous_distribution.h"
instruments_strategy_t
make_strategy(eval_fn_t time_fn, /* return seconds */
eval_fn_t energy_cost_fn, /* return mJ */
eval_fn_t data_cost_fn, /* return bytes */
void *strategy_arg, void *default_chooser_arg)
{
return new Strategy(time_fn, energy_cost_fn, data_cost_fn,
strategy_arg, default_chooser_arg);
}
instruments_strategy_t
make_redundant_strategy(const instruments_strategy_t *strategies,
size_t num_strategies)
{
return new Strategy(strategies, num_strategies);
}
void
set_strategy_name(instruments_strategy_t strategy_handle, const char * name)
{
Strategy *strategy = (Strategy *) strategy_handle;
strategy->setName(name);
}
const char *
get_strategy_name(instruments_strategy_t strategy_handle)
{
Strategy *strategy = (Strategy *) strategy_handle;
return strategy->getName();
}
void free_strategy(instruments_strategy_t strategy)
{
delete ((Strategy *) strategy);
}
double get_adjusted_estimator_value(instruments_context_t ctx, Estimator *estimator)
{
StrategyEvaluationContext *context = static_cast<StrategyEvaluationContext *>(ctx);
return context->getAdjustedEstimatorValue(estimator);
}
double get_estimator_value(instruments_context_t ctx,
instruments_estimator_t est_handle)
{
Estimator *estimator = static_cast<Estimator*>(est_handle);
return get_adjusted_estimator_value(ctx, estimator);
}
instruments_estimator_t
get_network_bandwidth_down_estimator(const char *iface)
{
return EstimatorRegistry::getNetworkBandwidthDownEstimator(iface);
}
instruments_estimator_t
get_network_bandwidth_up_estimator(const char *iface)
{
return EstimatorRegistry::getNetworkBandwidthUpEstimator(iface);
}
instruments_estimator_t
get_network_rtt_estimator(const char *iface)
{
return EstimatorRegistry::getNetworkRttEstimator(iface);
}
instruments_strategy_evaluator_t
register_strategy_set(const instruments_strategy_t *strategies, size_t num_strategies)
{
return StrategyEvaluator::create(strategies, num_strategies);
}
instruments_strategy_evaluator_t
register_strategy_set_with_method(const instruments_strategy_t *strategies, size_t num_strategies,
EvalMethod method)
{
return StrategyEvaluator::create(strategies, num_strategies, method);
}
void
free_strategy_evaluator(instruments_strategy_evaluator_t e)
{
StrategyEvaluator *evaluator = static_cast<StrategyEvaluator*>(e);
delete evaluator;
}
instruments_strategy_t
choose_strategy(instruments_strategy_evaluator_t evaluator_handle,
void *chooser_arg)
{
StrategyEvaluator *evaluator = (StrategyEvaluator *) evaluator_handle;
return evaluator->chooseStrategy(chooser_arg);
}
instruments_strategy_t
choose_nonredundant_strategy(instruments_strategy_evaluator_t evaluator_handle,
void *chooser_arg)
{
StrategyEvaluator *evaluator = (StrategyEvaluator *) evaluator_handle;
return evaluator->chooseStrategy(chooser_arg, /* redundancy = */ false);
}
double
get_last_strategy_time(instruments_strategy_evaluator_t evaluator_handle,
instruments_strategy_t strategy)
{
StrategyEvaluator *evaluator = (StrategyEvaluator *) evaluator_handle;
return evaluator->getLastStrategyTime(strategy);
}
void
choose_strategy_async(instruments_strategy_evaluator_t evaluator_handle,
void *chooser_arg,
instruments_strategy_chosen_callback_t callback,
void *callback_arg)
{
StrategyEvaluator *evaluator = (StrategyEvaluator *) evaluator_handle;
evaluator->chooseStrategyAsync(chooser_arg, callback, callback_arg);
}
instruments_scheduled_reevaluation_t
schedule_reevaluation(instruments_strategy_evaluator_t evaluator_handle,
void *chooser_arg,
instruments_pre_evaluation_callback_t pre_evaluation_callback,
void *pre_eval_callback_arg,
instruments_strategy_chosen_callback_t chosen_callback,
void *chosen_callback_arg,
double seconds_in_future)
{
StrategyEvaluator *evaluator = (StrategyEvaluator *) evaluator_handle;
return evaluator->scheduleReevaluation(chooser_arg,
pre_evaluation_callback, pre_eval_callback_arg,
chosen_callback, chosen_callback_arg,
seconds_in_future);
}
void cancel_scheduled_reevaluation(instruments_scheduled_reevaluation_t handle)
{
auto real_handle = static_cast<ScheduledReevaluationHandle *>(handle);
real_handle->cancel();
}
void free_scheduled_reevaluation(instruments_scheduled_reevaluation_t handle)
{
auto real_handle = static_cast<ScheduledReevaluationHandle *>(handle);
delete real_handle;
}
void
save_evaluator(instruments_strategy_evaluator_t evaluator_handle, const char *filename)
{
StrategyEvaluator *evaluator = (StrategyEvaluator *) evaluator_handle;
evaluator->saveToFile(filename);
}
void
restore_evaluator(instruments_strategy_evaluator_t evaluator_handle, const char *filename)
{
StrategyEvaluator *evaluator = (StrategyEvaluator *) evaluator_handle;
evaluator->restoreFromFile(filename);
}
static instruments_estimator_t
get_coin_flip_heads_estimator()
{
return EstimatorRegistry::getCoinFlipEstimator();
}
int coin_flip_lands_heads(instruments_context_t ctx)
{
instruments_estimator_t estimator = get_coin_flip_heads_estimator();
double value = get_estimator_value(ctx, estimator);
return (value >= 0.5);
}
void reset_coin_flip_estimator(EstimatorType type)
{
EstimatorRegistry::resetEstimator("CoinFlip", type);
}
void add_coin_flip_observation(int heads)
{
EstimatorRegistry::getCoinFlipEstimator()->addObservation(heads ? 1.0 : 0.0);
}
instruments_external_estimator_t
create_external_estimator(const char *name)
{
return new ExternalEstimator(name);
}
void free_external_estimator(instruments_external_estimator_t est_handle)
{
Estimator *estimator = static_cast<Estimator *>(est_handle);
delete estimator;
}
void add_observation(instruments_external_estimator_t est_handle,
double observation, double new_estimate)
{
ExternalEstimator *estimator = static_cast<ExternalEstimator *>(est_handle);
estimator->addObservation(observation, new_estimate);
}
void set_estimator_range_hints(instruments_estimator_t est_handle,
double min, double max, size_t num_bins)
{
Estimator *estimator = static_cast<Estimator *>(est_handle);
estimator->setRangeHints(min, max, num_bins);
}
int estimator_has_range_hints(instruments_estimator_t est_handle)
{
Estimator *estimator = static_cast<Estimator *>(est_handle);
return estimator->hasRangeHints() ? 1 : 0;
}
void set_estimator_condition(instruments_estimator_t est_handle,
instruments_estimator_condition_type_t condition_type,
double value)
{
Estimator *estimator = static_cast<Estimator *>(est_handle);
ConditionType type = ConditionType(condition_type);
estimator->setCondition(type, value);
}
void clear_estimator_conditions(instruments_estimator_t est_handle)
{
Estimator *estimator = static_cast<Estimator *>(est_handle);
estimator->clearConditions();
}
instruments_continuous_distribution_t create_continuous_distribution(double shape, double scale)
{
return new ContinuousDistribution(shape, scale);
}
void free_continuous_distribution(instruments_continuous_distribution_t distribution_handle)
{
ContinuousDistribution *dist = (ContinuousDistribution *) distribution_handle;
delete dist;
}
double get_probability_value_is_in_range(instruments_continuous_distribution_t distribution_handle,
double lower, double upper)
{
ContinuousDistribution *dist = (ContinuousDistribution *) distribution_handle;
return dist->getProbabilityValueIsInRange(lower, upper);
}
<commit_msg>Added option to just return raw estimator value if NULL context is passed.<commit_after>#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include <thread>
using std::thread;
#include <instruments.h>
#include <instruments_private.h>
#include "strategy.h"
#include "estimator.h"
#include "external_estimator.h"
#include "estimator_registry.h"
#include "strategy_evaluator.h"
#include "strategy_evaluation_context.h"
#include "continuous_distribution.h"
instruments_strategy_t
make_strategy(eval_fn_t time_fn, /* return seconds */
eval_fn_t energy_cost_fn, /* return mJ */
eval_fn_t data_cost_fn, /* return bytes */
void *strategy_arg, void *default_chooser_arg)
{
return new Strategy(time_fn, energy_cost_fn, data_cost_fn,
strategy_arg, default_chooser_arg);
}
instruments_strategy_t
make_redundant_strategy(const instruments_strategy_t *strategies,
size_t num_strategies)
{
return new Strategy(strategies, num_strategies);
}
void
set_strategy_name(instruments_strategy_t strategy_handle, const char * name)
{
Strategy *strategy = (Strategy *) strategy_handle;
strategy->setName(name);
}
const char *
get_strategy_name(instruments_strategy_t strategy_handle)
{
Strategy *strategy = (Strategy *) strategy_handle;
return strategy->getName();
}
void free_strategy(instruments_strategy_t strategy)
{
delete ((Strategy *) strategy);
}
double get_adjusted_estimator_value(instruments_context_t ctx, Estimator *estimator)
{
StrategyEvaluationContext *context = static_cast<StrategyEvaluationContext *>(ctx);
if (context) {
return context->getAdjustedEstimatorValue(estimator);
} else {
// app just wants the raw value.
return estimator->getEstimate();
}
}
double get_estimator_value(instruments_context_t ctx,
instruments_estimator_t est_handle)
{
Estimator *estimator = static_cast<Estimator*>(est_handle);
return get_adjusted_estimator_value(ctx, estimator);
}
instruments_estimator_t
get_network_bandwidth_down_estimator(const char *iface)
{
return EstimatorRegistry::getNetworkBandwidthDownEstimator(iface);
}
instruments_estimator_t
get_network_bandwidth_up_estimator(const char *iface)
{
return EstimatorRegistry::getNetworkBandwidthUpEstimator(iface);
}
instruments_estimator_t
get_network_rtt_estimator(const char *iface)
{
return EstimatorRegistry::getNetworkRttEstimator(iface);
}
instruments_strategy_evaluator_t
register_strategy_set(const instruments_strategy_t *strategies, size_t num_strategies)
{
return StrategyEvaluator::create(strategies, num_strategies);
}
instruments_strategy_evaluator_t
register_strategy_set_with_method(const instruments_strategy_t *strategies, size_t num_strategies,
EvalMethod method)
{
return StrategyEvaluator::create(strategies, num_strategies, method);
}
void
free_strategy_evaluator(instruments_strategy_evaluator_t e)
{
StrategyEvaluator *evaluator = static_cast<StrategyEvaluator*>(e);
delete evaluator;
}
instruments_strategy_t
choose_strategy(instruments_strategy_evaluator_t evaluator_handle,
void *chooser_arg)
{
StrategyEvaluator *evaluator = (StrategyEvaluator *) evaluator_handle;
return evaluator->chooseStrategy(chooser_arg);
}
instruments_strategy_t
choose_nonredundant_strategy(instruments_strategy_evaluator_t evaluator_handle,
void *chooser_arg)
{
StrategyEvaluator *evaluator = (StrategyEvaluator *) evaluator_handle;
return evaluator->chooseStrategy(chooser_arg, /* redundancy = */ false);
}
double
get_last_strategy_time(instruments_strategy_evaluator_t evaluator_handle,
instruments_strategy_t strategy)
{
StrategyEvaluator *evaluator = (StrategyEvaluator *) evaluator_handle;
return evaluator->getLastStrategyTime(strategy);
}
void
choose_strategy_async(instruments_strategy_evaluator_t evaluator_handle,
void *chooser_arg,
instruments_strategy_chosen_callback_t callback,
void *callback_arg)
{
StrategyEvaluator *evaluator = (StrategyEvaluator *) evaluator_handle;
evaluator->chooseStrategyAsync(chooser_arg, callback, callback_arg);
}
instruments_scheduled_reevaluation_t
schedule_reevaluation(instruments_strategy_evaluator_t evaluator_handle,
void *chooser_arg,
instruments_pre_evaluation_callback_t pre_evaluation_callback,
void *pre_eval_callback_arg,
instruments_strategy_chosen_callback_t chosen_callback,
void *chosen_callback_arg,
double seconds_in_future)
{
StrategyEvaluator *evaluator = (StrategyEvaluator *) evaluator_handle;
return evaluator->scheduleReevaluation(chooser_arg,
pre_evaluation_callback, pre_eval_callback_arg,
chosen_callback, chosen_callback_arg,
seconds_in_future);
}
void cancel_scheduled_reevaluation(instruments_scheduled_reevaluation_t handle)
{
auto real_handle = static_cast<ScheduledReevaluationHandle *>(handle);
real_handle->cancel();
}
void free_scheduled_reevaluation(instruments_scheduled_reevaluation_t handle)
{
auto real_handle = static_cast<ScheduledReevaluationHandle *>(handle);
delete real_handle;
}
void
save_evaluator(instruments_strategy_evaluator_t evaluator_handle, const char *filename)
{
StrategyEvaluator *evaluator = (StrategyEvaluator *) evaluator_handle;
evaluator->saveToFile(filename);
}
void
restore_evaluator(instruments_strategy_evaluator_t evaluator_handle, const char *filename)
{
StrategyEvaluator *evaluator = (StrategyEvaluator *) evaluator_handle;
evaluator->restoreFromFile(filename);
}
static instruments_estimator_t
get_coin_flip_heads_estimator()
{
return EstimatorRegistry::getCoinFlipEstimator();
}
int coin_flip_lands_heads(instruments_context_t ctx)
{
instruments_estimator_t estimator = get_coin_flip_heads_estimator();
double value = get_estimator_value(ctx, estimator);
return (value >= 0.5);
}
void reset_coin_flip_estimator(EstimatorType type)
{
EstimatorRegistry::resetEstimator("CoinFlip", type);
}
void add_coin_flip_observation(int heads)
{
EstimatorRegistry::getCoinFlipEstimator()->addObservation(heads ? 1.0 : 0.0);
}
instruments_external_estimator_t
create_external_estimator(const char *name)
{
return new ExternalEstimator(name);
}
void free_external_estimator(instruments_external_estimator_t est_handle)
{
Estimator *estimator = static_cast<Estimator *>(est_handle);
delete estimator;
}
void add_observation(instruments_external_estimator_t est_handle,
double observation, double new_estimate)
{
ExternalEstimator *estimator = static_cast<ExternalEstimator *>(est_handle);
estimator->addObservation(observation, new_estimate);
}
void set_estimator_range_hints(instruments_estimator_t est_handle,
double min, double max, size_t num_bins)
{
Estimator *estimator = static_cast<Estimator *>(est_handle);
estimator->setRangeHints(min, max, num_bins);
}
int estimator_has_range_hints(instruments_estimator_t est_handle)
{
Estimator *estimator = static_cast<Estimator *>(est_handle);
return estimator->hasRangeHints() ? 1 : 0;
}
void set_estimator_condition(instruments_estimator_t est_handle,
instruments_estimator_condition_type_t condition_type,
double value)
{
Estimator *estimator = static_cast<Estimator *>(est_handle);
ConditionType type = ConditionType(condition_type);
estimator->setCondition(type, value);
}
void clear_estimator_conditions(instruments_estimator_t est_handle)
{
Estimator *estimator = static_cast<Estimator *>(est_handle);
estimator->clearConditions();
}
instruments_continuous_distribution_t create_continuous_distribution(double shape, double scale)
{
return new ContinuousDistribution(shape, scale);
}
void free_continuous_distribution(instruments_continuous_distribution_t distribution_handle)
{
ContinuousDistribution *dist = (ContinuousDistribution *) distribution_handle;
delete dist;
}
double get_probability_value_is_in_range(instruments_continuous_distribution_t distribution_handle,
double lower, double upper)
{
ContinuousDistribution *dist = (ContinuousDistribution *) distribution_handle;
return dist->getProbabilityValueIsInRange(lower, upper);
}
<|endoftext|> |
<commit_before>/* +------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| http://www.mrpt.org/ |
| |
| Copyright (c) 2005-2018, Individual contributors, see AUTHORS file |
| See: http://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See details in http://www.mrpt.org/License |
+------------------------------------------------------------------------+ */
#include "hmtslam-precomp.h" // Precomp header
#include <mrpt/system/CTicTac.h>
#include <mrpt/random.h>
#include <mrpt/io/CFileStream.h>
#include <mrpt/containers/printf_vector.h>
#include <mrpt/poses/CPose3DPDFParticles.h>
#include <mrpt/system/os.h>
using namespace mrpt::slam;
using namespace mrpt::hmtslam;
using namespace mrpt::poses;
using namespace mrpt::obs;
using namespace std;
/*---------------------------------------------------------------
areaAbstraction
Area Abstraction (AA) process within HMT-SLAM
---------------------------------------------------------------*/
CHMTSLAM::TMessageLSLAMfromAA::Ptr CHMTSLAM::areaAbstraction(
CLocalMetricHypothesis* LMH, const TPoseIDList& newPoseIDs)
{
MRPT_START
ASSERT_(!newPoseIDs.empty());
ASSERT_(LMH);
CHMTSLAM* obj = LMH->m_parent.get();
ASSERT_(obj);
// The output results:
TMessageLSLAMfromAA::Ptr resMsg =
TMessageLSLAMfromAA::Ptr(new TMessageLSLAMfromAA());
// Process msg:
THypothesisID LMH_ID = LMH->m_ID;
resMsg->hypothesisID = LMH_ID;
for (TPoseIDList::const_iterator newID = newPoseIDs.begin();
newID != newPoseIDs.end(); ++newID)
{
// Add a new node to the graph:
obj->logFmt(
mrpt::system::LVL_DEBUG, "[thread_AA] Processing new pose ID: %u\n",
static_cast<unsigned>(*newID));
// Get SF & pose pdf for the new pose.
const CSensoryFrame* sf;
CPose3DPDFParticles::Ptr posePDF =
mrpt::make_aligned_shared<CPose3DPDFParticles>();
{
// std::lock_guard<std::mutex> lock( LMH->m_lock ); // We are
// already within the LMH's lock!
// SF:
std::map<TPoseID, CSensoryFrame>::const_iterator itSFs =
LMH->m_SFs.find(*newID);
ASSERT_(itSFs != LMH->m_SFs.end());
sf = &itSFs->second;
// Pose PDF:
LMH->getPoseParticles(*newID, *posePDF);
} // end of LMH's critical section lock
{
std::lock_guard<std::mutex> locker(LMH->m_robotPosesGraph.lock);
// Add to the graph partitioner:
LMH->m_robotPosesGraph.partitioner.options =
obj->m_options.AA_options;
unsigned int newIdx =
LMH->m_robotPosesGraph.partitioner.addMapFrame(
CSensoryFrame::Ptr(new CSensoryFrame(*sf)), posePDF);
LMH->m_robotPosesGraph.idx2pose[newIdx] = *newID;
} // end of critical section lock on "m_robotPosesGraph.lock"
} // end for each new ID
vector<std::vector<uint32_t>> partitions;
{
std::lock_guard<std::mutex> locker(LMH->m_robotPosesGraph.lock);
LMH->m_robotPosesGraph.partitioner.updatePartitions(partitions);
}
// Send result to LSLAM
resMsg->partitions.resize(partitions.size());
vector<TPoseIDList>::iterator itDest;
vector<std::vector<uint32_t>>::const_iterator itSrc;
for (itDest = resMsg->partitions.begin(), itSrc = partitions.begin();
itSrc != partitions.end(); itSrc++, itDest++)
{
itDest->resize(itSrc->size());
std::vector<uint32_t>::const_iterator it1;
TPoseIDList::iterator it2;
for (it1 = itSrc->begin(), it2 = itDest->begin(); it1 != itSrc->end();
it1++, it2++)
*it2 = LMH->m_robotPosesGraph.idx2pose[*it1];
}
resMsg->dumpToConsole();
return resMsg;
MRPT_END
}
void CHMTSLAM::TMessageLSLAMfromAA::dumpToConsole() const
{
cout << format(
"Hypo ID: %i has %i partitions:\n", (int)hypothesisID,
(int)partitions.size());
for (std::vector<TPoseIDList>::const_iterator it = partitions.begin();
it != partitions.end(); ++it)
{
mrpt::containers::printf_vector("%i", *it);
cout << endl;
}
}
<commit_msg>fix build<commit_after>/* +------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| http://www.mrpt.org/ |
| |
| Copyright (c) 2005-2018, Individual contributors, see AUTHORS file |
| See: http://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See details in http://www.mrpt.org/License |
+------------------------------------------------------------------------+ */
#include "hmtslam-precomp.h" // Precomp header
#include <mrpt/system/CTicTac.h>
#include <mrpt/random.h>
#include <mrpt/io/CFileStream.h>
#include <mrpt/containers/printf_vector.h>
#include <mrpt/poses/CPose3DPDFParticles.h>
#include <mrpt/system/os.h>
using namespace mrpt::slam;
using namespace mrpt::hmtslam;
using namespace mrpt::poses;
using namespace mrpt::obs;
using namespace std;
/*---------------------------------------------------------------
areaAbstraction
Area Abstraction (AA) process within HMT-SLAM
---------------------------------------------------------------*/
CHMTSLAM::TMessageLSLAMfromAA::Ptr CHMTSLAM::areaAbstraction(
CLocalMetricHypothesis* LMH, const TPoseIDList& newPoseIDs)
{
MRPT_START
ASSERT_(!newPoseIDs.empty());
ASSERT_(LMH);
CHMTSLAM* obj = LMH->m_parent.get();
ASSERT_(obj);
// The output results:
TMessageLSLAMfromAA::Ptr resMsg =
TMessageLSLAMfromAA::Ptr(new TMessageLSLAMfromAA());
// Process msg:
THypothesisID LMH_ID = LMH->m_ID;
resMsg->hypothesisID = LMH_ID;
for (TPoseIDList::const_iterator newID = newPoseIDs.begin();
newID != newPoseIDs.end(); ++newID)
{
// Add a new node to the graph:
obj->logFmt(
mrpt::system::LVL_DEBUG, "[thread_AA] Processing new pose ID: %u\n",
static_cast<unsigned>(*newID));
// Get SF & pose pdf for the new pose.
const CSensoryFrame* sf;
CPose3DPDFParticles::Ptr posePDF =
mrpt::make_aligned_shared<CPose3DPDFParticles>();
{
// std::lock_guard<std::mutex> lock( LMH->m_lock ); // We are
// already within the LMH's lock!
// SF:
std::map<TPoseID, CSensoryFrame>::const_iterator itSFs =
LMH->m_SFs.find(*newID);
ASSERT_(itSFs != LMH->m_SFs.end());
sf = &itSFs->second;
// Pose PDF:
LMH->getPoseParticles(*newID, *posePDF);
} // end of LMH's critical section lock
{
std::lock_guard<std::mutex> locker(LMH->m_robotPosesGraph.lock);
// Add to the graph partitioner:
LMH->m_robotPosesGraph.partitioner.options =
obj->m_options.AA_options;
unsigned int newIdx =
LMH->m_robotPosesGraph.partitioner.addMapFrame(
*sf, *posePDF);
LMH->m_robotPosesGraph.idx2pose[newIdx] = *newID;
} // end of critical section lock on "m_robotPosesGraph.lock"
} // end for each new ID
vector<std::vector<uint32_t>> partitions;
{
std::lock_guard<std::mutex> locker(LMH->m_robotPosesGraph.lock);
LMH->m_robotPosesGraph.partitioner.updatePartitions(partitions);
}
// Send result to LSLAM
resMsg->partitions.resize(partitions.size());
vector<TPoseIDList>::iterator itDest;
vector<std::vector<uint32_t>>::const_iterator itSrc;
for (itDest = resMsg->partitions.begin(), itSrc = partitions.begin();
itSrc != partitions.end(); itSrc++, itDest++)
{
itDest->resize(itSrc->size());
std::vector<uint32_t>::const_iterator it1;
TPoseIDList::iterator it2;
for (it1 = itSrc->begin(), it2 = itDest->begin(); it1 != itSrc->end();
it1++, it2++)
*it2 = LMH->m_robotPosesGraph.idx2pose[*it1];
}
resMsg->dumpToConsole();
return resMsg;
MRPT_END
}
void CHMTSLAM::TMessageLSLAMfromAA::dumpToConsole() const
{
cout << format(
"Hypo ID: %i has %i partitions:\n", (int)hypothesisID,
(int)partitions.size());
for (std::vector<TPoseIDList>::const_iterator it = partitions.begin();
it != partitions.end(); ++it)
{
mrpt::containers::printf_vector("%i", *it);
cout << endl;
}
}
<|endoftext|> |
<commit_before>// BaseDisplay.hh for Fluxbox Window Manager
// Copyright (c) 2001 - 2002 Henrik Kinnunen ([email protected])
//
// BaseDisplay.hh for Blackbox - an X11 Window manager
// Copyright (c) 1997 - 2000 Brad Hughes ([email protected])
//
// 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.
// $Id: BaseDisplay.hh,v 1.21 2002/05/17 11:55:31 fluxgen Exp $
#ifndef BASEDISPLAY_HH
#define BASEDISPLAY_HH
#include "NotCopyable.hh"
#include "FbAtoms.hh"
#include <X11/Xlib.h>
#ifdef XINERAMA
extern "C" {
#include <X11/extensions/Xinerama.h>
}
#endif // XINERAMA
#include <list>
#include <vector>
// forward declaration
class ScreenInfo;
#define PropBlackboxHintsElements (5)
#define PropBlackboxAttributesElements (8)
void bexec(const char *command, char* displaystring);
class BaseDisplay:private NotCopyable, public FbAtoms
{
public:
BaseDisplay(char *, char * = 0);
virtual ~BaseDisplay(void);
enum Attrib {
ATTRIB_SHADED = 0x01,
ATTRIB_MAXHORIZ = 0x02,
ATTRIB_MAXVERT = 0x04,
ATTRIB_OMNIPRESENT = 0x08,
ATTRIB_WORKSPACE = 0x10,
ATTRIB_STACK = 0x20,
ATTRIB_DECORATION = 0x40
};
typedef struct _blackbox_hints {
unsigned long flags, attrib, workspace, stack;
int decoration;
} BlackboxHints;
typedef struct _blackbox_attributes {
unsigned long flags, attrib, workspace, stack;
int premax_x, premax_y;
unsigned int premax_w, premax_h;
} BlackboxAttributes;
inline ScreenInfo *getScreenInfo(int s) { return screenInfoList[s]; }
inline bool hasShapeExtensions(void) const { return shape.extensions; }
inline bool doShutdown(void) const { return m_shutdown; }
inline bool isStartup(void) const { return m_startup; }
inline const Cursor &getSessionCursor(void) const { return cursor.session; }
inline const Cursor &getMoveCursor(void) const { return cursor.move; }
inline const Cursor &getLowerLeftAngleCursor(void) const { return cursor.ll_angle; }
inline const Cursor &getLowerRightAngleCursor(void) const { return cursor.lr_angle; }
inline Display *getXDisplay(void) { return m_display; }
inline const char *getXDisplayName(void) const { return const_cast<const char *>(m_display_name); }
inline const char *getApplicationName(void) const { return const_cast<const char *>(m_app_name); }
inline int getNumberOfScreens(void) const { return number_of_screens; }
inline int getShapeEventBase(void) const { return shape.event_basep; }
inline void shutdown(void) { m_shutdown = true; }
inline void run(void) { m_startup = m_shutdown = false; }
bool validateWindow(Window);
void grab(void);
void ungrab(void);
void eventLoop(void);
// another pure virtual... this is used to handle signals that BaseDisplay
// doesn't understand itself
virtual Bool handleSignal(int) = 0;
class GrabGuard:private NotCopyable
{
public:
GrabGuard(BaseDisplay &bd):m_bd(bd) { }
~GrabGuard() { m_bd.ungrab(); }
inline void grab() { m_bd.grab(); }
inline void ungrab() { m_bd.ungrab(); }
private:
BaseDisplay &m_bd;
};
private:
struct cursor {
Cursor session, move, ll_angle, lr_angle;
} cursor;
struct shape {
Bool extensions;
int event_basep, error_basep;
} shape;
bool m_startup, m_shutdown;
Display *m_display;
typedef std::vector<ScreenInfo *> ScreenInfoList;
ScreenInfoList screenInfoList;
char *m_display_name, *m_app_name;
int number_of_screens, m_server_grabs, colors_per_channel;
protected:
virtual void process_event(XEvent *) = 0;
};
class ScreenInfo {
public:
ScreenInfo(BaseDisplay *, int);
~ScreenInfo(void);
inline BaseDisplay *getBaseDisplay(void) { return basedisplay; }
inline Visual *getVisual(void) { return visual; }
inline const Window &getRootWindow(void) const { return root_window; }
inline const Colormap &getColormap(void) const { return colormap; }
inline int getDepth(void) const { return depth; }
inline int getScreenNumber(void) const { return screen_number; }
inline unsigned int getWidth(void) const { return width; }
inline unsigned int getHeight(void) const { return height; }
#ifdef XINERAMA
inline bool hasXinerama(void) const { return m_hasXinerama; }
inline int getNumHeads(void) const { return xineramaNumHeads; }
unsigned int getHead(int x, int y) const;
unsigned int getCurrHead(void) const;
unsigned int getHeadWidth(unsigned int head) const;
unsigned int getHeadHeight(unsigned int head) const;
int getHeadX(unsigned int head) const;
int getHeadY(unsigned int head) const;
#endif // XINERAMA
private:
BaseDisplay *basedisplay;
Visual *visual;
Window root_window;
Colormap colormap;
int depth, screen_number;
unsigned int width, height;
#ifdef XINERAMA
bool m_hasXinerama;
int xineramaMajor, xineramaMinor, xineramaNumHeads, xineramaLastHead;
XineramaScreenInfo *xineramaInfos;
#endif // XINERAMA
};
#endif // BASEDISPLAY_HH
<commit_msg>changed function name<commit_after>// BaseDisplay.hh for Fluxbox Window Manager
// Copyright (c) 2001 - 2002 Henrik Kinnunen ([email protected])
//
// BaseDisplay.hh for Blackbox - an X11 Window manager
// Copyright (c) 1997 - 2000 Brad Hughes ([email protected])
//
// 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.
// $Id: BaseDisplay.hh,v 1.22 2002/07/19 21:14:11 fluxgen Exp $
#ifndef BASEDISPLAY_HH
#define BASEDISPLAY_HH
#include "NotCopyable.hh"
#include "FbAtoms.hh"
#include <X11/Xlib.h>
#ifdef XINERAMA
extern "C" {
#include <X11/extensions/Xinerama.h>
}
#endif // XINERAMA
#include <list>
#include <vector>
// forward declaration
class ScreenInfo;
#define PropBlackboxHintsElements (5)
#define PropBlackboxAttributesElements (8)
void bexec(const char *command, char* displaystring);
class BaseDisplay:private NotCopyable, public FbAtoms
{
public:
BaseDisplay(char *, char * = 0);
virtual ~BaseDisplay(void);
enum Attrib {
ATTRIB_SHADED = 0x01,
ATTRIB_MAXHORIZ = 0x02,
ATTRIB_MAXVERT = 0x04,
ATTRIB_OMNIPRESENT = 0x08,
ATTRIB_WORKSPACE = 0x10,
ATTRIB_STACK = 0x20,
ATTRIB_DECORATION = 0x40
};
typedef struct _blackbox_hints {
unsigned long flags, attrib, workspace, stack;
int decoration;
} BlackboxHints;
typedef struct _blackbox_attributes {
unsigned long flags, attrib, workspace, stack;
int premax_x, premax_y;
unsigned int premax_w, premax_h;
} BlackboxAttributes;
inline ScreenInfo *getScreenInfo(int s) { return screenInfoList[s]; }
inline bool hasShapeExtensions(void) const { return shape.extensions; }
inline bool doShutdown(void) const { return m_shutdown; }
inline bool isStartup(void) const { return m_startup; }
inline const Cursor &getSessionCursor(void) const { return cursor.session; }
inline const Cursor &getMoveCursor(void) const { return cursor.move; }
inline const Cursor &getLowerLeftAngleCursor(void) const { return cursor.ll_angle; }
inline const Cursor &getLowerRightAngleCursor(void) const { return cursor.lr_angle; }
inline Display *getXDisplay(void) { return m_display; }
inline const char *getXDisplayName(void) const { return const_cast<const char *>(m_display_name); }
inline const char *getApplicationName(void) const { return const_cast<const char *>(m_app_name); }
inline int getNumberOfScreens(void) const { return number_of_screens; }
inline int getShapeEventBase(void) const { return shape.event_basep; }
inline void shutdown(void) { m_shutdown = true; }
inline void run(void) { m_startup = m_shutdown = false; }
bool validateWindow(Window);
void grab(void);
void ungrab(void);
void eventLoop(void);
// another pure virtual... this is used to handle signals that BaseDisplay
// doesn't understand itself
virtual Bool handleSignal(int) = 0;
class GrabGuard:private NotCopyable
{
public:
GrabGuard(BaseDisplay &bd):m_bd(bd) { }
~GrabGuard() { m_bd.ungrab(); }
inline void grab() { m_bd.grab(); }
inline void ungrab() { m_bd.ungrab(); }
private:
BaseDisplay &m_bd;
};
private:
struct cursor {
Cursor session, move, ll_angle, lr_angle;
} cursor;
struct shape {
Bool extensions;
int event_basep, error_basep;
} shape;
bool m_startup, m_shutdown;
Display *m_display;
typedef std::vector<ScreenInfo *> ScreenInfoList;
ScreenInfoList screenInfoList;
char *m_display_name, *m_app_name;
int number_of_screens, m_server_grabs, colors_per_channel;
protected:
virtual void process_event(XEvent *) = 0;
};
class ScreenInfo {
public:
ScreenInfo(BaseDisplay *, int);
~ScreenInfo(void);
inline BaseDisplay *getBaseDisplay(void) { return basedisplay; }
inline Visual *getVisual(void) { return visual; }
inline const Window &getRootWindow(void) const { return root_window; }
inline const Colormap &colormap(void) const { return m_colormap; }
inline int getDepth(void) const { return depth; }
inline int getScreenNumber(void) const { return screen_number; }
inline unsigned int getWidth(void) const { return width; }
inline unsigned int getHeight(void) const { return height; }
#ifdef XINERAMA
inline bool hasXinerama(void) const { return m_hasXinerama; }
inline int getNumHeads(void) const { return xineramaNumHeads; }
unsigned int getHead(int x, int y) const;
unsigned int getCurrHead(void) const;
unsigned int getHeadWidth(unsigned int head) const;
unsigned int getHeadHeight(unsigned int head) const;
int getHeadX(unsigned int head) const;
int getHeadY(unsigned int head) const;
#endif // XINERAMA
private:
BaseDisplay *basedisplay;
Visual *visual;
Window root_window;
Colormap m_colormap;
int depth, screen_number;
unsigned int width, height;
#ifdef XINERAMA
bool m_hasXinerama;
int xineramaMajor, xineramaMinor, xineramaNumHeads, xineramaLastHead;
XineramaScreenInfo *xineramaInfos;
#endif // XINERAMA
};
#endif // BASEDISPLAY_HH
<|endoftext|> |
<commit_before>#include "depthai-bootloader-shared/Bootloader.hpp"
namespace dai {
namespace bootloader {
// Bootloader.hpp definitions
// Requests
decltype(request::UsbRomBoot::VERSION) constexpr request::UsbRomBoot::VERSION;
decltype(request::UsbRomBoot::NAME) constexpr request::UsbRomBoot::NAME;
decltype(request::BootApplication::VERSION) constexpr request::BootApplication::VERSION;
decltype(request::BootApplication::NAME) constexpr request::BootApplication::NAME;
decltype(request::UpdateFlash::VERSION) constexpr request::UpdateFlash::VERSION;
decltype(request::UpdateFlash::NAME) constexpr request::UpdateFlash::NAME;
decltype(request::GetBootloaderVersion::VERSION) constexpr request::GetBootloaderVersion::VERSION;
decltype(request::GetBootloaderVersion::NAME) constexpr request::GetBootloaderVersion::NAME;
decltype(request::BootMemory::VERSION) constexpr request::BootMemory::VERSION;
decltype(request::BootMemory::NAME) constexpr request::BootMemory::NAME;
decltype(request::UpdateFlashEx::VERSION) constexpr request::UpdateFlashEx::VERSION;
decltype(request::UpdateFlashEx::NAME) constexpr request::UpdateFlashEx::NAME;
decltype(request::UpdateFlashEx2::VERSION) constexpr request::UpdateFlashEx2::VERSION;
decltype(request::UpdateFlashEx2::NAME) constexpr request::UpdateFlashEx2::NAME;
decltype(request::GetBootloaderType::VERSION) constexpr request::GetBootloaderType::VERSION;
decltype(request::GetBootloaderType::NAME) constexpr request::GetBootloaderType::NAME;
decltype(request::SetBootloaderConfig::VERSION) constexpr request::SetBootloaderConfig::VERSION;
decltype(request::SetBootloaderConfig::NAME) constexpr request::SetBootloaderConfig::NAME;
decltype(request::GetBootloaderConfig::VERSION) constexpr request::GetBootloaderConfig::VERSION;
decltype(request::GetBootloaderConfig::NAME) constexpr request::GetBootloaderConfig::NAME;
decltype(request::BootloaderMemory::VERSION) constexpr request::BootloaderMemory::VERSION;
decltype(request::BootloaderMemory::NAME) constexpr request::BootloaderMemory::NAME;
// Responses
decltype(response::FlashComplete::VERSION) constexpr response::FlashComplete::VERSION;
decltype(response::FlashComplete::NAME) constexpr response::FlashComplete::NAME;
decltype(response::FlashStatusUpdate::VERSION) constexpr response::FlashStatusUpdate::VERSION;
decltype(response::FlashStatusUpdate::NAME) constexpr response::FlashStatusUpdate::NAME;
decltype(response::BootloaderVersion::VERSION) constexpr response::BootloaderVersion::VERSION;
decltype(response::BootloaderVersion::NAME) constexpr response::BootloaderVersion::NAME;
decltype(response::BootloaderType::VERSION) constexpr response::BootloaderType::VERSION;
decltype(response::BootloaderType::NAME) constexpr response::BootloaderType::NAME;
decltype(response::GetBootloaderConfig::VERSION) constexpr response::GetBootloaderConfig::VERSION;
decltype(response::GetBootloaderConfig::NAME) constexpr response::GetBootloaderConfig::NAME;
decltype(response::BootloaderMemory::VERSION) constexpr response::BootloaderMemory::VERSION;
decltype(response::BootloaderMemory::NAME) constexpr response::BootloaderMemory::NAME;
decltype(response::BootApplication::VERSION) constexpr response::BootApplication::VERSION;
decltype(response::BootApplication::NAME) constexpr response::BootApplication::NAME;
} // namespace bootloader
} // namespace dai<commit_msg>Added declarations<commit_after>#include "depthai-bootloader-shared/Bootloader.hpp"
namespace dai {
namespace bootloader {
// Bootloader.hpp definitions
// Requests
decltype(request::UsbRomBoot::VERSION) constexpr request::UsbRomBoot::VERSION;
decltype(request::UsbRomBoot::NAME) constexpr request::UsbRomBoot::NAME;
decltype(request::BootApplication::VERSION) constexpr request::BootApplication::VERSION;
decltype(request::BootApplication::NAME) constexpr request::BootApplication::NAME;
decltype(request::UpdateFlash::VERSION) constexpr request::UpdateFlash::VERSION;
decltype(request::UpdateFlash::NAME) constexpr request::UpdateFlash::NAME;
decltype(request::GetBootloaderVersion::VERSION) constexpr request::GetBootloaderVersion::VERSION;
decltype(request::GetBootloaderVersion::NAME) constexpr request::GetBootloaderVersion::NAME;
decltype(request::BootMemory::VERSION) constexpr request::BootMemory::VERSION;
decltype(request::BootMemory::NAME) constexpr request::BootMemory::NAME;
decltype(request::UpdateFlashEx::VERSION) constexpr request::UpdateFlashEx::VERSION;
decltype(request::UpdateFlashEx::NAME) constexpr request::UpdateFlashEx::NAME;
decltype(request::UpdateFlashEx2::VERSION) constexpr request::UpdateFlashEx2::VERSION;
decltype(request::UpdateFlashEx2::NAME) constexpr request::UpdateFlashEx2::NAME;
decltype(request::GetBootloaderType::VERSION) constexpr request::GetBootloaderType::VERSION;
decltype(request::GetBootloaderType::NAME) constexpr request::GetBootloaderType::NAME;
decltype(request::SetBootloaderConfig::VERSION) constexpr request::SetBootloaderConfig::VERSION;
decltype(request::SetBootloaderConfig::NAME) constexpr request::SetBootloaderConfig::NAME;
decltype(request::GetBootloaderConfig::VERSION) constexpr request::GetBootloaderConfig::VERSION;
decltype(request::GetBootloaderConfig::NAME) constexpr request::GetBootloaderConfig::NAME;
decltype(request::BootloaderMemory::VERSION) constexpr request::BootloaderMemory::VERSION;
decltype(request::BootloaderMemory::NAME) constexpr request::BootloaderMemory::NAME;
decltype(request::UpdateBootHeader::VERSION) constexpr request::UpdateBootHeader::VERSION;
decltype(request::UpdateBootHeader::NAME) constexpr request::UpdateBootHeader::NAME;
decltype(request::ReadFlash::VERSION) constexpr request::ReadFlash::VERSION;
decltype(request::ReadFlash::NAME) constexpr request::ReadFlash::NAME;
// Responses
decltype(response::FlashComplete::VERSION) constexpr response::FlashComplete::VERSION;
decltype(response::FlashComplete::NAME) constexpr response::FlashComplete::NAME;
decltype(response::FlashStatusUpdate::VERSION) constexpr response::FlashStatusUpdate::VERSION;
decltype(response::FlashStatusUpdate::NAME) constexpr response::FlashStatusUpdate::NAME;
decltype(response::BootloaderVersion::VERSION) constexpr response::BootloaderVersion::VERSION;
decltype(response::BootloaderVersion::NAME) constexpr response::BootloaderVersion::NAME;
decltype(response::BootloaderType::VERSION) constexpr response::BootloaderType::VERSION;
decltype(response::BootloaderType::NAME) constexpr response::BootloaderType::NAME;
decltype(response::GetBootloaderConfig::VERSION) constexpr response::GetBootloaderConfig::VERSION;
decltype(response::GetBootloaderConfig::NAME) constexpr response::GetBootloaderConfig::NAME;
decltype(response::BootloaderMemory::VERSION) constexpr response::BootloaderMemory::VERSION;
decltype(response::BootloaderMemory::NAME) constexpr response::BootloaderMemory::NAME;
decltype(response::BootApplication::VERSION) constexpr response::BootApplication::VERSION;
decltype(response::BootApplication::NAME) constexpr response::BootApplication::NAME;
decltype(response::ReadFlash::VERSION) constexpr response::ReadFlash::VERSION;
decltype(response::ReadFlash::NAME) constexpr response::ReadFlash::NAME;
} // namespace bootloader
} // namespace dai<|endoftext|> |
<commit_before>#pragma once
// TODO only include iostream/write errors in debug
#include <csignal>
#include <dlfcn.h>
#include <functional>
#include <iostream>
#include <map>
#include <memory>
#include <string>
constexpr int LOAD_MODE = RTLD_NOW;
// This class should be unreachable from outside
namespace
{
template<class base>
struct module
{
module (std::function<base*()> f, void* h)
: function(f)
, handler(h)
{}
std::function<base*()> function;
void* handler;
};
};
template<class base>
class modular
{
using M = module<base>;
public:
// Get the singleton instance
static modular<base>& get_instance()
{
static modular<base> singleton_instance;
return singleton_instance;
}
// Load a library with a given path
void load (const std::string& path)
{
void* handler = dlopen(path.c_str(), LOAD_MODE);
if (!handler)
{
std::cerr << "(modular) Could not open path: " << path << '\n';
std::abort();
}
void* ctor = dlsym(handler, base::constructor);
if (dlerror() != nullptr)
{
std::cerr << "(modular) Could not read symbol: " << path << ":" << base::constructor << '\n';
dlclose(handler);
std::abort();
}
std::function<base*()> ptr = reinterpret_cast<base*(*)()>(ctor);
modules.insert(std::pair<std::string, M>(path, M(ptr, handler)));
}
// Create a new object from a mapped library
std::unique_ptr<base> create (const std::string& path) const
{
auto it = modules.find(path);
std::unique_ptr<base> module_instance(it->second.function());
// Check version and abort in case of version mismatch
if (module_instance->version() >= base::version_min && module_instance->version() <= base::version_max)
{
return module_instance;
}
else
{
std::cerr << "(modular) Module version mismatch:\n"
<< "Supported version range: " << base::version_min << " - " << base::version_max << '\n'
<< path << " version: " << module_instance->version() << '\n';
std::abort();
}
}
private:
modular (){};
~modular ()
{
for (auto& m : modules)
{
int error = dlclose(m.second.handler);
if (error)
{
std::cout << "(modular) Could not close library: " << m.first << '\n';
}
}
};
// Disable copy
modular (const modular&) = delete;
modular& operator= (const modular&) = delete;
// Disable move
modular (const modular&&) = delete;
modular& operator= (modular&&) = delete;
static std::map<std::string, M> modules;
};
template<typename base>
std::map<std::string, module<base>> modular<base>::modules;
<commit_msg>Refactor modular architecture.<commit_after>#pragma once
#include <dlfcn.h>
#include <functional>
#include <map>
#include <memory>
#include <string>
namespace
{
struct module_loader
{
using module_handler = std::unique_ptr<void, std::function<void(void*)>>;
static module_handler& get (const std::string& path)
{
auto handler = modules.find(path);
if (handler == modules.end())
{
handler = modules.emplace(path, module_handler(dlopen(path.c_str(), LOAD_MODE), dl_close)).first;
}
return handler->second;
}
private:
// dlopen load mode
static constexpr int LOAD_MODE = RTLD_NOW;
static void dl_close (void* handler)
{
dlclose(handler);
}
static std::map<std::string, module_handler> modules;
};
std::map<std::string, module_loader::module_handler> module_loader::modules;
template<class I>
struct _default
{
static std::unique_ptr<I> create (const std::string& path)
{
auto func = functions.find(path);
if (func == functions.end())
{
func = functions.emplace(path, reinterpret_cast<I*(*)()>(dlsym(module_loader::get(path).get(), I::default_param))).first;
}
return std::unique_ptr<I>(func->second());
}
private:
static std::map<std::string, std::function<I*()>> functions;
};
template<class I>
std::map<std::string, std::function<I*()>> _default<I>::functions;
template<class I, typename P, typename EP>
struct _copy
{
static std::unique_ptr<I> create (const std::string& path, const P& p, const EP& ep)
{
auto func = functions.find(path);
if (func == functions.end())
{
func = functions.emplace(path, reinterpret_cast<I*(*)(const P&, const EP&)>(dlsym(module_loader::get(path).get(), I::default_param))).first;
}
return std::unique_ptr<I>(func->second(p, ep));
}
private:
static std::map<std::string, std::function<I*(const P&, const EP&)>> functions;
};
template<class I, typename P, typename EP>
std::map<std::string, std::function<I*(const P&, const EP&)>> _copy<I, P, EP>::functions;
}
namespace modular
{
// struct interface
// {};
template<class I, typename dummy = char>
std::unique_ptr<I> create (const std::string& path, typename std::enable_if<I::enable_default, dummy>::type * = 0)
{
return _default<I>::create(path);
}
template<class I,
typename P = void,
typename EP = void,
typename dummy = char>
std::unique_ptr<I> create (const std::string& path, const P& p, const EP& ep, typename std::enable_if<I::enable_copy, dummy>::type * = 0)
{
return _copy<I, P, EP>::create(path, p, ep);
}
}
<|endoftext|> |
<commit_before>// Copyright 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "sandbox/src/broker_services.h"
#include "base/logging.h"
#include "sandbox/src/sandbox_policy_base.h"
#include "sandbox/src/sandbox.h"
#include "sandbox/src/target_process.h"
#include "sandbox/src/win2k_threadpool.h"
#include "sandbox/src/win_utils.h"
namespace {
// Utility function to associate a completion port to a job object.
bool AssociateCompletionPort(HANDLE job, HANDLE port, void* key) {
JOBOBJECT_ASSOCIATE_COMPLETION_PORT job_acp = { key, port };
return ::SetInformationJobObject(job,
JobObjectAssociateCompletionPortInformation,
&job_acp, sizeof(job_acp))? true : false;
}
// Utility function to do the cleanup necessary when something goes wrong
// while in SpawnTarget and we must terminate the target process.
sandbox::ResultCode SpawnCleanup(sandbox::TargetProcess* target, DWORD error) {
if (0 == error)
error = ::GetLastError();
target->Terminate();
delete target;
::SetLastError(error);
return sandbox::SBOX_ERROR_GENERIC;
}
// the different commands that you can send to the worker thread that
// executes TargetEventsThread().
enum {
THREAD_CTRL_NONE,
THREAD_CTRL_QUIT,
THREAD_CTRL_LAST
};
}
namespace sandbox {
BrokerServicesBase::BrokerServicesBase()
: thread_pool_(NULL), job_port_(NULL), no_targets_(NULL),
job_thread_(NULL) {
}
// The broker uses a dedicated worker thread that services the job completion
// port to perform policy notifications and associated cleanup tasks.
ResultCode BrokerServicesBase::Init() {
if ((NULL != job_port_) || (NULL != thread_pool_))
return SBOX_ERROR_UNEXPECTED_CALL;
::InitializeCriticalSection(&lock_);
job_port_ = ::CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0);
if (NULL == job_port_)
return SBOX_ERROR_GENERIC;
no_targets_ = ::CreateEventW(NULL, TRUE, FALSE, NULL);
job_thread_ = ::CreateThread(NULL, 0, // Default security and stack.
TargetEventsThread, this, NULL, NULL);
if (NULL == job_thread_)
return SBOX_ERROR_GENERIC;
return SBOX_ALL_OK;
}
// The destructor should only be called when the Broker process is terminating.
// Since BrokerServicesBase is a singleton, this is called from the CRT
// termination handlers, if this code lives on a DLL it is called during
// DLL_PROCESS_DETACH in other words, holding the loader lock, so we cannot
// wait for threads here.
BrokerServicesBase::~BrokerServicesBase() {
// Closing the port causes, that no more Job notifications are delivered to
// the worker thread and also causes the thread to exit. This is what we
// want to do since we are going to close all outstanding Jobs and notifying
// the policy objects ourselves.
::PostQueuedCompletionStatus(job_port_, 0, THREAD_CTRL_QUIT, FALSE);
::CloseHandle(job_port_);
if (WAIT_TIMEOUT == ::WaitForSingleObject(job_thread_, 1000)) {
NOTREACHED() << "Cannot clean broker services";
return;
}
JobTrackerList::iterator it;
for (it = tracker_list_.begin(); it != tracker_list_.end(); ++it) {
JobTracker* tracker = (*it);
FreeResources(tracker);
delete tracker;
}
::CloseHandle(job_thread_);
delete thread_pool_;
::CloseHandle(no_targets_);
// If job_port_ isn't NULL, assumes that the lock has been initialized.
if (job_port_)
::DeleteCriticalSection(&lock_);
}
TargetPolicy* BrokerServicesBase::CreatePolicy() {
// If you change the type of the object being created here you must also
// change the downcast to it in SpawnTarget().
return new PolicyBase;
}
void BrokerServicesBase::FreeResources(JobTracker* tracker) {
if (NULL != tracker->policy) {
BOOL res = ::TerminateJobObject(tracker->job, SBOX_ALL_OK);
DCHECK(res);
res = ::CloseHandle(tracker->job);
DCHECK(res);
tracker->policy->OnJobEmpty(tracker->job);
tracker->policy->Release();
tracker->policy = NULL;
}
}
// The worker thread stays in a loop waiting for asynchronous notifications
// from the job objects. Right now we only care about knowing when the last
// process on a job terminates, but in general this is the place to tell
// the policy about events.
DWORD WINAPI BrokerServicesBase::TargetEventsThread(PVOID param) {
if (NULL == param)
return 1;
BrokerServicesBase* broker = reinterpret_cast<BrokerServicesBase*>(param);
HANDLE port = broker->job_port_;
HANDLE no_targets = broker->no_targets_;
int target_counter = 0;
::ResetEvent(no_targets);
while (true) {
DWORD events = 0;
ULONG_PTR key = 0;
LPOVERLAPPED ovl = NULL;
if (!::GetQueuedCompletionStatus(port, &events, &key, &ovl, INFINITE))
// this call fails if the port has been closed before we have a
// chance to service the last packet which is 'exit' anyway so
// this is not an error.
return 1;
if (key > THREAD_CTRL_LAST) {
// The notification comes from a job object. There are nine notifications
// that jobs can send and some of them depend on the job attributes set.
JobTracker* tracker = reinterpret_cast<JobTracker*>(key);
switch (events) {
case JOB_OBJECT_MSG_ACTIVE_PROCESS_ZERO: {
// The job object has signaled that the last process associated
// with it has terminated. Assuming there is no way for a process
// to appear out of thin air in this job, it safe to assume that
// we can tell the policy to destroy the target object, and for
// us to release our reference to the policy object.
FreeResources(tracker);
break;
}
case JOB_OBJECT_MSG_NEW_PROCESS: {
++target_counter;
if (1 == target_counter) {
::ResetEvent(no_targets);
}
break;
}
case JOB_OBJECT_MSG_EXIT_PROCESS:
case JOB_OBJECT_MSG_ABNORMAL_EXIT_PROCESS: {
--target_counter;
if (0 == target_counter)
::SetEvent(no_targets);
DCHECK(target_counter >= 0);
break;
}
case JOB_OBJECT_MSG_ACTIVE_PROCESS_LIMIT: {
break;
}
default: {
NOTREACHED();
break;
}
}
} else if (THREAD_CTRL_QUIT == key) {
// The broker object is being destroyed so the thread needs to exit.
return 0;
} else {
// We have not implemented more commands.
NOTREACHED();
}
}
NOTREACHED();
return 0;
}
// SpawnTarget does all the interesting sandbox setup and creates the target
// process inside the sandbox.
ResultCode BrokerServicesBase::SpawnTarget(const wchar_t* exe_path,
const wchar_t* command_line,
TargetPolicy* policy,
PROCESS_INFORMATION* target_info) {
if (!exe_path)
return SBOX_ERROR_BAD_PARAMS;
if (!policy)
return SBOX_ERROR_BAD_PARAMS;
AutoLock lock(&lock_);
// This downcast is safe as long as we control CreatePolicy()
PolicyBase* policy_base = static_cast<PolicyBase*>(policy);
// Construct the tokens and the job object that we are going to associate
// with the soon to be created target process.
HANDLE lockdown_token = NULL;
HANDLE initial_token = NULL;
DWORD win_result = policy_base->MakeTokens(&initial_token, &lockdown_token);
if (ERROR_SUCCESS != win_result)
return SBOX_ERROR_GENERIC;
HANDLE job = NULL;
win_result = policy_base->MakeJobObject(&job);
if (ERROR_SUCCESS != win_result)
return SBOX_ERROR_GENERIC;
if (ERROR_ALREADY_EXISTS == ::GetLastError())
return SBOX_ERROR_GENERIC;
// Construct the thread pool here in case it is expensive.
// The thread pool is shared by all the targets
if (NULL == thread_pool_)
thread_pool_ = new Win2kThreadPool();
// Create the TargetProces object and spawn the target suspended. Note that
// Brokerservices does not own the target object. It is owned by the Policy.
PROCESS_INFORMATION process_info = {0};
TargetProcess* target = new TargetProcess(initial_token, lockdown_token,
job, thread_pool_);
std::wstring desktop = policy_base->GetDesktop();
win_result = target->Create(exe_path, command_line,
desktop.empty() ? NULL : desktop.c_str(),
&process_info);
if (ERROR_SUCCESS != win_result)
return SpawnCleanup(target, win_result);
if ((INVALID_HANDLE_VALUE == process_info.hProcess) ||
(INVALID_HANDLE_VALUE == process_info.hThread))
return SpawnCleanup(target, win_result);
// Now the policy is the owner of the target.
if (!policy_base->AddTarget(target)) {
return SpawnCleanup(target, 0);
}
// We are going to keep a pointer to the policy because we'll call it when
// the job object generates notifications using the completion port.
policy_base->AddRef();
JobTracker* tracker = new JobTracker(job, policy_base);
if (!AssociateCompletionPort(job, job_port_, tracker))
return SpawnCleanup(target, 0);
// Save the tracker because in cleanup we might need to force closing
// the Jobs.
tracker_list_.push_back(tracker);
// We return the caller a duplicate of the process handle so they
// can close it at will.
HANDLE dup_process_handle = NULL;
if (!::DuplicateHandle(::GetCurrentProcess(), process_info.hProcess,
::GetCurrentProcess(), &dup_process_handle,
0, FALSE, DUPLICATE_SAME_ACCESS))
return SpawnCleanup(target, 0);
*target_info = process_info;
target_info->hProcess = dup_process_handle;
return SBOX_ALL_OK;
}
ResultCode BrokerServicesBase::WaitForAllTargets() {
::WaitForSingleObject(no_targets_, INFINITE);
return SBOX_ALL_OK;
}
} // namespace sandbox
<commit_msg>When run chrome with --no-sandbox, the renderer process calls the dtor of BrokerServicesBase. There some API calls have invalid parameters.<commit_after>// Copyright 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "sandbox/src/broker_services.h"
#include "base/logging.h"
#include "sandbox/src/sandbox_policy_base.h"
#include "sandbox/src/sandbox.h"
#include "sandbox/src/target_process.h"
#include "sandbox/src/win2k_threadpool.h"
#include "sandbox/src/win_utils.h"
namespace {
// Utility function to associate a completion port to a job object.
bool AssociateCompletionPort(HANDLE job, HANDLE port, void* key) {
JOBOBJECT_ASSOCIATE_COMPLETION_PORT job_acp = { key, port };
return ::SetInformationJobObject(job,
JobObjectAssociateCompletionPortInformation,
&job_acp, sizeof(job_acp))? true : false;
}
// Utility function to do the cleanup necessary when something goes wrong
// while in SpawnTarget and we must terminate the target process.
sandbox::ResultCode SpawnCleanup(sandbox::TargetProcess* target, DWORD error) {
if (0 == error)
error = ::GetLastError();
target->Terminate();
delete target;
::SetLastError(error);
return sandbox::SBOX_ERROR_GENERIC;
}
// the different commands that you can send to the worker thread that
// executes TargetEventsThread().
enum {
THREAD_CTRL_NONE,
THREAD_CTRL_QUIT,
THREAD_CTRL_LAST
};
}
namespace sandbox {
BrokerServicesBase::BrokerServicesBase()
: thread_pool_(NULL), job_port_(NULL), no_targets_(NULL),
job_thread_(NULL) {
}
// The broker uses a dedicated worker thread that services the job completion
// port to perform policy notifications and associated cleanup tasks.
ResultCode BrokerServicesBase::Init() {
if ((NULL != job_port_) || (NULL != thread_pool_))
return SBOX_ERROR_UNEXPECTED_CALL;
::InitializeCriticalSection(&lock_);
job_port_ = ::CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0);
if (NULL == job_port_)
return SBOX_ERROR_GENERIC;
no_targets_ = ::CreateEventW(NULL, TRUE, FALSE, NULL);
job_thread_ = ::CreateThread(NULL, 0, // Default security and stack.
TargetEventsThread, this, NULL, NULL);
if (NULL == job_thread_)
return SBOX_ERROR_GENERIC;
return SBOX_ALL_OK;
}
// The destructor should only be called when the Broker process is terminating.
// Since BrokerServicesBase is a singleton, this is called from the CRT
// termination handlers, if this code lives on a DLL it is called during
// DLL_PROCESS_DETACH in other words, holding the loader lock, so we cannot
// wait for threads here.
BrokerServicesBase::~BrokerServicesBase() {
// If there is no port Init() was never called successfully.
if (!job_port_)
return;
// Closing the port causes, that no more Job notifications are delivered to
// the worker thread and also causes the thread to exit. This is what we
// want to do since we are going to close all outstanding Jobs and notifying
// the policy objects ourselves.
::PostQueuedCompletionStatus(job_port_, 0, THREAD_CTRL_QUIT, FALSE);
::CloseHandle(job_port_);
if (WAIT_TIMEOUT == ::WaitForSingleObject(job_thread_, 1000)) {
NOTREACHED() << "Cannot clean broker services";
return;
}
JobTrackerList::iterator it;
for (it = tracker_list_.begin(); it != tracker_list_.end(); ++it) {
JobTracker* tracker = (*it);
FreeResources(tracker);
delete tracker;
}
::CloseHandle(job_thread_);
delete thread_pool_;
::CloseHandle(no_targets_);
// If job_port_ isn't NULL, assumes that the lock has been initialized.
if (job_port_)
::DeleteCriticalSection(&lock_);
}
TargetPolicy* BrokerServicesBase::CreatePolicy() {
// If you change the type of the object being created here you must also
// change the downcast to it in SpawnTarget().
return new PolicyBase;
}
void BrokerServicesBase::FreeResources(JobTracker* tracker) {
if (NULL != tracker->policy) {
BOOL res = ::TerminateJobObject(tracker->job, SBOX_ALL_OK);
DCHECK(res);
res = ::CloseHandle(tracker->job);
DCHECK(res);
tracker->policy->OnJobEmpty(tracker->job);
tracker->policy->Release();
tracker->policy = NULL;
}
}
// The worker thread stays in a loop waiting for asynchronous notifications
// from the job objects. Right now we only care about knowing when the last
// process on a job terminates, but in general this is the place to tell
// the policy about events.
DWORD WINAPI BrokerServicesBase::TargetEventsThread(PVOID param) {
if (NULL == param)
return 1;
BrokerServicesBase* broker = reinterpret_cast<BrokerServicesBase*>(param);
HANDLE port = broker->job_port_;
HANDLE no_targets = broker->no_targets_;
int target_counter = 0;
::ResetEvent(no_targets);
while (true) {
DWORD events = 0;
ULONG_PTR key = 0;
LPOVERLAPPED ovl = NULL;
if (!::GetQueuedCompletionStatus(port, &events, &key, &ovl, INFINITE))
// this call fails if the port has been closed before we have a
// chance to service the last packet which is 'exit' anyway so
// this is not an error.
return 1;
if (key > THREAD_CTRL_LAST) {
// The notification comes from a job object. There are nine notifications
// that jobs can send and some of them depend on the job attributes set.
JobTracker* tracker = reinterpret_cast<JobTracker*>(key);
switch (events) {
case JOB_OBJECT_MSG_ACTIVE_PROCESS_ZERO: {
// The job object has signaled that the last process associated
// with it has terminated. Assuming there is no way for a process
// to appear out of thin air in this job, it safe to assume that
// we can tell the policy to destroy the target object, and for
// us to release our reference to the policy object.
FreeResources(tracker);
break;
}
case JOB_OBJECT_MSG_NEW_PROCESS: {
++target_counter;
if (1 == target_counter) {
::ResetEvent(no_targets);
}
break;
}
case JOB_OBJECT_MSG_EXIT_PROCESS:
case JOB_OBJECT_MSG_ABNORMAL_EXIT_PROCESS: {
--target_counter;
if (0 == target_counter)
::SetEvent(no_targets);
DCHECK(target_counter >= 0);
break;
}
case JOB_OBJECT_MSG_ACTIVE_PROCESS_LIMIT: {
break;
}
default: {
NOTREACHED();
break;
}
}
} else if (THREAD_CTRL_QUIT == key) {
// The broker object is being destroyed so the thread needs to exit.
return 0;
} else {
// We have not implemented more commands.
NOTREACHED();
}
}
NOTREACHED();
return 0;
}
// SpawnTarget does all the interesting sandbox setup and creates the target
// process inside the sandbox.
ResultCode BrokerServicesBase::SpawnTarget(const wchar_t* exe_path,
const wchar_t* command_line,
TargetPolicy* policy,
PROCESS_INFORMATION* target_info) {
if (!exe_path)
return SBOX_ERROR_BAD_PARAMS;
if (!policy)
return SBOX_ERROR_BAD_PARAMS;
AutoLock lock(&lock_);
// This downcast is safe as long as we control CreatePolicy()
PolicyBase* policy_base = static_cast<PolicyBase*>(policy);
// Construct the tokens and the job object that we are going to associate
// with the soon to be created target process.
HANDLE lockdown_token = NULL;
HANDLE initial_token = NULL;
DWORD win_result = policy_base->MakeTokens(&initial_token, &lockdown_token);
if (ERROR_SUCCESS != win_result)
return SBOX_ERROR_GENERIC;
HANDLE job = NULL;
win_result = policy_base->MakeJobObject(&job);
if (ERROR_SUCCESS != win_result)
return SBOX_ERROR_GENERIC;
if (ERROR_ALREADY_EXISTS == ::GetLastError())
return SBOX_ERROR_GENERIC;
// Construct the thread pool here in case it is expensive.
// The thread pool is shared by all the targets
if (NULL == thread_pool_)
thread_pool_ = new Win2kThreadPool();
// Create the TargetProces object and spawn the target suspended. Note that
// Brokerservices does not own the target object. It is owned by the Policy.
PROCESS_INFORMATION process_info = {0};
TargetProcess* target = new TargetProcess(initial_token, lockdown_token,
job, thread_pool_);
std::wstring desktop = policy_base->GetDesktop();
win_result = target->Create(exe_path, command_line,
desktop.empty() ? NULL : desktop.c_str(),
&process_info);
if (ERROR_SUCCESS != win_result)
return SpawnCleanup(target, win_result);
if ((INVALID_HANDLE_VALUE == process_info.hProcess) ||
(INVALID_HANDLE_VALUE == process_info.hThread))
return SpawnCleanup(target, win_result);
// Now the policy is the owner of the target.
if (!policy_base->AddTarget(target)) {
return SpawnCleanup(target, 0);
}
// We are going to keep a pointer to the policy because we'll call it when
// the job object generates notifications using the completion port.
policy_base->AddRef();
JobTracker* tracker = new JobTracker(job, policy_base);
if (!AssociateCompletionPort(job, job_port_, tracker))
return SpawnCleanup(target, 0);
// Save the tracker because in cleanup we might need to force closing
// the Jobs.
tracker_list_.push_back(tracker);
// We return the caller a duplicate of the process handle so they
// can close it at will.
HANDLE dup_process_handle = NULL;
if (!::DuplicateHandle(::GetCurrentProcess(), process_info.hProcess,
::GetCurrentProcess(), &dup_process_handle,
0, FALSE, DUPLICATE_SAME_ACCESS))
return SpawnCleanup(target, 0);
*target_info = process_info;
target_info->hProcess = dup_process_handle;
return SBOX_ALL_OK;
}
ResultCode BrokerServicesBase::WaitForAllTargets() {
::WaitForSingleObject(no_targets_, INFINITE);
return SBOX_ALL_OK;
}
} // namespace sandbox
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "sandbox/src/interceptors_64.h"
#include "sandbox/src/interceptors.h"
#include "sandbox/src/filesystem_interception.h"
#include "sandbox/src/named_pipe_interception.h"
#include "sandbox/src/policy_target.h"
#include "sandbox/src/process_thread_interception.h"
#include "sandbox/src/registry_interception.h"
#include "sandbox/src/sandbox_nt_types.h"
#include "sandbox/src/sandbox_types.h"
#include "sandbox/src/sync_interception.h"
#include "sandbox/src/target_interceptions.h"
namespace sandbox {
SANDBOX_INTERCEPT NtExports g_nt;
SANDBOX_INTERCEPT OriginalFunctions g_originals;
NTSTATUS WINAPI TargetNtMapViewOfSection64(
HANDLE section, HANDLE process, PVOID *base, ULONG_PTR zero_bits,
SIZE_T commit_size, PLARGE_INTEGER offset, PSIZE_T view_size,
SECTION_INHERIT inherit, ULONG allocation_type, ULONG protect) {
NtMapViewOfSectionFunction orig_fn = reinterpret_cast<
NtMapViewOfSectionFunction>(g_originals[MAP_VIEW_OF_SECTION_ID]);
return TargetNtMapViewOfSection(orig_fn, section, process, base, zero_bits,
commit_size, offset, view_size, inherit,
allocation_type, protect);
}
NTSTATUS WINAPI TargetNtUnmapViewOfSection64(HANDLE process, PVOID base) {
NtUnmapViewOfSectionFunction orig_fn = reinterpret_cast<
NtUnmapViewOfSectionFunction>(g_originals[UNMAP_VIEW_OF_SECTION_ID]);
return TargetNtUnmapViewOfSection(orig_fn, process, base);
}
// -----------------------------------------------------------------------
NTSTATUS WINAPI TargetNtSetInformationThread64(
HANDLE thread, THREAD_INFORMATION_CLASS thread_info_class,
PVOID thread_information, ULONG thread_information_bytes) {
NtSetInformationThreadFunction orig_fn = reinterpret_cast<
NtSetInformationThreadFunction>(g_originals[SET_INFORMATION_THREAD_ID]);
return TargetNtSetInformationThread(orig_fn, thread, thread_info_class,
thread_information,
thread_information_bytes);
}
NTSTATUS WINAPI TargetNtOpenThreadToken64(
HANDLE thread, ACCESS_MASK desired_access, BOOLEAN open_as_self,
PHANDLE token) {
NtOpenThreadTokenFunction orig_fn = reinterpret_cast<
NtOpenThreadTokenFunction>(g_originals[OPEN_THREAD_TOKEN_ID]);
return TargetNtOpenThreadToken(orig_fn, thread, desired_access, open_as_self,
token);
}
NTSTATUS WINAPI TargetNtOpenThreadTokenEx64(
HANDLE thread, ACCESS_MASK desired_access, BOOLEAN open_as_self,
ULONG handle_attributes, PHANDLE token) {
NtOpenThreadTokenExFunction orig_fn = reinterpret_cast<
NtOpenThreadTokenExFunction>(g_originals[OPEN_THREAD_TOKEN_EX_ID]);
return TargetNtOpenThreadTokenEx(orig_fn, thread, desired_access,
open_as_self, handle_attributes, token);
}
HANDLE WINAPI TargetCreateThread64(LPSECURITY_ATTRIBUTES thread_attributes,
SIZE_T stack_size, LPTHREAD_START_ROUTINE start_address,
PVOID parameter, DWORD creation_flags, LPDWORD thread_id) {
CreateThreadFunction orig_fn = reinterpret_cast<
CreateThreadFunction>(g_originals[CREATE_THREAD_ID]);
return TargetCreateThread(orig_fn, thread_attributes, stack_size,
start_address, parameter, creation_flags,
thread_id);
}
// -----------------------------------------------------------------------
SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtCreateFile64(
PHANDLE file, ACCESS_MASK desired_access,
POBJECT_ATTRIBUTES object_attributes, PIO_STATUS_BLOCK io_status,
PLARGE_INTEGER allocation_size, ULONG file_attributes, ULONG sharing,
ULONG disposition, ULONG options, PVOID ea_buffer, ULONG ea_length) {
NtCreateFileFunction orig_fn = reinterpret_cast<
NtCreateFileFunction>(g_originals[CREATE_FILE_ID]);
return TargetNtCreateFile(orig_fn, file, desired_access, object_attributes,
io_status, allocation_size, file_attributes,
sharing, disposition, options, ea_buffer,
ea_length);
}
SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenFile64(
PHANDLE file, ACCESS_MASK desired_access,
POBJECT_ATTRIBUTES object_attributes, PIO_STATUS_BLOCK io_status,
ULONG sharing, ULONG options) {
NtOpenFileFunction orig_fn = reinterpret_cast<
NtOpenFileFunction>(g_originals[OPEN_FILE_ID]);
return TargetNtOpenFile(orig_fn, file, desired_access, object_attributes,
io_status, sharing, options);
}
SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtQueryAttributesFile64(
POBJECT_ATTRIBUTES object_attributes,
PFILE_BASIC_INFORMATION file_attributes) {
NtQueryAttributesFileFunction orig_fn = reinterpret_cast<
NtQueryAttributesFileFunction>(g_originals[QUERY_ATTRIB_FILE_ID]);
return TargetNtQueryAttributesFile(orig_fn, object_attributes,
file_attributes);
}
SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtQueryFullAttributesFile64(
POBJECT_ATTRIBUTES object_attributes,
PFILE_NETWORK_OPEN_INFORMATION file_attributes) {
NtQueryFullAttributesFileFunction orig_fn = reinterpret_cast<
NtQueryFullAttributesFileFunction>(
g_originals[QUERY_FULL_ATTRIB_FILE_ID]);
return TargetNtQueryFullAttributesFile(orig_fn, object_attributes,
file_attributes);
}
SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtSetInformationFile64(
HANDLE file, PIO_STATUS_BLOCK io_status, PVOID file_information,
ULONG length, FILE_INFORMATION_CLASS file_information_class) {
NtSetInformationFileFunction orig_fn = reinterpret_cast<
NtSetInformationFileFunction>(g_originals[SET_INFO_FILE_ID]);
return TargetNtSetInformationFile(orig_fn, file, io_status, file_information,
length, file_information_class);
}
// -----------------------------------------------------------------------
SANDBOX_INTERCEPT HANDLE WINAPI TargetCreateNamedPipeW64(
LPCWSTR pipe_name, DWORD open_mode, DWORD pipe_mode, DWORD max_instance,
DWORD out_buffer_size, DWORD in_buffer_size, DWORD default_timeout,
LPSECURITY_ATTRIBUTES security_attributes) {
CreateNamedPipeWFunction orig_fn = reinterpret_cast<
CreateNamedPipeWFunction>(g_originals[CREATE_NAMED_PIPE_ID]);
return TargetCreateNamedPipeW(orig_fn, pipe_name, open_mode, pipe_mode,
max_instance, out_buffer_size, in_buffer_size,
default_timeout, security_attributes);
}
// -----------------------------------------------------------------------
SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenThread64(
PHANDLE thread, ACCESS_MASK desired_access,
POBJECT_ATTRIBUTES object_attributes, PCLIENT_ID client_id) {
NtOpenThreadFunction orig_fn = reinterpret_cast<
NtOpenThreadFunction>(g_originals[OPEN_TREAD_ID]);
return TargetNtOpenThread(orig_fn, thread, desired_access, object_attributes,
client_id);
}
SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenProcess64(
PHANDLE process, ACCESS_MASK desired_access,
POBJECT_ATTRIBUTES object_attributes, PCLIENT_ID client_id) {
NtOpenProcessFunction orig_fn = reinterpret_cast<
NtOpenProcessFunction>(g_originals[OPEN_PROCESS_ID]);
return TargetNtOpenProcess(orig_fn, process, desired_access,
object_attributes, client_id);
}
SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenProcessToken64(
HANDLE process, ACCESS_MASK desired_access, PHANDLE token) {
NtOpenProcessTokenFunction orig_fn = reinterpret_cast<
NtOpenProcessTokenFunction>(g_originals[OPEN_PROCESS_TOKEN_ID]);
return TargetNtOpenProcessToken(orig_fn, process, desired_access, token);
}
SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenProcessTokenEx64(
HANDLE process, ACCESS_MASK desired_access, ULONG handle_attributes,
PHANDLE token) {
NtOpenProcessTokenExFunction orig_fn = reinterpret_cast<
NtOpenProcessTokenExFunction>(g_originals[OPEN_PROCESS_TOKEN_EX_ID]);
return TargetNtOpenProcessTokenEx(orig_fn, process, desired_access,
handle_attributes, token);
}
SANDBOX_INTERCEPT BOOL WINAPI TargetCreateProcessW64(
LPCWSTR application_name, LPWSTR command_line,
LPSECURITY_ATTRIBUTES process_attributes,
LPSECURITY_ATTRIBUTES thread_attributes, BOOL inherit_handles, DWORD flags,
LPVOID environment, LPCWSTR current_directory, LPSTARTUPINFOW startup_info,
LPPROCESS_INFORMATION process_information) {
CreateProcessWFunction orig_fn = reinterpret_cast<
CreateProcessWFunction>(g_originals[CREATE_PROCESSW_ID]);
return TargetCreateProcessW(orig_fn, application_name, command_line,
process_attributes, thread_attributes,
inherit_handles, flags, environment,
current_directory, startup_info,
process_information);
}
SANDBOX_INTERCEPT BOOL WINAPI TargetCreateProcessA64(
LPCSTR application_name, LPSTR command_line,
LPSECURITY_ATTRIBUTES process_attributes,
LPSECURITY_ATTRIBUTES thread_attributes, BOOL inherit_handles, DWORD flags,
LPVOID environment, LPCSTR current_directory, LPSTARTUPINFOA startup_info,
LPPROCESS_INFORMATION process_information) {
CreateProcessAFunction orig_fn = reinterpret_cast<
CreateProcessAFunction>(g_originals[CREATE_PROCESSA_ID]);
return TargetCreateProcessA(orig_fn, application_name, command_line,
process_attributes, thread_attributes,
inherit_handles, flags, environment,
current_directory, startup_info,
process_information);
}
// -----------------------------------------------------------------------
SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtCreateKey64(
PHANDLE key, ACCESS_MASK desired_access,
POBJECT_ATTRIBUTES object_attributes, ULONG title_index,
PUNICODE_STRING class_name, ULONG create_options, PULONG disposition) {
NtCreateKeyFunction orig_fn = reinterpret_cast<
NtCreateKeyFunction>(g_originals[CREATE_KEY_ID]);
return TargetNtCreateKey(orig_fn, key, desired_access, object_attributes,
title_index, class_name, create_options,
disposition);
}
SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenKey64(
PHANDLE key, ACCESS_MASK desired_access,
POBJECT_ATTRIBUTES object_attributes) {
NtOpenKeyFunction orig_fn = reinterpret_cast<
NtOpenKeyFunction>(g_originals[OPEN_KEY_ID]);
return TargetNtOpenKey(orig_fn, key, desired_access, object_attributes);
}
SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenKeyEx64(
PHANDLE key, ACCESS_MASK desired_access,
POBJECT_ATTRIBUTES object_attributes, ULONG open_options) {
NtOpenKeyExFunction orig_fn = reinterpret_cast<
NtOpenKeyExFunction>(g_originals[OPEN_KEY_EX_ID]);
return TargetNtOpenKeyEx(orig_fn, key, desired_access, object_attributes,
open_options);
}
// -----------------------------------------------------------------------
SANDBOX_INTERCEPT HANDLE WINAPI TargetCreateEventW64(
LPSECURITY_ATTRIBUTES security_attributes, BOOL manual_reset,
BOOL initial_state, LPCWSTR name) {
CreateEventWFunction orig_fn = reinterpret_cast<
CreateEventWFunction>(g_originals[CREATE_EVENT_ID]);
return TargetCreateEventW(orig_fn, security_attributes, manual_reset,
initial_state, name);
}
SANDBOX_INTERCEPT HANDLE WINAPI TargetOpenEventW64(
ACCESS_MASK desired_access, BOOL inherit_handle, LPCWSTR name) {
OpenEventWFunction orig_fn = reinterpret_cast<
OpenEventWFunction>(g_originals[OPEN_EVENT_ID]);
return TargetOpenEventW(orig_fn, desired_access, inherit_handle, name);
}
} // namespace sandbox
<commit_msg>Sandbox: Fix a style nit. No actual code change.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "sandbox/src/interceptors_64.h"
#include "sandbox/src/interceptors.h"
#include "sandbox/src/filesystem_interception.h"
#include "sandbox/src/named_pipe_interception.h"
#include "sandbox/src/policy_target.h"
#include "sandbox/src/process_thread_interception.h"
#include "sandbox/src/registry_interception.h"
#include "sandbox/src/sandbox_nt_types.h"
#include "sandbox/src/sandbox_types.h"
#include "sandbox/src/sync_interception.h"
#include "sandbox/src/target_interceptions.h"
namespace sandbox {
SANDBOX_INTERCEPT NtExports g_nt;
SANDBOX_INTERCEPT OriginalFunctions g_originals;
NTSTATUS WINAPI TargetNtMapViewOfSection64(
HANDLE section, HANDLE process, PVOID *base, ULONG_PTR zero_bits,
SIZE_T commit_size, PLARGE_INTEGER offset, PSIZE_T view_size,
SECTION_INHERIT inherit, ULONG allocation_type, ULONG protect) {
NtMapViewOfSectionFunction orig_fn = reinterpret_cast<
NtMapViewOfSectionFunction>(g_originals[MAP_VIEW_OF_SECTION_ID]);
return TargetNtMapViewOfSection(orig_fn, section, process, base, zero_bits,
commit_size, offset, view_size, inherit,
allocation_type, protect);
}
NTSTATUS WINAPI TargetNtUnmapViewOfSection64(HANDLE process, PVOID base) {
NtUnmapViewOfSectionFunction orig_fn = reinterpret_cast<
NtUnmapViewOfSectionFunction>(g_originals[UNMAP_VIEW_OF_SECTION_ID]);
return TargetNtUnmapViewOfSection(orig_fn, process, base);
}
// -----------------------------------------------------------------------
NTSTATUS WINAPI TargetNtSetInformationThread64(
HANDLE thread, THREAD_INFORMATION_CLASS thread_info_class,
PVOID thread_information, ULONG thread_information_bytes) {
NtSetInformationThreadFunction orig_fn = reinterpret_cast<
NtSetInformationThreadFunction>(g_originals[SET_INFORMATION_THREAD_ID]);
return TargetNtSetInformationThread(orig_fn, thread, thread_info_class,
thread_information,
thread_information_bytes);
}
NTSTATUS WINAPI TargetNtOpenThreadToken64(
HANDLE thread, ACCESS_MASK desired_access, BOOLEAN open_as_self,
PHANDLE token) {
NtOpenThreadTokenFunction orig_fn = reinterpret_cast<
NtOpenThreadTokenFunction>(g_originals[OPEN_THREAD_TOKEN_ID]);
return TargetNtOpenThreadToken(orig_fn, thread, desired_access, open_as_self,
token);
}
NTSTATUS WINAPI TargetNtOpenThreadTokenEx64(
HANDLE thread, ACCESS_MASK desired_access, BOOLEAN open_as_self,
ULONG handle_attributes, PHANDLE token) {
NtOpenThreadTokenExFunction orig_fn = reinterpret_cast<
NtOpenThreadTokenExFunction>(g_originals[OPEN_THREAD_TOKEN_EX_ID]);
return TargetNtOpenThreadTokenEx(orig_fn, thread, desired_access,
open_as_self, handle_attributes, token);
}
HANDLE WINAPI TargetCreateThread64(
LPSECURITY_ATTRIBUTES thread_attributes, SIZE_T stack_size,
LPTHREAD_START_ROUTINE start_address, PVOID parameter, DWORD creation_flags,
LPDWORD thread_id) {
CreateThreadFunction orig_fn = reinterpret_cast<
CreateThreadFunction>(g_originals[CREATE_THREAD_ID]);
return TargetCreateThread(orig_fn, thread_attributes, stack_size,
start_address, parameter, creation_flags,
thread_id);
}
// -----------------------------------------------------------------------
SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtCreateFile64(
PHANDLE file, ACCESS_MASK desired_access,
POBJECT_ATTRIBUTES object_attributes, PIO_STATUS_BLOCK io_status,
PLARGE_INTEGER allocation_size, ULONG file_attributes, ULONG sharing,
ULONG disposition, ULONG options, PVOID ea_buffer, ULONG ea_length) {
NtCreateFileFunction orig_fn = reinterpret_cast<
NtCreateFileFunction>(g_originals[CREATE_FILE_ID]);
return TargetNtCreateFile(orig_fn, file, desired_access, object_attributes,
io_status, allocation_size, file_attributes,
sharing, disposition, options, ea_buffer,
ea_length);
}
SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenFile64(
PHANDLE file, ACCESS_MASK desired_access,
POBJECT_ATTRIBUTES object_attributes, PIO_STATUS_BLOCK io_status,
ULONG sharing, ULONG options) {
NtOpenFileFunction orig_fn = reinterpret_cast<
NtOpenFileFunction>(g_originals[OPEN_FILE_ID]);
return TargetNtOpenFile(orig_fn, file, desired_access, object_attributes,
io_status, sharing, options);
}
SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtQueryAttributesFile64(
POBJECT_ATTRIBUTES object_attributes,
PFILE_BASIC_INFORMATION file_attributes) {
NtQueryAttributesFileFunction orig_fn = reinterpret_cast<
NtQueryAttributesFileFunction>(g_originals[QUERY_ATTRIB_FILE_ID]);
return TargetNtQueryAttributesFile(orig_fn, object_attributes,
file_attributes);
}
SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtQueryFullAttributesFile64(
POBJECT_ATTRIBUTES object_attributes,
PFILE_NETWORK_OPEN_INFORMATION file_attributes) {
NtQueryFullAttributesFileFunction orig_fn = reinterpret_cast<
NtQueryFullAttributesFileFunction>(
g_originals[QUERY_FULL_ATTRIB_FILE_ID]);
return TargetNtQueryFullAttributesFile(orig_fn, object_attributes,
file_attributes);
}
SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtSetInformationFile64(
HANDLE file, PIO_STATUS_BLOCK io_status, PVOID file_information,
ULONG length, FILE_INFORMATION_CLASS file_information_class) {
NtSetInformationFileFunction orig_fn = reinterpret_cast<
NtSetInformationFileFunction>(g_originals[SET_INFO_FILE_ID]);
return TargetNtSetInformationFile(orig_fn, file, io_status, file_information,
length, file_information_class);
}
// -----------------------------------------------------------------------
SANDBOX_INTERCEPT HANDLE WINAPI TargetCreateNamedPipeW64(
LPCWSTR pipe_name, DWORD open_mode, DWORD pipe_mode, DWORD max_instance,
DWORD out_buffer_size, DWORD in_buffer_size, DWORD default_timeout,
LPSECURITY_ATTRIBUTES security_attributes) {
CreateNamedPipeWFunction orig_fn = reinterpret_cast<
CreateNamedPipeWFunction>(g_originals[CREATE_NAMED_PIPE_ID]);
return TargetCreateNamedPipeW(orig_fn, pipe_name, open_mode, pipe_mode,
max_instance, out_buffer_size, in_buffer_size,
default_timeout, security_attributes);
}
// -----------------------------------------------------------------------
SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenThread64(
PHANDLE thread, ACCESS_MASK desired_access,
POBJECT_ATTRIBUTES object_attributes, PCLIENT_ID client_id) {
NtOpenThreadFunction orig_fn = reinterpret_cast<
NtOpenThreadFunction>(g_originals[OPEN_TREAD_ID]);
return TargetNtOpenThread(orig_fn, thread, desired_access, object_attributes,
client_id);
}
SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenProcess64(
PHANDLE process, ACCESS_MASK desired_access,
POBJECT_ATTRIBUTES object_attributes, PCLIENT_ID client_id) {
NtOpenProcessFunction orig_fn = reinterpret_cast<
NtOpenProcessFunction>(g_originals[OPEN_PROCESS_ID]);
return TargetNtOpenProcess(orig_fn, process, desired_access,
object_attributes, client_id);
}
SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenProcessToken64(
HANDLE process, ACCESS_MASK desired_access, PHANDLE token) {
NtOpenProcessTokenFunction orig_fn = reinterpret_cast<
NtOpenProcessTokenFunction>(g_originals[OPEN_PROCESS_TOKEN_ID]);
return TargetNtOpenProcessToken(orig_fn, process, desired_access, token);
}
SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenProcessTokenEx64(
HANDLE process, ACCESS_MASK desired_access, ULONG handle_attributes,
PHANDLE token) {
NtOpenProcessTokenExFunction orig_fn = reinterpret_cast<
NtOpenProcessTokenExFunction>(g_originals[OPEN_PROCESS_TOKEN_EX_ID]);
return TargetNtOpenProcessTokenEx(orig_fn, process, desired_access,
handle_attributes, token);
}
SANDBOX_INTERCEPT BOOL WINAPI TargetCreateProcessW64(
LPCWSTR application_name, LPWSTR command_line,
LPSECURITY_ATTRIBUTES process_attributes,
LPSECURITY_ATTRIBUTES thread_attributes, BOOL inherit_handles, DWORD flags,
LPVOID environment, LPCWSTR current_directory, LPSTARTUPINFOW startup_info,
LPPROCESS_INFORMATION process_information) {
CreateProcessWFunction orig_fn = reinterpret_cast<
CreateProcessWFunction>(g_originals[CREATE_PROCESSW_ID]);
return TargetCreateProcessW(orig_fn, application_name, command_line,
process_attributes, thread_attributes,
inherit_handles, flags, environment,
current_directory, startup_info,
process_information);
}
SANDBOX_INTERCEPT BOOL WINAPI TargetCreateProcessA64(
LPCSTR application_name, LPSTR command_line,
LPSECURITY_ATTRIBUTES process_attributes,
LPSECURITY_ATTRIBUTES thread_attributes, BOOL inherit_handles, DWORD flags,
LPVOID environment, LPCSTR current_directory, LPSTARTUPINFOA startup_info,
LPPROCESS_INFORMATION process_information) {
CreateProcessAFunction orig_fn = reinterpret_cast<
CreateProcessAFunction>(g_originals[CREATE_PROCESSA_ID]);
return TargetCreateProcessA(orig_fn, application_name, command_line,
process_attributes, thread_attributes,
inherit_handles, flags, environment,
current_directory, startup_info,
process_information);
}
// -----------------------------------------------------------------------
SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtCreateKey64(
PHANDLE key, ACCESS_MASK desired_access,
POBJECT_ATTRIBUTES object_attributes, ULONG title_index,
PUNICODE_STRING class_name, ULONG create_options, PULONG disposition) {
NtCreateKeyFunction orig_fn = reinterpret_cast<
NtCreateKeyFunction>(g_originals[CREATE_KEY_ID]);
return TargetNtCreateKey(orig_fn, key, desired_access, object_attributes,
title_index, class_name, create_options,
disposition);
}
SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenKey64(
PHANDLE key, ACCESS_MASK desired_access,
POBJECT_ATTRIBUTES object_attributes) {
NtOpenKeyFunction orig_fn = reinterpret_cast<
NtOpenKeyFunction>(g_originals[OPEN_KEY_ID]);
return TargetNtOpenKey(orig_fn, key, desired_access, object_attributes);
}
SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenKeyEx64(
PHANDLE key, ACCESS_MASK desired_access,
POBJECT_ATTRIBUTES object_attributes, ULONG open_options) {
NtOpenKeyExFunction orig_fn = reinterpret_cast<
NtOpenKeyExFunction>(g_originals[OPEN_KEY_EX_ID]);
return TargetNtOpenKeyEx(orig_fn, key, desired_access, object_attributes,
open_options);
}
// -----------------------------------------------------------------------
SANDBOX_INTERCEPT HANDLE WINAPI TargetCreateEventW64(
LPSECURITY_ATTRIBUTES security_attributes, BOOL manual_reset,
BOOL initial_state, LPCWSTR name) {
CreateEventWFunction orig_fn = reinterpret_cast<
CreateEventWFunction>(g_originals[CREATE_EVENT_ID]);
return TargetCreateEventW(orig_fn, security_attributes, manual_reset,
initial_state, name);
}
SANDBOX_INTERCEPT HANDLE WINAPI TargetOpenEventW64(
ACCESS_MASK desired_access, BOOL inherit_handle, LPCWSTR name) {
OpenEventWFunction orig_fn = reinterpret_cast<
OpenEventWFunction>(g_originals[OPEN_EVENT_ID]);
return TargetOpenEventW(orig_fn, desired_access, inherit_handle, name);
}
} // namespace sandbox
<|endoftext|> |
<commit_before><commit_msg>sc tiled editing: Fix the conversion so that it works with zoom too.<commit_after><|endoftext|> |
<commit_before><?hh //strict
/**
* This file is part of hhpack\codegen.
*
* (c) Noritaka Horio <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace HHPack\Codegen\Cli;
use HHPack\Codegen\{LibraryFileGenerator, ClassFileGenerator, GenerateType, ClassFileGeneratable, OutputNamespace};
use HHPack\Codegen\Project\{PackageClassGenerator};
use HHPack\Codegen\HackUnit\{TestClassGenerator};
use function HHPack\Getopt\{ optparser, take_on, on };
use HHPack\Getopt\Parser\{OptionParser};
use Facebook\HackCodegen\{HackCodegenFactory, HackCodegenConfig};
final class Codegen {
const string PROGRAM_NAME = 'codegen';
const string PROGRAM_VERSION = '0.1.0';
private bool $help = false;
private bool $version = false;
private OptionParser $optionParser;
public function __construct() {
$this->optionParser = optparser(
[
on(
['-h', '--help'],
'Display help message',
() ==> {
$this->help = true;
},
),
on(
['-v', '--version'],
'Display version',
() ==> {
$this->version = true;
},
),
]);
}
public function run(Traversable<string> $argv): void {
$args = ImmVector::fromItems($argv)->skip(1);
$remainArgs = $this->optionParser->parse($args);
echo "run", PHP_EOL;
if ($this->help) {
$this->displayHelp();
} else if ($this->version) {
$this->displayVersion();
} else {
$type = $remainArgs->at(0);
$name = $remainArgs->at(1);
$genType = GenerateType::assert($type);
$this->generateBy(Pair { $genType, $name });
}
}
private function generateBy(Pair<GenerateType, string> $generateFile): void {
$generators = $this->loadGeneratorProvider()->generators();
$generator = LibraryFileGenerator::fromItems($generators);
$generator->generate($generateFile)->save();
}
private function loadGeneratorProvider(): CodegenGenerators {
$ref = new \ReflectionClass((string) \HHPack\Codegen\Example\Generators::class);
return $generatorProvider = $ref->newInstance();
}
private function displayVersion() : void {
fwrite(STDOUT, sprintf("%s - %s\n", static::PROGRAM_NAME, static::PROGRAM_VERSION));
}
private function displayHelp() : void {
fwrite(STDOUT, sprintf("Usage: %s [OPTIONS] [TYPE] [NAME]\n\n", static::PROGRAM_NAME));
fwrite(STDOUT, "Arguments:\n");
fwrite(STDOUT, " TYPE: generate type (ex. lib, test) \n");
fwrite(STDOUT, " NAME: generate class name (ex. Foo\\Bar)\n\n");
$this->optionParser->displayHelp();
}
}
<commit_msg>add result message<commit_after><?hh //strict
/**
* This file is part of hhpack\codegen.
*
* (c) Noritaka Horio <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace HHPack\Codegen\Cli;
use HHPack\Codegen\{LibraryFileGenerator, ClassFileGenerator, GenerateType, ClassFileGeneratable, OutputNamespace};
use HHPack\Codegen\Project\{PackageClassGenerator};
use HHPack\Codegen\HackUnit\{TestClassGenerator};
use function HHPack\Getopt\{ optparser, take_on, on };
use HHPack\Getopt\Parser\{OptionParser};
use Facebook\HackCodegen\{HackCodegenFactory, HackCodegenConfig, CodegenFileResult};
final class Codegen {
const string PROGRAM_NAME = 'codegen';
const string PROGRAM_VERSION = '0.1.0';
private bool $help = false;
private bool $version = false;
private OptionParser $optionParser;
public function __construct() {
$this->optionParser = optparser(
[
on(
['-h', '--help'],
'Display help message',
() ==> {
$this->help = true;
},
),
on(
['-v', '--version'],
'Display version',
() ==> {
$this->version = true;
},
),
]);
}
public function run(Traversable<string> $argv): void {
$args = ImmVector::fromItems($argv)->skip(1);
$remainArgs = $this->optionParser->parse($args);
if ($this->help) {
$this->displayHelp();
} else if ($this->version) {
$this->displayVersion();
} else {
$type = $remainArgs->at(0);
$name = $remainArgs->at(1);
$genType = GenerateType::assert($type);
$this->generateBy(Pair { $genType, $name });
}
}
private function generateBy(Pair<GenerateType, string> $generateClass): void {
$generators = $this->loadGeneratorProvider()->generators();
$generator = LibraryFileGenerator::fromItems($generators);
$classFile = $generator->generate($generateClass);
$result = $classFile->save();
if ($result === CodegenFileResult::CREATE) {
fwrite(STDOUT, sprintf("File %s is created\n", $classFile->getFileName()));
} else if ($result === CodegenFileResult::UPDATE) {
fwrite(STDOUT, sprintf("File %s is updated\n", $classFile->getFileName()));
} else if ($result === CodegenFileResult::NONE) {
fwrite(STDOUT, sprintf("File %s is already exists\n", $classFile->getFileName()));
}
}
private function loadGeneratorProvider(): CodegenGenerators {
$ref = new \ReflectionClass((string) \HHPack\Codegen\Example\Generators::class);
return $generatorProvider = $ref->newInstance();
}
private function displayVersion() : void {
fwrite(STDOUT, sprintf("%s - %s\n", static::PROGRAM_NAME, static::PROGRAM_VERSION));
}
private function displayHelp() : void {
fwrite(STDOUT, sprintf("Usage: %s [OPTIONS] [TYPE] [NAME]\n\n", static::PROGRAM_NAME));
fwrite(STDOUT, "Arguments:\n");
fwrite(STDOUT, " TYPE: generate type (ex. lib, test) \n");
fwrite(STDOUT, " NAME: generate class name (ex. Foo\\Bar)\n\n");
$this->optionParser->displayHelp();
}
}
<|endoftext|> |
<commit_before>#pragma once
#include <domains/messaging/dispatcher.hpp>
#include <domains/utils/function_traits.hpp>
namespace domains {
#if 0
namespace details_ {
template <class Switch, class... Translators>
class decoder_impl {
using decoded_types = std::tuple<argument_of_t<Translators, 1>...>;
static_assert(is_unique<as_parameter_pack_t<decoded_types>>::value,
"Ambiguous translation was found in decoder.");
Switch swtch;
decoded_types decoded_objects;
single_dispatcher<std::decay_t<Translators>...> decode_dispatcher;
template <class DomainDispatcher, class EncodedType>
class impl final {
decoder_impl &d;
template <class DecodedType>
std::error_code decode_and_dispatch(DomainDispatcher &&, EncodedType &&,
std::false_type) noexcept {
return make_error_code(std::errc::not_supported);
}
template <class DecodedType>
std::error_code decode_and_dispatch(DomainDispatcher &&domain_dispatcher,
EncodedType &&encoded_value, std::true_type) {
std::error_code error =
d.decode_dispatcher(encoded_value, std::get<DecodedType>(d.decoded_objects));
if (!error) {
error = std::forward<DomainDispatcher>(domain_dispatcher)(
std::get<DecodedType>(d.decoded_objects));
}
return error;
}
public:
explicit impl(decoder_impl &_d) noexcept : d{_d} {
}
template <class DecodedType>
std::error_code operator()(DomainDispatcher &&domain_dispatcher,
EncodedType &&encoded_value) {
constexpr bool is_safe =
is_dispatchable<single_dispatcher<Translators...>, EncodedType, DecodedType>::value &&
is_dispatchable<DomainDispatcher, DecodedType>::value;
return this->decode_and_dispatch<DecodedType>(
std::forward<DomainDispatcher>(domain_dispatcher), encoded_value,
std::integral_constant<bool, is_safe>{});
}
};
public:
explicit decoder_impl(Switch &&s, single_dispatcher<Translators...> &&t)
: swtch{std::forward<Switch>(s)},
decode_dispatcher{std::forward<single_dispatcher<Translators...>>(t)} {
}
template <class DomainDispatcher, class EncodedType>
std::error_code operator()(DomainDispatcher &&domain_dispatcher, EncodedType &&encoded_value) {
return swtch(std::forward<DomainDispatcher>(domain_dispatcher),
std::forward<EncodedType>(encoded_value),
impl<DomainDispatcher, EncodedType>{*this});
}
};
}
template <class Switch, class... Translators>
struct decoder final : details_::decoder_impl<std::decay_t<Switch>, std::decay_t<Translators>...> {
using details_::decoder_impl<std::decay_t<Switch>, std::decay_t<Translators>...>::decoder_impl;
using details_::decoder_impl<std::decay_t<Switch>, std::decay_t<Translators>...>::operator();
};
template <class Switch, class... Translators>
decoder<Switch, Translators...> make_decoder(Switch swtch, Translators &&... translators) noexcept {
return {std::move(swtch), make_single_dispatcher(std::forward<Translators>(translators)...)};
}
#endif
template <class>
struct decode_type final {};
namespace details_ {
template <class Router, class DecodeDispatcher, class... DecodedTypes>
class decoder_impl {
Router route;
std::aligned_union_t<0, DecodedTypes...> decoded_value_holder;
DecodeDispatcher decode_dispatcher;
struct destruct_only final {
template <class T>
std::enable_if_t<std::is_trivially_destructible<T>::value> operator()(T *const) noexcept {
}
template <class T>
std::enable_if_t<!std::is_trivially_destructible<T>::value> operator()(T *const t) noexcept {
t->~T();
}
};
template <class DecodedType>
std::unique_ptr<DecodedType, destruct_only> make_object() noexcept {
return {new (&decoded_value_holder) DecodedType(), destruct_only{}};
}
template <class DomainDispatcher>
class impl final {
decoder_impl &d;
DomainDispatcher &&domain_dispatcher;
public:
explicit impl(decoder_impl &d_, DomainDispatcher &&dd_) noexcept : d{d_},
domain_dispatcher{dd_} {
}
template <class DecodedType, class EncodedType>
std::error_code operator()(EncodedType &&encoded_value, decode_type<DecodedType> = {}) {
auto decoded_object = d.make_object<DecodedType>();
std::error_code error =
d.decode_dispatcher(std::forward<EncodedType>(encoded_value), *decoded_object);
if (!error) {
error = domain_dispatcher(*decoded_object);
}
return error;
}
};
public:
explicit decoder_impl(Router &&router, DecodeDispatcher &&decoder)
: route{std::forward<Router>(router)},
decode_dispatcher{std::forward<DecodeDispatcher>(decoder)} {
}
template <class DomainDispatcher, class EncodedType>
std::error_code operator()(DomainDispatcher &&domain_dispatcher, EncodedType &&encoded_value) {
return route(std::forward<EncodedType>(encoded_value),
impl<DomainDispatcher>{*this, domain_dispatcher});
}
};
}
template <class Router, class DecodeDispatcher, class... DecodedTypes>
struct decoder : details_::decoder_impl<std::decay_t<Router>, std::decay_t<DecodeDispatcher>,
std::decay_t<DecodedTypes>...> {
static_assert(is_unique_v<parameter_pack<std::decay_t<DecodedTypes>>...>,
"Decoded types must be not list types more than once.");
using base_type_ = details_::decoder_impl<std::decay_t<Router>, std::decay_t<DecodeDispatcher>,
std::decay_t<DecodedTypes>...>;
using base_type_::decoder_impl;
using base_type_::operator();
};
}
<commit_msg>Add null decoder and supporting types<commit_after>#pragma once
#include <domains/messaging/dispatcher.hpp>
#include <domains/utils/function_traits.hpp>
namespace domains {
template <class>
struct decode_type final {};
constexpr auto null_router = [](auto const &&, auto &&) noexcept -> std::error_code {
return {};
};
using null_router_t = decltype(null_router);
constexpr auto null_decode_dispatcher = [](auto const &&, auto &) noexcept -> std::error_code {
return {};
};
using null_decode_dispatcher_t = decltype(null_decode_dispatcher);
constexpr auto null_domain_dispatcher = [](auto const &) noexcept -> std::error_code {
return {};
};
using null_domain_dispatcher_t = decltype(null_domain_dispatcher);
namespace details_ {
template <class Router, class DecodeDispatcher, class... DecodedTypes>
class decoder_impl {
Router route;
std::aligned_union_t<0, DecodedTypes...> decoded_value_holder;
DecodeDispatcher decode_dispatcher;
struct destruct_only final {
template <class T>
std::enable_if_t<std::is_trivially_destructible<T>::value> operator()(T *const) noexcept {
}
template <class T>
std::enable_if_t<!std::is_trivially_destructible<T>::value> operator()(T *const t) noexcept {
t->~T();
}
};
template <class DecodedType>
std::unique_ptr<DecodedType, destruct_only> make_object() noexcept {
return {new (&decoded_value_holder) DecodedType(), destruct_only{}};
}
template <class DomainDispatcher>
class impl final {
decoder_impl &d;
DomainDispatcher &&domain_dispatcher;
public:
explicit impl(decoder_impl &d_, DomainDispatcher &&dd_) noexcept : d{d_},
domain_dispatcher{dd_} {
}
template <class DecodedType, class EncodedType>
std::error_code operator()(EncodedType &&encoded_value, decode_type<DecodedType> = {}) {
auto decoded_object = d.make_object<DecodedType>();
std::error_code error =
d.decode_dispatcher(std::forward<EncodedType>(encoded_value), *decoded_object);
if (!error) {
error = domain_dispatcher(*decoded_object);
}
return error;
}
};
public:
explicit decoder_impl(Router &&router = {}, DecodeDispatcher &&decoder = {})
: route{std::forward<Router>(router)},
decode_dispatcher{std::forward<DecodeDispatcher>(decoder)} {
}
template <class DomainDispatcher, class EncodedType>
std::error_code operator()(DomainDispatcher &&domain_dispatcher, EncodedType &&encoded_value) {
return route(std::forward<EncodedType>(encoded_value),
impl<DomainDispatcher>{*this, domain_dispatcher});
}
};
}
template <class Router, class DecodeDispatcher, class... DecodedTypes>
struct decoder : details_::decoder_impl<std::decay_t<Router>, std::decay_t<DecodeDispatcher>,
std::decay_t<DecodedTypes>...> {
static_assert(is_unique_v<parameter_pack<std::decay_t<DecodedTypes>>...>,
"Decoded types must be not list types more than once.");
using base_type_ = details_::decoder_impl<std::decay_t<Router>, std::decay_t<DecodeDispatcher>,
std::decay_t<DecodedTypes>...>;
using base_type_::decoder_impl;
using base_type_::operator();
};
template <class... T>
using null_decoder_t = decoder<null_router_t, null_decode_dispatcher_t, T...>;
}
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/dreamview/backend/sim_control/sim_control.h"
#include <cmath>
#include "modules/common/math/linear_interpolation.h"
#include "modules/common/math/math_utils.h"
#include "modules/common/math/quaternion.h"
#include "modules/common/time/time.h"
#include "modules/common/util/file.h"
namespace apollo {
namespace dreamview {
using apollo::canbus::Chassis;
using apollo::common::Header;
using apollo::common::Point3D;
using apollo::common::Quaternion;
using apollo::common::TrajectoryPoint;
using apollo::common::adapter::AdapterManager;
using apollo::common::math::HeadingToQuaternion;
using apollo::common::math::InverseQuaternionRotate;
using apollo::common::math::NormalizeAngle;
using apollo::common::math::QuaternionToHeading;
using apollo::common::time::Clock;
using apollo::common::util::GetProtoFromFile;
using apollo::localization::LocalizationEstimate;
using apollo::routing::RoutingResponse;
namespace {
void TransformToVRF(const Point3D& point_mrf, const Quaternion& orientation,
Point3D* point_vrf) {
Eigen::Vector3d v_mrf(point_mrf.x(), point_mrf.y(), point_mrf.z());
auto v_vrf = InverseQuaternionRotate(orientation, v_mrf);
point_vrf->set_x(v_vrf.x());
point_vrf->set_y(v_vrf.y());
point_vrf->set_z(v_vrf.z());
}
bool IsSameHeader(const Header& lhs, const Header& rhs) {
return lhs.sequence_num() == rhs.sequence_num() &&
lhs.timestamp_sec() == rhs.timestamp_sec();
}
} // namespace
SimControl::SimControl(const MapService* map_service)
: map_service_(map_service) {}
void SimControl::Init(bool set_start_point, double start_velocity,
double start_acceleration) {
// Setup planning and routing result data callback.
AdapterManager::AddPlanningCallback(&SimControl::OnPlanning, this);
AdapterManager::AddRoutingResponseCallback(&SimControl::OnRoutingResponse,
this);
AdapterManager::AddNavigationCallback(&SimControl::OnReceiveNavigationInfo,
this);
// Start timer to publish localization and chassis messages.
sim_control_timer_ = AdapterManager::CreateTimer(
ros::Duration(kSimControlInterval), &SimControl::TimerCallback, this);
if (set_start_point && !FLAGS_use_navigation_mode) {
apollo::common::PointENU start_point;
if (!map_service_->GetStartPoint(&start_point)) {
AWARN << "Failed to get a dummy start point from map!";
return;
}
TrajectoryPoint point;
point.mutable_path_point()->set_x(start_point.x());
point.mutable_path_point()->set_y(start_point.y());
point.mutable_path_point()->set_z(start_point.z());
point.set_v(start_velocity);
point.set_a(start_acceleration);
SetStartPoint(point);
}
start_velocity_ = start_velocity;
start_acceleration_ = start_acceleration;
}
void SimControl::OnReceiveNavigationInfo(
const relative_map::NavigationInfo& navigation_info) {
navigation_info_ = navigation_info;
if (navigation_info_.navigation_path_size() > 0) {
const auto& path = navigation_info_.navigation_path(0).path();
if (path.path_point_size() > 0) {
adc_position_ = path.path_point(0);
}
}
}
void SimControl::SetStartPoint(const TrajectoryPoint& start_point) {
next_point_ = start_point;
prev_point_index_ = next_point_index_ = 0;
received_planning_ = false;
}
void SimControl::ClearPlanning() {
current_trajectory_.Clear();
received_planning_ = false;
if (planning_count_ > 0) {
planning_count_ = 0;
}
}
void SimControl::Reset() {
current_routing_header_.Clear();
re_routing_triggered_ = false;
ClearPlanning();
}
void SimControl::OnRoutingResponse(const RoutingResponse& routing) {
if (!enabled_) {
return;
}
CHECK_GE(routing.routing_request().waypoint_size(), 2)
<< "routing should have at least two waypoints";
const auto& start_pose = routing.routing_request().waypoint(0).pose();
current_routing_header_ = routing.header();
// If this is from a planning re-routing request, don't reset car's location.
re_routing_triggered_ =
routing.routing_request().header().module_name() == "planning";
if (!re_routing_triggered_) {
ClearPlanning();
TrajectoryPoint point;
point.mutable_path_point()->set_x(start_pose.x());
point.mutable_path_point()->set_y(start_pose.y());
point.set_a(0.0);
point.set_v(0.0);
double theta = 0.0;
double s = 0.0;
map_service_->GetPoseWithRegardToLane(start_pose.x(), start_pose.y(),
&theta, &s);
point.mutable_path_point()->set_theta(theta);
SetStartPoint(point);
}
}
void SimControl::Start() {
if (!enabled_) {
if (!inited_) {
// Only place the car when there is not a localization.
Init(AdapterManager::GetLocalization()->Empty());
}
Reset();
sim_control_timer_.start();
enabled_ = true;
}
}
void SimControl::Stop() {
if (enabled_) {
sim_control_timer_.stop();
enabled_ = false;
}
}
void SimControl::OnPlanning(const apollo::planning::ADCTrajectory& trajectory) {
if (!enabled_) {
return;
}
// Reset current trajectory and the indices upon receiving a new trajectory.
// The routing SimControl owns must match with the one Planning has.
if (re_routing_triggered_ ||
IsSameHeader(trajectory.routing_header(), current_routing_header_)) {
// Hold a few cycles until the position information is fully refreshed on
// planning side. Don't wait for the very first planning received.
++planning_count_;
if (planning_count_ == 0 || planning_count_ >= kPlanningCountToStart) {
planning_count_ = kPlanningCountToStart;
current_trajectory_ = trajectory;
prev_point_index_ = 0;
next_point_index_ = 0;
received_planning_ = true;
}
} else {
ClearPlanning();
}
}
void SimControl::Freeze() {
next_point_.set_v(0.0);
next_point_.set_a(0.0);
prev_point_ = next_point_;
}
void SimControl::TimerCallback(const ros::TimerEvent& event) { RunOnce(); }
void SimControl::RunOnce() {
TrajectoryPoint trajectory_point;
if (!PerfectControlModel(&trajectory_point)) {
AERROR << "Failed to calculate next point with perfect control model";
return;
}
PublishChassis(trajectory_point.v());
PublishLocalization(trajectory_point);
}
bool SimControl::PerfectControlModel(TrajectoryPoint* point) {
// Result of the interpolation.
auto relative_time =
Clock::NowInSeconds() - current_trajectory_.header().timestamp_sec();
const auto& trajectory = current_trajectory_.trajectory_point();
if (!received_planning_) {
prev_point_ = next_point_;
} else {
if (current_trajectory_.estop().is_estop() ||
next_point_index_ >= trajectory.size()) {
// Freeze the car when there's an estop or the current trajectory has
// been exhausted.
Freeze();
} else {
// Determine the status of the car based on received planning message.
while (next_point_index_ < trajectory.size() &&
relative_time >
trajectory.Get(next_point_index_).relative_time()) {
++next_point_index_;
}
if (next_point_index_ == 0) {
AERROR << "First trajectory point is a future point!";
return false;
}
if (next_point_index_ >= trajectory.size()) {
next_point_index_ = trajectory.size() - 1;
}
prev_point_index_ = next_point_index_ - 1;
next_point_ = trajectory.Get(next_point_index_);
prev_point_ = trajectory.Get(prev_point_index_);
}
}
*point = apollo::common::math::InterpolateUsingLinearApproximation(
prev_point_, next_point_, relative_time);
return true;
}
void SimControl::PublishChassis(double cur_speed) {
Chassis chassis;
AdapterManager::FillChassisHeader("SimControl", &chassis);
chassis.set_engine_started(true);
chassis.set_driving_mode(Chassis::COMPLETE_AUTO_DRIVE);
chassis.set_gear_location(Chassis::GEAR_DRIVE);
chassis.set_speed_mps(cur_speed);
chassis.set_throttle_percentage(0.0);
chassis.set_brake_percentage(0.0);
AdapterManager::PublishChassis(chassis);
}
void SimControl::PublishLocalization(const TrajectoryPoint& point) {
LocalizationEstimate localization;
AdapterManager::FillLocalizationHeader("SimControl", &localization);
auto* pose = localization.mutable_pose();
auto prev = prev_point_.path_point();
auto next = next_point_.path_point();
// Set position
pose->mutable_position()->set_x(point.path_point().x());
pose->mutable_position()->set_y(point.path_point().y());
pose->mutable_position()->set_z(point.path_point().z());
// Set orientation and heading
double cur_theta = point.path_point().theta();
if (FLAGS_use_navigation_mode) {
double flu_x = point.path_point().x();
double flu_y = point.path_point().y();
double enu_x = 0.0;
double enu_y = 0.0;
common::math::RotateAxis(-cur_theta, flu_x, flu_y, &enu_x, &enu_y);
enu_x += adc_position_.x();
enu_y += adc_position_.y();
pose->mutable_position()->set_x(enu_x);
pose->mutable_position()->set_y(enu_y);
}
Eigen::Quaternion<double> cur_orientation =
HeadingToQuaternion<double>(cur_theta);
pose->mutable_orientation()->set_qw(cur_orientation.w());
pose->mutable_orientation()->set_qx(cur_orientation.x());
pose->mutable_orientation()->set_qy(cur_orientation.y());
pose->mutable_orientation()->set_qz(cur_orientation.z());
pose->set_heading(cur_theta);
// Set linear_velocity
pose->mutable_linear_velocity()->set_x(std::cos(cur_theta) * point.v());
pose->mutable_linear_velocity()->set_y(std::sin(cur_theta) * point.v());
pose->mutable_linear_velocity()->set_z(0);
// Set angular_velocity in both map reference frame and vehicle reference
// frame
pose->mutable_angular_velocity()->set_x(0);
pose->mutable_angular_velocity()->set_y(0);
pose->mutable_angular_velocity()->set_z(point.v() *
point.path_point().kappa());
TransformToVRF(pose->angular_velocity(), pose->orientation(),
pose->mutable_angular_velocity_vrf());
// Set linear_acceleration in both map reference frame and vehicle reference
// frame
auto* linear_acceleration = pose->mutable_linear_acceleration();
linear_acceleration->set_x(std::cos(cur_theta) * point.a());
linear_acceleration->set_y(std::sin(cur_theta) * point.a());
linear_acceleration->set_z(0);
TransformToVRF(pose->linear_acceleration(), pose->orientation(),
pose->mutable_linear_acceleration_vrf());
AdapterManager::PublishLocalization(localization);
adc_position_.set_x(pose->position().x());
adc_position_.set_y(pose->position().y());
adc_position_.set_z(pose->position().z());
}
} // namespace dreamview
} // namespace apollo
<commit_msg>Dreamview: Fix a bug that car goes endlessly in SimControl mode<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/dreamview/backend/sim_control/sim_control.h"
#include <cmath>
#include "modules/common/math/linear_interpolation.h"
#include "modules/common/math/math_utils.h"
#include "modules/common/math/quaternion.h"
#include "modules/common/time/time.h"
#include "modules/common/util/file.h"
namespace apollo {
namespace dreamview {
using apollo::canbus::Chassis;
using apollo::common::Header;
using apollo::common::Point3D;
using apollo::common::Quaternion;
using apollo::common::TrajectoryPoint;
using apollo::common::adapter::AdapterManager;
using apollo::common::math::HeadingToQuaternion;
using apollo::common::math::InverseQuaternionRotate;
using apollo::common::math::InterpolateUsingLinearApproximation;
using apollo::common::math::NormalizeAngle;
using apollo::common::math::QuaternionToHeading;
using apollo::common::time::Clock;
using apollo::common::util::GetProtoFromFile;
using apollo::localization::LocalizationEstimate;
using apollo::routing::RoutingResponse;
namespace {
void TransformToVRF(const Point3D& point_mrf, const Quaternion& orientation,
Point3D* point_vrf) {
Eigen::Vector3d v_mrf(point_mrf.x(), point_mrf.y(), point_mrf.z());
auto v_vrf = InverseQuaternionRotate(orientation, v_mrf);
point_vrf->set_x(v_vrf.x());
point_vrf->set_y(v_vrf.y());
point_vrf->set_z(v_vrf.z());
}
bool IsSameHeader(const Header& lhs, const Header& rhs) {
return lhs.sequence_num() == rhs.sequence_num() &&
lhs.timestamp_sec() == rhs.timestamp_sec();
}
} // namespace
SimControl::SimControl(const MapService* map_service)
: map_service_(map_service) {}
void SimControl::Init(bool set_start_point, double start_velocity,
double start_acceleration) {
// Setup planning and routing result data callback.
AdapterManager::AddPlanningCallback(&SimControl::OnPlanning, this);
AdapterManager::AddRoutingResponseCallback(&SimControl::OnRoutingResponse,
this);
AdapterManager::AddNavigationCallback(&SimControl::OnReceiveNavigationInfo,
this);
// Start timer to publish localization and chassis messages.
sim_control_timer_ = AdapterManager::CreateTimer(
ros::Duration(kSimControlInterval), &SimControl::TimerCallback, this);
if (set_start_point && !FLAGS_use_navigation_mode) {
apollo::common::PointENU start_point;
if (!map_service_->GetStartPoint(&start_point)) {
AWARN << "Failed to get a dummy start point from map!";
return;
}
TrajectoryPoint point;
point.mutable_path_point()->set_x(start_point.x());
point.mutable_path_point()->set_y(start_point.y());
point.mutable_path_point()->set_z(start_point.z());
point.set_v(start_velocity);
point.set_a(start_acceleration);
SetStartPoint(point);
}
start_velocity_ = start_velocity;
start_acceleration_ = start_acceleration;
}
void SimControl::OnReceiveNavigationInfo(
const relative_map::NavigationInfo& navigation_info) {
navigation_info_ = navigation_info;
if (navigation_info_.navigation_path_size() > 0) {
const auto& path = navigation_info_.navigation_path(0).path();
if (path.path_point_size() > 0) {
adc_position_ = path.path_point(0);
}
}
}
void SimControl::SetStartPoint(const TrajectoryPoint& start_point) {
next_point_ = start_point;
prev_point_index_ = next_point_index_ = 0;
received_planning_ = false;
}
void SimControl::ClearPlanning() {
current_trajectory_.Clear();
received_planning_ = false;
if (planning_count_ > 0) {
planning_count_ = 0;
}
}
void SimControl::Reset() {
current_routing_header_.Clear();
re_routing_triggered_ = false;
ClearPlanning();
}
void SimControl::OnRoutingResponse(const RoutingResponse& routing) {
if (!enabled_) {
return;
}
CHECK_GE(routing.routing_request().waypoint_size(), 2)
<< "routing should have at least two waypoints";
const auto& start_pose = routing.routing_request().waypoint(0).pose();
current_routing_header_ = routing.header();
// If this is from a planning re-routing request, don't reset car's location.
re_routing_triggered_ =
routing.routing_request().header().module_name() == "planning";
if (!re_routing_triggered_) {
ClearPlanning();
TrajectoryPoint point;
point.mutable_path_point()->set_x(start_pose.x());
point.mutable_path_point()->set_y(start_pose.y());
point.set_a(0.0);
point.set_v(0.0);
double theta = 0.0;
double s = 0.0;
map_service_->GetPoseWithRegardToLane(start_pose.x(), start_pose.y(),
&theta, &s);
point.mutable_path_point()->set_theta(theta);
SetStartPoint(point);
}
}
void SimControl::Start() {
if (!enabled_) {
if (!inited_) {
// Only place the car when there is not a localization.
Init(AdapterManager::GetLocalization()->Empty());
}
Reset();
sim_control_timer_.start();
enabled_ = true;
}
}
void SimControl::Stop() {
if (enabled_) {
sim_control_timer_.stop();
enabled_ = false;
}
}
void SimControl::OnPlanning(const apollo::planning::ADCTrajectory& trajectory) {
if (!enabled_) {
return;
}
// Reset current trajectory and the indices upon receiving a new trajectory.
// The routing SimControl owns must match with the one Planning has.
if (re_routing_triggered_ ||
IsSameHeader(trajectory.routing_header(), current_routing_header_)) {
// Hold a few cycles until the position information is fully refreshed on
// planning side. Don't wait for the very first planning received.
++planning_count_;
if (planning_count_ == 0 || planning_count_ >= kPlanningCountToStart) {
planning_count_ = kPlanningCountToStart;
current_trajectory_ = trajectory;
prev_point_index_ = 0;
next_point_index_ = 0;
received_planning_ = true;
}
} else {
ClearPlanning();
}
}
void SimControl::Freeze() {
next_point_.set_v(0.0);
next_point_.set_a(0.0);
prev_point_ = next_point_;
}
void SimControl::TimerCallback(const ros::TimerEvent& event) { RunOnce(); }
void SimControl::RunOnce() {
TrajectoryPoint trajectory_point;
if (!PerfectControlModel(&trajectory_point)) {
AERROR << "Failed to calculate next point with perfect control model";
return;
}
PublishChassis(trajectory_point.v());
PublishLocalization(trajectory_point);
}
bool SimControl::PerfectControlModel(TrajectoryPoint* point) {
// Result of the interpolation.
auto relative_time =
Clock::NowInSeconds() - current_trajectory_.header().timestamp_sec();
const auto& trajectory = current_trajectory_.trajectory_point();
if (!received_planning_) {
prev_point_ = next_point_;
} else {
if (current_trajectory_.estop().is_estop() ||
next_point_index_ >= trajectory.size()) {
// Freeze the car when there's an estop or the current trajectory has
// been exhausted.
Freeze();
} else {
// Determine the status of the car based on received planning message.
while (next_point_index_ < trajectory.size() &&
relative_time >
trajectory.Get(next_point_index_).relative_time()) {
++next_point_index_;
}
if (next_point_index_ == 0) {
AERROR << "First trajectory point is a future point!";
return false;
}
if (next_point_index_ >= trajectory.size()) {
next_point_index_ = trajectory.size() - 1;
}
prev_point_index_ = next_point_index_ - 1;
next_point_ = trajectory.Get(next_point_index_);
prev_point_ = trajectory.Get(prev_point_index_);
}
}
if (relative_time > next_point_.relative_time()) {
// Don't try to extrapolate if relative_time passes last point
*point = next_point_;
} else {
*point = InterpolateUsingLinearApproximation(prev_point_, next_point_,
relative_time);
}
return true;
}
void SimControl::PublishChassis(double cur_speed) {
Chassis chassis;
AdapterManager::FillChassisHeader("SimControl", &chassis);
chassis.set_engine_started(true);
chassis.set_driving_mode(Chassis::COMPLETE_AUTO_DRIVE);
chassis.set_gear_location(Chassis::GEAR_DRIVE);
chassis.set_speed_mps(cur_speed);
chassis.set_throttle_percentage(0.0);
chassis.set_brake_percentage(0.0);
AdapterManager::PublishChassis(chassis);
}
void SimControl::PublishLocalization(const TrajectoryPoint& point) {
LocalizationEstimate localization;
AdapterManager::FillLocalizationHeader("SimControl", &localization);
auto* pose = localization.mutable_pose();
auto prev = prev_point_.path_point();
auto next = next_point_.path_point();
// Set position
pose->mutable_position()->set_x(point.path_point().x());
pose->mutable_position()->set_y(point.path_point().y());
pose->mutable_position()->set_z(point.path_point().z());
// Set orientation and heading
double cur_theta = point.path_point().theta();
if (FLAGS_use_navigation_mode) {
double flu_x = point.path_point().x();
double flu_y = point.path_point().y();
double enu_x = 0.0;
double enu_y = 0.0;
common::math::RotateAxis(-cur_theta, flu_x, flu_y, &enu_x, &enu_y);
enu_x += adc_position_.x();
enu_y += adc_position_.y();
pose->mutable_position()->set_x(enu_x);
pose->mutable_position()->set_y(enu_y);
}
Eigen::Quaternion<double> cur_orientation =
HeadingToQuaternion<double>(cur_theta);
pose->mutable_orientation()->set_qw(cur_orientation.w());
pose->mutable_orientation()->set_qx(cur_orientation.x());
pose->mutable_orientation()->set_qy(cur_orientation.y());
pose->mutable_orientation()->set_qz(cur_orientation.z());
pose->set_heading(cur_theta);
// Set linear_velocity
pose->mutable_linear_velocity()->set_x(std::cos(cur_theta) * point.v());
pose->mutable_linear_velocity()->set_y(std::sin(cur_theta) * point.v());
pose->mutable_linear_velocity()->set_z(0);
// Set angular_velocity in both map reference frame and vehicle reference
// frame
pose->mutable_angular_velocity()->set_x(0);
pose->mutable_angular_velocity()->set_y(0);
pose->mutable_angular_velocity()->set_z(point.v() *
point.path_point().kappa());
TransformToVRF(pose->angular_velocity(), pose->orientation(),
pose->mutable_angular_velocity_vrf());
// Set linear_acceleration in both map reference frame and vehicle reference
// frame
auto* linear_acceleration = pose->mutable_linear_acceleration();
linear_acceleration->set_x(std::cos(cur_theta) * point.a());
linear_acceleration->set_y(std::sin(cur_theta) * point.a());
linear_acceleration->set_z(0);
TransformToVRF(pose->linear_acceleration(), pose->orientation(),
pose->mutable_linear_acceleration_vrf());
AdapterManager::PublishLocalization(localization);
adc_position_.set_x(pose->position().x());
adc_position_.set_y(pose->position().y());
adc_position_.set_z(pose->position().z());
}
} // namespace dreamview
} // namespace apollo
<|endoftext|> |
<commit_before>#include "Enemy.hpp"
#include "Weapon.hpp"
#include "Dialog.hpp"
#include "Bullet.hpp"
#include "../Resources.hpp"
#include "../Math.hpp"
#include <tuple>
#include <random>
#include <SFML/Graphics/Sprite.hpp>
#include <Kunlaboro/EntitySystem.hpp>
Enemy::Enemy() : Kunlaboro::Component("Game.Enemy"), mSheet(Resources::Texture_Enemy, 4, 2), mHealth(100), mArmor(1), mTime(0), mLastAng(0), mDrawAng(0), mFadeTime(0), mFear(false)
{
}
Enemy::~Enemy()
{
}
void Enemy::addedToEntity()
{
if (mPosition == sf::Vector2f())
{
sf::Vector2f playerPos;
auto reply = sendGlobalQuestion("Where's the player?");
if (reply.handled)
playerPos = boost::any_cast<sf::Vector2f>(reply.payload);
std::random_device dev;
float randAng = std::uniform_real_distribution<float>(0, M_PI * 2)(dev);
mPosition = playerPos + sf::Vector2f(cos(randAng), sin(randAng)) * 1024.f;
}
requestMessage("Event.Update", [this](const Kunlaboro::Message& msg)
{
float dt = boost::any_cast<float>(msg.payload);
std::random_device dev;
sf::Vector2f playerPos;
auto reply = sendGlobalQuestion("Where's the player?");
if (reply.handled)
playerPos = boost::any_cast<sf::Vector2f>(reply.payload);
float playerAng = atan2(playerPos.y - mPosition.y, playerPos.x - mPosition.x);
float randAng = std::uniform_real_distribution<float>(-0.1, 0.1)(dev);
mLastAng += randAng;
if (mFear)
mLastAng += (playerAng+M_PI - mLastAng) * dt;
else
mLastAng += (playerAng - mLastAng) * dt;
mPosition += sf::Vector2f(cos(mLastAng), sin(mLastAng)) * dt * 100.f;
mDrawAng += (mLastAng - mDrawAng) / 8.f;
mTime += dt;
if (mTime > 1)
{
mTime -= 1;
auto reply = sendQuestion("Such bullets?");
if (!reply.handled)
return;
if (dynamic_cast<Weapon*>(reply.sender)->weaponType() == "Bonus")
{
sendMessage("Throw it to the ground!");
return;
}
int ammo = boost::any_cast<int>(reply.payload);
if (ammo == 0)
{
sendMessage("More ammo!");
auto reply = sendQuestion("Out of mags?");
int mags = boost::any_cast<int>(reply.payload);;
if (mags == 0)
{
sendMessage("Throw it to the ground!");
return;
}
}
mLastFire = (playerAng + std::uniform_real_distribution<float>(-0.2, 0.2)(dev)) * (180/M_PI);
sendMessage("Fire ze missiles!");
}
if (mHealth <= 25 && !mFear)
{
auto dialog = dynamic_cast<Dialog*>(getEntitySystem()->createComponent("Game.Dialog"));
dialog->setMessage("The pain!");
addLocalComponent(dialog);
mFear = true;
}
if (mHealth <= 0)
{
sendMessage("Throw it to the ground!");
getEntitySystem()->destroyEntity(getOwnerId());
}
});
requestMessage("Event.Draw", [this](const Kunlaboro::Message& msg)
{
auto data = boost::any_cast<std::tuple<sf::RenderTarget*,float>>(msg.payload);
auto& target = *std::get<0>(data);
sf::FloatRect viewRect(target.getView().getCenter(), target.getView().getSize());
viewRect.left -= viewRect.width / 2.f;
viewRect.top -= viewRect.height / 2.f;
if (!viewRect.contains(mPosition))
{
mFadeTime += std::get<1>(data);
if (mFadeTime > 4)
getEntitySystem()->destroyEntity(getOwnerId());
}
else
{
mFadeTime = 0;
sf::Sprite enemy(Resources::Texture_Enemy);
enemy.setTextureRect(mSheet.getRect(0,0));
enemy.setOrigin(enemy.getTextureRect().width / 2, enemy.getTextureRect().height / 2);
enemy.setPosition(mPosition);
enemy.setRotation(mDrawAng * (180 / M_PI));
target.draw(enemy);
}
});
requestMessage("I'm ending this!", [this](const Kunlaboro::Message& msg) { getEntitySystem()->destroyEntity(getOwnerId()); });
requestMessage("Where am I?", [this](Kunlaboro::Message& msg) { msg.handled = true; msg.payload = mPosition; }, true);
requestMessage("Where am I shooting?", [this](Kunlaboro::Message& msg) { msg.handled = true; msg.payload = std::make_tuple(mPosition, mLastFire); });
requestMessage("Would the real slim shady please stand up?", [this](const Kunlaboro::Message& msg)
{
auto data = boost::any_cast<std::list<Enemy*>*>(msg.payload);
data->push_back(this);
});
requestMessage("Did I hit something?", [this](Kunlaboro::Message& msg)
{
if (msg.sender->getOwnerId() == getOwnerId()) return;
auto pos = boost::any_cast<sf::Vector2f>(msg.payload);
float diff = Math::distance(mPosition, pos);
if (diff < 32)
{
auto& sys = *getEntitySystem();
auto dialog = dynamic_cast<Dialog*>(sys.createComponent("Game.Dialog"));
dialog->setMessage("OW");
addLocalComponent(dialog);
auto bullet = dynamic_cast<Bullet*>(msg.sender);
mHealth -= bullet->getDamage();
if (mHealth < 0)
{
sendGlobalMessage("Enemy dead!");
}
msg.payload = true;
msg.handled = true;
}
});
requestComponent("Game.Weapon", [this](const Kunlaboro::Message& msg)
{
auto weap = dynamic_cast<Weapon*>(msg.sender);
if (msg.type == Kunlaboro::Type_Create)
{
auto& sys = *getEntitySystem();
{
auto dialog = dynamic_cast<Dialog*>(sys.createComponent("Game.Dialog"));
dialog->setMessage("Eat " + weap->bulletName() + " and die!");
addLocalComponent(dialog);
}
}
else
{
auto& sys = *getEntitySystem();
auto dialog = dynamic_cast<Dialog*>(sys.createComponent("Game.Dialog"));
dialog->setMessage("No more " + weap->bulletName()+ "?\nI AM FLEEING IN FEAR!");
addLocalComponent(dialog);
mFear = true;
}
});
}<commit_msg>Player specific kills<commit_after>#include "Enemy.hpp"
#include "Weapon.hpp"
#include "Dialog.hpp"
#include "Bullet.hpp"
#include "../Resources.hpp"
#include "../Math.hpp"
#include <tuple>
#include <random>
#include <SFML/Graphics/Sprite.hpp>
#include <Kunlaboro/EntitySystem.hpp>
Enemy::Enemy() : Kunlaboro::Component("Game.Enemy"), mSheet(Resources::Texture_Enemy, 4, 2), mHealth(100), mArmor(1), mTime(0), mLastAng(0), mDrawAng(0), mFadeTime(0), mFear(false)
{
}
Enemy::~Enemy()
{
}
void Enemy::addedToEntity()
{
if (mPosition == sf::Vector2f())
{
sf::Vector2f playerPos;
auto reply = sendGlobalQuestion("Where's the player?");
if (reply.handled)
playerPos = boost::any_cast<sf::Vector2f>(reply.payload);
std::random_device dev;
float randAng = std::uniform_real_distribution<float>(0, M_PI * 2)(dev);
mPosition = playerPos + sf::Vector2f(cos(randAng), sin(randAng)) * 1024.f;
}
requestMessage("Event.Update", [this](const Kunlaboro::Message& msg)
{
float dt = boost::any_cast<float>(msg.payload);
std::random_device dev;
sf::Vector2f playerPos;
auto reply = sendGlobalQuestion("Where's the player?");
if (reply.handled)
playerPos = boost::any_cast<sf::Vector2f>(reply.payload);
float playerAng = atan2(playerPos.y - mPosition.y, playerPos.x - mPosition.x);
float randAng = std::uniform_real_distribution<float>(-0.1, 0.1)(dev);
mLastAng += randAng;
if (mFear)
mLastAng += (playerAng+M_PI - mLastAng) * dt;
else
mLastAng += (playerAng - mLastAng) * dt;
mPosition += sf::Vector2f(cos(mLastAng), sin(mLastAng)) * dt * 100.f;
mDrawAng += (mLastAng - mDrawAng) / 8.f;
mTime += dt;
if (mTime > 1)
{
mTime -= 1;
auto reply = sendQuestion("Such bullets?");
if (!reply.handled)
return;
if (dynamic_cast<Weapon*>(reply.sender)->weaponType() == "Bonus")
{
sendMessage("Throw it to the ground!");
return;
}
int ammo = boost::any_cast<int>(reply.payload);
if (ammo == 0)
{
sendMessage("More ammo!");
auto reply = sendQuestion("Out of mags?");
int mags = boost::any_cast<int>(reply.payload);;
if (mags == 0)
{
sendMessage("Throw it to the ground!");
return;
}
}
mLastFire = (playerAng + std::uniform_real_distribution<float>(-0.2, 0.2)(dev)) * (180/M_PI);
sendMessage("Fire ze missiles!");
}
if (mHealth <= 25 && !mFear)
{
auto dialog = dynamic_cast<Dialog*>(getEntitySystem()->createComponent("Game.Dialog"));
dialog->setMessage("The pain!");
addLocalComponent(dialog);
mFear = true;
}
if (mHealth <= 0)
{
sendMessage("Throw it to the ground!");
getEntitySystem()->destroyEntity(getOwnerId());
}
});
requestMessage("Event.Draw", [this](const Kunlaboro::Message& msg)
{
auto data = boost::any_cast<std::tuple<sf::RenderTarget*,float>>(msg.payload);
auto& target = *std::get<0>(data);
sf::FloatRect viewRect(target.getView().getCenter(), target.getView().getSize());
viewRect.left -= viewRect.width / 2.f;
viewRect.top -= viewRect.height / 2.f;
if (!viewRect.contains(mPosition))
{
mFadeTime += std::get<1>(data);
if (mFadeTime > 4)
getEntitySystem()->destroyEntity(getOwnerId());
}
else
{
mFadeTime = 0;
sf::Sprite enemy(Resources::Texture_Enemy);
enemy.setTextureRect(mSheet.getRect(0,0));
enemy.setOrigin(enemy.getTextureRect().width / 2, enemy.getTextureRect().height / 2);
enemy.setPosition(mPosition);
enemy.setRotation(mDrawAng * (180 / M_PI));
target.draw(enemy);
}
});
requestMessage("I'm ending this!", [this](const Kunlaboro::Message& msg) { getEntitySystem()->destroyEntity(getOwnerId()); });
requestMessage("Where am I?", [this](Kunlaboro::Message& msg) { msg.handled = true; msg.payload = mPosition; }, true);
requestMessage("Where am I shooting?", [this](Kunlaboro::Message& msg) { msg.handled = true; msg.payload = std::make_tuple(mPosition, mLastFire); });
requestMessage("Would the real slim shady please stand up?", [this](const Kunlaboro::Message& msg)
{
auto data = boost::any_cast<std::list<Enemy*>*>(msg.payload);
data->push_back(this);
});
requestMessage("Did I hit something?", [this](Kunlaboro::Message& msg)
{
if (msg.sender->getOwnerId() == getOwnerId()) return;
auto pos = boost::any_cast<sf::Vector2f>(msg.payload);
float diff = Math::distance(mPosition, pos);
if (diff < 32)
{
auto& sys = *getEntitySystem();
auto dialog = dynamic_cast<Dialog*>(sys.createComponent("Game.Dialog"));
dialog->setMessage("OW");
addLocalComponent(dialog);
auto bullet = dynamic_cast<Bullet*>(msg.sender);
float lastHealth = mHealth;
mHealth -= bullet->getDamage();
if (mHealth <= 0 && lastHealth > 0)
{
bool playerKill = !getEntitySystem()->getAllComponentsOnEntity(msg.sender->getOwnerId(), "Game.Player").empty();
sendGlobalMessage("Enemy dead!", playerKill);
}
msg.payload = true;
msg.handled = true;
}
});
requestComponent("Game.Weapon", [this](const Kunlaboro::Message& msg)
{
auto weap = dynamic_cast<Weapon*>(msg.sender);
if (msg.type == Kunlaboro::Type_Create)
{
auto& sys = *getEntitySystem();
{
auto dialog = dynamic_cast<Dialog*>(sys.createComponent("Game.Dialog"));
dialog->setMessage("Eat " + weap->bulletName() + " and die!");
addLocalComponent(dialog);
}
}
else
{
auto& sys = *getEntitySystem();
auto dialog = dynamic_cast<Dialog*>(sys.createComponent("Game.Dialog"));
dialog->setMessage("No more " + weap->bulletName()+ "?\nI AM FLEEING IN FEAR!");
addLocalComponent(dialog);
mFear = true;
}
});
}<|endoftext|> |
<commit_before>#include "clang/Frontend/FrontendActions.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/Support/CommandLine.h"
#include "DotGenerator.h"
#include "HsmAstMatcher.h"
#include "HsmTypes.h"
using namespace clang;
using namespace clang::ast_matchers;
using namespace clang::tooling;
using namespace llvm;
static const char *ToolDescription = "A tool that analyzes C++ code that makes "
"use of the HSM library "
"(https://github.com/amaiorano/hsm)\n";
static cl::OptionCategory HsmAnalyzeCategory("hsm-analyze options");
static cl::opt<bool> PrintMap("map", cl::desc("Print state-transition map"),
cl::cat(HsmAnalyzeCategory));
static cl::opt<bool>
PrintDotFile("dot", cl::desc("Print state-transition dot file contents"),
cl::cat(HsmAnalyzeCategory));
static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);
int main(int argc, const char **argv) {
CommonOptionsParser OptionsParser(argc, argv, HsmAnalyzeCategory,
ToolDescription);
ClangTool Tool(OptionsParser.getCompilations(),
OptionsParser.getSourcePathList());
if (!(PrintMap || PrintDotFile)) {
llvm::errs() << "Nothing to do. Please specify "
"an action to perform.\n\n";
cl::PrintHelpMessage();
return -1;
}
StateTransitionMap Map;
MatchFinder Finder;
HsmAstMatcher::addMatchers(Finder, Map);
auto Result = Tool.run(newFrontendActionFactory(&Finder).get());
if (Result != 0) {
return Result;
}
if (PrintMap) {
for (auto &kvp : Map) {
auto SourceStateName = kvp.first;
auto TransType = std::get<0>(kvp.second);
auto TargetStateName = std::get<1>(kvp.second);
llvm::outs() << SourceStateName << " "
<< TransitionTypeVisualString[static_cast<int>(TransType)]
<< " " << TargetStateName << "\n";
llvm::outs().flush();
}
}
if (PrintDotFile) {
auto DotFileContents = DotGenerator::generateDotFileContents(Map);
llvm::outs() << DotFileContents;
llvm::outs().flush();
}
}
<commit_msg>Display version ("hsm-analyze 1.0.0.0") when -version is passed<commit_after>#include "clang/Basic/Version.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/Support/CommandLine.h"
#include "DotGenerator.h"
#include "HsmAstMatcher.h"
#include "HsmTypes.h"
using namespace clang;
using namespace clang::ast_matchers;
using namespace clang::tooling;
using namespace llvm;
const char *ToolName = "hsm-analyze";
const char *ToolVersiona = "1.0.0.0";
static const char *ToolDescription = "A tool that analyzes C++ code that makes "
"use of the HSM library "
"(https://github.com/amaiorano/hsm)\n";
static cl::OptionCategory HsmAnalyzeCategory("hsm-analyze options");
static cl::opt<bool> PrintMap("map", cl::desc("Print state-transition map"),
cl::cat(HsmAnalyzeCategory));
static cl::opt<bool>
PrintDotFile("dot", cl::desc("Print state-transition dot file contents"),
cl::cat(HsmAnalyzeCategory));
static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);
static void PrintVersion() {
outs() << ToolName << " " << ToolVersiona << '\n';
}
int main(int argc, const char **argv) {
cl::AddExtraVersionPrinter(PrintVersion);
CommonOptionsParser OptionsParser(argc, argv, HsmAnalyzeCategory,
ToolDescription);
ClangTool Tool(OptionsParser.getCompilations(),
OptionsParser.getSourcePathList());
if (!(PrintMap || PrintDotFile)) {
llvm::errs() << "Nothing to do. Please specify "
"an action to perform.\n\n";
cl::PrintHelpMessage();
return -1;
}
StateTransitionMap Map;
MatchFinder Finder;
HsmAstMatcher::addMatchers(Finder, Map);
auto Result = Tool.run(newFrontendActionFactory(&Finder).get());
if (Result != 0) {
return Result;
}
if (PrintMap) {
for (auto &kvp : Map) {
auto SourceStateName = kvp.first;
auto TransType = std::get<0>(kvp.second);
auto TargetStateName = std::get<1>(kvp.second);
llvm::outs() << SourceStateName << " "
<< TransitionTypeVisualString[static_cast<int>(TransType)]
<< " " << TargetStateName << "\n";
llvm::outs().flush();
}
}
if (PrintDotFile) {
auto DotFileContents = DotGenerator::generateDotFileContents(Map);
llvm::outs() << DotFileContents;
llvm::outs().flush();
}
}
<|endoftext|> |
<commit_before>#include "InputModel.hpp"
#include <glm/glm.hpp>
InputModel::InputModel() : m_firstMousePoll(true) {}
// TODO: Handle multiple keys in a binding
// TODO: Handle multiple functions in a binding
void InputModel::bindKey(int key, std::function<void()> callback) {
assert(m_keyBindings.count(key) == 0);
m_keyBindings.emplace(key, callback);
}
void InputModel::bindMouse(
std::function<void(glm::dvec2 lastPos, glm::dvec2 newPos)> callback) {
m_mouseBinding = callback;
}
void InputModel::update(GLFWwindow& window) {
for(auto pair : m_keyBindings)
if(glfwGetKey(&window, pair.first) == GLFW_PRESS) pair.second();
// Process mouse position
glfwGetCursorPos(&window, &m_newMousePos.x, &m_newMousePos.y);
if(m_firstMousePoll) {
m_oldMousePos = m_newMousePos;
m_firstMousePoll = false;
}
if(m_mouseBinding) m_mouseBinding(m_oldMousePos, m_newMousePos);
m_oldMousePos = m_newMousePos;
}
<commit_msg>Limit mouse procesing to input models with mouse callbacks<commit_after>#include "InputModel.hpp"
#include <glm/glm.hpp>
InputModel::InputModel() : m_firstMousePoll(true) {}
// TODO: Handle multiple keys in a binding
// TODO: Handle multiple functions in a binding
void InputModel::bindKey(int key, std::function<void()> callback) {
assert(m_keyBindings.count(key) == 0);
m_keyBindings.emplace(key, callback);
}
void InputModel::bindMouse(
std::function<void(glm::dvec2 lastPos, glm::dvec2 newPos)> callback) {
m_mouseBinding = callback;
}
void InputModel::update(GLFWwindow& window) {
for(auto pair : m_keyBindings)
if(glfwGetKey(&window, pair.first) == GLFW_PRESS) pair.second();
// Process mouse position
if(m_mouseBinding) {
glfwGetCursorPos(&window, &m_newMousePos.x, &m_newMousePos.y);
if(m_firstMousePoll) {
m_oldMousePos = m_newMousePos;
m_firstMousePoll = false;
}
m_mouseBinding(m_oldMousePos, m_newMousePos);
m_oldMousePos = m_newMousePos;
}
}
<|endoftext|> |
<commit_before>#include "../text_lib/std_lib_facilities.h"
int main()
{
double input;
double smallest = 0;
double largest = 0;
while (cin >> input) {
if (smallest == 0 && largest == 0) {
smallest = input;
largest = input;
}
if (input < smallest) {
smallest = input;
cout << "smallest so far" << '\n';
} else if (input > largest) {
largest = input;
cout << "largest so far" << '\n';
}
}
}
<commit_msg>Completed chapter 4 drill<commit_after>#include "../text_lib/std_lib_facilities.h"
bool check_unit(string unit) {
bool good_unit = false;
vector<string> acceptable_units = { "cm", "m", "in", "ft" };
for (string u : acceptable_units)
if (u == unit)
good_unit = true;
return good_unit;
}
double get_meters(double amount, string unit) {
constexpr double cm_to_m = 0.01;
constexpr double in_to_m = 0.0254;
constexpr double ft_to_m = 0.3048;
double in_meters = 0;
if (unit == "cm")
in_meters = amount * cm_to_m;
else if (unit == "in")
in_meters = amount * in_to_m;
else if (unit == "ft")
in_meters = amount * ft_to_m;
else if (unit == "m")
in_meters = amount;
return in_meters;
}
int main()
{
double amount;
double meters;
double sum_in_meters = 0;
double values_entered = 0;
double smallest = 0;
double largest = 0;
vector<double> measurements;
string unit;
while (cin >> amount >> unit) {
if (!check_unit(unit))
cout << "I can't calculate that measurement.\n";
else {
meters = get_meters(amount, unit);
if (smallest == 0 && largest == 0) {
smallest = meters;
largest = meters;
}
if (meters < smallest) {
smallest = meters;
cout << "smallest so far" << '\n';
} else if (meters > largest) {
largest = meters;
cout << "largest so far" << '\n';
}
measurements.push_back(meters);
sum_in_meters += meters;
values_entered += 1;
}
}
cout << "Results:\n";
sort(measurements);
for (double m : measurements)
cout << m << "m\n";
cout << "The smallest measurement was: " << smallest << "m\n"
<< "The largest measurement was: " << largest << "m\n"
<< "There were " << values_entered << " values entered\n"
<< "The sum of the values entered is " << sum_in_meters << "m\n";
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.