text stringlengths 54 60.6k |
|---|
<commit_before>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkModulusImageFilter.h"
#include "itkDanielssonDistanceMapImageFilter.h"
#include "itkRescaleIntensityImageFilter.h"
#include "itkSimpleFilterWatcher.h"
int itkModulusImageFilterTest(int argc, char * argv[])
{
if( argc < 3 )
{
std::cerr << "Missing Arguments" << std::endl;
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0] << " inputImage outputImage " << std::endl;
return EXIT_FAILURE;
}
const int dim = 2;
typedef unsigned char PType;
typedef itk::Image< PType, dim > IType;
typedef itk::ImageFileReader< IType > ReaderType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( argv[1] );
// get the distance map inside the spots
// spot are already black so there is no need to invert the image
typedef itk::DanielssonDistanceMapImageFilter< IType, IType > DistanceFilter;
DistanceFilter::Pointer distance = DistanceFilter::New();
distance->SetInput( reader->GetOutput() );
typedef itk::ModulusImageFilter< IType, IType > FilterType;
FilterType::Pointer filter = FilterType::New();
filter->SetInput( distance->GetOutput() );
filter->SetDividend( 8 );
filter->InPlaceOn();
filter->SetFunctor( filter->GetFunctor() );
itk::SimpleFilterWatcher watcher(filter);
typedef itk::RescaleIntensityImageFilter< IType, IType > ThresholdType;
ThresholdType::Pointer rescale = ThresholdType::New();
rescale->SetInput( filter->GetOutput() );
rescale->SetOutputMaximum( itk::NumericTraits< PType >::max() );
rescale->SetOutputMinimum( itk::NumericTraits< PType >::NonpositiveMin() );
typedef itk::ImageFileWriter< IType > WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetInput( rescale->GetOutput() );
writer->SetFileName( argv[2] );
writer->Update();
try
{
writer->Update();
}
catch( itk::ExceptionObject & excp )
{
std::cerr << "Exception caught ! " << std::endl;
std::cerr << excp << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>ENH: Improve itkModulusImageFilter coverage.<commit_after>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkModulusImageFilter.h"
#include "itkDanielssonDistanceMapImageFilter.h"
#include "itkRescaleIntensityImageFilter.h"
#include "itkSimpleFilterWatcher.h"
#include "itkTestingMacros.h"
int itkModulusImageFilterTest(int argc, char * argv[])
{
if( argc < 3 )
{
std::cerr << "Missing Arguments" << std::endl;
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0] << " inputImage outputImage " << std::endl;
return EXIT_FAILURE;
}
const unsigned int Dimension = 2;
typedef unsigned char PixelType;
typedef itk::Image< PixelType, Dimension > ImageType;
typedef itk::ImageFileReader< ImageType > ReaderType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( argv[1] );
// get the distance map inside the spots
// spot are already black so there is no need to invert the image
typedef itk::DanielssonDistanceMapImageFilter< ImageType, ImageType > DistanceFilter;
DistanceFilter::Pointer distance = DistanceFilter::New();
distance->SetInput( reader->GetOutput() );
typedef itk::ModulusImageFilter< ImageType, ImageType > FilterType;
FilterType::Pointer filter = FilterType::New();
EXERCISE_BASIC_OBJECT_METHODS( filter, ModulusImageFilter,
BinaryFunctorImageFilter );
filter->SetInput( distance->GetOutput() );
FilterType::InputPixelType dividend = 8;
filter->SetDividend( dividend );
TEST_SET_GET_VALUE( dividend, filter->GetDividend() )
filter->InPlaceOn();
filter->SetFunctor( filter->GetFunctor() );
itk::SimpleFilterWatcher watcher(filter);
typedef itk::RescaleIntensityImageFilter< ImageType, ImageType > ThresholdType;
ThresholdType::Pointer rescale = ThresholdType::New();
rescale->SetInput( filter->GetOutput() );
rescale->SetOutputMaximum( itk::NumericTraits< PixelType >::max() );
rescale->SetOutputMinimum( itk::NumericTraits< PixelType >::NonpositiveMin() );
typedef itk::ImageFileWriter< ImageType > WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetInput( rescale->GetOutput() );
writer->SetFileName( argv[2] );
TRY_EXPECT_NO_EXCEPTION( writer->Update() );
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>//===- PowerPCRegisterInfo.cpp - PowerPC Register Information ---*- C++ -*-===//
//
// 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 contains the PowerPC implementation of the MRegisterInfo class.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "reginfo"
#include "PowerPC.h"
#include "PowerPCRegisterInfo.h"
#include "PowerPCInstrBuilder.h"
#include "llvm/Constants.h"
#include "llvm/Type.h"
#include "llvm/CodeGen/ValueTypes.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/Target/TargetFrameInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "Support/CommandLine.h"
#include "Support/Debug.h"
#include "Support/STLExtras.h"
#include <iostream>
using namespace llvm;
PowerPCRegisterInfo::PowerPCRegisterInfo()
: PowerPCGenRegisterInfo(PPC32::ADJCALLSTACKDOWN,
PPC32::ADJCALLSTACKUP) {}
static unsigned getIdx(const TargetRegisterClass *RC) {
if (RC == PowerPC::GPRCRegisterClass) {
switch (RC->getSize()) {
default: assert(0 && "Invalid data size!");
case 1: return 0;
case 2: return 1;
case 4: return 2;
}
} else if (RC == PowerPC::FPRCRegisterClass) {
switch (RC->getSize()) {
default: assert(0 && "Invalid data size!");
case 4: return 3;
case 8: return 4;
}
}
std::cerr << "Invalid register class to getIdx()!\n";
abort();
}
int
PowerPCRegisterInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MI,
unsigned SrcReg, int FrameIdx,
const TargetRegisterClass *RC) const {
static const unsigned Opcode[] = {
PPC32::STB, PPC32::STH, PPC32::STW, PPC32::STFS, PPC32::STFD
};
unsigned OC = Opcode[getIdx(RC)];
MBB.insert(MI, addFrameReference(BuildMI(OC, 3).addReg(SrcReg),FrameIdx));
return 1;
}
int PowerPCRegisterInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MI,
unsigned DestReg, int FrameIdx,
const TargetRegisterClass *RC) const{
static const unsigned Opcode[] = {
PPC32::LBZ, PPC32::LHZ, PPC32::LWZ, PPC32::LFS, PPC32::LFD
};
unsigned OC = Opcode[getIdx(RC)];
MBB.insert(MI, addFrameReference(BuildMI(OC, 2, DestReg), FrameIdx));
return 1;
}
int PowerPCRegisterInfo::copyRegToReg(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MI,
unsigned DestReg, unsigned SrcReg,
const TargetRegisterClass *RC) const {
MachineInstr *I;
if (RC == PowerPC::GPRCRegisterClass) {
I = BuildMI(PPC32::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
} else if (RC == PowerPC::FPRCRegisterClass) {
I = BuildMI(PPC32::FMR, 1, DestReg).addReg(SrcReg);
} else {
std::cerr << "Attempt to copy register that is not GPR or FPR";
abort();
}
MBB.insert(MI, I);
return 1;
}
//===----------------------------------------------------------------------===//
// Stack Frame Processing methods
//===----------------------------------------------------------------------===//
// hasFP - Return true if the specified function should have a dedicated frame
// pointer register. This is true if the function has variable sized allocas or
// if frame pointer elimination is disabled.
//
static bool hasFP(MachineFunction &MF) {
return NoFramePointerElim || MF.getFrameInfo()->hasVarSizedObjects();
}
void PowerPCRegisterInfo::
eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
MachineBasicBlock::iterator I) const {
if (hasFP(MF)) {
// If we have a frame pointer, convert as follows:
// adjcallstackdown instruction => 'sub r1, r1, <amt>' and
// adjcallstackup instruction => 'add r1, r1, <amt>'
MachineInstr *Old = I;
int Amount = Old->getOperand(0).getImmedValue();
if (Amount != 0) {
// We need to keep the stack aligned properly. To do this, we round the
// amount of space needed for the outgoing arguments up to the next
// alignment boundary.
unsigned Align = MF.getTarget().getFrameInfo()->getStackAlignment();
Amount = (Amount+Align-1)/Align*Align;
MachineInstr *New;
if (Old->getOpcode() == PPC32::ADJCALLSTACKDOWN) {
New = BuildMI(PPC32::ADDI, 2, PPC32::R1).addReg(PPC32::R1)
.addSImm(-Amount);
} else {
assert(Old->getOpcode() == PPC32::ADJCALLSTACKUP);
New = BuildMI(PPC32::ADDI, 2, PPC32::R1).addReg(PPC32::R1)
.addSImm(Amount);
}
// Replace the pseudo instruction with a new instruction...
MBB.insert(I, New);
}
}
MBB.erase(I);
}
void
PowerPCRegisterInfo::eliminateFrameIndex(MachineFunction &MF,
MachineBasicBlock::iterator II) const {
unsigned i = 0;
MachineInstr &MI = *II;
while (!MI.getOperand(i).isFrameIndex()) {
++i;
assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
}
int FrameIndex = MI.getOperand(i).getFrameIndex();
// Replace the FrameIndex with base register with GPR1.
MI.SetMachineOperandReg(i, PPC32::R1);
// Take into account whether it's an add or mem instruction
unsigned OffIdx = (i == 2) ? 1 : 2;
// Now add the frame object offset to the offset from r1.
int Offset = MF.getFrameInfo()->getObjectOffset(FrameIndex) +
MI.getOperand(OffIdx).getImmedValue()+4;
if (!hasFP(MF))
Offset += MF.getFrameInfo()->getStackSize();
MI.SetMachineOperandConst(OffIdx, MachineOperand::MO_SignExtendedImmed, Offset);
DEBUG(std::cerr << "offset = " << Offset << std::endl);
}
void
PowerPCRegisterInfo::processFunctionBeforeFrameFinalized(MachineFunction &MF)
const {
// Do Nothing
}
void PowerPCRegisterInfo::emitPrologue(MachineFunction &MF) const {
MachineBasicBlock &MBB = MF.front(); // Prolog goes in entry BB
MachineBasicBlock::iterator MBBI = MBB.begin();
MachineFrameInfo *MFI = MF.getFrameInfo();
MachineInstr *MI;
// Get the number of bytes to allocate from the FrameInfo
unsigned NumBytes = MFI->getStackSize();
// FIXME: the assembly printer inserts "calls" aka branch-and-link to get the
// PC address. We may not know about those calls at this time, so be
// conservative.
if (MFI->hasCalls() || true) {
// When we have no frame pointer, we reserve argument space for call sites
// in the function immediately on entry to the current function. This
// eliminates the need for add/sub brackets around call sites.
//
NumBytes += MFI->getMaxCallFrameSize() +
24 /* Predefined PowerPC link area */ +
32 /* Predefined PowerPC params area */ +
0 /* local variables - managed by llvm*/ +
0 * 4 /* volatile GPRs used - managed by llvm */ +
0 * 8 /* volatile FPRs used - managed by llvm */;
// Round the size to a multiple of the alignment (don't forget the 4 byte
// offset though).
unsigned Align = MF.getTarget().getFrameInfo()->getStackAlignment();
NumBytes = ((NumBytes+4)+Align-1)/Align*Align - 4;
// Store the incoming LR so it is preserved across calls
MI = BuildMI(PPC32::MFLR, 0, PPC32::R0);
MBB.insert(MBBI, MI);
MI = BuildMI(PPC32::STW, 3).addReg(PPC32::R0).addImm(8).addReg(PPC32::R1);
MBB.insert(MBBI, MI);
}
// Update frame info to pretend that this is part of the stack...
MFI->setStackSize(NumBytes);
// adjust stack pointer: r1 -= numbytes
if (NumBytes) {
MI = BuildMI(PPC32::STWU, 2, PPC32::R1).addImm(-NumBytes).addReg(PPC32::R1);
MBB.insert(MBBI, MI);
}
}
void PowerPCRegisterInfo::emitEpilogue(MachineFunction &MF,
MachineBasicBlock &MBB) const {
const MachineFrameInfo *MFI = MF.getFrameInfo();
MachineBasicBlock::iterator MBBI = prior(MBB.end());
MachineInstr *MI;
assert(MBBI->getOpcode() == PPC32::BLR &&
"Can only insert epilog into returning blocks");
// Get the number of bytes allocated from the FrameInfo...
unsigned NumBytes = MFI->getStackSize();
// If we have calls, restore the LR value before we branch to it
// FIXME: the assembly printer inserts "calls" aka branch-and-link to get the
// PC address. We may not know about those calls at this time, so be
// conservative.
if (MFI->hasCalls() || true) {
// Restore LR
MI = BuildMI(PPC32::LWZ, 2, PPC32::R0).addSImm(NumBytes+8).addReg(PPC32::R1);
MBB.insert(MBBI, MI);
MI = BuildMI(PPC32::MTLR, 1).addReg(PPC32::R0);
MBB.insert(MBBI, MI);
}
// Adjust stack pointer back
MI = BuildMI(PPC32::ADDI, 2, PPC32::R1).addReg(PPC32::R1).addImm(NumBytes);
MBB.insert(MBBI, MI);
}
#include "PowerPCGenRegisterInfo.inc"
const TargetRegisterClass*
PowerPCRegisterInfo::getRegClassForType(const Type* Ty) const {
switch (Ty->getTypeID()) {
case Type::LongTyID:
case Type::ULongTyID: assert(0 && "Long values can't fit in registers!");
default: assert(0 && "Invalid type to getClass!");
case Type::BoolTyID:
case Type::SByteTyID:
case Type::UByteTyID:
case Type::ShortTyID:
case Type::UShortTyID:
case Type::IntTyID:
case Type::UIntTyID:
case Type::PointerTyID: return &GPRCInstance;
case Type::FloatTyID:
case Type::DoubleTyID: return &FPRCInstance;
}
}
<commit_msg>Use addSImm() instead of addImm() for stack offsets, which may be negative.<commit_after>//===- PowerPCRegisterInfo.cpp - PowerPC Register Information ---*- C++ -*-===//
//
// 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 contains the PowerPC implementation of the MRegisterInfo class.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "reginfo"
#include "PowerPC.h"
#include "PowerPCRegisterInfo.h"
#include "PowerPCInstrBuilder.h"
#include "llvm/Constants.h"
#include "llvm/Type.h"
#include "llvm/CodeGen/ValueTypes.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/Target/TargetFrameInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "Support/CommandLine.h"
#include "Support/Debug.h"
#include "Support/STLExtras.h"
#include <iostream>
using namespace llvm;
PowerPCRegisterInfo::PowerPCRegisterInfo()
: PowerPCGenRegisterInfo(PPC32::ADJCALLSTACKDOWN,
PPC32::ADJCALLSTACKUP) {}
static unsigned getIdx(const TargetRegisterClass *RC) {
if (RC == PowerPC::GPRCRegisterClass) {
switch (RC->getSize()) {
default: assert(0 && "Invalid data size!");
case 1: return 0;
case 2: return 1;
case 4: return 2;
}
} else if (RC == PowerPC::FPRCRegisterClass) {
switch (RC->getSize()) {
default: assert(0 && "Invalid data size!");
case 4: return 3;
case 8: return 4;
}
}
std::cerr << "Invalid register class to getIdx()!\n";
abort();
}
int
PowerPCRegisterInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MI,
unsigned SrcReg, int FrameIdx,
const TargetRegisterClass *RC) const {
static const unsigned Opcode[] = {
PPC32::STB, PPC32::STH, PPC32::STW, PPC32::STFS, PPC32::STFD
};
unsigned OC = Opcode[getIdx(RC)];
MBB.insert(MI, addFrameReference(BuildMI(OC, 3).addReg(SrcReg),FrameIdx));
return 1;
}
int PowerPCRegisterInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MI,
unsigned DestReg, int FrameIdx,
const TargetRegisterClass *RC) const{
static const unsigned Opcode[] = {
PPC32::LBZ, PPC32::LHZ, PPC32::LWZ, PPC32::LFS, PPC32::LFD
};
unsigned OC = Opcode[getIdx(RC)];
MBB.insert(MI, addFrameReference(BuildMI(OC, 2, DestReg), FrameIdx));
return 1;
}
int PowerPCRegisterInfo::copyRegToReg(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MI,
unsigned DestReg, unsigned SrcReg,
const TargetRegisterClass *RC) const {
MachineInstr *I;
if (RC == PowerPC::GPRCRegisterClass) {
I = BuildMI(PPC32::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
} else if (RC == PowerPC::FPRCRegisterClass) {
I = BuildMI(PPC32::FMR, 1, DestReg).addReg(SrcReg);
} else {
std::cerr << "Attempt to copy register that is not GPR or FPR";
abort();
}
MBB.insert(MI, I);
return 1;
}
//===----------------------------------------------------------------------===//
// Stack Frame Processing methods
//===----------------------------------------------------------------------===//
// hasFP - Return true if the specified function should have a dedicated frame
// pointer register. This is true if the function has variable sized allocas or
// if frame pointer elimination is disabled.
//
static bool hasFP(MachineFunction &MF) {
return NoFramePointerElim || MF.getFrameInfo()->hasVarSizedObjects();
}
void PowerPCRegisterInfo::
eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
MachineBasicBlock::iterator I) const {
if (hasFP(MF)) {
// If we have a frame pointer, convert as follows:
// adjcallstackdown instruction => 'sub r1, r1, <amt>' and
// adjcallstackup instruction => 'add r1, r1, <amt>'
MachineInstr *Old = I;
int Amount = Old->getOperand(0).getImmedValue();
if (Amount != 0) {
// We need to keep the stack aligned properly. To do this, we round the
// amount of space needed for the outgoing arguments up to the next
// alignment boundary.
unsigned Align = MF.getTarget().getFrameInfo()->getStackAlignment();
Amount = (Amount+Align-1)/Align*Align;
MachineInstr *New;
if (Old->getOpcode() == PPC32::ADJCALLSTACKDOWN) {
New = BuildMI(PPC32::ADDI, 2, PPC32::R1).addReg(PPC32::R1)
.addSImm(-Amount);
} else {
assert(Old->getOpcode() == PPC32::ADJCALLSTACKUP);
New = BuildMI(PPC32::ADDI, 2, PPC32::R1).addReg(PPC32::R1)
.addSImm(Amount);
}
// Replace the pseudo instruction with a new instruction...
MBB.insert(I, New);
}
}
MBB.erase(I);
}
void
PowerPCRegisterInfo::eliminateFrameIndex(MachineFunction &MF,
MachineBasicBlock::iterator II) const {
unsigned i = 0;
MachineInstr &MI = *II;
while (!MI.getOperand(i).isFrameIndex()) {
++i;
assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
}
int FrameIndex = MI.getOperand(i).getFrameIndex();
// Replace the FrameIndex with base register with GPR1.
MI.SetMachineOperandReg(i, PPC32::R1);
// Take into account whether it's an add or mem instruction
unsigned OffIdx = (i == 2) ? 1 : 2;
// Now add the frame object offset to the offset from r1.
int Offset = MF.getFrameInfo()->getObjectOffset(FrameIndex) +
MI.getOperand(OffIdx).getImmedValue()+4;
if (!hasFP(MF))
Offset += MF.getFrameInfo()->getStackSize();
MI.SetMachineOperandConst(OffIdx, MachineOperand::MO_SignExtendedImmed, Offset);
DEBUG(std::cerr << "offset = " << Offset << std::endl);
}
void
PowerPCRegisterInfo::processFunctionBeforeFrameFinalized(MachineFunction &MF)
const {
// Do Nothing
}
void PowerPCRegisterInfo::emitPrologue(MachineFunction &MF) const {
MachineBasicBlock &MBB = MF.front(); // Prolog goes in entry BB
MachineBasicBlock::iterator MBBI = MBB.begin();
MachineFrameInfo *MFI = MF.getFrameInfo();
MachineInstr *MI;
// Get the number of bytes to allocate from the FrameInfo
unsigned NumBytes = MFI->getStackSize();
// FIXME: the assembly printer inserts "calls" aka branch-and-link to get the
// PC address. We may not know about those calls at this time, so be
// conservative.
if (MFI->hasCalls() || true) {
// When we have no frame pointer, we reserve argument space for call sites
// in the function immediately on entry to the current function. This
// eliminates the need for add/sub brackets around call sites.
//
NumBytes += MFI->getMaxCallFrameSize() +
24 /* Predefined PowerPC link area */ +
32 /* Predefined PowerPC params area */ +
0 /* local variables - managed by llvm*/ +
0 * 4 /* volatile GPRs used - managed by llvm */ +
0 * 8 /* volatile FPRs used - managed by llvm */;
// Round the size to a multiple of the alignment (don't forget the 4 byte
// offset though).
unsigned Align = MF.getTarget().getFrameInfo()->getStackAlignment();
NumBytes = ((NumBytes+4)+Align-1)/Align*Align - 4;
// Store the incoming LR so it is preserved across calls
MI = BuildMI(PPC32::MFLR, 0, PPC32::R0);
MBB.insert(MBBI, MI);
MI = BuildMI(PPC32::STW, 3).addReg(PPC32::R0).addSImm(8).addReg(PPC32::R1);
MBB.insert(MBBI, MI);
}
// Update frame info to pretend that this is part of the stack...
MFI->setStackSize(NumBytes);
// adjust stack pointer: r1 -= numbytes
if (NumBytes) {
MI = BuildMI(PPC32::STWU, 2, PPC32::R1).addSImm(-NumBytes).addReg(PPC32::R1);
MBB.insert(MBBI, MI);
}
}
void PowerPCRegisterInfo::emitEpilogue(MachineFunction &MF,
MachineBasicBlock &MBB) const {
const MachineFrameInfo *MFI = MF.getFrameInfo();
MachineBasicBlock::iterator MBBI = prior(MBB.end());
MachineInstr *MI;
assert(MBBI->getOpcode() == PPC32::BLR &&
"Can only insert epilog into returning blocks");
// Get the number of bytes allocated from the FrameInfo...
unsigned NumBytes = MFI->getStackSize();
// If we have calls, restore the LR value before we branch to it
// FIXME: the assembly printer inserts "calls" aka branch-and-link to get the
// PC address. We may not know about those calls at this time, so be
// conservative.
if (MFI->hasCalls() || true) {
// Restore LR
MI = BuildMI(PPC32::LWZ, 2, PPC32::R0).addSImm(NumBytes+8).addReg(PPC32::R1);
MBB.insert(MBBI, MI);
MI = BuildMI(PPC32::MTLR, 1).addReg(PPC32::R0);
MBB.insert(MBBI, MI);
}
// Adjust stack pointer back
MI = BuildMI(PPC32::ADDI, 2, PPC32::R1).addReg(PPC32::R1).addSImm(NumBytes);
MBB.insert(MBBI, MI);
}
#include "PowerPCGenRegisterInfo.inc"
const TargetRegisterClass*
PowerPCRegisterInfo::getRegClassForType(const Type* Ty) const {
switch (Ty->getTypeID()) {
case Type::LongTyID:
case Type::ULongTyID: assert(0 && "Long values can't fit in registers!");
default: assert(0 && "Invalid type to getClass!");
case Type::BoolTyID:
case Type::SByteTyID:
case Type::UByteTyID:
case Type::ShortTyID:
case Type::UShortTyID:
case Type::IntTyID:
case Type::UIntTyID:
case Type::PointerTyID: return &GPRCInstance;
case Type::FloatTyID:
case Type::DoubleTyID: return &FPRCInstance;
}
}
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "itkRandomImageSource.h"
#include "itkThresholdImageFilter.h"
#include "itkTextOutput.h"
#include "itksys/ios/sstream"
int itkThresholdImageFilterTest(int, char* [] )
{
// Comment the following if you want to use the itk text output window
itk::OutputWindow::SetInstance(itk::TextOutput::New());
// Uncomment the following if you want to see each message independently
// itk::OutputWindow::GetInstance()->PromptUserOn();
typedef itk::Image<float,2> FloatImage2DType;
itk::RandomImageSource<FloatImage2DType>::Pointer random;
random = itk::RandomImageSource<FloatImage2DType>::New();
random->SetMin(0.0);
random->SetMax(1000.0);
random->ReleaseDataFlagOn();
FloatImage2DType::SpacingValueType spacing[2] = {0.7, 2.1};
random->SetSpacing( spacing );
FloatImage2DType::PointValueType origin[2] = {15, 400};
random->SetOrigin( origin );
itksys_ios::ostringstream *os;
// Test #1, filter goes out of scope
itk::OutputWindow::GetInstance()->DisplayText( "Test #1: Filter goes out of scope -----------------" );
{
itk::ThresholdImageFilter<FloatImage2DType>::Pointer threshold;
threshold = itk::ThresholdImageFilter<FloatImage2DType>::New();
threshold->SetInput(random->GetOutput());
// Exercise threshold setting functions
threshold->ThresholdAbove( 10.0 );
threshold->ThresholdBelow( 900.0 );
threshold->ThresholdOutside( 5.0, 40.0 );
// Call update multiple times to make sure that the RandomImageSource
// is releasing and regenerating its data
threshold->Update();
threshold->Modified();
threshold->Update();
std::cout << "Input spacing: " << random->GetOutput()->GetSpacing()[0]
<< ", "
<< random->GetOutput()->GetSpacing()[1] << std::endl;
std::cout << "Output spacing: " << threshold->GetOutput()->GetSpacing()[0]
<< ", "
<< threshold->GetOutput()->GetSpacing()[1] << std::endl;
os = new itksys_ios::ostringstream();
*os << "Filter: " << threshold.GetPointer();
itk::OutputWindow::GetInstance()->DisplayText( os->str().c_str() );
delete os;
os = new itksys_ios::ostringstream();
*os << "Output #0: " << threshold->GetOutput(0);
itk::OutputWindow::GetInstance()->DisplayText( os->str().c_str() );
delete os;
itk::OutputWindow::GetInstance()->DisplayText( "Ending Test #1: filter goes out of scope" );
itk::OutputWindow::GetInstance()->DisplayText( "End of Test #1 -----------------------------------" );
}
// Test #2, user keeps an extra handle to an output
itk::OutputWindow::GetInstance()->DisplayText( "Test #2: User keeps an extra hold on an output -----------------" );
{
FloatImage2DType::Pointer keep;
itk::ThresholdImageFilter<FloatImage2DType>::Pointer threshold;
threshold = itk::ThresholdImageFilter<FloatImage2DType>::New();
threshold->SetInput(random->GetOutput());
threshold->Update();
os = new itksys_ios::ostringstream();
*os << "Filter: " << threshold.GetPointer();
itk::OutputWindow::GetInstance()->DisplayText( os->str().c_str() );
delete os;
os = new itksys_ios::ostringstream();
*os << "Output #0: " << threshold->GetOutput(0);
itk::OutputWindow::GetInstance()->DisplayText( os->str().c_str() );
delete os;
keep = threshold->GetOutput(0);
itk::OutputWindow::GetInstance()->DisplayText( "End of Test #2: last handle on output 0 should go out of scope");
}
itk::OutputWindow::GetInstance()->DisplayText( "End of Test #2 -----------------------------------");
// Test #3, user disconnects a data object from the pipeline
itk::OutputWindow::GetInstance()->DisplayText( "Test #3: user disconnects a data object from the pipeline -----------------" );
{
FloatImage2DType::Pointer keep;
itk::ThresholdImageFilter<FloatImage2DType>::Pointer threshold;
threshold = itk::ThresholdImageFilter<FloatImage2DType>::New();
threshold->SetInput(random->GetOutput());
threshold->Update();
os = new itksys_ios::ostringstream;
*os << "Filter: " << threshold.GetPointer();
itk::OutputWindow::GetInstance()->DisplayText( os->str().c_str() );
delete os;
os = new itksys_ios::ostringstream();
*os << "Output #0: " << threshold->GetOutput(0);
itk::OutputWindow::GetInstance()->DisplayText( os->str().c_str() );
delete os;
keep = threshold->GetOutput(0);
keep->DisconnectPipeline();
itk::OutputWindow::GetInstance()->DisplayText( "End of Test #3: last handle on output 0 should go out of scope");
}
itk::OutputWindow::GetInstance()->DisplayText( "End of Test #3 -----------------------------------");
return EXIT_SUCCESS;
}
<commit_msg>ENH: Add unit test to itkThresholdImageFilterTest<commit_after>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "itkRandomImageSource.h"
#include "itkThresholdImageFilter.h"
#include "itkTextOutput.h"
#include "itksys/ios/sstream"
int itkThresholdImageFilterTest(int, char* [] )
{
// Comment the following if you want to use the itk text output window
itk::OutputWindow::SetInstance(itk::TextOutput::New());
// Uncomment the following if you want to see each message independently
// itk::OutputWindow::GetInstance()->PromptUserOn();
typedef itk::Image<float,2> FloatImage2DType;
itk::RandomImageSource<FloatImage2DType>::Pointer random;
random = itk::RandomImageSource<FloatImage2DType>::New();
random->SetMin(0.0);
random->SetMax(1000.0);
random->ReleaseDataFlagOn();
FloatImage2DType::SpacingValueType spacing[2] = {0.7, 2.1};
random->SetSpacing( spacing );
FloatImage2DType::PointValueType origin[2] = {15, 400};
random->SetOrigin( origin );
itksys_ios::ostringstream *os;
// Test #1, filter goes out of scope
itk::OutputWindow::GetInstance()->DisplayText( "Test #1: Filter goes out of scope -----------------" );
{
itk::ThresholdImageFilter<FloatImage2DType>::Pointer threshold;
threshold = itk::ThresholdImageFilter<FloatImage2DType>::New();
threshold->SetInput(random->GetOutput());
// Exercise threshold setting functions
threshold->ThresholdAbove( 10.0 );
threshold->ThresholdBelow( 900.0 );
threshold->ThresholdOutside( 5.0, 40.0 );
// Call update multiple times to make sure that the RandomImageSource
// is releasing and regenerating its data
threshold->Update();
threshold->Modified();
threshold->Update();
std::cout << "Input spacing: " << random->GetOutput()->GetSpacing()[0]
<< ", "
<< random->GetOutput()->GetSpacing()[1] << std::endl;
std::cout << "Output spacing: " << threshold->GetOutput()->GetSpacing()[0]
<< ", "
<< threshold->GetOutput()->GetSpacing()[1] << std::endl;
os = new itksys_ios::ostringstream();
*os << "Filter: " << threshold.GetPointer();
itk::OutputWindow::GetInstance()->DisplayText( os->str().c_str() );
delete os;
os = new itksys_ios::ostringstream();
*os << "Output #0: " << threshold->GetOutput(0);
itk::OutputWindow::GetInstance()->DisplayText( os->str().c_str() );
delete os;
itk::OutputWindow::GetInstance()->DisplayText( "Ending Test #1: filter goes out of scope" );
itk::OutputWindow::GetInstance()->DisplayText( "End of Test #1 -----------------------------------" );
}
// Test #2, user keeps an extra handle to an output
itk::OutputWindow::GetInstance()->DisplayText( "Test #2: User keeps an extra hold on an output -----------------" );
{
FloatImage2DType::Pointer keep;
itk::ThresholdImageFilter<FloatImage2DType>::Pointer threshold;
threshold = itk::ThresholdImageFilter<FloatImage2DType>::New();
threshold->SetInput(random->GetOutput());
threshold->Update();
os = new itksys_ios::ostringstream();
*os << "Filter: " << threshold.GetPointer();
itk::OutputWindow::GetInstance()->DisplayText( os->str().c_str() );
delete os;
os = new itksys_ios::ostringstream();
*os << "Output #0: " << threshold->GetOutput(0);
itk::OutputWindow::GetInstance()->DisplayText( os->str().c_str() );
delete os;
keep = threshold->GetOutput(0);
itk::OutputWindow::GetInstance()->DisplayText( "End of Test #2: last handle on output 0 should go out of scope");
}
itk::OutputWindow::GetInstance()->DisplayText( "End of Test #2 -----------------------------------");
// Test #3, user disconnects a data object from the pipeline
itk::OutputWindow::GetInstance()->DisplayText( "Test #3: user disconnects a data object from the pipeline -----------------" );
{
FloatImage2DType::Pointer keep;
itk::ThresholdImageFilter<FloatImage2DType>::Pointer threshold;
threshold = itk::ThresholdImageFilter<FloatImage2DType>::New();
threshold->SetInput(random->GetOutput());
threshold->Update();
os = new itksys_ios::ostringstream;
*os << "Filter: " << threshold.GetPointer();
itk::OutputWindow::GetInstance()->DisplayText( os->str().c_str() );
delete os;
os = new itksys_ios::ostringstream();
*os << "Output #0: " << threshold->GetOutput(0);
itk::OutputWindow::GetInstance()->DisplayText( os->str().c_str() );
delete os;
keep = threshold->GetOutput(0);
keep->DisconnectPipeline();
itk::OutputWindow::GetInstance()->DisplayText( "End of Test #3: last handle on output 0 should go out of scope");
}
itk::OutputWindow::GetInstance()->DisplayText( "End of Test #3 -----------------------------------");
// Test #4, threshold values
itk::OutputWindow::GetInstance()->DisplayText( "Test #4: threshold values -----------------" );
{
typedef itk::Image<int,1> IntImage1DType;
IntImage1DType::Pointer input = IntImage1DType::New();
IntImage1DType::SpacingValueType inputSpacing[1] = {0.7};
input->SetSpacing( inputSpacing );
IntImage1DType::PointValueType inputOrigin[1] = {15};
input->SetOrigin(inputOrigin);
IntImage1DType::SizeValueType inputSize = 1;
IntImage1DType::RegionType inputRegion;
inputRegion.SetSize(0, inputSize);
input->SetRegions(inputRegion);
input->Allocate();
int inputValue = 0;
input->FillBuffer(inputValue);
itk::ThresholdImageFilter<IntImage1DType>::Pointer threshold;
threshold = itk::ThresholdImageFilter<IntImage1DType>::New();
threshold->SetInput(input);
int outsideValue = 99;
threshold->SetOutsideValue(outsideValue);
IntImage1DType::IndexType index;
index.Fill(0);
int outputValue;
// Above -1
threshold->ThresholdAbove(-1);
threshold->Update();
outputValue = threshold->GetOutput()->GetPixel(index);
if ( outputValue != outsideValue)
{
os = new itksys_ios::ostringstream;
*os << "Filter above failed:"
<< " lower: " << threshold->GetLower()
<< " upper: " << threshold->GetUpper()
<< " output: " << outputValue;
itk::OutputWindow::GetInstance()->DisplayText( os->str().c_str() );
return EXIT_FAILURE;
}
// Above 1
threshold->ThresholdAbove(1);
threshold->Update();
outputValue = threshold->GetOutput()->GetPixel(index);
if ( outputValue != inputValue)
{
os = new itksys_ios::ostringstream;
*os << "Filter above failed:"
<< " lower: " << threshold->GetLower()
<< " upper: " << threshold->GetUpper()
<< " output: " << outputValue;
itk::OutputWindow::GetInstance()->DisplayText( os->str().c_str() );
return EXIT_FAILURE;
}
// Below -1
threshold->ThresholdBelow(-1);
threshold->Update();
outputValue = threshold->GetOutput()->GetPixel(index);
if ( outputValue != inputValue)
{
os = new itksys_ios::ostringstream;
*os << "Filter below failed:"
<< " lower: " << threshold->GetLower()
<< " upper: " << threshold->GetUpper()
<< " output: " << outputValue;
itk::OutputWindow::GetInstance()->DisplayText( os->str().c_str() );
return EXIT_FAILURE;
}
// Below 1
threshold->ThresholdBelow(1);
threshold->Update();
outputValue = threshold->GetOutput()->GetPixel(index);
if ( outputValue != outsideValue)
{
os = new itksys_ios::ostringstream;
*os << "Filter below failed:"
<< " lower: " << threshold->GetLower()
<< " upper: " << threshold->GetUpper()
<< " output: " << outputValue;
itk::OutputWindow::GetInstance()->DisplayText( os->str().c_str() );
return EXIT_FAILURE;
}
// Outside [-1 1]
threshold->ThresholdOutside(-1, 1);
threshold->Update();
outputValue = threshold->GetOutput()->GetPixel(index);
if ( outputValue != inputValue)
{
os = new itksys_ios::ostringstream;
*os << "Filter outside failed:"
<< " lower: " << threshold->GetLower()
<< " upper: " << threshold->GetUpper()
<< " output: " << outputValue;
itk::OutputWindow::GetInstance()->DisplayText( os->str().c_str() );
return EXIT_FAILURE;
}
// Outside [0, 2]
threshold->ThresholdOutside(0, 2);
threshold->Update();
outputValue = threshold->GetOutput()->GetPixel(index);
if ( outputValue != inputValue)
{
os = new itksys_ios::ostringstream;
*os << "Filter outside failed:"
<< " lower: " << threshold->GetLower()
<< " upper: " << threshold->GetUpper()
<< " output: " << outputValue;
itk::OutputWindow::GetInstance()->DisplayText( os->str().c_str() );
return EXIT_FAILURE;
}
// Outside [1, 3]
threshold->ThresholdOutside(1, 3);
threshold->Update();
outputValue = threshold->GetOutput()->GetPixel(index);
if ( outputValue != outsideValue)
{
os = new itksys_ios::ostringstream;
*os << "Filter above failed:"
<< " lower: " << threshold->GetLower()
<< " upper: " << threshold->GetUpper()
<< " output: " << outputValue;
itk::OutputWindow::GetInstance()->DisplayText( os->str().c_str() );
return EXIT_FAILURE;
}
}
itk::OutputWindow::GetInstance()->DisplayText( "End of Test #4 -----------------------------------");
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include <boost/python.hpp>
#include "IECore/bindings/ParameterBinding.h"
#include "IECore/bindings/Wrapper.h"
#include "IECore/TypedObjectParameter.h"
#include "IECore/CompoundObject.h"
#include "IECore/bindings/WrapperToPython.h"
#include "IECore/bindings/IntrusivePtrPatch.h"
#include "IECore/bindings/RunTimeTypedBinding.h"
#include "IECore/Renderable.h"
#include "IECore/StateRenderable.h"
#include "IECore/AttributeState.h"
#include "IECore/Shader.h"
#include "IECore/Transform.h"
#include "IECore/MatrixMotionTransform.h"
#include "IECore/MatrixTransform.h"
#include "IECore/VisibleRenderable.h"
#include "IECore/Group.h"
#include "IECore/MotionPrimitive.h"
#include "IECore/Primitive.h"
#include "IECore/ImagePrimitive.h"
#include "IECore/MeshPrimitive.h"
#include "IECore/PointsPrimitive.h"
using namespace std;
using namespace boost;
using namespace boost::python;
namespace IECore
{
template<typename T>
class TypedObjectParameterWrap : public TypedObjectParameter<T>, public Wrapper< TypedObjectParameter<T> >
{
protected:
static typename TypedObjectParameter<T>::ObjectPresetsMap makePresets( const dict &d )
{
typename TypedObjectParameter<T>::ObjectPresetsMap p;
boost::python::list keys = d.keys();
boost::python::list values = d.values();
for( int i = 0; i<keys.attr( "__len__" )(); i++ )
{
extract<typename T::Ptr> e( values[i] );
p.insert( typename TypedObjectParameter<T>::ObjectPresetsMap::value_type( extract<string>( keys[i] )(), e() ) );
}
return p;
}
public :
TypedObjectParameterWrap( PyObject *self, const std::string &n, const std::string &d, typename T::Ptr dv, const dict &p = dict(), bool po = false, CompoundObjectPtr ud = 0 )
: TypedObjectParameter<T>( n, d, dv, makePresets( p ), po, ud ), Wrapper< TypedObjectParameter<T> >( self, this ) {};
TypedObjectParameterWrap( PyObject *self, const std::string &n, const std::string &d, typename T::Ptr dv, CompoundObjectPtr ud )
: TypedObjectParameter<T>( n, d, dv, typename TypedObjectParameter<T>::ObjectPresetsMap(), false, ud ), Wrapper< TypedObjectParameter<T> >( self, this ) {};
IE_COREPYTHON_PARAMETERWRAPPERFNS( TypedObjectParameter<T> );
};
template<typename T>
static void bindTypedObjectParameter( const char *name )
{
typedef class_< TypedObjectParameter<T>, intrusive_ptr< TypedObjectParameterWrap< T > >, boost::noncopyable, bases<ObjectParameter> > TypedObjectParameterPyClass;
TypedObjectParameterPyClass( name, no_init )
.def( init< const std::string &, const std::string &, typename T::Ptr, optional<const dict &, bool, CompoundObjectPtr > >( args( "name", "description", "defaultValue", "presets", "presetsOnly", "userData") ) )
.def( init< const std::string &, const std::string &, typename T::Ptr, CompoundObjectPtr >( args( "name", "description", "defaultValue", "userData") ) )
.IE_COREPYTHON_DEFPARAMETERWRAPPERFNS( TypedObjectParameter<T> )
.IE_COREPYTHON_DEFRUNTIMETYPEDSTATICMETHODS( TypedObjectParameter<T> )
;
WrapperToPython< intrusive_ptr<TypedObjectParameter<T> > >();
INTRUSIVE_PTR_PATCH( TypedObjectParameter<T>, typename TypedObjectParameterPyClass );
implicitly_convertible<intrusive_ptr<TypedObjectParameter<T> >, ObjectParameterPtr>();
}
void bindTypedObjectParameter()
{
bindTypedObjectParameter<MeshPrimitive>( "MeshPrimitiveParameter" );
bindTypedObjectParameter<Renderable>( "RenderableParameter" );
bindTypedObjectParameter<StateRenderable>( "StateRenderableParameter" );
bindTypedObjectParameter<AttributeState>( "AttributeStateParameter" );
bindTypedObjectParameter<Shader>( "ShaderParameter" );
bindTypedObjectParameter<Transform>( "TransformParameter" );
bindTypedObjectParameter<MatrixMotionTransform>( "MatrixMotionTransformParameter" );
bindTypedObjectParameter<MatrixTransform>( "MatrixTransformParameter" );
bindTypedObjectParameter<VisibleRenderable>( "VisibleRenderableParameter" );
bindTypedObjectParameter<Group>( "GroupParameter" );
bindTypedObjectParameter<MotionPrimitive>( "MotionPrimitiveParameter" );
bindTypedObjectParameter<Primitive>( "PrimitiveParameter" );
bindTypedObjectParameter<ImagePrimitive>( "ImagePrimitiveParameter" );
bindTypedObjectParameter<MeshPrimitive>( "MeshPrimitiveParameter" );
bindTypedObjectParameter<PointsPrimitive>( "PointsPrimitiveParameter" );
}
} // namespace IECore
<commit_msg>Removed duplicate bind of MeshPrimitive<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include <boost/python.hpp>
#include "IECore/bindings/ParameterBinding.h"
#include "IECore/bindings/Wrapper.h"
#include "IECore/TypedObjectParameter.h"
#include "IECore/CompoundObject.h"
#include "IECore/bindings/WrapperToPython.h"
#include "IECore/bindings/IntrusivePtrPatch.h"
#include "IECore/bindings/RunTimeTypedBinding.h"
#include "IECore/Renderable.h"
#include "IECore/StateRenderable.h"
#include "IECore/AttributeState.h"
#include "IECore/Shader.h"
#include "IECore/Transform.h"
#include "IECore/MatrixMotionTransform.h"
#include "IECore/MatrixTransform.h"
#include "IECore/VisibleRenderable.h"
#include "IECore/Group.h"
#include "IECore/MotionPrimitive.h"
#include "IECore/Primitive.h"
#include "IECore/ImagePrimitive.h"
#include "IECore/MeshPrimitive.h"
#include "IECore/PointsPrimitive.h"
using namespace std;
using namespace boost;
using namespace boost::python;
namespace IECore
{
template<typename T>
class TypedObjectParameterWrap : public TypedObjectParameter<T>, public Wrapper< TypedObjectParameter<T> >
{
protected:
static typename TypedObjectParameter<T>::ObjectPresetsMap makePresets( const dict &d )
{
typename TypedObjectParameter<T>::ObjectPresetsMap p;
boost::python::list keys = d.keys();
boost::python::list values = d.values();
for( int i = 0; i<keys.attr( "__len__" )(); i++ )
{
extract<typename T::Ptr> e( values[i] );
p.insert( typename TypedObjectParameter<T>::ObjectPresetsMap::value_type( extract<string>( keys[i] )(), e() ) );
}
return p;
}
public :
TypedObjectParameterWrap( PyObject *self, const std::string &n, const std::string &d, typename T::Ptr dv, const dict &p = dict(), bool po = false, CompoundObjectPtr ud = 0 )
: TypedObjectParameter<T>( n, d, dv, makePresets( p ), po, ud ), Wrapper< TypedObjectParameter<T> >( self, this ) {};
TypedObjectParameterWrap( PyObject *self, const std::string &n, const std::string &d, typename T::Ptr dv, CompoundObjectPtr ud )
: TypedObjectParameter<T>( n, d, dv, typename TypedObjectParameter<T>::ObjectPresetsMap(), false, ud ), Wrapper< TypedObjectParameter<T> >( self, this ) {};
IE_COREPYTHON_PARAMETERWRAPPERFNS( TypedObjectParameter<T> );
};
template<typename T>
static void bindTypedObjectParameter( const char *name )
{
typedef class_< TypedObjectParameter<T>, intrusive_ptr< TypedObjectParameterWrap< T > >, boost::noncopyable, bases<ObjectParameter> > TypedObjectParameterPyClass;
TypedObjectParameterPyClass( name, no_init )
.def( init< const std::string &, const std::string &, typename T::Ptr, optional<const dict &, bool, CompoundObjectPtr > >( args( "name", "description", "defaultValue", "presets", "presetsOnly", "userData") ) )
.def( init< const std::string &, const std::string &, typename T::Ptr, CompoundObjectPtr >( args( "name", "description", "defaultValue", "userData") ) )
.IE_COREPYTHON_DEFPARAMETERWRAPPERFNS( TypedObjectParameter<T> )
.IE_COREPYTHON_DEFRUNTIMETYPEDSTATICMETHODS( TypedObjectParameter<T> )
;
WrapperToPython< intrusive_ptr<TypedObjectParameter<T> > >();
INTRUSIVE_PTR_PATCH( TypedObjectParameter<T>, typename TypedObjectParameterPyClass );
implicitly_convertible<intrusive_ptr<TypedObjectParameter<T> >, ObjectParameterPtr>();
}
void bindTypedObjectParameter()
{
bindTypedObjectParameter<Renderable>( "RenderableParameter" );
bindTypedObjectParameter<StateRenderable>( "StateRenderableParameter" );
bindTypedObjectParameter<AttributeState>( "AttributeStateParameter" );
bindTypedObjectParameter<Shader>( "ShaderParameter" );
bindTypedObjectParameter<Transform>( "TransformParameter" );
bindTypedObjectParameter<MatrixMotionTransform>( "MatrixMotionTransformParameter" );
bindTypedObjectParameter<MatrixTransform>( "MatrixTransformParameter" );
bindTypedObjectParameter<VisibleRenderable>( "VisibleRenderableParameter" );
bindTypedObjectParameter<Group>( "GroupParameter" );
bindTypedObjectParameter<MotionPrimitive>( "MotionPrimitiveParameter" );
bindTypedObjectParameter<Primitive>( "PrimitiveParameter" );
bindTypedObjectParameter<ImagePrimitive>( "ImagePrimitiveParameter" );
bindTypedObjectParameter<MeshPrimitive>( "MeshPrimitiveParameter" );
bindTypedObjectParameter<PointsPrimitive>( "PointsPrimitiveParameter" );
}
} // namespace IECore
<|endoftext|> |
<commit_before>#pragma once
#include "funcs/trid.h"
#include "funcs/qing.h"
#include "funcs/beale.h"
#include "funcs/booth.h"
#include "funcs/cauchy.h"
#include "funcs/sphere.h"
#include "funcs/matyas.h"
#include "funcs/powell.h"
#include "funcs/sargan.h"
#include "funcs/colville.h"
#include "funcs/zakharov.h"
#include "funcs/mccormick.h"
#include "funcs/himmelblau.h"
#include "funcs/rosenbrock.h"
#include "funcs/exponential.h"
#include "funcs/3hump_camel.h"
#include "funcs/dixon_price.h"
#include "funcs/bohachevsky.h"
#include "funcs/chung_reynolds.h"
#include "funcs/goldstein_price.h"
#include "funcs/styblinski_tang.h"
#include "funcs/rotated_ellipsoid.h"
#include "funcs/schumer_steiglitz.h"
namespace nano
{
enum class test_type
{
easy, ///< easy test functions even for GD (e.g. convex) - mostly useful for unit testing
all
};
///
/// \brief run the given operator for each test function having the number of dimensions within the given range
///
template
<
test_type type,
typename toperator
>
void foreach_test_function(
const tensor_size_t min_dims,
const tensor_size_t max_dims,
const toperator& op)
{
if (min_dims == 1)
{
switch (type)
{
case test_type::all:
op(function_beale_t());
op(function_booth_t());
op(function_matyas_t());
op(function_colville_t());
op(function_mccormick_t());
op(function_3hump_camel_t());
op(function_goldstein_price_t());
op(function_himmelblau_t());
op(function_bohachevsky_t(function_bohachevsky_t::btype::one));
op(function_bohachevsky_t(function_bohachevsky_t::btype::two));
op(function_bohachevsky_t(function_bohachevsky_t::btype::three));
break;
default:
break;
}
}
for (tensor_size_t dims = min_dims; dims <= max_dims; dims *= 2)
{
switch (type)
{
case test_type::all:
op(function_trid_t(dims));
op(function_qing_t(dims));
op(function_cauchy_t(dims));
op(function_sargan_t(dims));
op(function_powell_t(dims));
op(function_zakharov_t(dims));
op(function_rosenbrock_t(dims));
op(function_exponential_t(dims));
op(function_dixon_price_t(dims));
op(function_chung_reynolds_t(dims));
op(function_styblinski_tang_t(dims));
// NB: fallthrough!
case test_type::easy:
default:
op(function_sphere_t(dims));
op(function_schumer_steiglitz_t(dims));
op(function_rotated_ellipsoid_t(dims));
break;
}
}
}
}
<commit_msg>fix test<commit_after>#pragma once
#include "funcs/trid.h"
#include "funcs/qing.h"
#include "funcs/beale.h"
#include "funcs/booth.h"
#include "funcs/cauchy.h"
#include "funcs/sphere.h"
#include "funcs/matyas.h"
#include "funcs/powell.h"
#include "funcs/sargan.h"
#include "funcs/colville.h"
#include "funcs/zakharov.h"
#include "funcs/mccormick.h"
#include "funcs/himmelblau.h"
#include "funcs/rosenbrock.h"
#include "funcs/exponential.h"
#include "funcs/3hump_camel.h"
#include "funcs/dixon_price.h"
#include "funcs/bohachevsky.h"
#include "funcs/chung_reynolds.h"
#include "funcs/goldstein_price.h"
#include "funcs/styblinski_tang.h"
#include "funcs/rotated_ellipsoid.h"
#include "funcs/schumer_steiglitz.h"
namespace nano
{
enum class test_type
{
easy, ///< easy test functions even for GD (e.g. convex) - mostly useful for unit testing
all
};
///
/// \brief run the given operator for each test function having the number of dimensions within the given range
///
template
<
test_type type,
typename toperator
>
void foreach_test_function(
const tensor_size_t min_dims,
const tensor_size_t max_dims,
const toperator& op)
{
if (min_dims == 1)
{
switch (type)
{
case test_type::all:
op(function_beale_t());
op(function_booth_t());
op(function_matyas_t());
op(function_colville_t());
op(function_mccormick_t());
op(function_3hump_camel_t());
op(function_goldstein_price_t());
op(function_himmelblau_t());
op(function_bohachevsky_t(function_bohachevsky_t::btype::one));
op(function_bohachevsky_t(function_bohachevsky_t::btype::two));
op(function_bohachevsky_t(function_bohachevsky_t::btype::three));
break;
default:
break;
}
}
for (tensor_size_t dims = min_dims; dims <= max_dims; dims *= 2)
{
switch (type)
{
case test_type::all:
op(function_trid_t(dims));
op(function_qing_t(dims));
op(function_cauchy_t(dims));
op(function_sargan_t(dims));
op(function_powell_t(dims));
op(function_zakharov_t(dims));
if (dims > 1) op(function_rosenbrock_t(dims));
op(function_exponential_t(dims));
op(function_dixon_price_t(dims));
op(function_chung_reynolds_t(dims));
op(function_styblinski_tang_t(dims));
// NB: fallthrough!
case test_type::easy:
default:
op(function_sphere_t(dims));
op(function_schumer_steiglitz_t(dims));
op(function_rotated_ellipsoid_t(dims));
break;
}
}
}
}
<|endoftext|> |
<commit_before>//
// Aspia Project
// Copyright (C) 2020 Dmitry Chapyshev <dmitry@aspia.ru>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//
#include "host/video_frame_pump.h"
#include "base/logging.h"
#include "codec/video_encoder.h"
#include "common/message_serialization.h"
#include "desktop/desktop_frame_aligned.h"
#include "desktop/shared_desktop_frame.h"
#include "net/network_channel_proxy.h"
namespace host {
VideoFramePump::VideoFramePump(std::shared_ptr<net::ChannelProxy> channel_proxy,
std::unique_ptr<codec::VideoEncoder> encoder)
: channel_proxy_(std::move(channel_proxy)),
work_event_(base::WaitableEvent::ResetPolicy::AUTOMATIC,
base::WaitableEvent::InitialState::NOT_SIGNALED),
encoder_(std::move(encoder))
{
DCHECK(channel_proxy_);
DCHECK(encoder_);
}
VideoFramePump::~VideoFramePump()
{
work_event_.signal();
stop();
}
void VideoFramePump::encodeFrame(const desktop::Frame& frame)
{
std::scoped_lock lock(input_frame_lock_);
if (!input_frame_ || frame.size() != input_frame_->size() || frame.format() != input_frame_->format())
{
std::unique_ptr<desktop::Frame> input_frame =
desktop::FrameAligned::create(frame.size(), frame.format(), 32);
input_frame_ = desktop::SharedFrame::wrap(std::move(input_frame));
desktop::Rect frame_rect = desktop::Rect::makeSize(input_frame_->size());
// The frame is completely replaced. Add the entire frame to the changed area.
input_frame_->updatedRegion()->addRect(frame_rect);
input_frame_->copyPixelsFrom(frame, desktop::Point(0, 0), frame_rect);
}
else
{
for (desktop::Region::Iterator it(frame.constUpdatedRegion()); !it.isAtEnd(); it.advance())
{
const desktop::Rect& rect = it.rect();
input_frame_->copyPixelsFrom(frame, rect.topLeft(), rect);
input_frame_->updatedRegion()->addRect(rect);
}
}
work_event_.signal();
}
void VideoFramePump::run()
{
waitForFirstFrame();
while (!isStopping())
{
reloadWorkFrame();
if (!work_frame_->constUpdatedRegion().isEmpty())
{
outgoing_message_.Clear();
// Encode the frame into a video packet.
encoder_->encode(work_frame_.get(), outgoing_message_.mutable_video_packet());
channel_proxy_->send(common::serializeMessage(outgoing_message_));
// Clear the region.
work_frame_->updatedRegion()->clear();
}
work_event_.wait();
}
}
void VideoFramePump::waitForFirstFrame()
{
while (!isStopping())
{
{
std::scoped_lock lock(input_frame_lock_);
if (input_frame_)
return;
}
work_event_.wait();
}
}
void VideoFramePump::reloadWorkFrame()
{
std::scoped_lock lock(input_frame_lock_);
if (input_frame_->constUpdatedRegion().isEmpty())
return;
if (!input_frame_->shareFrameWith(*work_frame_))
work_frame_ = input_frame_->share();
work_frame_->copyFrameInfoFrom(*input_frame_);
}
} // namespace host
<commit_msg>- Check for nullptr.<commit_after>//
// Aspia Project
// Copyright (C) 2020 Dmitry Chapyshev <dmitry@aspia.ru>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//
#include "host/video_frame_pump.h"
#include "base/logging.h"
#include "codec/video_encoder.h"
#include "common/message_serialization.h"
#include "desktop/desktop_frame_aligned.h"
#include "desktop/shared_desktop_frame.h"
#include "net/network_channel_proxy.h"
namespace host {
VideoFramePump::VideoFramePump(std::shared_ptr<net::ChannelProxy> channel_proxy,
std::unique_ptr<codec::VideoEncoder> encoder)
: channel_proxy_(std::move(channel_proxy)),
work_event_(base::WaitableEvent::ResetPolicy::AUTOMATIC,
base::WaitableEvent::InitialState::NOT_SIGNALED),
encoder_(std::move(encoder))
{
DCHECK(channel_proxy_);
DCHECK(encoder_);
}
VideoFramePump::~VideoFramePump()
{
work_event_.signal();
stop();
}
void VideoFramePump::encodeFrame(const desktop::Frame& frame)
{
std::scoped_lock lock(input_frame_lock_);
if (!input_frame_ || frame.size() != input_frame_->size() || frame.format() != input_frame_->format())
{
std::unique_ptr<desktop::Frame> input_frame =
desktop::FrameAligned::create(frame.size(), frame.format(), 32);
input_frame_ = desktop::SharedFrame::wrap(std::move(input_frame));
desktop::Rect frame_rect = desktop::Rect::makeSize(input_frame_->size());
// The frame is completely replaced. Add the entire frame to the changed area.
input_frame_->updatedRegion()->addRect(frame_rect);
input_frame_->copyPixelsFrom(frame, desktop::Point(0, 0), frame_rect);
}
else
{
for (desktop::Region::Iterator it(frame.constUpdatedRegion()); !it.isAtEnd(); it.advance())
{
const desktop::Rect& rect = it.rect();
input_frame_->copyPixelsFrom(frame, rect.topLeft(), rect);
input_frame_->updatedRegion()->addRect(rect);
}
}
work_event_.signal();
}
void VideoFramePump::run()
{
waitForFirstFrame();
while (!isStopping())
{
reloadWorkFrame();
if (!work_frame_->constUpdatedRegion().isEmpty())
{
outgoing_message_.Clear();
// Encode the frame into a video packet.
encoder_->encode(work_frame_.get(), outgoing_message_.mutable_video_packet());
channel_proxy_->send(common::serializeMessage(outgoing_message_));
// Clear the region.
work_frame_->updatedRegion()->clear();
}
work_event_.wait();
}
}
void VideoFramePump::waitForFirstFrame()
{
while (!isStopping())
{
{
std::scoped_lock lock(input_frame_lock_);
if (input_frame_)
return;
}
work_event_.wait();
}
}
void VideoFramePump::reloadWorkFrame()
{
std::scoped_lock lock(input_frame_lock_);
if (input_frame_->constUpdatedRegion().isEmpty())
return;
if (!work_frame_ || !input_frame_->shareFrameWith(*work_frame_))
work_frame_ = input_frame_->share();
work_frame_->copyFrameInfoFrom(*input_frame_);
}
} // namespace host
<|endoftext|> |
<commit_before><commit_msg>[mer] Allow creation of 'native' glyph nodes.<commit_after><|endoftext|> |
<commit_before>/*
* File: LocalExpansionCoeff.cpp
* Author: matteo
*
* Created on April 3, 2015, 6:05 PM
*/
#include "local_expansion_coeff.h"
#include "string.h"
#include <iostream>
using std::cout;
using std::endl;
LocalExpansionCoeff::LocalExpansionCoeff()
{
_p=0;
_coeff= NULL;
}
LocalExpansionCoeff::LocalExpansionCoeff(const unsigned int &p)
{
_p=p;
_coeff= new double[(p+1)*(p+1)*(p+1)*(p+2)/2];
}
LocalExpansionCoeff::LocalExpansionCoeff(const LocalExpansionCoeff &orig)
{
_p=orig._p;
_coeff = new double[(_p+1)*(_p+1)*(_p+1)*(_p+2)/2];
memcpy(_coeff, orig._coeff, this->getNumberOfElements());
}
LocalExpansionCoeff::~LocalExpansionCoeff()
{
delete [] _coeff;
}
inline unsigned int LocalExpansionCoeff::getNumberOfElements()
{
return (_p+1)*(_p+1)*(_p+1)*(_p+2)/2;
}
double LocalExpansionCoeff::get(const unsigned int &n, const unsigned int &m, const unsigned int &nn, const unsigned int &mm)
{
return _coeff[ (mm+nn) +
getNNOffset(nn) +
getMOffset(m) +
getNOffset(n)];
}
void LocalExpansionCoeff::set(const unsigned int &n, const unsigned int &m, const unsigned int &nn, const unsigned int &mm, const double &value)
{
_coeff[ (mm+nn) +
getNNOffset(nn) +
getMOffset(m) +
getNOffset(n)]=value;
}
unsigned int LocalExpansionCoeff::getNNOffset(const unsigned int &nn)
{
return (nn)*(nn);
}
unsigned int LocalExpansionCoeff::getMOffset(const unsigned int &m)
{
return (_p+1)*(_p+1)*m;
}
unsigned int LocalExpansionCoeff::getNOffset(const unsigned int &n)
{
return ((_p+1)*(_p+1)*(n+1)*(n))/2;
}
/*
* Debugging and test of indexes
*/
//unsigned int const LocalExpansionCoeff::loopDebugger(const unsigned int & p){
// unsigned int count=0;
// for(unsigned int n=0; n< p+1; ++n){
// for(unsigned int m=0; m < n+1; ++m){
// for(int nn=0; nn< p+1; ++nn){
// for(int mm=-nn; mm< nn+1; ++mm){
// ++count;
// }
// }
// }
// }
// return count;
//}
//
//void LocalExpansionCoeff::fillCoeffWithIndex(){
// unsigned int count=0;
// for(unsigned int n=0; n< _p+1; ++n){
// for(unsigned int m=0; m < n+1; ++m){
// for(int nn=0; nn< _p+1; ++nn){
// for(int mm=-nn; mm< nn+1; ++mm){
// ++count;
// _coeff[count-1]=count;
//
// }
// }
// }
// }
//}
//
//void LocalExpansionCoeff::printCoeff(){
// unsigned int count=0;
// for(unsigned int n=0; n< _p+1; ++n){
// for(unsigned int m=0; m < n+1; ++m){
// for(int nn=0; nn< _p+1; ++nn){
// for(int mm=-nn; mm< nn+1; ++mm){
// ++count;
// cout << "(" << n << " " << m << " " << nn << " " << mm << ")"<< endl;
// cout << "_coeff: " << _coeff[count-1]<< endl;
// cout << "idx:" << (mm+nn) +
// getNNOffset(nn) +
// getMOffset(m)+
// getNOffset(n) << endl;
// cout << "get: " << this->get(n,m,nn,mm) << endl;
// cout << endl;
//
// }
// }
// }
// }
//}
<commit_msg>indent<commit_after>/*
* File: LocalExpansionCoeff.cpp
* Author: matteo
*
* Created on April 3, 2015, 6:05 PM
*/
#include "local_expansion_coeff.h"
#include "string.h"
#include <iostream>
using std::cout;
using std::endl;
LocalExpansionCoeff::LocalExpansionCoeff()
{
_p=0;
_coeff= NULL;
}
LocalExpansionCoeff::LocalExpansionCoeff(const unsigned int &p)
{
_p=p;
_coeff= new double[(p+1)*(p+1)*(p+1)*(p+2)/2];
}
LocalExpansionCoeff::LocalExpansionCoeff(const LocalExpansionCoeff &orig)
{
_p=orig._p;
_coeff = new double[(_p+1)*(_p+1)*(_p+1)*(_p+2)/2];
memcpy(_coeff, orig._coeff, this->getNumberOfElements());
}
LocalExpansionCoeff::~LocalExpansionCoeff()
{
delete [] _coeff;
}
inline unsigned int LocalExpansionCoeff::getNumberOfElements()
{
return (_p+1)*(_p+1)*(_p+1)*(_p+2)/2;
}
double LocalExpansionCoeff::get(const unsigned int &n, const unsigned int &m, const unsigned int &nn, const unsigned int &mm)
{
return _coeff[ (mm+nn) +
getNNOffset(nn) +
getMOffset(m) +
getNOffset(n)];
}
void LocalExpansionCoeff::set(const unsigned int &n, const unsigned int &m, const unsigned int &nn, const unsigned int &mm, const double &value)
{
_coeff[ (mm+nn) +
getNNOffset(nn) +
getMOffset(m) +
getNOffset(n)]=value;
}
unsigned int LocalExpansionCoeff::getNNOffset(const unsigned int &nn)
{
return (nn)*(nn);
}
unsigned int LocalExpansionCoeff::getMOffset(const unsigned int &m)
{
return (_p+1)*(_p+1)*m;
}
unsigned int LocalExpansionCoeff::getNOffset(const unsigned int &n)
{
return ((_p+1)*(_p+1)*(n+1)*(n))/2;
}
/*
* Debugging and test of indexes
*/
//unsigned int const LocalExpansionCoeff::loopDebugger(const unsigned int & p){
// unsigned int count=0;
// for(unsigned int n=0; n< p+1; ++n){
// for(unsigned int m=0; m < n+1; ++m){
// for(int nn=0; nn< p+1; ++nn){
// for(int mm=-nn; mm< nn+1; ++mm){
// ++count;
// }
// }
// }
// }
// return count;
//}
//
//void LocalExpansionCoeff::fillCoeffWithIndex(){
// unsigned int count=0;
// for(unsigned int n=0; n< _p+1; ++n){
// for(unsigned int m=0; m < n+1; ++m){
// for(int nn=0; nn< _p+1; ++nn){
// for(int mm=-nn; mm< nn+1; ++mm){
// ++count;
// _coeff[count-1]=count;
//
// }
// }
// }
// }
//}
//
//void LocalExpansionCoeff::printCoeff(){
// unsigned int count=0;
// for(unsigned int n=0; n< _p+1; ++n){
// for(unsigned int m=0; m < n+1; ++m){
// for(int nn=0; nn< _p+1; ++nn){
// for(int mm=-nn; mm< nn+1; ++mm){
// ++count;
// cout << "(" << n << " " << m << " " << nn << " " << mm << ")"<< endl;
// cout << "_coeff: " << _coeff[count-1]<< endl;
// cout << "idx:" << (mm+nn) +
// getNNOffset(nn) +
// getMOffset(m)+
// getNOffset(n) << endl;
// cout << "get: " << this->get(n,m,nn,mm) << endl;
// cout << endl;
//
// }
// }
// }
// }
//}
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "Stage.h"
#include "SceneMgr.h"
#include "RenderMgr.h"
#include "Terrain.h"
#include "TimeMgr.h"
#include "ObjMgr.h"
#include "Flower.h"
#include "Player.h"
#include "StaticObject.h"
#include "Camera.h"
#include "Info.h"
#include "ResourcesMgr.h"
#include "Frustum.h"
CStage::CStage()
: m_bFirstLogin(false)
{
}
CStage::~CStage()
{
}
HRESULT CStage::Initialize(void)
{
if (FAILED(CreateObj()))
return E_FAIL;
return S_OK;
}
int CStage::Update(void)
{
if (m_bFirstLogin == false)
{
m_bFirstLogin = true;
}
CObjMgr::GetInstance()->Update();
return 0;
}
void CStage::Render(void)
{
float fTime = CTimeMgr::GetInstance()->GetTime();
CRenderMgr::GetInstance()->Render(fTime);
}
void CStage::Release(void)
{
//CResourcesMgr::GetInstance()->ResourceReset(RESOURCE_STATIC);
//CResourcesMgr::GetInstance()->ResourceReset(RESOURCE_STAGE);
}
CStage * CStage::Create(void)
{
CStage* pLogo = new CStage;
if (FAILED(pLogo->Initialize()))
{
::Safe_Delete(pLogo);
}
return pLogo;
}
HRESULT CStage::CreateObj(void)
{
CRenderMgr* pRenderer = CRenderMgr::GetInstance();
//ͷ
CObj* pObj = NULL;
///////////////߸///////////////
TCHAR szMeshKey[MAX_PATH] = L"";
TCHAR szTexKey[MAX_PATH] = L"";
int iHigh = 0;
pObj = CTerrain::Create();
if (pObj == NULL)
return E_FAIL;
CObjMgr::GetInstance()->AddObject(L"Terrain", pObj);
/*for (int i = 0; i < 20; ++i)
{
pObj = CFlower::Create();
if (pObj == NULL)
return E_FAIL;
float fX = float(rand() % VERTEXCOUNTX);
float fZ = float(rand() % VERTEXCOUNTZ);
pObj->SetPos(D3DXVECTOR3(fX, 0.f, fZ));
CObjMgr::GetInstance()->AddObject(L"Flower", pObj);
}*/
pObj = CPlayer::Create();
pObj->SetPos(D3DXVECTOR3(155.f, 0.f, 400.f));
CObjMgr::GetInstance()->AddObject(L"Player", pObj);
CCamera::GetInstance()->SetCameraTarget(pObj->GetInfo());
DataLoad();
return S_OK;
}
void CStage::DataLoad(void)
{
HANDLE hFile = CreateFile(L"..\\Resource\\Data\\Norumac2.dat", GENERIC_READ,
0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
DWORD dwByte;
int iObjSize = 0;
ReadFile(hFile, &iObjSize, sizeof(int), &dwByte, NULL);
for (int i = 0; i < iObjSize; ++i)
{
TCHAR* pObjectKey = new TCHAR[50];
ReadFile(hFile, pObjectKey, sizeof(TCHAR) * 50, &dwByte, NULL);
int iNum;
ReadFile(hFile, &iNum, sizeof(int), &dwByte, NULL);
if(0==iNum)
continue;
CObj* pGameObject = NULL;
for (int j = 0; j < iNum; ++j)
{
pGameObject = CStaticObject::Create(pObjectKey);
CObjMgr::GetInstance()->AddObject(pObjectKey, pGameObject);
CRenderMgr::GetInstance()->AddRenderGroup(TYPE_NONEALPHA, pGameObject);
const CComponent* pComponent = pGameObject->GetComponent(L"Transform");
ReadFile(hFile, ((CInfo*)pComponent)->m_fAngle, sizeof(float) * ANGLE_END, &dwByte, NULL);
ReadFile(hFile, ((CInfo*)pComponent)->m_vScale, sizeof(D3DXVECTOR3), &dwByte, NULL);
ReadFile(hFile, ((CInfo*)pComponent)->m_vPos, sizeof(D3DXVECTOR3), &dwByte, NULL);
ReadFile(hFile, ((CInfo*)pComponent)->m_vDir, sizeof(D3DXVECTOR3), &dwByte, NULL);
ReadFile(hFile, ((CInfo*)pComponent)->m_matWorld, sizeof(D3DXMATRIX), &dwByte, NULL);
}
}
}
<commit_msg>[김형준] 나무 두번째 클라에서 안뜨는 문제 수정<commit_after>#include "stdafx.h"
#include "Stage.h"
#include "SceneMgr.h"
#include "RenderMgr.h"
#include "Terrain.h"
#include "TimeMgr.h"
#include "ObjMgr.h"
#include "Flower.h"
#include "Player.h"
#include "StaticObject.h"
#include "Camera.h"
#include "Info.h"
#include "ResourcesMgr.h"
#include "Frustum.h"
CStage::CStage()
: m_bFirstLogin(false)
{
}
CStage::~CStage()
{
}
HRESULT CStage::Initialize(void)
{
if (FAILED(CreateObj()))
return E_FAIL;
return S_OK;
}
int CStage::Update(void)
{
if (m_bFirstLogin == false)
{
m_bFirstLogin = true;
}
CObjMgr::GetInstance()->Update();
return 0;
}
void CStage::Render(void)
{
float fTime = CTimeMgr::GetInstance()->GetTime();
CRenderMgr::GetInstance()->Render(fTime);
}
void CStage::Release(void)
{
//CResourcesMgr::GetInstance()->ResourceReset(RESOURCE_STATIC);
//CResourcesMgr::GetInstance()->ResourceReset(RESOURCE_STAGE);
}
CStage * CStage::Create(void)
{
CStage* pLogo = new CStage;
if (FAILED(pLogo->Initialize()))
{
::Safe_Delete(pLogo);
}
return pLogo;
}
HRESULT CStage::CreateObj(void)
{
CRenderMgr* pRenderer = CRenderMgr::GetInstance();
//ͷ
CObj* pObj = NULL;
///////////////߸///////////////
TCHAR szMeshKey[MAX_PATH] = L"";
TCHAR szTexKey[MAX_PATH] = L"";
int iHigh = 0;
pObj = CTerrain::Create();
if (pObj == NULL)
return E_FAIL;
CObjMgr::GetInstance()->AddObject(L"Terrain", pObj);
/*for (int i = 0; i < 20; ++i)
{
pObj = CFlower::Create();
if (pObj == NULL)
return E_FAIL;
float fX = float(rand() % VERTEXCOUNTX);
float fZ = float(rand() % VERTEXCOUNTZ);
pObj->SetPos(D3DXVECTOR3(fX, 0.f, fZ));
CObjMgr::GetInstance()->AddObject(L"Flower", pObj);
}*/
pObj = CPlayer::Create();
pObj->SetPos(D3DXVECTOR3(155.f, 0.f, 400.f));
CObjMgr::GetInstance()->AddObject(L"Player", pObj);
CCamera::GetInstance()->SetCameraTarget(pObj->GetInfo());
DataLoad();
return S_OK;
}
void CStage::DataLoad(void)
{
HANDLE hFile = CreateFile(L"..\\Resource\\Data\\Norumac2.dat", GENERIC_READ,
0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
DWORD dwByte;
int iObjSize = 0;
ReadFile(hFile, &iObjSize, sizeof(int), &dwByte, NULL);
for (int i = 0; i < iObjSize; ++i)
{
TCHAR* pObjectKey = new TCHAR[50];
ReadFile(hFile, pObjectKey, sizeof(TCHAR) * 50, &dwByte, NULL);
int iNum;
ReadFile(hFile, &iNum, sizeof(int), &dwByte, NULL);
if(0==iNum)
continue;
CObj* pGameObject = NULL;
for (int j = 0; j < iNum; ++j)
{
pGameObject = CStaticObject::Create(pObjectKey);
CObjMgr::GetInstance()->AddObject(pObjectKey, pGameObject);
CRenderMgr::GetInstance()->AddRenderGroup(TYPE_NONEALPHA, pGameObject);
const CComponent* pComponent = pGameObject->GetComponent(L"Transform");
ReadFile(hFile, ((CInfo*)pComponent)->m_fAngle, sizeof(float) * ANGLE_END, &dwByte, NULL);
ReadFile(hFile, ((CInfo*)pComponent)->m_vScale, sizeof(D3DXVECTOR3), &dwByte, NULL);
ReadFile(hFile, ((CInfo*)pComponent)->m_vPos, sizeof(D3DXVECTOR3), &dwByte, NULL);
ReadFile(hFile, ((CInfo*)pComponent)->m_vDir, sizeof(D3DXVECTOR3), &dwByte, NULL);
ReadFile(hFile, ((CInfo*)pComponent)->m_matWorld, sizeof(D3DXMATRIX), &dwByte, NULL);
}
}
CloseHandle(hFile);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: actiontriggerhelper.cxx,v $
*
* $Revision: 1.1 $
*
* last change: $Author: cd $ $Date: 2001-12-04 07:45:19 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef __FRAMEWORK_HELPER_ACTIONTRIGGERHELPER_HXX_
#include <helper/actiontriggerhelper.hxx>
#endif
#ifndef __FRAMEWORK_CLASSES_ACTIONTRIGGERSEPARATORPROPERTYSET_HXX_
#include <classes/actiontriggerseparatorpropertyset.hxx>
#endif
#ifndef __FRAMEWORK_CLASSES_ROOTACTIONTRIGGERCONTAINER_HXX_
#include <classes/rootactiontriggercontainer.hxx>
#endif
#ifndef __FRAMEWORK_CLASSES_IMAGEWRAPPER_HXX_
#include <classes/imagewrapper.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XBITMAP_HPP_
#include <com/sun/star/awt/XBitmap.hpp>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
const USHORT START_ITEMID = 20000;
using namespace rtl;
using namespace vos;
using namespace com::sun::star::awt;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::container;
namespace framework
{
// ----------------------------------------------------------------------------
// implementation helper ( menu => ActionTrigger )
// ----------------------------------------------------------------------------
sal_Bool IsSeparator( Reference< XPropertySet > xPropertySet )
{
Reference< XServiceInfo > xServiceInfo( xPropertySet, UNO_QUERY );
try
{
return xServiceInfo->supportsService( OUString( RTL_CONSTASCII_USTRINGPARAM( SERVICENAME_ACTIONTRIGGERSEPARATOR )) );
}
catch ( Exception& )
{
}
return sal_False;
}
void GetMenuItemAttributes( Reference< XPropertySet > xActionTriggerPropertySet,
OUString& aMenuLabel,
OUString& aCommandURL,
OUString& aHelpURL,
Reference< XBitmap >& xBitmap,
Reference< XIndexContainer >& xSubContainer )
{
Any a;
try
{
// mandatory properties
a = xActionTriggerPropertySet->getPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "Text" )) );
a >>= aMenuLabel;
a = xActionTriggerPropertySet->getPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "CommandURL" )) );
a >>= aCommandURL;
a = xActionTriggerPropertySet->getPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "Image" )) );
a >>= xBitmap;
a = xActionTriggerPropertySet->getPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "SubContainer" )) );
a >>= xSubContainer;
}
catch ( Exception& )
{
}
// optional properties
try
{
a = xActionTriggerPropertySet->getPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "HelpURL" )) );
a >>= aHelpURL;
}
catch ( Exception& )
{
}
}
void InsertSubMenuItems( Menu* pSubMenu, USHORT& nItemId, Reference< XIndexContainer > xActionTriggerContainer )
{
Reference< XIndexAccess > xIndexAccess( xActionTriggerContainer, UNO_QUERY );
if ( xIndexAccess.is() )
{
OUString aSlotURL( RTL_CONSTASCII_USTRINGPARAM( "slot:" ));
for ( sal_Int32 i = 0; i < xIndexAccess->getCount(); i++ )
{
try
{
Reference< XPropertySet > xPropSet;
Any a = xIndexAccess->getByIndex( i );
if (( a >>= xPropSet ) && ( xPropSet.is() ))
{
if ( IsSeparator( xPropSet ))
{
// Separator
OGuard aGuard( Application::GetSolarMutex() );
pSubMenu->InsertSeparator();
}
else
{
// Menu item
OUString aLabel;
OUString aCommandURL;
OUString aHelpURL;
Reference< XBitmap > xBitmap;
Reference< XIndexContainer > xSubContainer;
sal_Bool bSpecialItemId = sal_False;
USHORT nNewItemId = nItemId++;
GetMenuItemAttributes( xPropSet, aLabel, aCommandURL, aHelpURL, xBitmap, xSubContainer );
OGuard aGuard( Application::GetSolarMutex() );
{
// insert new menu item
sal_Int32 nIndex = aCommandURL.indexOf( aSlotURL );
if ( nIndex >= 0 )
{
// Special code for our menu implementation: some menu items don't have a
// command url but uses the item id as a unqiue identifier. These entries
// got a special url during conversion from menu=>actiontriggercontainer.
// Now we have to extract this special url and set the correct item id!!!
bSpecialItemId = sal_True;
nNewItemId = (USHORT)aCommandURL.copy( nIndex+aSlotURL.getLength() ).toInt32();
pSubMenu->InsertItem( nNewItemId, aLabel );
}
else
{
pSubMenu->InsertItem( nNewItemId, aLabel );
pSubMenu->SetItemCommand( nNewItemId, aCommandURL );
}
// handle bitmap
if ( xBitmap.is() )
{
sal_Bool bImageSet = sal_False;
Reference< XUnoTunnel > xUnoTunnel( xBitmap, UNO_QUERY );
if ( xUnoTunnel.is() )
{
// Try to get implementation pointer through XUnoTunnel
sal_Int64 nPointer = xUnoTunnel->getSomething( ImageWrapper::GetUnoTunnelId() );
if ( nPointer )
{
// This is our own optimized implementation of menu images!
ImageWrapper* pImageWrapper = (ImageWrapper *)nPointer;
Image aMenuImage = pImageWrapper->GetImage();
if ( !!aMenuImage )
pSubMenu->SetItemImage( nNewItemId, aMenuImage );
bImageSet = sal_True;
}
}
if ( !bImageSet )
{
// This is a unknown implementation of XBitmap interface. We have to
// use a more time consuming way to build an Image!
// TODO: use memory streams to build a bitmap and this can be used
// to create an image!!
Image aImage;
Bitmap aBitmap;
Sequence< sal_Int8 > aDIBSeq;
{
aDIBSeq = xBitmap->getDIB();
SvMemoryStream aMem( (void *)aDIBSeq.getConstArray(), aDIBSeq.getLength(), STREAM_READ );
aMem >> aBitmap;
}
aDIBSeq = xBitmap->getMaskDIB();
if ( aDIBSeq.getLength() > 0 )
{
Bitmap aMaskBitmap;
SvMemoryStream aMem( (void *)aDIBSeq.getConstArray(), aDIBSeq.getLength(), STREAM_READ );
aMem >> aMaskBitmap;
aImage = Image( aBitmap, aMaskBitmap );
}
else
aImage = Image( aBitmap );
}
}
if ( xSubContainer.is() )
{
PopupMenu* pNewSubMenu = new PopupMenu;
// Sub menu (recursive call CreateSubMenu )
InsertSubMenuItems( pNewSubMenu, nItemId, xSubContainer );
pSubMenu->SetPopupMenu( nNewItemId, pNewSubMenu );
}
}
}
}
}
catch ( IndexOutOfBoundsException )
{
return;
}
catch ( WrappedTargetException )
{
return;
}
catch ( RuntimeException )
{
return;
}
}
}
}
// ----------------------------------------------------------------------------
// implementation helper ( ActionTrigger => menu )
// ----------------------------------------------------------------------------
Reference< XPropertySet > CreateActionTrigger( USHORT nItemId, const Menu* pMenu, const Reference< XIndexContainer >& rActionTriggerContainer ) throw ( RuntimeException )
{
Reference< XPropertySet > xPropSet;
Reference< XMultiServiceFactory > xMultiServiceFactory( rActionTriggerContainer, UNO_QUERY );
if ( xMultiServiceFactory.is() )
{
xPropSet = Reference< XPropertySet >( xMultiServiceFactory->createInstance(
OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.ui.ActionTrigger" )) ),
UNO_QUERY );
Any a;
try
{
// Retrieve the menu attributes and set them in our PropertySet
OUString aLabel = pMenu->GetItemText( nItemId );
a <<= aLabel;
xPropSet->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "Text" )), a );
OUString aCommandURL = pMenu->GetItemCommand( nItemId );
if ( aCommandURL.getLength() == 0 )
{
aCommandURL = OUString( RTL_CONSTASCII_USTRINGPARAM( "slot:" ));
aCommandURL += OUString::valueOf( (sal_Int32)nItemId );
}
a <<= aCommandURL;
xPropSet->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "CommandURL" )), a );
Image aImage = pMenu->GetItemImage( nItemId );
if ( !!aImage )
{
// We use our own optimized XBitmap implementation
Reference< XBitmap > xBitmap( static_cast< cppu::OWeakObject* >( new ImageWrapper( aImage )), UNO_QUERY );
a <<= xBitmap;
xPropSet->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "Image" )), a );
}
}
catch ( Exception& )
{
}
}
return xPropSet;
}
Reference< XPropertySet > CreateActionTriggerSeparator( const Reference< XIndexContainer >& rActionTriggerContainer ) throw ( RuntimeException )
{
Reference< XMultiServiceFactory > xMultiServiceFactory( rActionTriggerContainer, UNO_QUERY );
if ( xMultiServiceFactory.is() )
{
return Reference< XPropertySet >( xMultiServiceFactory->createInstance(
OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.ui.ActionTriggerSeparator" )) ),
UNO_QUERY );
}
return Reference< XPropertySet >();
}
Reference< XIndexContainer > CreateActionTriggerContainer( const Reference< XIndexContainer >& rActionTriggerContainer ) throw ( RuntimeException )
{
Reference< XMultiServiceFactory > xMultiServiceFactory( rActionTriggerContainer, UNO_QUERY );
if ( xMultiServiceFactory.is() )
{
return Reference< XIndexContainer >( xMultiServiceFactory->createInstance(
OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.ui.ActionTriggerContainer" )) ),
UNO_QUERY );
}
return Reference< XIndexContainer >();
}
void FillActionTriggerContainerWithMenu( const Menu* pMenu, Reference< XIndexContainer >& rActionTriggerContainer )
{
OGuard aGuard( Application::GetSolarMutex() );
for ( USHORT nPos = 0; nPos < pMenu->GetItemCount(); nPos++ )
{
USHORT nItemId = pMenu->GetItemId( nPos );
MenuItemType nType = pMenu->GetItemType( nPos );
try
{
Any a;
Reference< XPropertySet > xPropSet;
if ( nType == MENUITEM_SEPARATOR )
{
xPropSet = CreateActionTriggerSeparator( rActionTriggerContainer );
a <<= xPropSet;
rActionTriggerContainer->insertByIndex( nPos, a );
}
else
{
xPropSet = CreateActionTrigger( nItemId, pMenu, rActionTriggerContainer );
a <<= xPropSet;
rActionTriggerContainer->insertByIndex( nPos, a );
PopupMenu* pPopupMenu = pMenu->GetPopupMenu( nItemId );
if ( pPopupMenu )
{
// recursive call to build next sub menu
Any a;
Reference< XIndexContainer > xSubContainer = CreateActionTriggerContainer( rActionTriggerContainer );
a <<= xSubContainer;
xPropSet->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "SubContainer" )), a );
FillActionTriggerContainerWithMenu( pPopupMenu, xSubContainer );
}
}
}
catch ( Exception& )
{
}
}
}
void ActionTriggerHelper::CreateMenuFromActionTriggerContainer(
Menu* pNewMenu,
const Reference< XIndexContainer >& rActionTriggerContainer )
{
USHORT nItemId = START_ITEMID;
if ( rActionTriggerContainer.is() )
InsertSubMenuItems( pNewMenu, nItemId, rActionTriggerContainer );
}
void ActionTriggerHelper::FillActionTriggerContainerFromMenu(
Reference< XIndexContainer >& xActionTriggerContainer,
const Menu* pMenu )
{
FillActionTriggerContainerWithMenu( pMenu, xActionTriggerContainer );
}
Reference< XIndexContainer > ActionTriggerHelper::CreateActionTriggerContainerFromMenu( const Menu* pMenu )
{
return new RootActionTriggerContainer( pMenu, ::comphelper::getProcessServiceFactory() );
}
}
<commit_msg>#96208#: don't use reserved slot ids<commit_after>/*************************************************************************
*
* $RCSfile: actiontriggerhelper.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: mba $ $Date: 2002-06-27 07:28:56 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef __FRAMEWORK_HELPER_ACTIONTRIGGERHELPER_HXX_
#include <helper/actiontriggerhelper.hxx>
#endif
#ifndef __FRAMEWORK_CLASSES_ACTIONTRIGGERSEPARATORPROPERTYSET_HXX_
#include <classes/actiontriggerseparatorpropertyset.hxx>
#endif
#ifndef __FRAMEWORK_CLASSES_ROOTACTIONTRIGGERCONTAINER_HXX_
#include <classes/rootactiontriggercontainer.hxx>
#endif
#ifndef __FRAMEWORK_CLASSES_IMAGEWRAPPER_HXX_
#include <classes/imagewrapper.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XBITMAP_HPP_
#include <com/sun/star/awt/XBitmap.hpp>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
const USHORT START_ITEMID = 1000;
using namespace rtl;
using namespace vos;
using namespace com::sun::star::awt;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::container;
namespace framework
{
// ----------------------------------------------------------------------------
// implementation helper ( menu => ActionTrigger )
// ----------------------------------------------------------------------------
sal_Bool IsSeparator( Reference< XPropertySet > xPropertySet )
{
Reference< XServiceInfo > xServiceInfo( xPropertySet, UNO_QUERY );
try
{
return xServiceInfo->supportsService( OUString( RTL_CONSTASCII_USTRINGPARAM( SERVICENAME_ACTIONTRIGGERSEPARATOR )) );
}
catch ( Exception& )
{
}
return sal_False;
}
void GetMenuItemAttributes( Reference< XPropertySet > xActionTriggerPropertySet,
OUString& aMenuLabel,
OUString& aCommandURL,
OUString& aHelpURL,
Reference< XBitmap >& xBitmap,
Reference< XIndexContainer >& xSubContainer )
{
Any a;
try
{
// mandatory properties
a = xActionTriggerPropertySet->getPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "Text" )) );
a >>= aMenuLabel;
a = xActionTriggerPropertySet->getPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "CommandURL" )) );
a >>= aCommandURL;
a = xActionTriggerPropertySet->getPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "Image" )) );
a >>= xBitmap;
a = xActionTriggerPropertySet->getPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "SubContainer" )) );
a >>= xSubContainer;
}
catch ( Exception& )
{
}
// optional properties
try
{
a = xActionTriggerPropertySet->getPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "HelpURL" )) );
a >>= aHelpURL;
}
catch ( Exception& )
{
}
}
void InsertSubMenuItems( Menu* pSubMenu, USHORT& nItemId, Reference< XIndexContainer > xActionTriggerContainer )
{
Reference< XIndexAccess > xIndexAccess( xActionTriggerContainer, UNO_QUERY );
if ( xIndexAccess.is() )
{
OUString aSlotURL( RTL_CONSTASCII_USTRINGPARAM( "slot:" ));
for ( sal_Int32 i = 0; i < xIndexAccess->getCount(); i++ )
{
try
{
Reference< XPropertySet > xPropSet;
Any a = xIndexAccess->getByIndex( i );
if (( a >>= xPropSet ) && ( xPropSet.is() ))
{
if ( IsSeparator( xPropSet ))
{
// Separator
OGuard aGuard( Application::GetSolarMutex() );
pSubMenu->InsertSeparator();
}
else
{
// Menu item
OUString aLabel;
OUString aCommandURL;
OUString aHelpURL;
Reference< XBitmap > xBitmap;
Reference< XIndexContainer > xSubContainer;
sal_Bool bSpecialItemId = sal_False;
USHORT nNewItemId = nItemId++;
GetMenuItemAttributes( xPropSet, aLabel, aCommandURL, aHelpURL, xBitmap, xSubContainer );
OGuard aGuard( Application::GetSolarMutex() );
{
// insert new menu item
sal_Int32 nIndex = aCommandURL.indexOf( aSlotURL );
if ( nIndex >= 0 )
{
// Special code for our menu implementation: some menu items don't have a
// command url but uses the item id as a unqiue identifier. These entries
// got a special url during conversion from menu=>actiontriggercontainer.
// Now we have to extract this special url and set the correct item id!!!
bSpecialItemId = sal_True;
nNewItemId = (USHORT)aCommandURL.copy( nIndex+aSlotURL.getLength() ).toInt32();
pSubMenu->InsertItem( nNewItemId, aLabel );
}
else
{
pSubMenu->InsertItem( nNewItemId, aLabel );
pSubMenu->SetItemCommand( nNewItemId, aCommandURL );
}
// handle bitmap
if ( xBitmap.is() )
{
sal_Bool bImageSet = sal_False;
Reference< XUnoTunnel > xUnoTunnel( xBitmap, UNO_QUERY );
if ( xUnoTunnel.is() )
{
// Try to get implementation pointer through XUnoTunnel
sal_Int64 nPointer = xUnoTunnel->getSomething( ImageWrapper::GetUnoTunnelId() );
if ( nPointer )
{
// This is our own optimized implementation of menu images!
ImageWrapper* pImageWrapper = (ImageWrapper *)nPointer;
Image aMenuImage = pImageWrapper->GetImage();
if ( !!aMenuImage )
pSubMenu->SetItemImage( nNewItemId, aMenuImage );
bImageSet = sal_True;
}
}
if ( !bImageSet )
{
// This is a unknown implementation of XBitmap interface. We have to
// use a more time consuming way to build an Image!
// TODO: use memory streams to build a bitmap and this can be used
// to create an image!!
Image aImage;
Bitmap aBitmap;
Sequence< sal_Int8 > aDIBSeq;
{
aDIBSeq = xBitmap->getDIB();
SvMemoryStream aMem( (void *)aDIBSeq.getConstArray(), aDIBSeq.getLength(), STREAM_READ );
aMem >> aBitmap;
}
aDIBSeq = xBitmap->getMaskDIB();
if ( aDIBSeq.getLength() > 0 )
{
Bitmap aMaskBitmap;
SvMemoryStream aMem( (void *)aDIBSeq.getConstArray(), aDIBSeq.getLength(), STREAM_READ );
aMem >> aMaskBitmap;
aImage = Image( aBitmap, aMaskBitmap );
}
else
aImage = Image( aBitmap );
}
}
if ( xSubContainer.is() )
{
PopupMenu* pNewSubMenu = new PopupMenu;
// Sub menu (recursive call CreateSubMenu )
InsertSubMenuItems( pNewSubMenu, nItemId, xSubContainer );
pSubMenu->SetPopupMenu( nNewItemId, pNewSubMenu );
}
}
}
}
}
catch ( IndexOutOfBoundsException )
{
return;
}
catch ( WrappedTargetException )
{
return;
}
catch ( RuntimeException )
{
return;
}
}
}
}
// ----------------------------------------------------------------------------
// implementation helper ( ActionTrigger => menu )
// ----------------------------------------------------------------------------
Reference< XPropertySet > CreateActionTrigger( USHORT nItemId, const Menu* pMenu, const Reference< XIndexContainer >& rActionTriggerContainer ) throw ( RuntimeException )
{
Reference< XPropertySet > xPropSet;
Reference< XMultiServiceFactory > xMultiServiceFactory( rActionTriggerContainer, UNO_QUERY );
if ( xMultiServiceFactory.is() )
{
xPropSet = Reference< XPropertySet >( xMultiServiceFactory->createInstance(
OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.ui.ActionTrigger" )) ),
UNO_QUERY );
Any a;
try
{
// Retrieve the menu attributes and set them in our PropertySet
OUString aLabel = pMenu->GetItemText( nItemId );
a <<= aLabel;
xPropSet->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "Text" )), a );
OUString aCommandURL = pMenu->GetItemCommand( nItemId );
if ( aCommandURL.getLength() == 0 )
{
aCommandURL = OUString( RTL_CONSTASCII_USTRINGPARAM( "slot:" ));
aCommandURL += OUString::valueOf( (sal_Int32)nItemId );
}
a <<= aCommandURL;
xPropSet->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "CommandURL" )), a );
Image aImage = pMenu->GetItemImage( nItemId );
if ( !!aImage )
{
// We use our own optimized XBitmap implementation
Reference< XBitmap > xBitmap( static_cast< cppu::OWeakObject* >( new ImageWrapper( aImage )), UNO_QUERY );
a <<= xBitmap;
xPropSet->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "Image" )), a );
}
}
catch ( Exception& )
{
}
}
return xPropSet;
}
Reference< XPropertySet > CreateActionTriggerSeparator( const Reference< XIndexContainer >& rActionTriggerContainer ) throw ( RuntimeException )
{
Reference< XMultiServiceFactory > xMultiServiceFactory( rActionTriggerContainer, UNO_QUERY );
if ( xMultiServiceFactory.is() )
{
return Reference< XPropertySet >( xMultiServiceFactory->createInstance(
OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.ui.ActionTriggerSeparator" )) ),
UNO_QUERY );
}
return Reference< XPropertySet >();
}
Reference< XIndexContainer > CreateActionTriggerContainer( const Reference< XIndexContainer >& rActionTriggerContainer ) throw ( RuntimeException )
{
Reference< XMultiServiceFactory > xMultiServiceFactory( rActionTriggerContainer, UNO_QUERY );
if ( xMultiServiceFactory.is() )
{
return Reference< XIndexContainer >( xMultiServiceFactory->createInstance(
OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.ui.ActionTriggerContainer" )) ),
UNO_QUERY );
}
return Reference< XIndexContainer >();
}
void FillActionTriggerContainerWithMenu( const Menu* pMenu, Reference< XIndexContainer >& rActionTriggerContainer )
{
OGuard aGuard( Application::GetSolarMutex() );
for ( USHORT nPos = 0; nPos < pMenu->GetItemCount(); nPos++ )
{
USHORT nItemId = pMenu->GetItemId( nPos );
MenuItemType nType = pMenu->GetItemType( nPos );
try
{
Any a;
Reference< XPropertySet > xPropSet;
if ( nType == MENUITEM_SEPARATOR )
{
xPropSet = CreateActionTriggerSeparator( rActionTriggerContainer );
a <<= xPropSet;
rActionTriggerContainer->insertByIndex( nPos, a );
}
else
{
xPropSet = CreateActionTrigger( nItemId, pMenu, rActionTriggerContainer );
a <<= xPropSet;
rActionTriggerContainer->insertByIndex( nPos, a );
PopupMenu* pPopupMenu = pMenu->GetPopupMenu( nItemId );
if ( pPopupMenu )
{
// recursive call to build next sub menu
Any a;
Reference< XIndexContainer > xSubContainer = CreateActionTriggerContainer( rActionTriggerContainer );
a <<= xSubContainer;
xPropSet->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "SubContainer" )), a );
FillActionTriggerContainerWithMenu( pPopupMenu, xSubContainer );
}
}
}
catch ( Exception& )
{
}
}
}
void ActionTriggerHelper::CreateMenuFromActionTriggerContainer(
Menu* pNewMenu,
const Reference< XIndexContainer >& rActionTriggerContainer )
{
USHORT nItemId = START_ITEMID;
if ( rActionTriggerContainer.is() )
InsertSubMenuItems( pNewMenu, nItemId, rActionTriggerContainer );
}
void ActionTriggerHelper::FillActionTriggerContainerFromMenu(
Reference< XIndexContainer >& xActionTriggerContainer,
const Menu* pMenu )
{
FillActionTriggerContainerWithMenu( pMenu, xActionTriggerContainer );
}
Reference< XIndexContainer > ActionTriggerHelper::CreateActionTriggerContainerFromMenu( const Menu* pMenu )
{
return new RootActionTriggerContainer( pMenu, ::comphelper::getProcessServiceFactory() );
}
}
<|endoftext|> |
<commit_before>//
// Created by david on 2019-08-07.
//
#include <complex.h>
#undef I
#include <complex>
#define lapack_complex_float std::complex<float>
#define lapack_complex_double std::complex<double>
#if __has_include(<mkl_lapacke.h>)
#include <mkl_lapacke.h>
#elif __has_include(<lapacke.h>)
#include <lapacke.h>
#endif
#include <Eigen/Core>
#include <iostream>
#include <math/svd.h>
template<typename Scalar>
std::tuple<svd::solver::MatrixType<Scalar>, svd::solver::VectorType<Scalar>, svd::solver::MatrixType<Scalar>, long>
svd::solver::do_svd_lapacke(const Scalar *mat_ptr, long rows, long cols, std::optional<long> rank_max) {
if(not rank_max.has_value()) rank_max = std::min(rows, cols);
MatrixType<Scalar> A = Eigen::Map<const MatrixType<Scalar>>(mat_ptr, rows, cols);
svd::log->trace("Starting SVD with lapacke");
if(rows <= 0) throw std::runtime_error("SVD error: rows() == 0");
if(cols <= 0) throw std::runtime_error("SVD error: cols() == 0");
if(not A.allFinite()) throw std::runtime_error("SVD error: matrix has inf's or nan's");
if(A.isZero(0)) throw std::runtime_error("SVD error: matrix is all zeros");
int info = 0;
int rowsU = static_cast<int>(rows);
int colsU = static_cast<int>(std::min(rows, cols));
int rowsVT = static_cast<int>(std::min(rows, cols));
int colsVT = static_cast<int>(cols);
int sizeS = static_cast<int>(std::min(rows, cols));
int lda = static_cast<int>(rows);
int ldu = static_cast<int>(rowsU);
int ldvt = static_cast<int>(rowsVT);
MatrixType<Scalar> U(rowsU, colsU);
VectorType<double> S(sizeS);
MatrixType<Scalar> VT(rowsVT, colsVT);
VectorType<Scalar> work(1);
if constexpr(std::is_same<Scalar, double>::value) {
svd::log->trace("Querying dgesvd");
info = LAPACKE_dgesvd_work(LAPACK_COL_MAJOR, 'S', 'S', static_cast<int>(rows), static_cast<int>(cols), A.data(), lda, S.data(), U.data(), ldu,
VT.data(), ldvt, work.data(), -1);
int lwork = static_cast<int>(work(0));
svd::log->trace("Resizing work array");
work.resize(lwork);
svd::log->trace("Running dgesvd");
info = LAPACKE_dgesvd_work(LAPACK_COL_MAJOR, 'S', 'S', static_cast<int>(rows), static_cast<int>(cols), A.data(), lda, S.data(), U.data(), ldu,
VT.data(), ldvt, work.data(), lwork);
}
if constexpr(std::is_same<Scalar, std::complex<double>>::value) {
int lrwork = static_cast<int>(5 * std::min(rows, cols));
VectorType<double> rwork(lrwork);
auto Ap = reinterpret_cast<lapack_complex_double *>(A.data());
auto Up = reinterpret_cast<lapack_complex_double *>(U.data());
auto VTp = reinterpret_cast<lapack_complex_double *>(VT.data());
auto Wp_qry = reinterpret_cast<lapack_complex_double *>(work.data());
svd::log->trace("Querying zgesvd");
info = LAPACKE_zgesvd_work(LAPACK_COL_MAJOR, 'S', 'S', static_cast<int>(rows), static_cast<int>(cols), Ap, lda, S.data(), Up, ldu, VTp, ldvt, Wp_qry,
-1, rwork.data());
int lwork = static_cast<int>(std::real(work(0)));
svd::log->trace("Resizing work array");
work.resize(lwork);
auto Wp = reinterpret_cast<lapack_complex_double *>(work.data());
svd::log->trace("Running zgesvd");
info = LAPACKE_zgesvd_work(LAPACK_COL_MAJOR, 'S', 'S', static_cast<int>(rows), static_cast<int>(cols), Ap, lda, S.data(), Up, ldu, VTp, ldvt, Wp, lwork,
rwork.data());
}
svd::log->trace("Truncation singular values");
long max_size = std::min(S.size(), rank_max.value());
long rank = (S.head(max_size).array() >= SVDThreshold).count();
if(rank == S.size()) {
truncation_error = 0;
} else {
truncation_error = S.tail(S.size() - rank).norm();
}
if(rank <= 0 or not U.leftCols(rank).allFinite() or not S.head(rank).allFinite() or not VT.topRows(rank).allFinite()) {
std::cerr << "SVD error \n"
<< " svd_threshold = " << SVDThreshold << '\n'
<< " Truncation Error = " << truncation_error << '\n'
<< " Rank = " << rank << '\n'
<< " U all finite : " << std::boolalpha << U.leftCols(rank).allFinite() << '\n'
<< " S all finite : " << std::boolalpha << S.head(rank).allFinite() << '\n'
<< " V all finite : " << std::boolalpha << VT.topRows(rank).allFinite() << '\n'
<< " Lapacke info = " << info << '\n';
throw std::runtime_error("SVD lapacke error: Erroneous results");
}
svd::log->trace("SVD with lapacke finished successfully");
return std::make_tuple(U.leftCols(rank), S.head(rank), VT.topRows(rank), rank);
}
//! \relates svd::class_SVD
//! \brief force instantiation of do_svd_lapacke for type 'double'
template std::tuple<svd::solver::MatrixType<double>, svd::solver::VectorType<double>, svd::solver::MatrixType<double>, long>
svd::solver::do_svd_lapacke(const double *, long, long, std::optional<long>);
using cplx = std::complex<double>;
//! \relates svd::class_SVD
//! \brief force instantiation of do_svd_lapacke for type 'std::complex<double>'
template std::tuple<svd::solver::MatrixType<cplx>, svd::solver::VectorType<cplx>, svd::solver::MatrixType<cplx>, long>
svd::solver::do_svd_lapacke(const cplx *, long, long, std::optional<long>);
<commit_msg>Check that macro is undefined before defining<commit_after>//
// Created by david on 2019-08-07.
//
#include <complex.h>
#undef I
#include <complex>
#ifndef lapack_complex_float
#define lapack_complex_float std::complex<float>
#endif
#ifndef lapack_complex_double
#define lapack_complex_double std::complex<double>
#endif
#if __has_include(<mkl_lapacke.h>)
#include <mkl_lapacke.h>
#elif __has_include(<lapacke.h>)
#include <lapacke.h>
#endif
#include <Eigen/Core>
#include <iostream>
#include <math/svd.h>
template<typename Scalar>
std::tuple<svd::solver::MatrixType<Scalar>, svd::solver::VectorType<Scalar>, svd::solver::MatrixType<Scalar>, long>
svd::solver::do_svd_lapacke(const Scalar *mat_ptr, long rows, long cols, std::optional<long> rank_max) {
if(not rank_max.has_value()) rank_max = std::min(rows, cols);
MatrixType<Scalar> A = Eigen::Map<const MatrixType<Scalar>>(mat_ptr, rows, cols);
svd::log->trace("Starting SVD with lapacke");
if(rows <= 0) throw std::runtime_error("SVD error: rows() == 0");
if(cols <= 0) throw std::runtime_error("SVD error: cols() == 0");
if(not A.allFinite()) throw std::runtime_error("SVD error: matrix has inf's or nan's");
if(A.isZero(0)) throw std::runtime_error("SVD error: matrix is all zeros");
int info = 0;
int rowsU = static_cast<int>(rows);
int colsU = static_cast<int>(std::min(rows, cols));
int rowsVT = static_cast<int>(std::min(rows, cols));
int colsVT = static_cast<int>(cols);
int sizeS = static_cast<int>(std::min(rows, cols));
int lda = static_cast<int>(rows);
int ldu = static_cast<int>(rowsU);
int ldvt = static_cast<int>(rowsVT);
MatrixType<Scalar> U(rowsU, colsU);
VectorType<double> S(sizeS);
MatrixType<Scalar> VT(rowsVT, colsVT);
VectorType<Scalar> work(1);
if constexpr(std::is_same<Scalar, double>::value) {
svd::log->trace("Querying dgesvd");
info = LAPACKE_dgesvd_work(LAPACK_COL_MAJOR, 'S', 'S', static_cast<int>(rows), static_cast<int>(cols), A.data(), lda, S.data(), U.data(), ldu,
VT.data(), ldvt, work.data(), -1);
int lwork = static_cast<int>(work(0));
svd::log->trace("Resizing work array");
work.resize(lwork);
svd::log->trace("Running dgesvd");
info = LAPACKE_dgesvd_work(LAPACK_COL_MAJOR, 'S', 'S', static_cast<int>(rows), static_cast<int>(cols), A.data(), lda, S.data(), U.data(), ldu,
VT.data(), ldvt, work.data(), lwork);
}
if constexpr(std::is_same<Scalar, std::complex<double>>::value) {
int lrwork = static_cast<int>(5 * std::min(rows, cols));
VectorType<double> rwork(lrwork);
auto Ap = reinterpret_cast<lapack_complex_double *>(A.data());
auto Up = reinterpret_cast<lapack_complex_double *>(U.data());
auto VTp = reinterpret_cast<lapack_complex_double *>(VT.data());
auto Wp_qry = reinterpret_cast<lapack_complex_double *>(work.data());
svd::log->trace("Querying zgesvd");
info = LAPACKE_zgesvd_work(LAPACK_COL_MAJOR, 'S', 'S', static_cast<int>(rows), static_cast<int>(cols), Ap, lda, S.data(), Up, ldu, VTp, ldvt, Wp_qry,
-1, rwork.data());
int lwork = static_cast<int>(std::real(work(0)));
svd::log->trace("Resizing work array");
work.resize(lwork);
auto Wp = reinterpret_cast<lapack_complex_double *>(work.data());
svd::log->trace("Running zgesvd");
info = LAPACKE_zgesvd_work(LAPACK_COL_MAJOR, 'S', 'S', static_cast<int>(rows), static_cast<int>(cols), Ap, lda, S.data(), Up, ldu, VTp, ldvt, Wp, lwork,
rwork.data());
}
svd::log->trace("Truncation singular values");
long max_size = std::min(S.size(), rank_max.value());
long rank = (S.head(max_size).array() >= SVDThreshold).count();
if(rank == S.size()) {
truncation_error = 0;
} else {
truncation_error = S.tail(S.size() - rank).norm();
}
if(rank <= 0 or not U.leftCols(rank).allFinite() or not S.head(rank).allFinite() or not VT.topRows(rank).allFinite()) {
std::cerr << "SVD error \n"
<< " svd_threshold = " << SVDThreshold << '\n'
<< " Truncation Error = " << truncation_error << '\n'
<< " Rank = " << rank << '\n'
<< " U all finite : " << std::boolalpha << U.leftCols(rank).allFinite() << '\n'
<< " S all finite : " << std::boolalpha << S.head(rank).allFinite() << '\n'
<< " V all finite : " << std::boolalpha << VT.topRows(rank).allFinite() << '\n'
<< " Lapacke info = " << info << '\n';
throw std::runtime_error("SVD lapacke error: Erroneous results");
}
svd::log->trace("SVD with lapacke finished successfully");
return std::make_tuple(U.leftCols(rank), S.head(rank), VT.topRows(rank), rank);
}
//! \relates svd::class_SVD
//! \brief force instantiation of do_svd_lapacke for type 'double'
template std::tuple<svd::solver::MatrixType<double>, svd::solver::VectorType<double>, svd::solver::MatrixType<double>, long>
svd::solver::do_svd_lapacke(const double *, long, long, std::optional<long>);
using cplx = std::complex<double>;
//! \relates svd::class_SVD
//! \brief force instantiation of do_svd_lapacke for type 'std::complex<double>'
template std::tuple<svd::solver::MatrixType<cplx>, svd::solver::VectorType<cplx>, svd::solver::MatrixType<cplx>, long>
svd::solver::do_svd_lapacke(const cplx *, long, long, std::optional<long>);
<|endoftext|> |
<commit_before>
// A game fragment adapted from Andre La Mothe's book
// Ported by Antonello Dettori
// The Black Art of 3D Games Programming
// Modified by CJM 24/9/'08 to run without error or warnings:
// 1. hconsole - called TEXT( ) for parameter 1
// 2. added _ as prefix to deprecated kbhit() function
// 3. added _ as prefix to deprecated getch() function
// Note: this is very old-fashioned code originally written for 16-bit PCs
// INCLUDES ///////////////////////////////////////////////
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <ncurses.h>
#include <time.h>
#include <string>
#include <unistd.h>
// DEFINES ////////////////////////////////////////////////
#define MAX_X 80 // maximum x position for player
#define SCROLL_POS 24 // the point that scrolling occurs
// PROTOTYPES /////////////////////////////////////////////
void Init_Graphics();
void Set_Color(int fcolor, int bcolor);
void Draw_String(int x, int y, char *string);
// GLOBALS ////////////////////////////////////////////////
int game_running = 1; // state of game, 0=done, 1=run
// FUNCTIONS //////////////////////////////////////////////
void Init_Graphics()
{
// this function initializes the console graphics engine
setlocale(LC_ALL,"uk");
initscr();
cbreak(); /* Line buffering disabled */
keypad(stdscr, TRUE); /* We get F1, F2 etc.. */
noecho(); /* Don't echo() while we do getch */
start_color();
init_pair(1, 15, 0);
// seed the random number generator with time
srand((unsigned)time(NULL));
} // end Init_Graphics
///////////////////////////////////////////////////////////
//void Set_Color(int fcolor, int bcolor = 0)
//{
// this function sets the color of the console output
// SetConsoleTextAttribute(hconsole, (WORD)((bcolor << 4) |
// fcolor));
//
//} // Set_Color
///////////////////////////////////////////////////////////
void Draw_String(int x, int y, char *string)
{
// this function draws a string at the given x,y
int cursor_pos_x = x;
int cursor_pos_y = y;
// set printing position
// mvinsch(cursor_pos_x,cursor_pos_y, ' ');
// print the string in current color
mvprintw(cursor_pos_y, cursor_pos_x, string);
} // end Draw_String
///////////////////////////////////////////////////////////
void Clear_Screen(void)
{
// this function clears the screen
// set color to white on black
// Set_Color(15, 0);
// color_set(COLOR_PAIR(1));
// clear the screen
for (int index = 0; index <= SCROLL_POS; index++)
Draw_String(0, SCROLL_POS, "\n");
} // end Clear_Screen
// MAIN GAME LOOP /////////////////////////////////////////
using namespace std;
int main()
{
char key; // player input data
int player_x = 40; // player's x
// SECTION: initialization
// set up the console text graphics system
Init_Graphics();
// clear the screen
// Clear_Screen();
// SECTION: main event loop, this is where all the action
// takes place, the general loop is erase-move-draw
while (game_running)
{
// SECTION: erase all the objects or clear screen
// nothing to erase in our case
// SECTION: get player input
/* if (_kbhit())
{
// get keyboard data, and filter it
key = toupper(_getch());
// is player trying to exit, if so exit
if (key == 'Q' || key == 27)
game_running = 0;
// is player moving left
if (key == 'A')
player_x--;
// is player moving right
if (key == 'S')
player_x++;
} // end if
*/
// SECTION: game logic and further processing
// make sure player stays on screen
if (++player_x > MAX_X)
player_x = MAX_X;
if (--player_x < 0)
player_x = 0;
// SECTION: draw everything
// draw next star at random position
// Set_Color(15, 0);
Draw_String(rand() % MAX_X, SCROLL_POS, ".\n");
// draw player
// Set_Color(rand() % 15, 0);
Draw_String(player_x, 0, "<--*-->");
Draw_String(0, 0, "");
refresh();
// SECTION: synchronize to a constant frame rate
usleep(100);
} // end while
// SECTION: shutdown and bail
// Clear_Screen();
refresh();
printf("\nG A M E O V E R \n\n");
endwin();
return 0;
} // end main
<commit_msg>Various fixes<commit_after>
// A game fragment adapted from Andre La Mothe's book
// Ported by Antonello Dettori
// The Black Art of 3D Games Programming
// Modified by CJM 24/9/'08 to run without error or warnings:
// 1. hconsole - called TEXT( ) for parameter 1
// 2. added _ as prefix to deprecated kbhit() function
// 3. added _ as prefix to deprecated getch() function
// Note: this is very old-fashioned code originally written for 16-bit PCs
// INCLUDES ///////////////////////////////////////////////
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <ncurses.h>
#include <time.h>
#include <string>
#include <unistd.h>
// DEFINES ////////////////////////////////////////////////
#define MAX_X 80 // maximum x position for player
#define SCROLL_POS 24 // the point that scrolling occurs
// PROTOTYPES /////////////////////////////////////////////
void Init_Graphics();
void Set_Color(int fcolor, int bcolor);
void Draw_String(int x, int y, char *string);
// GLOBALS ////////////////////////////////////////////////
int game_running = 1; // state of game, 0=done, 1=run
// FUNCTIONS //////////////////////////////////////////////
void Init_Graphics()
{
// this function initializes the console graphics engine
setlocale(LC_ALL,"uk");
initscr();
cbreak(); /* Line buffering disabled */
keypad(stdscr, TRUE); /* We get F1, F2 etc.. */
noecho(); /* Don't echo() while we do getch */
start_color();
init_pair(1, COLOR_RED, COLOR_BLACK);
// seed the random number generator with time
srand((unsigned)time(NULL));
} // end Init_Graphics
///////////////////////////////////////////////////////////
//void Set_Color(int fcolor, int bcolor = 0)
//{
// this function sets the color of the console output
// SetConsoleTextAttribute(hconsole, (WORD)((bcolor << 4) |
// fcolor));
//
//} // Set_Color
///////////////////////////////////////////////////////////
void Draw_String(int x, int y, char *string)
{
// this function draws a string at the given x,y
int cursor_pos_x = x;
int cursor_pos_y = y;
// print the string in current color and position
mvaddstring(cursor_pos_y, cursor_pos_x, string);
} // end Draw_String
///////////////////////////////////////////////////////////
void Clear_Screen(void)
{
// this function clears the screen
// set color to white on black
// Set_Color(15, 0);
// color_set(COLOR_PAIR(1));
// clear the screen
for (int index = 0; index <= SCROLL_POS; index++)
Draw_String(0, SCROLL_POS, "\n");
} // end Clear_Screen
// MAIN GAME LOOP /////////////////////////////////////////
using namespace std;
int main()
{
char key; // player input data
int player_x = 40; // player's x
// SECTION: initialization
// set up the console text graphics system
Init_Graphics();
// clear the screen
// Clear_Screen();
// SECTION: main event loop, this is where all the action
// takes place, the general loop is erase-move-draw
while (game_running)
{
// SECTION: erase all the objects or clear screen
// nothing to erase in our case
// SECTION: get player input
if (getch())
{
// get keyboard data, and filter it
key = getch();
// is player trying to exit, if so exit
if (key == 'q' || key == 27)
game_running = 0;
// is player moving left
if (key == 'a')
player_x--;
// is player moving right
if (key == 's')
player_x++;
} // end if
// SECTION: game logic and further processing
// make sure player stays on screen
if (++player_x > MAX_X)
player_x = MAX_X;
if (--player_x < 0)
player_x = 0;
// SECTION: draw everything
// draw next star at random position
// Set_Color(15, 0);
Draw_String(rand() % MAX_X, SCROLL_POS, ".\n");
// draw player
// Set_Color(rand() % 15, 0);
Draw_String(player_x, 0, "<--*-->");
// Draw_String(0, 0, "");
refresh();
// SECTION: synchronize to a constant frame rate
usleep(100);
} // end while
// SECTION: shutdown and bail
// Clear_Screen();
refresh();
printf("\nG A M E O V E R \n\n");
endwin();
return 0;
} // end main
<|endoftext|> |
<commit_before>/*
Copyright (C) 2013 David Edmundson (davidedmundson@kde.org)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "persondata.h"
#include "metacontact.h"
#include "personmanager.h"
#include "personpluginmanager.h"
#include "basepersonsdatasource.h"
#include "contactmonitor.h"
#include <QDebug>
namespace KPeople {
class PersonDataPrivate {
public:
QStringList contactIds;
MetaContact metaContact;
QList<ContactMonitorPtr> watchers;
};
}
using namespace KPeople;
KPeople::PersonData::PersonData(const QString &id, QObject* parent):
QObject(parent),
d_ptr(new PersonDataPrivate)
{
Q_D(PersonData);
const QString personId;
//query DB
const QStringList contactIds;
if (id.startsWith("kpeople://")) {
personId = id;
d->contactIds = PersonManager::instance()->contactsForPersonId(personId);
} else {
personId = PersonManager::instance()->personIdForContact(personId); //TODO merge into one method + query
d->contactIds = PersonManager::instance()->contactsForPersonId(personId);
}
KABC::Addressee::Map contacts;
Q_FOREACH(BasePersonsDataSource *dataSource, PersonPluginManager::dataSourcePlugins()) {
Q_FOREACH(const QString &contactId, d->contactIds) {
//FIXME this is terrible.. we have to ask every datasource for the contact
//future idea: plugins have a method of what their URIs will start with
//then we keep plugins as a map
ContactMonitorPtr cw = dataSource->contactMonitor(contactId);
d->watchers << cw;
if (!cw->contact().isEmpty()) {
contacts[contactId] = cw->contact();
}
connect(cw.data(), SIGNAL(contactChanged()), SLOT(onContactChanged()));
}
}
d->metaContact = MetaContact(personId, contacts);
}
PersonData::~PersonData()
{
delete d_ptr;
}
KABC::Addressee PersonData::person() const
{
Q_D(const PersonData);
return d->metaContact.personAddressee();
}
KABC::AddresseeList PersonData::contacts() const
{
Q_D(const PersonData);
return d->metaContact.contacts();
}
void PersonData::onContactChanged()
{
Q_D(PersonData);
ContactMonitor *watcher = qobject_cast<ContactMonitor*>(sender());
d->metaContact.updateContact(watcher->contactId(), watcher->contact());
Q_EMIT dataChanged();
}
<commit_msg>Fix build, remove unused variable<commit_after>/*
Copyright (C) 2013 David Edmundson (davidedmundson@kde.org)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "persondata.h"
#include "metacontact.h"
#include "personmanager.h"
#include "personpluginmanager.h"
#include "basepersonsdatasource.h"
#include "contactmonitor.h"
#include <QDebug>
namespace KPeople {
class PersonDataPrivate {
public:
QStringList contactIds;
MetaContact metaContact;
QList<ContactMonitorPtr> watchers;
};
}
using namespace KPeople;
KPeople::PersonData::PersonData(const QString &id, QObject* parent):
QObject(parent),
d_ptr(new PersonDataPrivate)
{
Q_D(PersonData);
QString personId;
//query DB
if (id.startsWith("kpeople://")) {
personId = id;
d->contactIds = PersonManager::instance()->contactsForPersonId(personId);
} else {
personId = PersonManager::instance()->personIdForContact(personId); //TODO merge into one method + query
d->contactIds = PersonManager::instance()->contactsForPersonId(personId);
}
KABC::Addressee::Map contacts;
Q_FOREACH(BasePersonsDataSource *dataSource, PersonPluginManager::dataSourcePlugins()) {
Q_FOREACH(const QString &contactId, d->contactIds) {
//FIXME this is terrible.. we have to ask every datasource for the contact
//future idea: plugins have a method of what their URIs will start with
//then we keep plugins as a map
ContactMonitorPtr cw = dataSource->contactMonitor(contactId);
d->watchers << cw;
if (!cw->contact().isEmpty()) {
contacts[contactId] = cw->contact();
}
connect(cw.data(), SIGNAL(contactChanged()), SLOT(onContactChanged()));
}
}
d->metaContact = MetaContact(personId, contacts);
}
PersonData::~PersonData()
{
delete d_ptr;
}
KABC::Addressee PersonData::person() const
{
Q_D(const PersonData);
return d->metaContact.personAddressee();
}
KABC::AddresseeList PersonData::contacts() const
{
Q_D(const PersonData);
return d->metaContact.contacts();
}
void PersonData::onContactChanged()
{
Q_D(PersonData);
ContactMonitor *watcher = qobject_cast<ContactMonitor*>(sender());
d->metaContact.updateContact(watcher->contactId(), watcher->contact());
Q_EMIT dataChanged();
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include "paddle/memory/memory.h"
#include "paddle/memory/detail/memory_block.h"
#include "paddle/memory/detail/meta_data.h"
#include "paddle/platform/cpu_info.h"
#include "paddle/platform/gpu_info.h"
#include "paddle/platform/place.h"
#include <gtest/gtest.h>
#include <unordered_map>
inline bool is_aligned(void const *p, const size_t n) {
return 0 == (reinterpret_cast<uintptr_t>(p) & 0x3);
}
size_t align(size_t size, paddle::platform::CPUPlace place) {
size += sizeof(paddle::memory::detail::Metadata);
size_t alignment = paddle::platform::CpuMinChunkSize();
size_t remaining = size % alignment;
return remaining == 0 ? size : size + (alignment - remaining);
}
TEST(BuddyAllocator, CPUAllocation) {
void *p = nullptr;
EXPECT_EQ(p, nullptr);
paddle::platform::CPUPlace cpu;
p = paddle::memory::Alloc(cpu, 4096);
EXPECT_NE(p, nullptr);
paddle::memory::Free(cpu, p);
}
TEST(BuddyAllocator, CPUMultAlloc) {
paddle::platform::CPUPlace cpu;
std::unordered_map<void *, size_t> ps;
size_t total_size = paddle::memory::Used(cpu);
EXPECT_EQ(total_size, 0UL);
for (auto size :
{128, 256, 1024, 4096, 16384, 65536, 262144, 1048576, 4194304}) {
ps[paddle::memory::Alloc(cpu, size)] = size;
// Buddy Allocator doesn't manage too large memory chunk
if (paddle::memory::Used(cpu) == total_size) continue;
size_t aligned_size = align(size, cpu);
total_size += aligned_size;
EXPECT_EQ(total_size, paddle::memory::Used(cpu));
}
for (auto p : ps) {
EXPECT_EQ(is_aligned(p.first, 32), true);
paddle::memory::Free(cpu, p.first);
// Buddy Allocator doesn't manage too large memory chunk
if (paddle::memory::Used(cpu) == total_size) continue;
size_t aligned_size = align(p.second, cpu);
total_size -= aligned_size;
EXPECT_EQ(total_size, paddle::memory::Used(cpu));
}
}
#ifndef PADDLE_ONLY_CPU
size_t align(size_t size, paddle::platform::GPUPlace place) {
size += sizeof(paddle::memory::detail::Metadata);
size_t alignment = paddle::platform::GpuMinChunkSize();
size_t remaining = size % alignment;
return remaining == 0 ? size : size + (alignment - remaining);
}
TEST(BuddyAllocator, GPUAllocation) {
void *p = nullptr;
EXPECT_EQ(p, nullptr);
paddle::platform::GPUPlace gpu(0);
p = paddle::memory::Alloc(gpu, 4096);
EXPECT_NE(p, nullptr);
paddle::memory::Free(gpu, p);
}
TEST(BuddyAllocator, GPUMultAlloc) {
paddle::platform::GPUPlace gpu;
std::unordered_map<void *, size_t> ps;
size_t total_size = paddle::memory::Used(gpu);
EXPECT_EQ(total_size, 0UL);
for (auto size :
{128, 256, 1024, 4096, 16384, 65536, 262144, 1048576, 4194304}) {
ps[paddle::memory::Alloc(gpu, size)] = size;
// Buddy Allocator doesn't manage too large memory chunk
if (paddle::memory::Used(gpu) == total_size) continue;
size_t aligned_size = align(size, gpu);
total_size += aligned_size;
EXPECT_EQ(total_size, paddle::memory::Used(gpu));
}
for (auto p : ps) {
EXPECT_EQ(is_aligned(p.first, 32), true);
paddle::memory::Free(gpu, p.first);
// Buddy Allocator doesn't manage too large memory chunk
if (paddle::memory::Used(gpu) == total_size) continue;
size_t aligned_size = align(p.second, gpu);
total_size -= aligned_size;
EXPECT_EQ(total_size, paddle::memory::Used(gpu));
}
}
#endif // PADDLE_ONLY_CPU
<commit_msg>update<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include "paddle/memory/memory.h"
#include "paddle/memory/detail/memory_block.h"
#include "paddle/memory/detail/meta_data.h"
#include "paddle/platform/cpu_info.h"
#include "paddle/platform/gpu_info.h"
#include "paddle/platform/place.h"
#include <gtest/gtest.h>
#include <unordered_map>
inline bool is_aligned(void const *p) {
return 0 == (reinterpret_cast<uintptr_t>(p) & 0x3);
}
size_t align(size_t size, paddle::platform::CPUPlace place) {
size += sizeof(paddle::memory::detail::Metadata);
size_t alignment = paddle::platform::CpuMinChunkSize();
size_t remaining = size % alignment;
return remaining == 0 ? size : size + (alignment - remaining);
}
TEST(BuddyAllocator, CPUAllocation) {
void *p = nullptr;
EXPECT_EQ(p, nullptr);
paddle::platform::CPUPlace cpu;
p = paddle::memory::Alloc(cpu, 4096);
EXPECT_NE(p, nullptr);
paddle::memory::Free(cpu, p);
}
TEST(BuddyAllocator, CPUMultAlloc) {
paddle::platform::CPUPlace cpu;
std::unordered_map<void *, size_t> ps;
size_t total_size = paddle::memory::Used(cpu);
EXPECT_EQ(total_size, 0UL);
for (auto size :
{128, 256, 1024, 4096, 16384, 65536, 262144, 1048576, 4194304}) {
ps[paddle::memory::Alloc(cpu, size)] = size;
// Buddy Allocator doesn't manage too large memory chunk
if (paddle::memory::Used(cpu) == total_size) continue;
size_t aligned_size = align(size, cpu);
total_size += aligned_size;
EXPECT_EQ(total_size, paddle::memory::Used(cpu));
}
for (auto p : ps) {
EXPECT_EQ(is_aligned(p.first), true);
paddle::memory::Free(cpu, p.first);
// Buddy Allocator doesn't manage too large memory chunk
if (paddle::memory::Used(cpu) == total_size) continue;
size_t aligned_size = align(p.second, cpu);
total_size -= aligned_size;
EXPECT_EQ(total_size, paddle::memory::Used(cpu));
}
}
#ifndef PADDLE_ONLY_CPU
size_t align(size_t size, paddle::platform::GPUPlace place) {
size += sizeof(paddle::memory::detail::Metadata);
size_t alignment = paddle::platform::GpuMinChunkSize();
size_t remaining = size % alignment;
return remaining == 0 ? size : size + (alignment - remaining);
}
TEST(BuddyAllocator, GPUAllocation) {
void *p = nullptr;
EXPECT_EQ(p, nullptr);
paddle::platform::GPUPlace gpu(0);
p = paddle::memory::Alloc(gpu, 4096);
EXPECT_NE(p, nullptr);
paddle::memory::Free(gpu, p);
}
TEST(BuddyAllocator, GPUMultAlloc) {
paddle::platform::GPUPlace gpu;
std::unordered_map<void *, size_t> ps;
size_t total_size = paddle::memory::Used(gpu);
EXPECT_EQ(total_size, 0UL);
for (auto size :
{128, 256, 1024, 4096, 16384, 65536, 262144, 1048576, 4194304}) {
ps[paddle::memory::Alloc(gpu, size)] = size;
// Buddy Allocator doesn't manage too large memory chunk
if (paddle::memory::Used(gpu) == total_size) continue;
size_t aligned_size = align(size, gpu);
total_size += aligned_size;
EXPECT_EQ(total_size, paddle::memory::Used(gpu));
}
for (auto p : ps) {
EXPECT_EQ(is_aligned(p.first), true);
paddle::memory::Free(gpu, p.first);
// Buddy Allocator doesn't manage too large memory chunk
if (paddle::memory::Used(gpu) == total_size) continue;
size_t aligned_size = align(p.second, gpu);
total_size -= aligned_size;
EXPECT_EQ(total_size, paddle::memory::Used(gpu));
}
}
#endif // PADDLE_ONLY_CPU
<|endoftext|> |
<commit_before>// Copyright (c) 2016-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 <policy/rbf.h>
#include <util/rbf.h>
RBFTransactionState IsRBFOptIn(const CTransaction& tx, const CTxMemPool& pool)
{
AssertLockHeld(pool.cs);
CTxMemPool::setEntries setAncestors;
// First check the transaction itself.
if (SignalsOptInRBF(tx)) {
return RBFTransactionState::REPLACEABLE_BIP125;
}
// If this transaction is not in our mempool, then we can't be sure
// we will know about all its inputs.
if (!pool.exists(tx.GetHash())) {
return RBFTransactionState::UNKNOWN;
}
// If all the inputs have nSequence >= maxint-1, it still might be
// signaled for RBF if any unconfirmed parents have signaled.
uint64_t noLimit = std::numeric_limits<uint64_t>::max();
std::string dummy;
CTxMemPoolEntry entry = *pool.mapTx.find(tx.GetHash());
pool.CalculateMemPoolAncestors(entry, setAncestors, noLimit, noLimit, noLimit, noLimit, dummy, false);
for (CTxMemPool::txiter it : setAncestors) {
if (SignalsOptInRBF(it->GetTx())) {
return RBFTransactionState::REPLACEABLE_BIP125;
}
}
return RBFTransactionState::FINAL;
}
// SYSCOIN
RBFTransactionState IsRBFOptIn(const CTransaction& tx, const CTxMemPool& pool, CTxMemPool::setEntries &setAncestors)
{
AssertLockHeld(pool.cs);
// First check the transaction itself.
if (SignalsOptInRBF(tx)) {
return RBFTransactionState::REPLACEABLE_BIP125;
}
// If this transaction is not in our mempool, then we can't be sure
// we will know about all its inputs.
if (!pool.exists(tx.GetHash())) {
return RBFTransactionState::UNKNOWN;
}
// If all the inputs have nSequence >= maxint-1, it still might be
// signaled for RBF if any unconfirmed parents have signaled.
uint64_t noLimit = std::numeric_limits<uint64_t>::max();
std::string dummy;
CTxMemPoolEntry entry = *pool.mapTx.find(tx.GetHash());
pool.CalculateMemPoolAncestors(entry, setAncestors, noLimit, noLimit, noLimit, noLimit, dummy, false);
for (CTxMemPool::txiter it : setAncestors) {
if (SignalsOptInRBF(it->GetTx())) {
return RBFTransactionState::REPLACEABLE_BIP125;
}
}
return RBFTransactionState::FINAL;
RBFTransactionState IsRBFOptInEmptyMempool(const CTransaction& tx)
{
// If we don't have a local mempool we can only check the transaction itself.
return SignalsOptInRBF(tx) ? RBFTransactionState::REPLACEABLE_BIP125 : RBFTransactionState::UNKNOWN;
}
<commit_msg>compile<commit_after>// Copyright (c) 2016-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 <policy/rbf.h>
#include <util/rbf.h>
RBFTransactionState IsRBFOptIn(const CTransaction& tx, const CTxMemPool& pool)
{
AssertLockHeld(pool.cs);
CTxMemPool::setEntries setAncestors;
// First check the transaction itself.
if (SignalsOptInRBF(tx)) {
return RBFTransactionState::REPLACEABLE_BIP125;
}
// If this transaction is not in our mempool, then we can't be sure
// we will know about all its inputs.
if (!pool.exists(tx.GetHash())) {
return RBFTransactionState::UNKNOWN;
}
// If all the inputs have nSequence >= maxint-1, it still might be
// signaled for RBF if any unconfirmed parents have signaled.
uint64_t noLimit = std::numeric_limits<uint64_t>::max();
std::string dummy;
CTxMemPoolEntry entry = *pool.mapTx.find(tx.GetHash());
pool.CalculateMemPoolAncestors(entry, setAncestors, noLimit, noLimit, noLimit, noLimit, dummy, false);
for (CTxMemPool::txiter it : setAncestors) {
if (SignalsOptInRBF(it->GetTx())) {
return RBFTransactionState::REPLACEABLE_BIP125;
}
}
return RBFTransactionState::FINAL;
}
// SYSCOIN
RBFTransactionState IsRBFOptIn(const CTransaction& tx, const CTxMemPool& pool, CTxMemPool::setEntries &setAncestors)
{
AssertLockHeld(pool.cs);
// First check the transaction itself.
if (SignalsOptInRBF(tx)) {
return RBFTransactionState::REPLACEABLE_BIP125;
}
// If this transaction is not in our mempool, then we can't be sure
// we will know about all its inputs.
if (!pool.exists(tx.GetHash())) {
return RBFTransactionState::UNKNOWN;
}
// If all the inputs have nSequence >= maxint-1, it still might be
// signaled for RBF if any unconfirmed parents have signaled.
uint64_t noLimit = std::numeric_limits<uint64_t>::max();
std::string dummy;
CTxMemPoolEntry entry = *pool.mapTx.find(tx.GetHash());
pool.CalculateMemPoolAncestors(entry, setAncestors, noLimit, noLimit, noLimit, noLimit, dummy, false);
for (CTxMemPool::txiter it : setAncestors) {
if (SignalsOptInRBF(it->GetTx())) {
return RBFTransactionState::REPLACEABLE_BIP125;
}
}
return RBFTransactionState::FINAL;
}
RBFTransactionState IsRBFOptInEmptyMempool(const CTransaction& tx)
{
// If we don't have a local mempool we can only check the transaction itself.
return SignalsOptInRBF(tx) ? RBFTransactionState::REPLACEABLE_BIP125 : RBFTransactionState::UNKNOWN;
}
<|endoftext|> |
<commit_before>#pragma once
#include "lubee/error.hpp"
#include <unordered_set>
#include <memory>
namespace spi {
template <class T, class F_Hash=std::hash<T>, class F_Cmp=std::equal_to<>>
class Flyweight {
private:
using value_t = T;
public:
using SP = std::shared_ptr<const value_t>;
private:
struct WP {
using P = std::weak_ptr<const value_t>;
P wp;
const value_t* ptr = nullptr;
std::size_t hash_value;
WP(const SP& sp):
wp(sp),
hash_value(F_Hash()(*sp))
{}
WP(const value_t* ptr):
ptr(ptr),
hash_value(F_Hash()(*ptr))
{}
bool operator == (const WP& w) const noexcept {
const SP sp0 = wp.lock(),
sp1 = w.wp.lock();
const value_t *p0, *p1;
p0 = ptr ? ptr : sp0.get();
p1 = w.ptr ? w.ptr : sp1.get();
if(!p1) {
return F_Cmp()(p0, nullptr);
}
return F_Cmp()(*p0, *p1);
}
};
struct Hash {
std::size_t operator()(const WP& w) const noexcept {
return w.hash_value;
}
};
using Set = std::unordered_set<WP, Hash>;
Set _set;
public:
void gc() {
auto itr = _set.begin();
while(itr != _set.end()) {
if(itr->wp.expired()) {
itr = _set.erase(itr);
} else
++itr;
}
}
template <class V>
SP make(V&& v) {
{
const auto itr = _set.find(WP(&v));
if(itr != _set.end()) {
if(const auto sp = itr->wp.lock())
return sp;
_set.erase(itr);
}
}
SP ret = std::make_shared<const value_t>(std::forward<V>(v));
_set.emplace(WP(ret));
return ret;
}
};
}
<commit_msg>Flyweight: make()の引数がemplace的な引数指定でコンパイルエラーになっていたのを修正<commit_after>#pragma once
#include "lubee/error.hpp"
#include <unordered_set>
#include <memory>
namespace spi {
template <class T, class F_Hash=std::hash<T>, class F_Cmp=std::equal_to<>>
class Flyweight {
private:
using value_t = T;
public:
using SP = std::shared_ptr<const value_t>;
private:
struct WP {
using P = std::weak_ptr<const value_t>;
P wp;
const value_t* ptr = nullptr;
std::size_t hash_value;
WP(const SP& sp):
wp(sp),
hash_value(F_Hash()(*sp))
{}
WP(const value_t* ptr):
ptr(ptr),
hash_value(F_Hash()(*ptr))
{}
bool operator == (const WP& w) const noexcept {
const SP sp0 = wp.lock(),
sp1 = w.wp.lock();
const value_t *p0, *p1;
p0 = ptr ? ptr : sp0.get();
p1 = w.ptr ? w.ptr : sp1.get();
if(!p1) {
return F_Cmp()(p0, nullptr);
}
return F_Cmp()(*p0, *p1);
}
};
struct Hash {
std::size_t operator()(const WP& w) const noexcept {
return w.hash_value;
}
};
using Set = std::unordered_set<WP, Hash>;
Set _set;
public:
void gc() {
auto itr = _set.begin();
while(itr != _set.end()) {
if(itr->wp.expired()) {
itr = _set.erase(itr);
} else
++itr;
}
}
template <
class V,
ENABLE_IF((std::is_same_v<std::decay_t<V>, value_t>))
>
SP make(V&& v) {
{
const auto itr = _set.find(WP(&v));
if(itr != _set.end()) {
if(const auto sp = itr->wp.lock())
return sp;
_set.erase(itr);
}
}
SP ret = std::make_shared<const value_t>(std::forward<V>(v));
_set.emplace(WP(ret));
return ret;
}
template <
class V,
ENABLE_IF(!(std::is_same_v<std::decay_t<V>, value_t>))
>
SP make(V&& v) {
return make(value_t(std::forward<V>(v)));
}
};
}
<|endoftext|> |
<commit_before>/*
* LinkBasedFileLock.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/FileLock.hpp>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <set>
#include <vector>
#include <core/SafeConvert.hpp>
#include <core/Algorithm.hpp>
#include <core/Thread.hpp>
#include <core/Error.hpp>
#include <core/Log.hpp>
#include <core/FilePath.hpp>
#include <core/FileSerializer.hpp>
#include <core/system/Process.hpp>
#include <core/system/System.hpp>
#include <boost/foreach.hpp>
#include <boost/system/error_code.hpp>
#define LOG(__X__) \
do \
{ \
if (::rstudio::core::FileLock::isLoggingEnabled()) \
{ \
std::stringstream ss; \
ss << "(PID " << ::getpid() << "): " << __X__ << std::endl; \
::rstudio::core::FileLock::log(ss.str()); \
} \
} while (0)
namespace rstudio {
namespace core {
namespace {
const char * const kFileLockPrefix =
".rstudio-lock-41c29";
std::string pidString()
{
PidType pid = system::currentProcessId();
return safe_convert::numberToString((long) pid);
}
std::string hostName()
{
char buffer[256];
int status = ::gethostname(buffer, 255);
if (status)
LOG_ERROR(systemError(errno, ERROR_LOCATION));
return std::string(buffer);
}
std::string threadId()
{
std::stringstream ss;
ss << boost::this_thread::get_id();
return ss.str();
}
std::string proxyLockFileName()
{
return std::string()
+ kFileLockPrefix
+ "-" + hostName()
+ "-" + pidString()
+ "-" + threadId();
}
bool isLockFileStale(const FilePath& lockFilePath)
{
return LinkBasedFileLock::isLockFileStale(lockFilePath);
}
bool isLockFileOrphaned(const FilePath& lockFilePath)
{
#ifndef _WIN32
Error error;
// attempt to read pid from lockfile
std::string pid;
error = core::readStringFromFile(lockFilePath, &pid);
if (error)
{
LOG_ERROR(error);
return false;
}
pid = string_utils::trimWhitespace(pid);
#ifdef __linux__
// on linux, we can check the proc filesystem for an associated
// process -- if there is no such directory, then we assume that
// this lockfile has been orphaned
FilePath procPath("/proc/" + pid);
if (!procPath.exists())
return true;
#endif
// call 'ps' to attempt to see if a process associated
// with this process id exists (and get information about it)
using namespace core::system;
std::string command = "ps -p " + pid;
ProcessOptions options;
ProcessResult result;
error = core::system::runCommand(command, options, &result);
if (error)
{
LOG_ERROR(error);
return false;
}
// ps will return a non-zero exit status if no process with
// the requested id is available -- if there is no process,
// then this lockfile has been orphaned
if (result.exitStatus != EXIT_SUCCESS)
return true;
#endif /* _WIN32 */
// assume the process is not orphaned if all previous checks failed
return false;
}
} // end anonymous namespace
bool LinkBasedFileLock::isLockFileStale(const FilePath& lockFilePath)
{
// check for orphaned lockfile
if (isLockFileOrphaned(lockFilePath))
return true;
double seconds = s_timeoutInterval.total_seconds();
double diff = ::difftime(::time(NULL), lockFilePath.lastWriteTime());
return diff >= seconds;
}
namespace {
void cleanStaleLockfiles(const FilePath& dir)
{
std::vector<FilePath> children;
Error error = dir.children(&children);
if (error)
LOG_ERROR(error);
BOOST_FOREACH(const FilePath& filePath, children)
{
if (boost::algorithm::starts_with(filePath.filename(), kFileLockPrefix) &&
isLockFileStale(filePath))
{
Error error = filePath.removeIfExists();
if (error)
LOG_ERROR(error);
}
}
}
class LockRegistration : boost::noncopyable
{
public:
void registerLock(const FilePath& lockFilePath)
{
LOCK_MUTEX(mutex_)
{
registration_.insert(lockFilePath);
}
END_LOCK_MUTEX
}
void deregisterLock(const FilePath& lockFilePath)
{
LOCK_MUTEX(mutex_)
{
registration_.erase(lockFilePath);
}
END_LOCK_MUTEX
}
void refreshLocks()
{
LOCK_MUTEX(mutex_)
{
BOOST_FOREACH(const FilePath& lockFilePath, registration_)
{
LOG("Bumping write time: " << lockFilePath.absolutePath());
lockFilePath.setLastWriteTime();
}
}
END_LOCK_MUTEX
}
void clearLocks()
{
LOCK_MUTEX(mutex_)
{
BOOST_FOREACH(const FilePath& lockFilePath, registration_)
{
Error error = lockFilePath.removeIfExists();
if (error)
LOG_ERROR(error);
LOG("Clearing lock: " << lockFilePath.absolutePath());
}
registration_.clear();
}
END_LOCK_MUTEX
}
private:
boost::mutex mutex_;
std::set<FilePath> registration_;
};
LockRegistration& lockRegistration()
{
static LockRegistration instance;
return instance;
}
Error writeLockFile(const FilePath& lockFilePath)
{
#ifndef _WIN32
// generate proxy lockfile
FilePath proxyPath = lockFilePath.parent().complete(proxyLockFileName());
// since the proxy lockfile should be unique, it should _never_ be possible
// for a collision to be found. if that does happen, it must be a leftover
// from a previous process that crashed in this stage
Error error = proxyPath.removeIfExists();
if (error)
LOG_ERROR(error);
// ensure the proxy file is created, and remove it when we're done
RemoveOnExitScope scope(proxyPath, ERROR_LOCATION);
error = core::writeStringToFile(proxyPath, pidString());
if (error)
{
// log the error since it isn't expected and could get swallowed
// upstream by a caller ignore lock_not_available errors
LOG_ERROR(error);
return error;
}
// attempt to link to the desired location -- ignore return value
// and just stat our original link after, as that's a more reliable
// indicator of success on old NFS systems
int status = ::link(
proxyPath.absolutePathNative().c_str(),
lockFilePath.absolutePathNative().c_str());
// log errors (remove this if it is too noisy on NFS)
if (status == -1)
{
int errorNumber = errno;
// verbose logging
LOG("ERROR: ::link() failed (errno " << errorNumber << ")" << std::endl <<
"Attempted to link:" << std::endl << " - " <<
"'" << proxyPath.absolutePathNative() << "'" <<
" => " <<
"'" << lockFilePath.absolutePathNative() << "'");
LOG_ERROR(systemError(errorNumber, ERROR_LOCATION));
}
struct stat info;
int errc = ::stat(proxyPath.absolutePathNative().c_str(), &info);
if (errc)
{
int errorNumber = errno;
// verbose logging
LOG("ERROR: ::stat() failed (errno " << errorNumber << ")" << std::endl <<
"Attempted to stat:" << std::endl << " - " <<
"'" << proxyPath.absolutePathNative() << "'");
// log the error since it isn't expected and could get swallowed
// upstream by a caller ignoring lock_not_available errors
Error error = systemError(errorNumber, ERROR_LOCATION);
LOG_ERROR(error);
return error;
}
// assume that a failure here is the result of someone else
// acquiring the lock before we could
if (info.st_nlink != 2)
{
LOG("WARNING: Failed to acquire lock (info.st_nlink == " << info.st_nlink << ")");
return fileExistsError(ERROR_LOCATION);
}
return Success();
#else
return systemError(boost::system::errc::function_not_supported, ERROR_LOCATION);
#endif
}
} // end anonymous namespace
struct LinkBasedFileLock::Impl
{
FilePath lockFilePath;
};
LinkBasedFileLock::LinkBasedFileLock()
: pImpl_(new Impl())
{
}
LinkBasedFileLock::~LinkBasedFileLock()
{
}
FilePath LinkBasedFileLock::lockFilePath() const
{
return pImpl_->lockFilePath;
}
bool LinkBasedFileLock::isLocked(const FilePath& lockFilePath) const
{
if (!lockFilePath.exists())
return false;
return !isLockFileStale(lockFilePath);
}
Error LinkBasedFileLock::acquire(const FilePath& lockFilePath)
{
// if the lock file exists...
if (lockFilePath.exists())
{
// ... and it's stale, it's a leftover lock from a previously
// (crashed?) process. remove it and acquire our own lock
if (isLockFileStale(lockFilePath))
{
// note that multiple processes may attempt to remove this
// file at the same time, so errors shouldn't be fatal
LOG("Removing stale lockfile: " << lockFilePath.absolutePath());
Error error = lockFilePath.remove();
if (error)
LOG_ERROR(error);
}
// ... it's not stale -- someone else has the lock, cannot proceed
else
{
LOG("No lock available: " << lockFilePath.absolutePath());
return systemError(boost::system::errc::no_lock_available,
ERROR_LOCATION);
}
}
// ensure the parent directory exists
Error error = lockFilePath.parent().ensureDirectory();
if (error)
return error;
// write the lock file -- this step _must_ be atomic and so only one
// competing process should be able to succeed here
error = writeLockFile(lockFilePath);
if (error)
{
LOG("Failed to acquire lock: " << lockFilePath.absolutePath());
return systemError(boost::system::errc::no_lock_available,
error,
ERROR_LOCATION);
}
// clean any other stale lockfiles in that directory
cleanStaleLockfiles(lockFilePath.parent());
// register our lock (for refresh)
pImpl_->lockFilePath = lockFilePath;
lockRegistration().registerLock(lockFilePath);
LOG("Acquired lock: " << lockFilePath.absolutePath());
return Success();
}
Error LinkBasedFileLock::release()
{
const FilePath& lockFilePath = pImpl_->lockFilePath;
LOG("Released lock: " << lockFilePath.absolutePath());
Error error = lockFilePath.remove();
if (error)
LOG_ERROR(error);
pImpl_->lockFilePath = FilePath();
lockRegistration().deregisterLock(lockFilePath);
return error;
}
void LinkBasedFileLock::refresh()
{
lockRegistration().refreshLocks();
}
void LinkBasedFileLock::cleanUp()
{
lockRegistration().clearLocks();
}
} // namespace core
} // namespace rstudio
<commit_msg>de-register lock before re-assignment<commit_after>/*
* LinkBasedFileLock.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/FileLock.hpp>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <set>
#include <vector>
#include <core/SafeConvert.hpp>
#include <core/Algorithm.hpp>
#include <core/Thread.hpp>
#include <core/Error.hpp>
#include <core/Log.hpp>
#include <core/FilePath.hpp>
#include <core/FileSerializer.hpp>
#include <core/system/Process.hpp>
#include <core/system/System.hpp>
#include <boost/foreach.hpp>
#include <boost/system/error_code.hpp>
#define LOG(__X__) \
do \
{ \
if (::rstudio::core::FileLock::isLoggingEnabled()) \
{ \
std::stringstream ss; \
ss << "(PID " << ::getpid() << "): " << __X__ << std::endl; \
::rstudio::core::FileLock::log(ss.str()); \
} \
} while (0)
namespace rstudio {
namespace core {
namespace {
const char * const kFileLockPrefix =
".rstudio-lock-41c29";
std::string pidString()
{
PidType pid = system::currentProcessId();
return safe_convert::numberToString((long) pid);
}
std::string hostName()
{
char buffer[256];
int status = ::gethostname(buffer, 255);
if (status)
LOG_ERROR(systemError(errno, ERROR_LOCATION));
return std::string(buffer);
}
std::string threadId()
{
std::stringstream ss;
ss << boost::this_thread::get_id();
return ss.str();
}
std::string proxyLockFileName()
{
return std::string()
+ kFileLockPrefix
+ "-" + hostName()
+ "-" + pidString()
+ "-" + threadId();
}
bool isLockFileStale(const FilePath& lockFilePath)
{
return LinkBasedFileLock::isLockFileStale(lockFilePath);
}
bool isLockFileOrphaned(const FilePath& lockFilePath)
{
#ifndef _WIN32
Error error;
// attempt to read pid from lockfile
std::string pid;
error = core::readStringFromFile(lockFilePath, &pid);
if (error)
{
LOG_ERROR(error);
return false;
}
pid = string_utils::trimWhitespace(pid);
#ifdef __linux__
// on linux, we can check the proc filesystem for an associated
// process -- if there is no such directory, then we assume that
// this lockfile has been orphaned
FilePath procPath("/proc/" + pid);
if (!procPath.exists())
return true;
#endif
// call 'ps' to attempt to see if a process associated
// with this process id exists (and get information about it)
using namespace core::system;
std::string command = "ps -p " + pid;
ProcessOptions options;
ProcessResult result;
error = core::system::runCommand(command, options, &result);
if (error)
{
LOG_ERROR(error);
return false;
}
// ps will return a non-zero exit status if no process with
// the requested id is available -- if there is no process,
// then this lockfile has been orphaned
if (result.exitStatus != EXIT_SUCCESS)
return true;
#endif /* _WIN32 */
// assume the process is not orphaned if all previous checks failed
return false;
}
} // end anonymous namespace
bool LinkBasedFileLock::isLockFileStale(const FilePath& lockFilePath)
{
// check for orphaned lockfile
if (isLockFileOrphaned(lockFilePath))
return true;
double seconds = s_timeoutInterval.total_seconds();
double diff = ::difftime(::time(NULL), lockFilePath.lastWriteTime());
return diff >= seconds;
}
namespace {
void cleanStaleLockfiles(const FilePath& dir)
{
std::vector<FilePath> children;
Error error = dir.children(&children);
if (error)
LOG_ERROR(error);
BOOST_FOREACH(const FilePath& filePath, children)
{
if (boost::algorithm::starts_with(filePath.filename(), kFileLockPrefix) &&
isLockFileStale(filePath))
{
Error error = filePath.removeIfExists();
if (error)
LOG_ERROR(error);
}
}
}
class LockRegistration : boost::noncopyable
{
public:
void registerLock(const FilePath& lockFilePath)
{
LOCK_MUTEX(mutex_)
{
registration_.insert(lockFilePath);
}
END_LOCK_MUTEX
}
void deregisterLock(const FilePath& lockFilePath)
{
LOCK_MUTEX(mutex_)
{
registration_.erase(lockFilePath);
}
END_LOCK_MUTEX
}
void refreshLocks()
{
LOCK_MUTEX(mutex_)
{
BOOST_FOREACH(const FilePath& lockFilePath, registration_)
{
LOG("Bumping write time: " << lockFilePath.absolutePath());
lockFilePath.setLastWriteTime();
}
}
END_LOCK_MUTEX
}
void clearLocks()
{
LOCK_MUTEX(mutex_)
{
BOOST_FOREACH(const FilePath& lockFilePath, registration_)
{
Error error = lockFilePath.removeIfExists();
if (error)
LOG_ERROR(error);
LOG("Clearing lock: " << lockFilePath.absolutePath());
}
registration_.clear();
}
END_LOCK_MUTEX
}
private:
boost::mutex mutex_;
std::set<FilePath> registration_;
};
LockRegistration& lockRegistration()
{
static LockRegistration instance;
return instance;
}
Error writeLockFile(const FilePath& lockFilePath)
{
#ifndef _WIN32
// generate proxy lockfile
FilePath proxyPath = lockFilePath.parent().complete(proxyLockFileName());
// since the proxy lockfile should be unique, it should _never_ be possible
// for a collision to be found. if that does happen, it must be a leftover
// from a previous process that crashed in this stage
Error error = proxyPath.removeIfExists();
if (error)
LOG_ERROR(error);
// ensure the proxy file is created, and remove it when we're done
RemoveOnExitScope scope(proxyPath, ERROR_LOCATION);
error = core::writeStringToFile(proxyPath, pidString());
if (error)
{
// log the error since it isn't expected and could get swallowed
// upstream by a caller ignore lock_not_available errors
LOG_ERROR(error);
return error;
}
// attempt to link to the desired location -- ignore return value
// and just stat our original link after, as that's a more reliable
// indicator of success on old NFS systems
int status = ::link(
proxyPath.absolutePathNative().c_str(),
lockFilePath.absolutePathNative().c_str());
// log errors (remove this if it is too noisy on NFS)
if (status == -1)
{
int errorNumber = errno;
// verbose logging
LOG("ERROR: ::link() failed (errno " << errorNumber << ")" << std::endl <<
"Attempted to link:" << std::endl << " - " <<
"'" << proxyPath.absolutePathNative() << "'" <<
" => " <<
"'" << lockFilePath.absolutePathNative() << "'");
LOG_ERROR(systemError(errorNumber, ERROR_LOCATION));
}
struct stat info;
int errc = ::stat(proxyPath.absolutePathNative().c_str(), &info);
if (errc)
{
int errorNumber = errno;
// verbose logging
LOG("ERROR: ::stat() failed (errno " << errorNumber << ")" << std::endl <<
"Attempted to stat:" << std::endl << " - " <<
"'" << proxyPath.absolutePathNative() << "'");
// log the error since it isn't expected and could get swallowed
// upstream by a caller ignoring lock_not_available errors
Error error = systemError(errorNumber, ERROR_LOCATION);
LOG_ERROR(error);
return error;
}
// assume that a failure here is the result of someone else
// acquiring the lock before we could
if (info.st_nlink != 2)
{
LOG("WARNING: Failed to acquire lock (info.st_nlink == " << info.st_nlink << ")");
return fileExistsError(ERROR_LOCATION);
}
return Success();
#else
return systemError(boost::system::errc::function_not_supported, ERROR_LOCATION);
#endif
}
} // end anonymous namespace
struct LinkBasedFileLock::Impl
{
FilePath lockFilePath;
};
LinkBasedFileLock::LinkBasedFileLock()
: pImpl_(new Impl())
{
}
LinkBasedFileLock::~LinkBasedFileLock()
{
}
FilePath LinkBasedFileLock::lockFilePath() const
{
return pImpl_->lockFilePath;
}
bool LinkBasedFileLock::isLocked(const FilePath& lockFilePath) const
{
if (!lockFilePath.exists())
return false;
return !isLockFileStale(lockFilePath);
}
Error LinkBasedFileLock::acquire(const FilePath& lockFilePath)
{
// if the lock file exists...
if (lockFilePath.exists())
{
// ... and it's stale, it's a leftover lock from a previously
// (crashed?) process. remove it and acquire our own lock
if (isLockFileStale(lockFilePath))
{
// note that multiple processes may attempt to remove this
// file at the same time, so errors shouldn't be fatal
LOG("Removing stale lockfile: " << lockFilePath.absolutePath());
Error error = lockFilePath.remove();
if (error)
LOG_ERROR(error);
}
// ... it's not stale -- someone else has the lock, cannot proceed
else
{
LOG("No lock available: " << lockFilePath.absolutePath());
return systemError(boost::system::errc::no_lock_available,
ERROR_LOCATION);
}
}
// ensure the parent directory exists
Error error = lockFilePath.parent().ensureDirectory();
if (error)
return error;
// write the lock file -- this step _must_ be atomic and so only one
// competing process should be able to succeed here
error = writeLockFile(lockFilePath);
if (error)
{
LOG("Failed to acquire lock: " << lockFilePath.absolutePath());
return systemError(boost::system::errc::no_lock_available,
error,
ERROR_LOCATION);
}
// clean any other stale lockfiles in that directory
cleanStaleLockfiles(lockFilePath.parent());
// register our lock (for refresh)
pImpl_->lockFilePath = lockFilePath;
lockRegistration().registerLock(lockFilePath);
LOG("Acquired lock: " << lockFilePath.absolutePath());
return Success();
}
Error LinkBasedFileLock::release()
{
const FilePath& lockFilePath = pImpl_->lockFilePath;
LOG("Released lock: " << lockFilePath.absolutePath());
Error error = lockFilePath.remove();
if (error)
LOG_ERROR(error);
lockRegistration().deregisterLock(lockFilePath);
pImpl_->lockFilePath = FilePath();
return error;
}
void LinkBasedFileLock::refresh()
{
lockRegistration().refreshLocks();
}
void LinkBasedFileLock::cleanUp()
{
lockRegistration().clearLocks();
}
} // namespace core
} // namespace rstudio
<|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.
*
*/
#ifndef PCL_SEARCH_IMPL_BRUTE_FORCE_SEARCH_H_
#define PCL_SEARCH_IMPL_BRUTE_FORCE_SEARCH_H_
#include "pcl/search/brute_force.h"
#include <queue>
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> float
pcl::search::BruteForce<PointT>::getDistSqr (
const PointT& point1, const PointT& point2) const
{
return (point1.getVector3fMap () - point2.getVector3fMap ()).squaredNorm ();
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> int
pcl::search::BruteForce<PointT>::nearestKSearch (
const PointT& point, int k, std::vector<int>& k_indices, std::vector<float>& k_distances) const
{
k_indices.clear ();
k_distances.clear ();
if (!pcl_isfinite (point.x) || k < 1)
return 0;
if (input_->is_dense)
return denseKSearch (point, k, k_indices, k_distances);
else
return sparseKSearch (point, k, k_indices, k_distances);
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> int
pcl::search::BruteForce<PointT>::denseKSearch (
const PointT &point, int k, std::vector<int> &k_indices, std::vector<float> &k_distances) const
{
// container for first k elements -> O(1) for insertion, since order not required here
std::vector<Entry> result;
result.reserve (k);
std::priority_queue<Entry> queue;
if (indices_ != NULL)
{
std::vector<int>::const_iterator iIt =indices_->begin ();
std::vector<int>::const_iterator iEnd = indices_->begin () + std::min ((unsigned) k, (unsigned) input_->size ());
for (; iIt != iEnd; ++iIt)
result.push_back (Entry (*iIt, getDistSqr (input_->points[*iIt], point)));
queue = std::priority_queue<Entry> (result.begin (), result.end ());
// add the rest
Entry entry;
for (; iIt != indices_->end (); ++iIt)
{
entry.distance = getDistSqr (input_->points[*iIt], point);
if (queue.top ().distance > entry.distance)
{
entry.index = *iIt;
queue.pop ();
queue.push (entry);
}
}
}
else
{
Entry entry;
for (entry.index = 0; entry.index < std::min ((unsigned) k, (unsigned) input_->size ()); ++entry.index)
{
entry.distance = getDistSqr (input_->points[entry.index], point);
result.push_back (entry);
}
queue = std::priority_queue<Entry> (result.begin (), result.end ());
// add the rest
for (; entry.index < input_->size (); ++entry.index)
{
entry.distance = getDistSqr (input_->points[entry.index], point);
if (queue.top ().distance > entry.distance)
{
queue.pop ();
queue.push (entry);
}
}
}
k_indices.resize (queue.size ());
k_distances.resize (queue.size ());
int idx = queue.size () - 1;
while (!queue.empty ())
{
k_indices [idx] = queue.top ().index;
k_distances [idx] = queue.top ().distance;
queue.pop ();
--idx;
}
return k_indices.size ();
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> int
pcl::search::BruteForce<PointT>::sparseKSearch (
const PointT &point, int k, std::vector<int> &k_indices, std::vector<float> &k_distances) const
{
// result used to collect the first k neighbors -> unordered
std::vector<Entry> result;
result.reserve (k);
std::priority_queue<Entry> queue;
if (indices_ != NULL)
{
std::vector<int>::const_iterator iIt =indices_->begin ();
for (; iIt != indices_->end () && result.size () < (unsigned) k; ++iIt)
{
if (pcl_isfinite (input_->points[*iIt].x))
result.push_back (Entry (*iIt, getDistSqr (input_->points[*iIt], point)));
}
queue = std::priority_queue<Entry> (result.begin (), result.end ());
// either we have k elements, or there are none left to iterate >in either case we're fine
// add the rest
Entry entry;
for (; iIt != indices_->end (); ++iIt)
{
if (!pcl_isfinite (input_->points[*iIt].x))
continue;
entry.distance = getDistSqr (input_->points[*iIt], point);
if (queue.top ().distance > entry.distance)
{
entry.index = *iIt;
queue.pop ();
queue.push (entry);
}
}
}
else
{
Entry entry;
for (entry.index = 0; entry.index < input_->size () && result.size () < (unsigned)k; ++entry.index)
{
if (pcl_isfinite (input_->points[entry.index].x))
{
entry.distance = getDistSqr (input_->points[entry.index], point);
result.push_back (entry);
}
}
queue = std::priority_queue<Entry> (result.begin (), result.end ());
// add the rest
for (; entry.index < input_->size (); ++entry.index)
{
if (!pcl_isfinite (input_->points[entry.index].x))
continue;
entry.distance = getDistSqr (input_->points[entry.index], point);
if (queue.top ().distance > entry.distance)
{
queue.pop ();
queue.push (entry);
}
}
}
k_indices.resize (queue.size ());
k_distances.resize (queue.size ());
int idx = queue.size () - 1;
while (!queue.empty ())
{
k_indices [idx] = queue.top ().index;
k_distances [idx] = queue.top ().distance;
queue.pop ();
--idx;
}
return k_indices.size ();
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> int
pcl::search::BruteForce<PointT>::denseRadiusSearch (
const PointT& point, double radius,
std::vector<int> &k_indices, std::vector<float> &k_sqr_distances,
unsigned int max_nn) const
{
radius *= radius;
int reserve = max_nn;
if (reserve == 0)
{
if (indices_ != NULL)
reserve = std::min (indices_->size (), input_->size ());
else
reserve = input_->size ();
}
k_indices.reserve (reserve);
k_sqr_distances.reserve (reserve);
float distance;
if (indices_ != NULL)
{
for (std::vector<int>::const_iterator iIt =indices_->begin (); iIt != indices_->end (); ++iIt)
{
distance = getDistSqr (input_->points[*iIt], point);
if (distance <= radius)
{
k_indices.push_back (*iIt);
k_sqr_distances.push_back (distance);
if (k_indices.size () == max_nn) // max_nn = 0 -> never true
break;
}
}
}
else
{
for (unsigned index = 0; index < input_->size (); ++index)
{
distance = getDistSqr (input_->points[index], point);
if (distance < radius)
{
k_indices.push_back (index);
k_sqr_distances.push_back (distance);
if (k_indices.size () == max_nn) // never true if max_nn = 0
break;
}
}
}
if (sorted_results_)
this->sortResults (k_indices, k_sqr_distances);
return k_indices.size ();
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> int
pcl::search::BruteForce<PointT>::sparseRadiusSearch (
const PointT& point, double radius,
std::vector<int> &k_indices, std::vector<float> &k_sqr_distances,
unsigned int max_nn) const
{
radius *= radius;
int reserve = max_nn;
if (reserve == 0)
{
if (indices_ != NULL)
reserve = std::min (indices_->size (), input_->size ());
else
reserve = input_->size ();
}
k_indices.reserve (reserve);
k_sqr_distances.reserve (reserve);
float distance;
if (indices_ != NULL)
{
for (std::vector<int>::const_iterator iIt =indices_->begin (); iIt != indices_->end (); ++iIt)
{
if (!pcl_isfinite (input_->points[*iIt].x))
continue;
distance = getDistSqr (input_->points[*iIt], point);
if (distance <= radius)
{
k_indices.push_back (*iIt);
k_sqr_distances.push_back (distance);
if (k_indices.size () == max_nn) // never true if max_nn = 0
break;
}
}
}
else
{
for (unsigned index = 0; index < input_->size (); ++index)
{
if (!pcl_isfinite (input_->points[index].x))
continue;
distance = getDistSqr (input_->points[index], point);
if (distance < radius)
{
k_indices.push_back (index);
k_sqr_distances.push_back (distance);
if (k_indices.size () == max_nn) // never true if max_nn = 0
break;
}
}
}
if (sorted_results_)
this->sortResults (k_indices, k_sqr_distances);
return k_indices.size ();
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> int
pcl::search::BruteForce<PointT>::radiusSearch (
const PointT& point, double radius, std::vector<int> &k_indices,
std::vector<float> &k_sqr_distances, unsigned int max_nn) const
{
k_indices.clear ();
k_sqr_distances.clear ();
if (!pcl_isfinite (point.x) || radius <= 0)
return 0;
if (input_->is_dense)
return denseRadiusSearch (point, radius, k_indices, k_sqr_distances, max_nn);
else
return sparseRadiusSearch (point, radius, k_indices, k_sqr_distances, max_nn);
}
#define PCL_INSTANTIATE_BruteForce(T) template class PCL_EXPORTS pcl::search::BruteForce<T>;
#endif //PCL_SEARCH_IMPL_BRUTE_FORCE_SEARCH_H_
<commit_msg>fix a crash in BruteForce<PointT>::denseKSearch<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.
*
*/
#ifndef PCL_SEARCH_IMPL_BRUTE_FORCE_SEARCH_H_
#define PCL_SEARCH_IMPL_BRUTE_FORCE_SEARCH_H_
#include "pcl/search/brute_force.h"
#include <queue>
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> float
pcl::search::BruteForce<PointT>::getDistSqr (
const PointT& point1, const PointT& point2) const
{
return (point1.getVector3fMap () - point2.getVector3fMap ()).squaredNorm ();
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> int
pcl::search::BruteForce<PointT>::nearestKSearch (
const PointT& point, int k, std::vector<int>& k_indices, std::vector<float>& k_distances) const
{
k_indices.clear ();
k_distances.clear ();
if (!pcl_isfinite (point.x) || k < 1)
return 0;
if (input_->is_dense)
return denseKSearch (point, k, k_indices, k_distances);
else
return sparseKSearch (point, k, k_indices, k_distances);
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> int
pcl::search::BruteForce<PointT>::denseKSearch (
const PointT &point, int k, std::vector<int> &k_indices, std::vector<float> &k_distances) const
{
// container for first k elements -> O(1) for insertion, since order not required here
std::vector<Entry> result;
result.reserve (k);
std::priority_queue<Entry> queue;
if (indices_ != NULL)
{
std::vector<int>::const_iterator iIt =indices_->begin ();
std::vector<int>::const_iterator iEnd = indices_->begin () + std::min ((unsigned) k, (unsigned) indices_->size ());
for (; iIt != iEnd; ++iIt)
result.push_back (Entry (*iIt, getDistSqr (input_->points[*iIt], point)));
queue = std::priority_queue<Entry> (result.begin (), result.end ());
// add the rest
Entry entry;
for (; iIt != indices_->end (); ++iIt)
{
entry.distance = getDistSqr (input_->points[*iIt], point);
if (queue.top ().distance > entry.distance)
{
entry.index = *iIt;
queue.pop ();
queue.push (entry);
}
}
}
else
{
Entry entry;
for (entry.index = 0; entry.index < std::min ((unsigned) k, (unsigned) input_->size ()); ++entry.index)
{
entry.distance = getDistSqr (input_->points[entry.index], point);
result.push_back (entry);
}
queue = std::priority_queue<Entry> (result.begin (), result.end ());
// add the rest
for (; entry.index < input_->size (); ++entry.index)
{
entry.distance = getDistSqr (input_->points[entry.index], point);
if (queue.top ().distance > entry.distance)
{
queue.pop ();
queue.push (entry);
}
}
}
k_indices.resize (queue.size ());
k_distances.resize (queue.size ());
int idx = queue.size () - 1;
while (!queue.empty ())
{
k_indices [idx] = queue.top ().index;
k_distances [idx] = queue.top ().distance;
queue.pop ();
--idx;
}
return k_indices.size ();
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> int
pcl::search::BruteForce<PointT>::sparseKSearch (
const PointT &point, int k, std::vector<int> &k_indices, std::vector<float> &k_distances) const
{
// result used to collect the first k neighbors -> unordered
std::vector<Entry> result;
result.reserve (k);
std::priority_queue<Entry> queue;
if (indices_ != NULL)
{
std::vector<int>::const_iterator iIt =indices_->begin ();
for (; iIt != indices_->end () && result.size () < (unsigned) k; ++iIt)
{
if (pcl_isfinite (input_->points[*iIt].x))
result.push_back (Entry (*iIt, getDistSqr (input_->points[*iIt], point)));
}
queue = std::priority_queue<Entry> (result.begin (), result.end ());
// either we have k elements, or there are none left to iterate >in either case we're fine
// add the rest
Entry entry;
for (; iIt != indices_->end (); ++iIt)
{
if (!pcl_isfinite (input_->points[*iIt].x))
continue;
entry.distance = getDistSqr (input_->points[*iIt], point);
if (queue.top ().distance > entry.distance)
{
entry.index = *iIt;
queue.pop ();
queue.push (entry);
}
}
}
else
{
Entry entry;
for (entry.index = 0; entry.index < input_->size () && result.size () < (unsigned)k; ++entry.index)
{
if (pcl_isfinite (input_->points[entry.index].x))
{
entry.distance = getDistSqr (input_->points[entry.index], point);
result.push_back (entry);
}
}
queue = std::priority_queue<Entry> (result.begin (), result.end ());
// add the rest
for (; entry.index < input_->size (); ++entry.index)
{
if (!pcl_isfinite (input_->points[entry.index].x))
continue;
entry.distance = getDistSqr (input_->points[entry.index], point);
if (queue.top ().distance > entry.distance)
{
queue.pop ();
queue.push (entry);
}
}
}
k_indices.resize (queue.size ());
k_distances.resize (queue.size ());
int idx = queue.size () - 1;
while (!queue.empty ())
{
k_indices [idx] = queue.top ().index;
k_distances [idx] = queue.top ().distance;
queue.pop ();
--idx;
}
return k_indices.size ();
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> int
pcl::search::BruteForce<PointT>::denseRadiusSearch (
const PointT& point, double radius,
std::vector<int> &k_indices, std::vector<float> &k_sqr_distances,
unsigned int max_nn) const
{
radius *= radius;
int reserve = max_nn;
if (reserve == 0)
{
if (indices_ != NULL)
reserve = std::min (indices_->size (), input_->size ());
else
reserve = input_->size ();
}
k_indices.reserve (reserve);
k_sqr_distances.reserve (reserve);
float distance;
if (indices_ != NULL)
{
for (std::vector<int>::const_iterator iIt =indices_->begin (); iIt != indices_->end (); ++iIt)
{
distance = getDistSqr (input_->points[*iIt], point);
if (distance <= radius)
{
k_indices.push_back (*iIt);
k_sqr_distances.push_back (distance);
if (k_indices.size () == max_nn) // max_nn = 0 -> never true
break;
}
}
}
else
{
for (unsigned index = 0; index < input_->size (); ++index)
{
distance = getDistSqr (input_->points[index], point);
if (distance < radius)
{
k_indices.push_back (index);
k_sqr_distances.push_back (distance);
if (k_indices.size () == max_nn) // never true if max_nn = 0
break;
}
}
}
if (sorted_results_)
this->sortResults (k_indices, k_sqr_distances);
return k_indices.size ();
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> int
pcl::search::BruteForce<PointT>::sparseRadiusSearch (
const PointT& point, double radius,
std::vector<int> &k_indices, std::vector<float> &k_sqr_distances,
unsigned int max_nn) const
{
radius *= radius;
int reserve = max_nn;
if (reserve == 0)
{
if (indices_ != NULL)
reserve = std::min (indices_->size (), input_->size ());
else
reserve = input_->size ();
}
k_indices.reserve (reserve);
k_sqr_distances.reserve (reserve);
float distance;
if (indices_ != NULL)
{
for (std::vector<int>::const_iterator iIt =indices_->begin (); iIt != indices_->end (); ++iIt)
{
if (!pcl_isfinite (input_->points[*iIt].x))
continue;
distance = getDistSqr (input_->points[*iIt], point);
if (distance <= radius)
{
k_indices.push_back (*iIt);
k_sqr_distances.push_back (distance);
if (k_indices.size () == max_nn) // never true if max_nn = 0
break;
}
}
}
else
{
for (unsigned index = 0; index < input_->size (); ++index)
{
if (!pcl_isfinite (input_->points[index].x))
continue;
distance = getDistSqr (input_->points[index], point);
if (distance < radius)
{
k_indices.push_back (index);
k_sqr_distances.push_back (distance);
if (k_indices.size () == max_nn) // never true if max_nn = 0
break;
}
}
}
if (sorted_results_)
this->sortResults (k_indices, k_sqr_distances);
return k_indices.size ();
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> int
pcl::search::BruteForce<PointT>::radiusSearch (
const PointT& point, double radius, std::vector<int> &k_indices,
std::vector<float> &k_sqr_distances, unsigned int max_nn) const
{
k_indices.clear ();
k_sqr_distances.clear ();
if (!pcl_isfinite (point.x) || radius <= 0)
return 0;
if (input_->is_dense)
return denseRadiusSearch (point, radius, k_indices, k_sqr_distances, max_nn);
else
return sparseRadiusSearch (point, radius, k_indices, k_sqr_distances, max_nn);
}
#define PCL_INSTANTIATE_BruteForce(T) template class PCL_EXPORTS pcl::search::BruteForce<T>;
#endif //PCL_SEARCH_IMPL_BRUTE_FORCE_SEARCH_H_
<|endoftext|> |
<commit_before>/**
* \file
* \brief SerialPort class implementation
*
* \author Copyright (C) 2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "distortos/devices/communication/SerialPort.hpp"
#include "distortos/internal/devices/UartLowLevel.hpp"
#include "distortos/architecture/InterruptMaskingLock.hpp"
#include "distortos/Semaphore.hpp"
#include "estd/ScopeGuard.hpp"
#include <cerrno>
#include <cstring>
namespace distortos
{
namespace devices
{
namespace
{
/*---------------------------------------------------------------------------------------------------------------------+
| local functions
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief Reads data from circular buffer.
*
* \param [in] circularBuffer is a reference to circular buffer from which the data will be read
* \param [out] buffer is a buffer to which the data will be written
* \param [in] size is the size of \a buffer, bytes
*
* \return number of bytes read from \a circularBuffer and written to \a buffer
*/
size_t readFromCircularBuffer(SerialPort::CircularBuffer& circularBuffer, uint8_t* const buffer, const size_t size)
{
decltype(circularBuffer.getReadBlock()) readBlock;
size_t bytesRead {};
while (readBlock = circularBuffer.getReadBlock(), readBlock.second != 0 && bytesRead != size)
{
const auto copySize = std::min(readBlock.second, size - bytesRead);
memcpy(buffer + bytesRead, readBlock.first, copySize);
circularBuffer.increaseReadPosition(copySize);
bytesRead += copySize;
}
return bytesRead;
}
/**
* \brief Writes data to circular buffer.
*
* \param [in] buffer is a buffer from which the data will be read
* \param [in] size is the size of \a buffer, bytes
* \param [in] circularBuffer is a reference to circular buffer to which the data will be written
*
* \return number of bytes read from \a buffer and written to \a circularBuffer
*/
size_t writeToCircularBuffer(const uint8_t* const buffer, const size_t size, SerialPort::CircularBuffer& circularBuffer)
{
decltype(circularBuffer.getWriteBlock()) writeBlock;
size_t bytesWritten {};
while (writeBlock = circularBuffer.getWriteBlock(), writeBlock.second != 0 && bytesWritten != size)
{
const auto copySize = std::min(writeBlock.second, size - bytesWritten);
memcpy(writeBlock.first, buffer + bytesWritten, copySize);
circularBuffer.increaseWritePosition(copySize);
bytesWritten += copySize;
}
return bytesWritten;
}
} // namespace
/*---------------------------------------------------------------------------------------------------------------------+
| SerialPort::CircularBuffer public functions
+---------------------------------------------------------------------------------------------------------------------*/
std::pair<const uint8_t*, size_t> SerialPort::CircularBuffer::getReadBlock() const
{
const auto readPosition = readPosition_;
const auto writePosition = writePosition_;
return {buffer_ + readPosition, (writePosition >= readPosition ? writePosition : size_) - readPosition};
}
std::pair<uint8_t*, size_t> SerialPort::CircularBuffer::getWriteBlock() const
{
const auto readPosition = readPosition_;
const auto writePosition = writePosition_;
const auto freeBytes = (readPosition > writePosition ? readPosition - writePosition :
size_ - writePosition + readPosition) - 2;
const auto writeBlockSize = (readPosition > writePosition ? readPosition : size_) - writePosition;
return {buffer_ + writePosition, std::min(freeBytes, writeBlockSize)};
}
/*---------------------------------------------------------------------------------------------------------------------+
| public functions
+---------------------------------------------------------------------------------------------------------------------*/
SerialPort::~SerialPort()
{
if (openCount_ == 0)
return;
readMutex_.lock();
writeMutex_.lock();
const auto readWriteMutexScopeGuard = estd::makeScopeGuard(
[this]()
{
writeMutex_.unlock();
readMutex_.unlock();
});
uart_.stopRead();
uart_.stopWrite();
uart_.stop();
}
int SerialPort::close()
{
readMutex_.lock();
writeMutex_.lock();
const auto readWriteMutexScopeGuard = estd::makeScopeGuard(
[this]()
{
writeMutex_.unlock();
readMutex_.unlock();
});
if (openCount_ == 0) // device is not open anymore?
return EBADF;
if (openCount_ == 1) // last close?
{
while (transmitInProgress_ == true) // wait for physical end of write operation
{
Semaphore semaphore {0};
transmitSemaphore_ = &semaphore;
const auto transmitSemaphoreScopeGuard = estd::makeScopeGuard(
[this]()
{
transmitSemaphore_ = {};
});
if (transmitInProgress_ == true)
{
const auto ret = semaphore.wait();
if (ret != 0)
return ret;
}
}
uart_.stopRead();
const auto ret = uart_.stop();
if (ret != 0)
return ret;
readBuffer_.clear();
writeBuffer_.clear();
}
--openCount_;
return 0;
}
int SerialPort::open(const uint32_t baudRate, const uint8_t characterLength, const devices::UartParity parity,
const bool _2StopBits)
{
readMutex_.lock();
writeMutex_.lock();
const auto readWriteMutexScopeGuard = estd::makeScopeGuard(
[this]()
{
writeMutex_.unlock();
readMutex_.unlock();
});
if (openCount_ == std::numeric_limits<decltype(openCount_)>::max()) // device is already opened too many times?
return EMFILE;
if (openCount_ == 0) // first open?
{
if (readBuffer_.getCapacity() < 2 || writeBuffer_.getCapacity() < 2)
return ENOBUFS;
{
const auto ret = uart_.start(*this, baudRate, characterLength, parity, _2StopBits);
if (ret.first != 0)
return ret.first;
}
{
const auto ret = startReadWrapper(SIZE_MAX);
if (ret != 0)
return ret;
}
baudRate_ = baudRate;
characterLength_ = characterLength;
parity_ = parity;
_2StopBits_ = _2StopBits;
}
else // if (openCount_ != 0)
{
// provided arguments don't match current configuration of already opened device?
if (baudRate_ != baudRate || characterLength_ != characterLength || parity_ != parity ||
_2StopBits_ != _2StopBits)
return EINVAL;
}
++openCount_;
return 0;
}
std::pair<int, size_t> SerialPort::read(void* const buffer, const size_t size)
{
if (buffer == nullptr || size == 0)
return {EINVAL, {}};
readMutex_.lock();
const auto readMutexScopeGuard = estd::makeScopeGuard(
[this]()
{
readMutex_.unlock();
});
if (openCount_ == 0)
return {EBADF, {}};
if (characterLength_ > 8 && size % 2 != 0)
return {EINVAL, {}};
const size_t minSize = characterLength_ <= 8 ? 1 : 2;
const auto bufferUint8 = static_cast<uint8_t*>(buffer);
size_t bytesRead {};
while (bytesRead < minSize)
{
bytesRead += readFromCircularBuffer(readBuffer_, bufferUint8 + bytesRead, size - bytesRead);
if (bytesRead == size) // buffer already full?
return {{}, bytesRead};
Semaphore semaphore {0};
readSemaphore_ = &semaphore;
const auto readSemaphoreScopeGuard = estd::makeScopeGuard(
[this]()
{
readSemaphore_ = {};
});
{
// stop and restart the read operation to get the characters that were already received
architecture::InterruptMaskingLock interruptMaskingLock;
const auto bytesReceived = uart_.stopRead();
readBuffer_.increaseWritePosition(bytesReceived);
// limit of new read operation is selected to have a notification when requested minimum will be received
const auto ret = startReadWrapper(minSize > bytesRead + bytesReceived ?
minSize - bytesRead - bytesReceived : SIZE_MAX);
if (ret != 0)
return {ret, bytesRead};
}
bytesRead += readFromCircularBuffer(readBuffer_, bufferUint8 + bytesRead, size - bytesRead);
if (bytesRead < minSize) // wait for data only if requested minimum is not already read
{
const auto ret = semaphore.wait();
if (ret != 0)
return {ret, bytesRead};
}
}
return {{}, bytesRead};
}
std::pair<int, size_t> SerialPort::write(const void* const buffer, const size_t size)
{
if (buffer == nullptr || size == 0)
return {EINVAL, {}};
writeMutex_.lock();
const auto writeMutexScopeGuard = estd::makeScopeGuard(
[this]()
{
writeMutex_.unlock();
});
if (openCount_ == 0)
return {EBADF, {}};
if (characterLength_ > 8 && size % 2 != 0)
return {EINVAL, {}};
const auto bufferUint8 = static_cast<const uint8_t*>(buffer);
size_t bytesWritten {};
while (bytesWritten < size)
{
Semaphore semaphore {0};
writeSemaphore_ = &semaphore;
const auto writeSemaphoreScopeGuard = estd::makeScopeGuard(
[this]()
{
writeSemaphore_ = {};
});
bytesWritten += writeToCircularBuffer(bufferUint8 + bytesWritten, size - bytesWritten, writeBuffer_);
// restart write operation if it is not currently in progress and the write buffer is not already empty
if (writeInProgress_ == false && writeBuffer_.isEmpty() == false)
{
const auto ret = startWriteWrapper();
if (ret != 0)
return {ret, bytesWritten};
}
// wait for free space only if write operation is in progress and there is still some data left to write
else if (bytesWritten != size)
{
const auto ret = semaphore.wait();
if (ret != 0)
return {ret, bytesWritten};
}
}
return {{}, bytesWritten};
}
/*---------------------------------------------------------------------------------------------------------------------+
| private functions
+---------------------------------------------------------------------------------------------------------------------*/
void SerialPort::readCompleteEvent(const size_t bytesRead)
{
readBuffer_.increaseWritePosition(bytesRead);
if (readSemaphore_ != nullptr)
{
readSemaphore_->post();
readSemaphore_ = {};
}
if (readBuffer_.isFull() == true)
return;
startReadWrapper(SIZE_MAX);
}
void SerialPort::receiveErrorEvent(ErrorSet)
{
}
int SerialPort::startReadWrapper(const size_t limit)
{
const auto writeBlock = readBuffer_.getWriteBlock();
const auto readBufferHalf = ((readBuffer_.getSize() / 2) / 2) * 2;
return uart_.startRead(writeBlock.first, std::min({writeBlock.second, readBufferHalf, limit}));
}
int SerialPort::startWriteWrapper()
{
if (writeInProgress_ == true || writeBuffer_.isEmpty() == true)
return 0;
transmitInProgress_ = true;
writeInProgress_ = true;
const auto readBlock = writeBuffer_.getReadBlock();
const auto writeBufferHalf = ((writeBuffer_.getSize() / 2) / 2) * 2;
const auto writeLimit = writeLimit_;
return uart_.startWrite(readBlock.first,
std::min({readBlock.second, writeBufferHalf, writeLimit != 0 ? writeLimit : SIZE_MAX}));
}
size_t SerialPort::stopWriteWrapper()
{
const auto bytesWritten = uart_.stopWrite();
writeBuffer_.increaseReadPosition(bytesWritten);
const auto writeLimit = writeLimit_;
writeLimit_ = writeLimit - (bytesWritten < writeLimit ? bytesWritten : writeLimit);
writeInProgress_ = false;
return bytesWritten;
}
void SerialPort::transmitCompleteEvent()
{
if (transmitSemaphore_ != nullptr)
{
transmitSemaphore_->post();
transmitSemaphore_ = {};
}
transmitInProgress_ = false;
}
void SerialPort::writeCompleteEvent(const size_t bytesWritten)
{
writeBuffer_.increaseReadPosition(bytesWritten);
const auto writeLimit = writeLimit_;
writeLimit_ = writeLimit - (bytesWritten < writeLimit ? bytesWritten : writeLimit);
writeInProgress_ = false;
if (writeSemaphore_ != nullptr)
{
writeSemaphore_->post();
writeSemaphore_ = {};
}
startWriteWrapper();
}
} // namespace devices
} // namespace distortos
<commit_msg>Use CircularBuffer::getCapacity() in SerialPort::startReadWrapper()<commit_after>/**
* \file
* \brief SerialPort class implementation
*
* \author Copyright (C) 2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "distortos/devices/communication/SerialPort.hpp"
#include "distortos/internal/devices/UartLowLevel.hpp"
#include "distortos/architecture/InterruptMaskingLock.hpp"
#include "distortos/Semaphore.hpp"
#include "estd/ScopeGuard.hpp"
#include <cerrno>
#include <cstring>
namespace distortos
{
namespace devices
{
namespace
{
/*---------------------------------------------------------------------------------------------------------------------+
| local functions
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief Reads data from circular buffer.
*
* \param [in] circularBuffer is a reference to circular buffer from which the data will be read
* \param [out] buffer is a buffer to which the data will be written
* \param [in] size is the size of \a buffer, bytes
*
* \return number of bytes read from \a circularBuffer and written to \a buffer
*/
size_t readFromCircularBuffer(SerialPort::CircularBuffer& circularBuffer, uint8_t* const buffer, const size_t size)
{
decltype(circularBuffer.getReadBlock()) readBlock;
size_t bytesRead {};
while (readBlock = circularBuffer.getReadBlock(), readBlock.second != 0 && bytesRead != size)
{
const auto copySize = std::min(readBlock.second, size - bytesRead);
memcpy(buffer + bytesRead, readBlock.first, copySize);
circularBuffer.increaseReadPosition(copySize);
bytesRead += copySize;
}
return bytesRead;
}
/**
* \brief Writes data to circular buffer.
*
* \param [in] buffer is a buffer from which the data will be read
* \param [in] size is the size of \a buffer, bytes
* \param [in] circularBuffer is a reference to circular buffer to which the data will be written
*
* \return number of bytes read from \a buffer and written to \a circularBuffer
*/
size_t writeToCircularBuffer(const uint8_t* const buffer, const size_t size, SerialPort::CircularBuffer& circularBuffer)
{
decltype(circularBuffer.getWriteBlock()) writeBlock;
size_t bytesWritten {};
while (writeBlock = circularBuffer.getWriteBlock(), writeBlock.second != 0 && bytesWritten != size)
{
const auto copySize = std::min(writeBlock.second, size - bytesWritten);
memcpy(writeBlock.first, buffer + bytesWritten, copySize);
circularBuffer.increaseWritePosition(copySize);
bytesWritten += copySize;
}
return bytesWritten;
}
} // namespace
/*---------------------------------------------------------------------------------------------------------------------+
| SerialPort::CircularBuffer public functions
+---------------------------------------------------------------------------------------------------------------------*/
std::pair<const uint8_t*, size_t> SerialPort::CircularBuffer::getReadBlock() const
{
const auto readPosition = readPosition_;
const auto writePosition = writePosition_;
return {buffer_ + readPosition, (writePosition >= readPosition ? writePosition : size_) - readPosition};
}
std::pair<uint8_t*, size_t> SerialPort::CircularBuffer::getWriteBlock() const
{
const auto readPosition = readPosition_;
const auto writePosition = writePosition_;
const auto freeBytes = (readPosition > writePosition ? readPosition - writePosition :
size_ - writePosition + readPosition) - 2;
const auto writeBlockSize = (readPosition > writePosition ? readPosition : size_) - writePosition;
return {buffer_ + writePosition, std::min(freeBytes, writeBlockSize)};
}
/*---------------------------------------------------------------------------------------------------------------------+
| public functions
+---------------------------------------------------------------------------------------------------------------------*/
SerialPort::~SerialPort()
{
if (openCount_ == 0)
return;
readMutex_.lock();
writeMutex_.lock();
const auto readWriteMutexScopeGuard = estd::makeScopeGuard(
[this]()
{
writeMutex_.unlock();
readMutex_.unlock();
});
uart_.stopRead();
uart_.stopWrite();
uart_.stop();
}
int SerialPort::close()
{
readMutex_.lock();
writeMutex_.lock();
const auto readWriteMutexScopeGuard = estd::makeScopeGuard(
[this]()
{
writeMutex_.unlock();
readMutex_.unlock();
});
if (openCount_ == 0) // device is not open anymore?
return EBADF;
if (openCount_ == 1) // last close?
{
while (transmitInProgress_ == true) // wait for physical end of write operation
{
Semaphore semaphore {0};
transmitSemaphore_ = &semaphore;
const auto transmitSemaphoreScopeGuard = estd::makeScopeGuard(
[this]()
{
transmitSemaphore_ = {};
});
if (transmitInProgress_ == true)
{
const auto ret = semaphore.wait();
if (ret != 0)
return ret;
}
}
uart_.stopRead();
const auto ret = uart_.stop();
if (ret != 0)
return ret;
readBuffer_.clear();
writeBuffer_.clear();
}
--openCount_;
return 0;
}
int SerialPort::open(const uint32_t baudRate, const uint8_t characterLength, const devices::UartParity parity,
const bool _2StopBits)
{
readMutex_.lock();
writeMutex_.lock();
const auto readWriteMutexScopeGuard = estd::makeScopeGuard(
[this]()
{
writeMutex_.unlock();
readMutex_.unlock();
});
if (openCount_ == std::numeric_limits<decltype(openCount_)>::max()) // device is already opened too many times?
return EMFILE;
if (openCount_ == 0) // first open?
{
if (readBuffer_.getCapacity() < 2 || writeBuffer_.getCapacity() < 2)
return ENOBUFS;
{
const auto ret = uart_.start(*this, baudRate, characterLength, parity, _2StopBits);
if (ret.first != 0)
return ret.first;
}
{
const auto ret = startReadWrapper(SIZE_MAX);
if (ret != 0)
return ret;
}
baudRate_ = baudRate;
characterLength_ = characterLength;
parity_ = parity;
_2StopBits_ = _2StopBits;
}
else // if (openCount_ != 0)
{
// provided arguments don't match current configuration of already opened device?
if (baudRate_ != baudRate || characterLength_ != characterLength || parity_ != parity ||
_2StopBits_ != _2StopBits)
return EINVAL;
}
++openCount_;
return 0;
}
std::pair<int, size_t> SerialPort::read(void* const buffer, const size_t size)
{
if (buffer == nullptr || size == 0)
return {EINVAL, {}};
readMutex_.lock();
const auto readMutexScopeGuard = estd::makeScopeGuard(
[this]()
{
readMutex_.unlock();
});
if (openCount_ == 0)
return {EBADF, {}};
if (characterLength_ > 8 && size % 2 != 0)
return {EINVAL, {}};
const size_t minSize = characterLength_ <= 8 ? 1 : 2;
const auto bufferUint8 = static_cast<uint8_t*>(buffer);
size_t bytesRead {};
while (bytesRead < minSize)
{
bytesRead += readFromCircularBuffer(readBuffer_, bufferUint8 + bytesRead, size - bytesRead);
if (bytesRead == size) // buffer already full?
return {{}, bytesRead};
Semaphore semaphore {0};
readSemaphore_ = &semaphore;
const auto readSemaphoreScopeGuard = estd::makeScopeGuard(
[this]()
{
readSemaphore_ = {};
});
{
// stop and restart the read operation to get the characters that were already received
architecture::InterruptMaskingLock interruptMaskingLock;
const auto bytesReceived = uart_.stopRead();
readBuffer_.increaseWritePosition(bytesReceived);
// limit of new read operation is selected to have a notification when requested minimum will be received
const auto ret = startReadWrapper(minSize > bytesRead + bytesReceived ?
minSize - bytesRead - bytesReceived : SIZE_MAX);
if (ret != 0)
return {ret, bytesRead};
}
bytesRead += readFromCircularBuffer(readBuffer_, bufferUint8 + bytesRead, size - bytesRead);
if (bytesRead < minSize) // wait for data only if requested minimum is not already read
{
const auto ret = semaphore.wait();
if (ret != 0)
return {ret, bytesRead};
}
}
return {{}, bytesRead};
}
std::pair<int, size_t> SerialPort::write(const void* const buffer, const size_t size)
{
if (buffer == nullptr || size == 0)
return {EINVAL, {}};
writeMutex_.lock();
const auto writeMutexScopeGuard = estd::makeScopeGuard(
[this]()
{
writeMutex_.unlock();
});
if (openCount_ == 0)
return {EBADF, {}};
if (characterLength_ > 8 && size % 2 != 0)
return {EINVAL, {}};
const auto bufferUint8 = static_cast<const uint8_t*>(buffer);
size_t bytesWritten {};
while (bytesWritten < size)
{
Semaphore semaphore {0};
writeSemaphore_ = &semaphore;
const auto writeSemaphoreScopeGuard = estd::makeScopeGuard(
[this]()
{
writeSemaphore_ = {};
});
bytesWritten += writeToCircularBuffer(bufferUint8 + bytesWritten, size - bytesWritten, writeBuffer_);
// restart write operation if it is not currently in progress and the write buffer is not already empty
if (writeInProgress_ == false && writeBuffer_.isEmpty() == false)
{
const auto ret = startWriteWrapper();
if (ret != 0)
return {ret, bytesWritten};
}
// wait for free space only if write operation is in progress and there is still some data left to write
else if (bytesWritten != size)
{
const auto ret = semaphore.wait();
if (ret != 0)
return {ret, bytesWritten};
}
}
return {{}, bytesWritten};
}
/*---------------------------------------------------------------------------------------------------------------------+
| private functions
+---------------------------------------------------------------------------------------------------------------------*/
void SerialPort::readCompleteEvent(const size_t bytesRead)
{
readBuffer_.increaseWritePosition(bytesRead);
if (readSemaphore_ != nullptr)
{
readSemaphore_->post();
readSemaphore_ = {};
}
if (readBuffer_.isFull() == true)
return;
startReadWrapper(SIZE_MAX);
}
void SerialPort::receiveErrorEvent(ErrorSet)
{
}
int SerialPort::startReadWrapper(const size_t limit)
{
const auto writeBlock = readBuffer_.getWriteBlock();
// rounding up is valid, capacity is never less than 2 and is always even
const auto readBufferHalf = ((readBuffer_.getCapacity() / 2 + 1) / 2) * 2;
return uart_.startRead(writeBlock.first, std::min({writeBlock.second, readBufferHalf, limit}));
}
int SerialPort::startWriteWrapper()
{
if (writeInProgress_ == true || writeBuffer_.isEmpty() == true)
return 0;
transmitInProgress_ = true;
writeInProgress_ = true;
const auto readBlock = writeBuffer_.getReadBlock();
const auto writeBufferHalf = ((writeBuffer_.getSize() / 2) / 2) * 2;
const auto writeLimit = writeLimit_;
return uart_.startWrite(readBlock.first,
std::min({readBlock.second, writeBufferHalf, writeLimit != 0 ? writeLimit : SIZE_MAX}));
}
size_t SerialPort::stopWriteWrapper()
{
const auto bytesWritten = uart_.stopWrite();
writeBuffer_.increaseReadPosition(bytesWritten);
const auto writeLimit = writeLimit_;
writeLimit_ = writeLimit - (bytesWritten < writeLimit ? bytesWritten : writeLimit);
writeInProgress_ = false;
return bytesWritten;
}
void SerialPort::transmitCompleteEvent()
{
if (transmitSemaphore_ != nullptr)
{
transmitSemaphore_->post();
transmitSemaphore_ = {};
}
transmitInProgress_ = false;
}
void SerialPort::writeCompleteEvent(const size_t bytesWritten)
{
writeBuffer_.increaseReadPosition(bytesWritten);
const auto writeLimit = writeLimit_;
writeLimit_ = writeLimit - (bytesWritten < writeLimit ? bytesWritten : writeLimit);
writeInProgress_ = false;
if (writeSemaphore_ != nullptr)
{
writeSemaphore_->post();
writeSemaphore_ = {};
}
startWriteWrapper();
}
} // namespace devices
} // namespace distortos
<|endoftext|> |
<commit_before>// (C) Copyright Gennadiy Rozental 2001-2014.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/test for the library home page.
//
// File : $RCSfile$
//
// Version : $Revision$
//
// Description : as a central place for global configuration switches
// ***************************************************************************
#ifndef BOOST_TEST_CONFIG_HPP_071894GER
#define BOOST_TEST_CONFIG_HPP_071894GER
// Boost
#include <boost/config.hpp> // compilers workarounds
#include <boost/detail/workaround.hpp>
#if defined(_WIN32) && !defined(BOOST_DISABLE_WIN32) && \
(!defined(__COMO__) && !defined(__MWERKS__) && !defined(__GNUC__) || \
BOOST_WORKAROUND(__MWERKS__, >= 0x3000))
# define BOOST_SEH_BASED_SIGNAL_HANDLING
#endif
#if defined(__COMO__) && defined(_MSC_VER)
// eh.h uses type_info without declaring it.
class type_info;
# define BOOST_SEH_BASED_SIGNAL_HANDLING
#endif
//____________________________________________________________________________//
#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x570)) || \
BOOST_WORKAROUND(__IBMCPP__, BOOST_TESTED_AT(600)) || \
(defined __sgi && BOOST_WORKAROUND(_COMPILER_VERSION, BOOST_TESTED_AT(730)))
# define BOOST_TEST_SHIFTED_LINE
#endif
//____________________________________________________________________________//
#if defined(BOOST_MSVC) || (defined(__BORLANDC__) && !defined(BOOST_DISABLE_WIN32))
# define BOOST_TEST_CALL_DECL __cdecl
#else
# define BOOST_TEST_CALL_DECL /**/
#endif
//____________________________________________________________________________//
#if !defined(BOOST_NO_STD_LOCALE) && !defined(__MWERKS__)
# define BOOST_TEST_USE_STD_LOCALE 1
#endif
//____________________________________________________________________________//
#if BOOST_WORKAROUND(__BORLANDC__, <= 0x570) || \
BOOST_WORKAROUND( __COMO__, <= 0x433 ) || \
BOOST_WORKAROUND( __INTEL_COMPILER, <= 800 ) || \
defined(__sgi) && _COMPILER_VERSION <= 730 || \
BOOST_WORKAROUND(__IBMCPP__, BOOST_TESTED_AT(600)) || \
defined(__DECCXX) || \
defined(__DMC__)
# define BOOST_TEST_NO_PROTECTED_USING
#endif
//____________________________________________________________________________//
#if defined(__GNUC__) || BOOST_WORKAROUND(BOOST_MSVC, == 1400)
#define BOOST_TEST_PROTECTED_VIRTUAL virtual
#else
#define BOOST_TEST_PROTECTED_VIRTUAL
#endif
//____________________________________________________________________________//
#if !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564)) && \
!BOOST_WORKAROUND(__SUNPRO_CC, BOOST_TESTED_AT(0x530))
# define BOOST_TEST_SUPPORT_INTERACTION_TESTING 1
#endif
//____________________________________________________________________________//
#if !defined(__BORLANDC__) && !BOOST_WORKAROUND( __SUNPRO_CC, < 0x5100 )
#define BOOST_TEST_SUPPORT_TOKEN_ITERATOR 1
#endif
//____________________________________________________________________________//
#if defined(BOOST_ALL_DYN_LINK) && !defined(BOOST_TEST_DYN_LINK)
# define BOOST_TEST_DYN_LINK
#endif
#if defined(BOOST_TEST_INCLUDED)
# undef BOOST_TEST_DYN_LINK
#endif
#if defined(BOOST_TEST_DYN_LINK)
# define BOOST_TEST_ALTERNATIVE_INIT_API
# ifdef BOOST_TEST_SOURCE
# define BOOST_TEST_DECL BOOST_SYMBOL_EXPORT
# else
# define BOOST_TEST_DECL BOOST_SYMBOL_IMPORT
# endif // BOOST_TEST_SOURCE
#else
# define BOOST_TEST_DECL
#endif
#if !defined(BOOST_TEST_MAIN) && defined(BOOST_AUTO_TEST_MAIN)
#define BOOST_TEST_MAIN BOOST_AUTO_TEST_MAIN
#endif
#if !defined(BOOST_TEST_MAIN) && defined(BOOST_TEST_MODULE)
#define BOOST_TEST_MAIN BOOST_TEST_MODULE
#endif
#ifdef __PGI
#define BOOST_PP_VARIADICS 1
#endif
#endif // BOOST_TEST_CONFIG_HPP_071894GER
<commit_msg>Adding a macro for switching between C++98 throw() and C++11 noexcept<commit_after>// (C) Copyright Gennadiy Rozental 2001-2014.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/test for the library home page.
//
/// @file a central place for global configuration switches
// ***************************************************************************
#ifndef BOOST_TEST_CONFIG_HPP_071894GER
#define BOOST_TEST_CONFIG_HPP_071894GER
// Boost
#include <boost/config.hpp> // compilers workarounds
#include <boost/detail/workaround.hpp>
#if defined(_WIN32) && !defined(BOOST_DISABLE_WIN32) && \
(!defined(__COMO__) && !defined(__MWERKS__) && !defined(__GNUC__) || \
BOOST_WORKAROUND(__MWERKS__, >= 0x3000))
# define BOOST_SEH_BASED_SIGNAL_HANDLING
#endif
#if defined(__COMO__) && defined(_MSC_VER)
// eh.h uses type_info without declaring it.
class type_info;
# define BOOST_SEH_BASED_SIGNAL_HANDLING
#endif
//____________________________________________________________________________//
#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x570)) || \
BOOST_WORKAROUND(__IBMCPP__, BOOST_TESTED_AT(600)) || \
(defined __sgi && BOOST_WORKAROUND(_COMPILER_VERSION, BOOST_TESTED_AT(730)))
# define BOOST_TEST_SHIFTED_LINE
#endif
//____________________________________________________________________________//
#if defined(BOOST_MSVC) || (defined(__BORLANDC__) && !defined(BOOST_DISABLE_WIN32))
# define BOOST_TEST_CALL_DECL __cdecl
#else
# define BOOST_TEST_CALL_DECL /**/
#endif
//____________________________________________________________________________//
#if !defined(BOOST_NO_STD_LOCALE) && !defined(__MWERKS__)
# define BOOST_TEST_USE_STD_LOCALE 1
#endif
//____________________________________________________________________________//
#if BOOST_WORKAROUND(__BORLANDC__, <= 0x570) || \
BOOST_WORKAROUND( __COMO__, <= 0x433 ) || \
BOOST_WORKAROUND( __INTEL_COMPILER, <= 800 ) || \
defined(__sgi) && _COMPILER_VERSION <= 730 || \
BOOST_WORKAROUND(__IBMCPP__, BOOST_TESTED_AT(600)) || \
defined(__DECCXX) || \
defined(__DMC__)
# define BOOST_TEST_NO_PROTECTED_USING
#endif
//____________________________________________________________________________//
#if defined(__GNUC__) || BOOST_WORKAROUND(BOOST_MSVC, == 1400)
#define BOOST_TEST_PROTECTED_VIRTUAL virtual
#else
#define BOOST_TEST_PROTECTED_VIRTUAL
#endif
//____________________________________________________________________________//
#if !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564)) && \
!BOOST_WORKAROUND(__SUNPRO_CC, BOOST_TESTED_AT(0x530))
# define BOOST_TEST_SUPPORT_INTERACTION_TESTING 1
#endif
//____________________________________________________________________________//
#if !defined(__BORLANDC__) && !BOOST_WORKAROUND( __SUNPRO_CC, < 0x5100 )
#define BOOST_TEST_SUPPORT_TOKEN_ITERATOR 1
#endif
//____________________________________________________________________________//
#if defined(BOOST_ALL_DYN_LINK) && !defined(BOOST_TEST_DYN_LINK)
# define BOOST_TEST_DYN_LINK
#endif
#if defined(BOOST_TEST_INCLUDED)
# undef BOOST_TEST_DYN_LINK
#endif
#if defined(BOOST_TEST_DYN_LINK)
# define BOOST_TEST_ALTERNATIVE_INIT_API
# ifdef BOOST_TEST_SOURCE
# define BOOST_TEST_DECL BOOST_SYMBOL_EXPORT
# else
# define BOOST_TEST_DECL BOOST_SYMBOL_IMPORT
# endif // BOOST_TEST_SOURCE
#else
# define BOOST_TEST_DECL
#endif
#if !defined(BOOST_TEST_MAIN) && defined(BOOST_AUTO_TEST_MAIN)
#define BOOST_TEST_MAIN BOOST_AUTO_TEST_MAIN
#endif
#if !defined(BOOST_TEST_MAIN) && defined(BOOST_TEST_MODULE)
#define BOOST_TEST_MAIN BOOST_TEST_MODULE
#endif
#ifdef __PGI
#define BOOST_PP_VARIADICS 1
#endif
#ifdef BOOST_NO_CXX11_NOEXCEPT
# define BOOST_TEST_NOEXCEPT_OR_THROW_VOID throw()
#else
# define BOOST_TEST_NOEXCEPT_OR_THROW_VOID noexcept
#endif
#endif // BOOST_TEST_CONFIG_HPP_071894GER
<|endoftext|> |
<commit_before>/*
* SessionRSConnect.cpp
*
* Copyright (C) 2009-14 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionRSConnect.hpp"
#include <boost/algorithm/string.hpp>
#include <boost/foreach.hpp>
#include <core/Error.hpp>
#include <core/Exec.hpp>
#include <r/RSexp.hpp>
#include <r/RExec.hpp>
#include <session/SessionModuleContext.hpp>
#include <session/SessionAsyncRProcess.hpp>
#define kFinishedMarker "Deployment completed: "
#define kRSConnectFolder "rsconnect/"
#define kPackratFolder "packrat/"
#define kMaxDeploymentSize 104857600
using namespace rstudio::core;
namespace rstudio {
namespace session {
namespace modules {
namespace rsconnect {
namespace {
class ShinyAppDeploy : public async_r::AsyncRProcess
{
public:
static boost::shared_ptr<ShinyAppDeploy> create(
const std::string& dir,
const json::Array& fileList,
const std::string& file,
const std::string& account,
const std::string& server,
const std::string& app)
{
boost::shared_ptr<ShinyAppDeploy> pDeploy(new ShinyAppDeploy(file));
std::string cmd("{ options(repos = c(CRAN='" +
module_context::CRANReposURL() + "')); ");
// join and quote incoming filenames to deploy
std::string files;
for (size_t i = 0; i < fileList.size(); i++)
{
files += "'" + fileList[i].get_str() + "'";
if (i < fileList.size() - 1)
files += ", ";
}
// form the deploy command to hand off to the async deploy process
cmd += "rsconnect::deployApp("
"appDir = '" + dir + "'," +
(files.empty() ? "" : "appFiles = c(" + files + "), ") +
"account = '" + account + "',"
"server = '" + server + "', "
"appName = '" + app + "', "
"launch.browser = function (url) { "
" message('" kFinishedMarker "', url) "
"}, "
"lint = FALSE)}";
pDeploy->start(cmd.c_str(), FilePath(), async_r::R_PROCESS_VANILLA);
return pDeploy;
}
private:
ShinyAppDeploy(const std::string& file)
{
sourceFile_ = file;
}
void onStderr(const std::string& output)
{
onOutput(module_context::kCompileOutputNormal, output);
}
void onStdout(const std::string& output)
{
onOutput(module_context::kCompileOutputError, output);
}
void onOutput(int type, const std::string& output)
{
r::sexp::Protect protect;
Error error;
// look on each line of emitted output to see whether it contains the
// finished marker
std::vector<std::string> lines;
boost::algorithm::split(lines, output,
boost::algorithm::is_any_of("\n\r"));
int ncharMarker = sizeof(kFinishedMarker) - 1;
BOOST_FOREACH(std::string& line, lines)
{
if (line.substr(0, ncharMarker) == kFinishedMarker)
{
deployedUrl_ = line.substr(ncharMarker, line.size() - ncharMarker);
// check to see if a source file was specified; if so return a URL
// with the source file appended
if (!sourceFile_.empty() &&
!boost::algorithm::iends_with(deployedUrl_, ".rmd") &&
(string_utils::toLower(sourceFile_) != "index.rmd"))
{
// append / to the URL if it doesn't already have one
if (deployedUrl_[deployedUrl_.length() - 1] != '/')
deployedUrl_.append("/");
deployedUrl_.append(sourceFile_);
}
}
}
// emit the output to the client for display
module_context::CompileOutput deployOutput(type, output);
ClientEvent event(client_events::kRmdRSConnectDeploymentOutput,
module_context::compileOutputAsJson(deployOutput));
module_context::enqueClientEvent(event);
}
void onCompleted(int exitStatus)
{
// when the process completes, emit the discovered URL, if any
ClientEvent event(client_events::kRmdRSConnectDeploymentCompleted,
deployedUrl_);
module_context::enqueClientEvent(event);
}
std::string deployedUrl_;
std::string sourceFile_;
};
boost::shared_ptr<ShinyAppDeploy> s_pShinyAppDeploy_;
Error deployShinyApp(const json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
json::Array sourceFiles;
std::string sourceDir, sourceFile, account, server, appName;
Error error = json::readParams(request.params, &sourceDir, &sourceFiles,
&sourceFile, &account, &server, &appName);
if (error)
return error;
if (s_pShinyAppDeploy_ &&
s_pShinyAppDeploy_->isRunning())
{
pResponse->setResult(false);
}
else
{
s_pShinyAppDeploy_ = ShinyAppDeploy::create(sourceDir, sourceFiles,
sourceFile, account, server,
appName);
pResponse->setResult(true);
}
return Success();
}
} // anonymous namespace
Error initialize()
{
using boost::bind;
using namespace module_context;
ExecBlock initBlock;
initBlock.addFunctions()
(bind(registerRpcMethod, "deploy_shiny_app", deployShinyApp))
(bind(sourceModuleRFile, "SessionRSConnect.R"));
return initBlock.execute();
}
} // namespace rsconnect
} // namespace modules
} // namespace session
} // namespace rstudio
<commit_msg>pass primary R Markdown doc information to rsconnect package<commit_after>/*
* SessionRSConnect.cpp
*
* Copyright (C) 2009-14 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionRSConnect.hpp"
#include <boost/algorithm/string.hpp>
#include <boost/foreach.hpp>
#include <core/Error.hpp>
#include <core/Exec.hpp>
#include <r/RSexp.hpp>
#include <r/RExec.hpp>
#include <session/SessionModuleContext.hpp>
#include <session/SessionAsyncRProcess.hpp>
#define kFinishedMarker "Deployment completed: "
#define kRSConnectFolder "rsconnect/"
#define kPackratFolder "packrat/"
#define kMaxDeploymentSize 104857600
using namespace rstudio::core;
namespace rstudio {
namespace session {
namespace modules {
namespace rsconnect {
namespace {
class ShinyAppDeploy : public async_r::AsyncRProcess
{
public:
static boost::shared_ptr<ShinyAppDeploy> create(
const std::string& dir,
const json::Array& fileList,
const std::string& file,
const std::string& account,
const std::string& server,
const std::string& app)
{
boost::shared_ptr<ShinyAppDeploy> pDeploy(new ShinyAppDeploy(file));
std::string cmd("{ options(repos = c(CRAN='" +
module_context::CRANReposURL() + "')); ");
// join and quote incoming filenames to deploy
std::string files;
for (size_t i = 0; i < fileList.size(); i++)
{
files += "'" + fileList[i].get_str() + "'";
if (i < fileList.size() - 1)
files += ", ";
}
// if a R Markdown document is being deployed, mark it as the primary
// file
std::string primaryRmd;
if (!file.empty())
{
FilePath sourceFile = module_context::resolveAliasedPath(file);
if (sourceFile.extensionLowerCase() == ".rmd")
{
primaryRmd = file;
}
}
// form the deploy command to hand off to the async deploy process
cmd += "rsconnect::deployApp("
"appDir = '" + dir + "'," +
(files.empty() ? "" : "appFiles = c(" + files + "), ") +
(primaryRmd.empty() ? "" : "appPrimaryRmd = '" + primaryRmd + "', ") +
"account = '" + account + "',"
"server = '" + server + "', "
"appName = '" + app + "', "
"launch.browser = function (url) { "
" message('" kFinishedMarker "', url) "
"}, "
"lint = FALSE)}";
pDeploy->start(cmd.c_str(), FilePath(), async_r::R_PROCESS_VANILLA);
return pDeploy;
}
private:
ShinyAppDeploy(const std::string& file)
{
sourceFile_ = file;
}
void onStderr(const std::string& output)
{
onOutput(module_context::kCompileOutputNormal, output);
}
void onStdout(const std::string& output)
{
onOutput(module_context::kCompileOutputError, output);
}
void onOutput(int type, const std::string& output)
{
r::sexp::Protect protect;
Error error;
// look on each line of emitted output to see whether it contains the
// finished marker
std::vector<std::string> lines;
boost::algorithm::split(lines, output,
boost::algorithm::is_any_of("\n\r"));
int ncharMarker = sizeof(kFinishedMarker) - 1;
BOOST_FOREACH(std::string& line, lines)
{
if (line.substr(0, ncharMarker) == kFinishedMarker)
{
deployedUrl_ = line.substr(ncharMarker, line.size() - ncharMarker);
// check to see if a source file was specified; if so return a URL
// with the source file appended
if (!sourceFile_.empty() &&
!boost::algorithm::iends_with(deployedUrl_, ".rmd") &&
(string_utils::toLower(sourceFile_) != "index.rmd"))
{
// append / to the URL if it doesn't already have one
if (deployedUrl_[deployedUrl_.length() - 1] != '/')
deployedUrl_.append("/");
deployedUrl_.append(sourceFile_);
}
}
}
// emit the output to the client for display
module_context::CompileOutput deployOutput(type, output);
ClientEvent event(client_events::kRmdRSConnectDeploymentOutput,
module_context::compileOutputAsJson(deployOutput));
module_context::enqueClientEvent(event);
}
void onCompleted(int exitStatus)
{
// when the process completes, emit the discovered URL, if any
ClientEvent event(client_events::kRmdRSConnectDeploymentCompleted,
deployedUrl_);
module_context::enqueClientEvent(event);
}
std::string deployedUrl_;
std::string sourceFile_;
};
boost::shared_ptr<ShinyAppDeploy> s_pShinyAppDeploy_;
Error deployShinyApp(const json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
json::Array sourceFiles;
std::string sourceDir, sourceFile, account, server, appName;
Error error = json::readParams(request.params, &sourceDir, &sourceFiles,
&sourceFile, &account, &server, &appName);
if (error)
return error;
if (s_pShinyAppDeploy_ &&
s_pShinyAppDeploy_->isRunning())
{
pResponse->setResult(false);
}
else
{
s_pShinyAppDeploy_ = ShinyAppDeploy::create(sourceDir, sourceFiles,
sourceFile, account, server,
appName);
pResponse->setResult(true);
}
return Success();
}
} // anonymous namespace
Error initialize()
{
using boost::bind;
using namespace module_context;
ExecBlock initBlock;
initBlock.addFunctions()
(bind(registerRpcMethod, "deploy_shiny_app", deployShinyApp))
(bind(sourceModuleRFile, "SessionRSConnect.R"));
return initBlock.execute();
}
} // namespace rsconnect
} // namespace modules
} // namespace session
} // namespace rstudio
<|endoftext|> |
<commit_before>// recalibrate_main.cpp: mapping quality recalibration for GAM files
#include <omp.h>
#include <unistd.h>
#include <getopt.h>
#include <string>
#include <sstream>
#include <subcommand.hpp>
#include "../alignment.hpp"
#include "../vg.hpp"
#include <vowpalwabbit/vw.h>
using namespace std;
using namespace vg;
using namespace vg::subcommand;
void help_recalibrate(char** argv) {
cerr << "usage: " << argv[0] << " recalibrate [options] --model learned.model mapped.gam > recalibrated.gam" << endl
<< " " << argv[0] << " recalibrate [options] --model learned.model --train compared.gam" << endl
<< endl
<< "options:" << endl
<< " -T, --train read the input GAM file, and use the mapped_correctly flags from vg gamcompare to train a model" << endl
<< " -m, --model FILE load/save the model to/from the given file" << endl
<< " -t, --threads N number of threads to use" << endl;
}
/// Turn an Alignment into a Vowpal Wabbit format example line.
/// If train is true, give it a label so that VW will train on it.
/// If train is false, do not label the data.
string alignment_to_example_string(const Alignment& aln, bool train) {
// We will dump it to a string stream
stringstream s;
if (train) {
// First is the class; 1 for correct or -1 for wrong
s << (aln.correctly_mapped() ? "1 " : "-1 ");
}
// Drop all the features into the mepty-string namespace
s << "| ";
// Original MAPQ is a feature
s << "origMapq:" << to_string(aln.mapping_quality()) << " ";
// As is score
s << "score:" << to_string(aln.score()) << " ";
// And the top secondary alignment score
double secondary_score = 0;
if (aln.secondary_score_size() > 0) {
secondary_score = aln.secondary_score(0);
}
s << "secondaryScore:" << to_string(secondary_score) << " ";
// Count the secondary alignments
s << "secondaryCount:" << aln.secondary_score_size() << " ";
// Also do the identity
s << "identity:" << aln.identity() << " ";
// TODO: more features
return s.str();
}
int main_recalibrate(int argc, char** argv) {
if (argc == 2) {
help_recalibrate(argv);
exit(1);
}
int threads = 1;
bool train = false;
string model_filename;
int c;
optind = 2;
while (true) {
static struct option long_options[] =
{
{"help", no_argument, 0, 'h'},
{"train", no_argument, 0, 'T'},
{"model", required_argument, 0, 'm'},
{"threads", required_argument, 0, 't'},
{0, 0, 0, 0}
};
int option_index = 0;
c = getopt_long (argc, argv, "hTm:t:",
long_options, &option_index);
// Detect the end of the options.
if (c == -1) break;
switch (c)
{
case 'T':
train = true;
break;
case 'm':
model_filename = optarg;
break;
case 't':
threads = atoi(optarg);
omp_set_num_threads(threads);
break;
case 'h':
case '?':
help_recalibrate(argv);
exit(1);
break;
default:
abort ();
}
}
get_input_file(optind, argc, argv, [&](istream& gam_stream) {
// With the GAM input
if (train) {
// We want to train a model.
// Get a VW model.
// Most of the parameters are passed as a command-line option string.
// We must always pass --no_stdin because
// <https://github.com/JohnLangford/vowpal_wabbit/commit/7d5754e168c679ff8968f18a967ccd11a2ba1e80>
// says so.
string vw_args = "--no_stdin";
// We need the logistic stuff to make the predictor predict probabilities
vw_args += " --link=logistic --loss_function=logistic";
// We need this to do quadradic interaction features (kernel)
vw_args += " -q ::";
// Add L2 regularization
vw_args += " --l2 0.000001";
// We also apparently have to decide now what file name we want output to go to and use -f to send it there.
if (!model_filename.empty()) {
// Save to the given model
vw_args += " -f " + model_filename;
// Also dump a human-readable version where feature names aren't hashed.
vw_args += " --invert_hash " + model_filename + ".inv";
}
// TODO: what do any of the other parameters do?
// TODO: Note that vw defines a VW namespace but dumps its vw type into the global namespace.
vw* model = VW::initialize(vw_args);
function<void(Alignment&)> train_on = [&](Alignment& aln) {
// Turn each Alignment into a VW-format string
string example_string = alignment_to_example_string(aln, true);
// Load an example for each Alignment.
// You can apparently only have so many examples at a time because they live in a ring buffer of unspecified size.
// TODO: There are non-string-parsing-based ways to do this too.
// TODO: Why link against vw at all if we're just going to shuffle strings around? We could pipe to it.
// TODO: vw alo dumps "example" into the global namespace...
example* example = VW::read_example(*model, example_string);
// Now we call the learn method, defined in vowpalwabbit/global_data.h.
// It's not clear what it does but it is probably training.
// If we didn't label the data, this would just predict instead.
model->learn(example);
// Clean up the example
VW::finish_example(*model, example);
};
// TODO: We have to go in serial because vw isn't thread safe I think.
stream::for_each(gam_stream, train_on);
// Now we want to output the model.
// TODO: We had to specify that already. I think it is magic?
// Clean up the VW model
VW::finish(*model);
} else {
// We are in run mode
string vw_args = "--no_stdin";
if (!model_filename.empty()) {
// Load from the given model
vw_args += " -i " + model_filename;
}
// Make the model
vw* model = VW::initialize(vw_args);
// Define a buffer for alignments to print
vector<Alignment> buf;
// Specify how to recalibrate an alignment
function<void(Alignment&)> recalibrate = [&](Alignment& aln) {
// Turn each Alignment into a VW-format string
string example_string = alignment_to_example_string(aln, false);
// Load an example for each Alignment.
example* example = VW::read_example(*model, example_string);
// Now we call the learn method, defined in vowpalwabbit/global_data.h.
// It's not clear what it does but it is probably training.
// If we didn't label the data, this would just predict instead.
model->learn(example);
// Get the correctness prediction from -1 to 1
double prob = example->pred.prob;
// Convert into a real MAPQ estimate.
double guess = prob_to_phred(1.0 - prob);
// Clamp to 0 to 60
double clamped = max(0.0, min(60.0, guess));
#ifdef debug
cerr << example_string << " -> " << prob << " -> " << guess << " -> " << clamped << endl;
#endif
// Set the MAPQ to output.
aln.set_mapping_quality(clamped);
// Clean up the example
VW::finish_example(*model, example);
#pragma omp critical (buf)
{
// Save to the buffer
buf.push_back(aln);
if (buf.size() > 1000) {
// And output if buffer is full
write_alignments(std::cout, buf);
buf.clear();
}
}
};
// For each read, recalibrate and buffer and maybe print it.
// TODO: It would be nice if this could be parallel...
stream::for_each(gam_stream, recalibrate);
VW::finish(*model);
// Flush the buffer
write_alignments(std::cout, buf);
buf.clear();
cout.flush();
}
});
return 0;
}
// Register subcommand
static Subcommand vg_recalibrate("recalibrate", "recalibrate mapping qualities", main_recalibrate);
<commit_msg>Don't always invert hash<commit_after>// recalibrate_main.cpp: mapping quality recalibration for GAM files
#include <omp.h>
#include <unistd.h>
#include <getopt.h>
#include <string>
#include <sstream>
#include <subcommand.hpp>
#include "../alignment.hpp"
#include "../vg.hpp"
#include <vowpalwabbit/vw.h>
using namespace std;
using namespace vg;
using namespace vg::subcommand;
void help_recalibrate(char** argv) {
cerr << "usage: " << argv[0] << " recalibrate [options] --model learned.model mapped.gam > recalibrated.gam" << endl
<< " " << argv[0] << " recalibrate [options] --model learned.model --train compared.gam" << endl
<< endl
<< "options:" << endl
<< " -T, --train read the input GAM file, and use the mapped_correctly flags from vg gamcompare to train a model" << endl
<< " -m, --model FILE load/save the model to/from the given file" << endl
<< " -t, --threads N number of threads to use" << endl;
}
/// Turn an Alignment into a Vowpal Wabbit format example line.
/// If train is true, give it a label so that VW will train on it.
/// If train is false, do not label the data.
string alignment_to_example_string(const Alignment& aln, bool train) {
// We will dump it to a string stream
stringstream s;
if (train) {
// First is the class; 1 for correct or -1 for wrong
s << (aln.correctly_mapped() ? "1 " : "-1 ");
}
// Drop all the features into the mepty-string namespace
s << "| ";
// Original MAPQ is a feature
s << "origMapq:" << to_string(aln.mapping_quality()) << " ";
// As is score
s << "score:" << to_string(aln.score()) << " ";
// And the top secondary alignment score
double secondary_score = 0;
if (aln.secondary_score_size() > 0) {
secondary_score = aln.secondary_score(0);
}
s << "secondaryScore:" << to_string(secondary_score) << " ";
// Count the secondary alignments
s << "secondaryCount:" << aln.secondary_score_size() << " ";
// Also do the identity
s << "identity:" << aln.identity() << " ";
// TODO: more features
return s.str();
}
int main_recalibrate(int argc, char** argv) {
if (argc == 2) {
help_recalibrate(argv);
exit(1);
}
int threads = 1;
bool train = false;
string model_filename;
int c;
optind = 2;
while (true) {
static struct option long_options[] =
{
{"help", no_argument, 0, 'h'},
{"train", no_argument, 0, 'T'},
{"model", required_argument, 0, 'm'},
{"threads", required_argument, 0, 't'},
{0, 0, 0, 0}
};
int option_index = 0;
c = getopt_long (argc, argv, "hTm:t:",
long_options, &option_index);
// Detect the end of the options.
if (c == -1) break;
switch (c)
{
case 'T':
train = true;
break;
case 'm':
model_filename = optarg;
break;
case 't':
threads = atoi(optarg);
omp_set_num_threads(threads);
break;
case 'h':
case '?':
help_recalibrate(argv);
exit(1);
break;
default:
abort ();
}
}
get_input_file(optind, argc, argv, [&](istream& gam_stream) {
// With the GAM input
if (train) {
// We want to train a model.
// Get a VW model.
// Most of the parameters are passed as a command-line option string.
// We must always pass --no_stdin because
// <https://github.com/JohnLangford/vowpal_wabbit/commit/7d5754e168c679ff8968f18a967ccd11a2ba1e80>
// says so.
string vw_args = "--no_stdin";
// We need the logistic stuff to make the predictor predict probabilities
vw_args += " --link=logistic --loss_function=logistic";
// We need this to do quadradic interaction features (kernel)
vw_args += " -q ::";
// Add L2 regularization
vw_args += " --l2 0.000001";
// We also apparently have to decide now what file name we want output to go to and use -f to send it there.
if (!model_filename.empty()) {
// Save to the given model
vw_args += " -f " + model_filename;
#ifdef debug
// Also dump a human-readable version where feature names aren't hashed.
vw_args += " --invert_hash " + model_filename + ".inv";
#endif
}
// TODO: what do any of the other parameters do?
// TODO: Note that vw defines a VW namespace but dumps its vw type into the global namespace.
vw* model = VW::initialize(vw_args);
function<void(Alignment&)> train_on = [&](Alignment& aln) {
// Turn each Alignment into a VW-format string
string example_string = alignment_to_example_string(aln, true);
// Load an example for each Alignment.
// You can apparently only have so many examples at a time because they live in a ring buffer of unspecified size.
// TODO: There are non-string-parsing-based ways to do this too.
// TODO: Why link against vw at all if we're just going to shuffle strings around? We could pipe to it.
// TODO: vw alo dumps "example" into the global namespace...
example* example = VW::read_example(*model, example_string);
// Now we call the learn method, defined in vowpalwabbit/global_data.h.
// It's not clear what it does but it is probably training.
// If we didn't label the data, this would just predict instead.
model->learn(example);
// Clean up the example
VW::finish_example(*model, example);
};
// TODO: We have to go in serial because vw isn't thread safe I think.
stream::for_each(gam_stream, train_on);
// Now we want to output the model.
// TODO: We had to specify that already. I think it is magic?
// Clean up the VW model
VW::finish(*model);
} else {
// We are in run mode
string vw_args = "--no_stdin";
if (!model_filename.empty()) {
// Load from the given model
vw_args += " -i " + model_filename;
}
// Make the model
vw* model = VW::initialize(vw_args);
// Define a buffer for alignments to print
vector<Alignment> buf;
// Specify how to recalibrate an alignment
function<void(Alignment&)> recalibrate = [&](Alignment& aln) {
// Turn each Alignment into a VW-format string
string example_string = alignment_to_example_string(aln, false);
// Load an example for each Alignment.
example* example = VW::read_example(*model, example_string);
// Now we call the learn method, defined in vowpalwabbit/global_data.h.
// It's not clear what it does but it is probably training.
// If we didn't label the data, this would just predict instead.
model->learn(example);
// Get the correctness prediction from -1 to 1
double prob = example->pred.prob;
// Convert into a real MAPQ estimate.
double guess = prob_to_phred(1.0 - prob);
// Clamp to 0 to 60
double clamped = max(0.0, min(60.0, guess));
#ifdef debug
cerr << example_string << " -> " << prob << " -> " << guess << " -> " << clamped << endl;
#endif
// Set the MAPQ to output.
aln.set_mapping_quality(clamped);
// Clean up the example
VW::finish_example(*model, example);
#pragma omp critical (buf)
{
// Save to the buffer
buf.push_back(aln);
if (buf.size() > 1000) {
// And output if buffer is full
write_alignments(std::cout, buf);
buf.clear();
}
}
};
// For each read, recalibrate and buffer and maybe print it.
// TODO: It would be nice if this could be parallel...
stream::for_each(gam_stream, recalibrate);
VW::finish(*model);
// Flush the buffer
write_alignments(std::cout, buf);
buf.clear();
cout.flush();
}
});
return 0;
}
// Register subcommand
static Subcommand vg_recalibrate("recalibrate", "recalibrate mapping qualities", main_recalibrate);
<|endoftext|> |
<commit_before>#include "cbase.h"
#include "ios_fieldbot.h"
#include "sdk_player.h"
#include "team.h"
#include "in_buttons.h"
LINK_ENTITY_TO_CLASS(ios_fieldbot, CFieldBot);
ConVar bot_shootatgoal("bot_shootatgoal", "1");
void CFieldBot::BotThink()
{
if (m_vDirToBall.Length2D() > 25)
BotRunToBall();
else
BotShootBall();
}
void CFieldBot::BotShootBall()
{
Vector shotDir;
if (bot_shootatgoal.GetBool())
{
Vector target = GetOppTeam()->m_vGoalCenter;
float ownDistToGoal = (GetOppTeam()->m_vGoalCenter - GetLocalOrigin()).Length2D();
bool isGoalShot = true;
for (int i = 1; i <= gpGlobals->maxClients; i++ )
{
CSDKPlayer *pPl = (CSDKPlayer *)UTIL_PlayerByIndex(i);
if (!CSDKPlayer::IsOnField(pPl))
continue;
if (pPl->GetTeamNumber() != GetTeamNumber())
continue;
float distToGoal = (GetOppTeam()->m_vGoalCenter - pPl->GetLocalOrigin()).Length2D();
if (distToGoal < ownDistToGoal)
{
target = pPl->GetLocalOrigin();
isGoalShot = false;
break;
}
}
target.x += g_IOSRand.RandomFloat(-200, 200);
shotDir = target - GetLocalOrigin();
if (isGoalShot)
{
if (ownDistToGoal > 1000)
m_cmd.buttons |= IN_ATTACK;
else
{
m_cmd.buttons |= IN_ATTACK;
}
}
else
{
m_cmd.buttons |= IN_ATTACK;
}
VectorAngles(shotDir, m_cmd.viewangles);
m_cmd.viewangles[PITCH] = g_IOSRand.RandomFloat(-89, 89);
}
else
{
if (GetFlags() & FL_ATCONTROLS)
{
//float xDir = g_IOSRand.RandomFloat(0.1f, 1) * Sign((SDKGameRules()->m_vKickOff - GetLocalOrigin()).x);
float xDir = g_IOSRand.RandomFloat(-1, 1);
shotDir = Vector(xDir, GetTeam()->m_nForward, 0);
}
else
{
shotDir = Vector(g_IOSRand.RandomFloat(-1, 1), GetTeam()->m_nForward, 0);
}
VectorAngles(shotDir, m_cmd.viewangles);
m_cmd.buttons |= IN_ATTACK;
m_cmd.viewangles[PITCH] = 0;
}
if (m_vDirToBall.z > GetPlayerMaxs().z + 10)
m_cmd.buttons |= IN_JUMP;
}
void CFieldBot::BotRunToBall()
{
float closestDist = FLT_MAX;
CSDKPlayer *pClosest = NULL;
for (int i = 1; i <= gpGlobals->maxClients; i++ )
{
CSDKPlayer *pPl = (CSDKPlayer *)UTIL_PlayerByIndex(i);
if (!CSDKPlayer::IsOnField(pPl))
continue;
if (pPl->GetTeamNumber() != GetTeamNumber())
continue;
float dist = (m_vBallPos - pPl->GetLocalOrigin()).Length2D();
if (dist < closestDist)
{
closestDist = dist;
pClosest = pPl;
}
}
if (pClosest == this)
{
VectorAngles(m_vDirToBall, m_cmd.viewangles);
m_cmd.forwardmove = clamp(m_oldcmd.forwardmove + g_IOSRand.RandomFloat(-200, 200) * gpGlobals->frametime * 2, mp_runspeed.GetInt(), mp_sprintspeed.GetInt());
}
else
{
Vector pos = GetLocalOrigin();
if (pos.x < SDKGameRules()->m_vFieldMin.GetX() - 100 || pos.x > SDKGameRules()->m_vFieldMax.GetX() + 100 || pos.y < SDKGameRules()->m_vFieldMin.GetY() - 100 || pos.y > SDKGameRules()->m_vFieldMax.GetY() + 100)
{
QAngle ang;
VectorAngles(SDKGameRules()->m_vKickOff - pos, ang);
m_cmd.viewangles[YAW] = ang[YAW];
}
else
m_cmd.viewangles[YAW] = m_oldcmd.viewangles[YAW] + g_IOSRand.RandomFloat(-180, 180) * gpGlobals->frametime * 4;
m_cmd.forwardmove = clamp(m_oldcmd.forwardmove + g_IOSRand.RandomFloat(-200, 200) * gpGlobals->frametime * 2, -mp_walkspeed.GetInt() / 2, mp_walkspeed.GetInt());
m_cmd.sidemove = clamp(m_oldcmd.sidemove + g_IOSRand.RandomFloat(-200, 200) * gpGlobals->frametime * 2, -mp_walkspeed.GetInt() / 2, mp_walkspeed.GetInt() / 2);
//Vector forward = Vector(0, GetTeam()->m_nForward, 0);
//VectorAngles(forward, m_cmd.viewangles);
//
//if (!m_bIsOffside && Sign(m_vDirToBall.y) == GetTeam()->m_nForward)
// m_cmd.forwardmove = mp_runspeed.GetInt();
//else if (Sign(pos.y - GetTeam()->m_vPlayerSpawns[GetShirtNumber() - 1].y) == GetTeam()->m_nForward)
// m_cmd.forwardmove = -mp_runspeed.GetInt();
}
}<commit_msg>Improve field bots<commit_after>#include "cbase.h"
#include "ios_fieldbot.h"
#include "sdk_player.h"
#include "team.h"
#include "in_buttons.h"
LINK_ENTITY_TO_CLASS(ios_fieldbot, CFieldBot);
ConVar bot_shootatgoal("bot_shootatgoal", "1");
void CFieldBot::BotThink()
{
if (!ShotButtonsReleased())
return;
if (m_vDirToBall.Length2D() > 35)
BotRunToBall();
else
BotShootBall();
}
void CFieldBot::BotShootBall()
{
Vector shotDir;
if (bot_shootatgoal.GetBool())
{
Vector target = GetOppTeam()->m_vGoalCenter;
float ownDistToGoal = (GetOppTeam()->m_vGoalCenter - GetLocalOrigin()).Length2D();
bool isGoalShot = true;
for (int i = 1; i <= gpGlobals->maxClients; i++ )
{
CSDKPlayer *pPl = (CSDKPlayer *)UTIL_PlayerByIndex(i);
if (!CSDKPlayer::IsOnField(pPl))
continue;
if (pPl->GetTeamNumber() != GetTeamNumber())
continue;
float distToGoal = (GetOppTeam()->m_vGoalCenter - pPl->GetLocalOrigin()).Length2D();
if (distToGoal < ownDistToGoal)
{
target = pPl->GetLocalOrigin();
isGoalShot = false;
break;
}
}
target.x += g_IOSRand.RandomFloat(-200, 200);
shotDir = target - GetLocalOrigin();
if (m_pHoldingBall)
{
if (!m_Shared.m_bIsShotCharging)
{
m_cmd.buttons |= IN_ATTACK2;
}
}
else if (isGoalShot)
{
if (ownDistToGoal > 1000)
{
m_cmd.buttons |= IN_ATTACK;
}
else
{
m_cmd.buttons |= IN_ATTACK;
}
}
else
{
m_cmd.buttons |= IN_ATTACK;
}
VectorAngles(shotDir, m_cmd.viewangles);
m_cmd.viewangles[PITCH] = g_IOSRand.RandomFloat(-89, 89);
}
else
{
if (GetFlags() & FL_ATCONTROLS)
{
//float xDir = g_IOSRand.RandomFloat(0.1f, 1) * Sign((SDKGameRules()->m_vKickOff - GetLocalOrigin()).x);
}
else
{
}
if (m_pHoldingBall)
{
if (!m_Shared.m_bIsShotCharging)
{
m_cmd.buttons |= IN_ATTACK2;
}
int kickOffDir = Sign(SDKGameRules()->m_vKickOff.GetX() - GetLocalOrigin().x);
shotDir = Vector(g_IOSRand.RandomFloat(0.25f, 1.0f) * kickOffDir, g_IOSRand.RandomFloat(-1, 1), 0);
}
else
{
m_cmd.buttons |= IN_ATTACK;
shotDir = Vector(g_IOSRand.RandomFloat(-1, 1), GetTeam()->m_nForward, 0);
}
VectorAngles(shotDir, m_cmd.viewangles);
m_cmd.viewangles[PITCH] = 0;
}
if (m_vDirToBall.z > GetPlayerMaxs().z + 10)
m_cmd.buttons |= IN_JUMP;
}
void CFieldBot::BotRunToBall()
{
float closestDist = FLT_MAX;
CSDKPlayer *pClosest = NULL;
for (int i = 1; i <= gpGlobals->maxClients; i++ )
{
CSDKPlayer *pPl = (CSDKPlayer *)UTIL_PlayerByIndex(i);
if (!CSDKPlayer::IsOnField(pPl))
continue;
if (pPl->GetTeamNumber() != GetTeamNumber())
continue;
float dist = (m_vBallPos - pPl->GetLocalOrigin()).Length2D();
if (dist < closestDist)
{
closestDist = dist;
pClosest = pPl;
}
}
if (pClosest == this)
{
VectorAngles(m_vDirToBall, m_cmd.viewangles);
m_cmd.forwardmove = clamp(m_oldcmd.forwardmove + g_IOSRand.RandomFloat(-mp_runspeed.GetInt(), mp_sprintspeed.GetInt()) * gpGlobals->frametime * 2, mp_runspeed.GetInt(), mp_sprintspeed.GetInt());
}
else
{
Vector pos = GetLocalOrigin();
if (pos.x < SDKGameRules()->m_vFieldMin.GetX() - 100 || pos.x > SDKGameRules()->m_vFieldMax.GetX() + 100 || pos.y < SDKGameRules()->m_vFieldMin.GetY() - 100 || pos.y > SDKGameRules()->m_vFieldMax.GetY() + 100)
{
QAngle ang;
VectorAngles(SDKGameRules()->m_vKickOff - pos, ang);
m_cmd.viewangles[YAW] = ang[YAW];
}
else
m_cmd.viewangles[YAW] = m_oldcmd.viewangles[YAW] + g_IOSRand.RandomFloat(-180, 180) * gpGlobals->frametime * 4;
m_cmd.forwardmove = clamp(m_oldcmd.forwardmove + g_IOSRand.RandomFloat(-mp_sprintspeed.GetInt(), mp_sprintspeed.GetInt()) * gpGlobals->frametime * 2, -mp_sprintspeed.GetInt() / 2, mp_sprintspeed.GetInt());
m_cmd.sidemove = clamp(m_oldcmd.sidemove + g_IOSRand.RandomFloat(-mp_sprintspeed.GetInt(), mp_sprintspeed.GetInt()) * gpGlobals->frametime * 2, -mp_sprintspeed.GetInt() / 2, mp_sprintspeed.GetInt() / 2);
}
if (m_cmd.forwardmove > mp_runspeed.GetInt() || m_cmd.sidemove > mp_runspeed.GetInt())
m_cmd.buttons |= IN_SPEED;
}<|endoftext|> |
<commit_before>/*
* SessionUserPrefs.hpp
*
* Copyright (C) 2009-19 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/system/Xdg.hpp>
#include <core/FileSerializer.hpp>
#include <core/json/JsonRpc.hpp>
#include <core/json/rapidjson/schema.h>
#include <session/SessionOptions.hpp>
#include "SessionUserPrefs.hpp"
using namespace rstudio::core;
namespace rstudio {
namespace session {
namespace modules {
namespace prefs {
namespace {
static boost::shared_ptr<json::Object> s_pUserPrefs;
}
json::Object userPrefs()
{
if (s_pUserPrefs)
return *s_pUserPrefs;
return json::Object();
}
Error initialize()
{
// Load schema for validation
FilePath schemaFile =
options().rResourcesPath().complete("prefs").complete("user-prefs-schema.json");
std::string schemaContents;
Error error = readStringFromFile(schemaFile, &schemaContents);
if (error)
return error;
rapidjson::Document sd;
if (sd.Parse(schemaContents).HasParseError())
{
return Error(json::errc::ParseError, ERROR_LOCATION);
}
// TODO: check for version-specific file first
FilePath prefsFile = core::system::xdg::userConfigDir().complete(kUserPrefsFile);
if (!prefsFile.exists())
return Success();
// TODO: validate version stored in file
std::string prefsContents;
error = readStringFromFile(prefsFile, &prefsContents);
if (error)
{
// don't fail here since it will cause startup to fail, we'll just live with no prefs
LOG_ERROR(error);
return Success();
}
// Parse the user preferences
rapidjson::Document pd;
if (pd.Parse(prefsContents).HasParseError())
{
return Error(json::errc::ParseError, ERROR_LOCATION);
}
// Validate the user prefs according to the schema
rapidjson::SchemaDocument schema(sd);
rapidjson::SchemaValidator validator(schema);
if (!pd.Accept(validator))
{
rapidjson::StringBuffer sb;
validator.GetInvalidSchemaPointer().StringifyUriFragment(sb);
error = Error(json::errc::ParseError, ERROR_LOCATION);
error.addProperty("schema", sb.GetString());
error.addProperty("keyword", validator.GetInvalidSchemaKeyword());
return error;
}
s_pUserPrefs = boost::make_shared<json::Object>();
// Iterate over every known preference value (which are exhaustively enumerated in the schema
// document) and read the value from the user prefs file if present
for (auto & it: sd["properties"].GetObject())
{
// Read the name of the preference
std::string prefName(it.name.GetString());
// See if the preference has a user-defined value
auto userPref = pd.FindMember(prefName);
rapidjson::Value val;
if (pd != pd.MemberEnd())
{
// It has a user-defined value; use it
val = userPref->value;
}
else
{
// No user defined value; use the default from the schema if we can find it.
auto pref = it.value;
if (pref.HasMember("default"))
{
val = pref["default"];
}
}
s_pUserPrefs[prefName] = val;
}
return Success();
}
} // namespace prefs
} // namespace modules
} // namespace session
} // namespace rstudio
<commit_msg>temporarily disable default building in ui prefs<commit_after>/*
* SessionUserPrefs.hpp
*
* Copyright (C) 2009-19 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/system/Xdg.hpp>
#include <core/FileSerializer.hpp>
#include <core/json/JsonRpc.hpp>
#include <core/json/rapidjson/schema.h>
#include <session/SessionOptions.hpp>
#include "SessionUserPrefs.hpp"
using namespace rstudio::core;
namespace rstudio {
namespace session {
namespace modules {
namespace prefs {
namespace {
static boost::shared_ptr<json::Object> s_pUserPrefs;
}
json::Object userPrefs()
{
if (s_pUserPrefs)
return *s_pUserPrefs;
return json::Object();
}
Error initialize()
{
// Load schema for validation
FilePath schemaFile =
options().rResourcesPath().complete("prefs").complete("user-prefs-schema.json");
std::string schemaContents;
Error error = readStringFromFile(schemaFile, &schemaContents);
if (error)
return error;
rapidjson::Document sd;
if (sd.Parse(schemaContents).HasParseError())
{
return Error(json::errc::ParseError, ERROR_LOCATION);
}
// TODO: check for version-specific file first
FilePath prefsFile = core::system::xdg::userConfigDir().complete(kUserPrefsFile);
if (!prefsFile.exists())
return Success();
// TODO: validate version stored in file
std::string prefsContents;
error = readStringFromFile(prefsFile, &prefsContents);
if (error)
{
// don't fail here since it will cause startup to fail, we'll just live with no prefs
LOG_ERROR(error);
return Success();
}
// Parse the user preferences
rapidjson::Document pd;
if (pd.Parse(prefsContents).HasParseError())
{
return Error(json::errc::ParseError, ERROR_LOCATION);
}
// Validate the user prefs according to the schema
rapidjson::SchemaDocument schema(sd);
rapidjson::SchemaValidator validator(schema);
if (!pd.Accept(validator))
{
rapidjson::StringBuffer sb;
validator.GetInvalidSchemaPointer().StringifyUriFragment(sb);
error = Error(json::errc::ParseError, ERROR_LOCATION);
error.addProperty("schema", sb.GetString());
error.addProperty("keyword", validator.GetInvalidSchemaKeyword());
return error;
}
s_pUserPrefs = boost::make_shared<json::Object>();
// Iterate over every known preference value (which are exhaustively enumerated in the schema
// document) and read the value from the user prefs file if present
/*
for (auto & it: sd["properties"].GetObject())
{
// Read the name of the preference
std::string prefName(it.name.GetString());
// See if the preference has a user-defined value
auto userPref = pd.FindMember(prefName);
rapidjson::Value val;
if (pd != pd.MemberEnd())
{
// It has a user-defined value; use it
val = userPref->value;
}
else
{
// No user defined value; use the default from the schema if we can find it.
auto pref = it.value;
if (pref.HasMember("default"))
{
val = pref["default"];
}
}
s_pUserPrefs[prefName] = val;
}
*/
return Success();
}
} // namespace prefs
} // namespace modules
} // namespace session
} // namespace rstudio
<|endoftext|> |
<commit_before>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
/**
* @file File.cpp
* @brief Implementation of all methods from the class File.
*/
#include <fstream>
#include <vector>
#include <pandora/Util.hpp>
#include <pandora/File.hpp>
#include <pandora/Block.hpp>
#include <pandora/Section.hpp>
#include <pandora/SectionIterator.hpp>
#include <pandora/SectionTreeIterator.hpp>
using namespace std;
namespace pandora {
// Format definition
const string File::VERSION = "1.0";
const string File::FORMAT = "pandora";
static unsigned int map_file_mode(FileMode mode) {
switch (mode) {
case FileMode::ReadWrite:
return H5F_ACC_RDWR;
case FileMode::ReadOnly:
return H5F_ACC_RDONLY;
case FileMode::Overwrite:
return H5F_ACC_TRUNC;
default:
return H5F_ACC_DEFAULT;
}
}
File::File(string name, FileMode mode)
{
if (!fileExists(name)) {
mode = FileMode::Overwrite;
}
unsigned int h5mode = map_file_mode(mode);
h5file = H5::H5File(name.c_str(), h5mode);
root = Group(h5file.openGroup("/"));
metadata = root.openGroup("metadata");
data = root.openGroup("data");
setCreatedAt();
setUpdatedAt();
if(!checkHeader()) {
/// TODO throw an exception here
}
}
File::File(const File &file)
: h5file(file.h5file), root(file.root), metadata(file.metadata), data(file.data)
{}
bool File::hasBlock(const std::string &id) const {
return data.hasGroup(id);
}
Block File::getBlock(const std::string &id) const {
return Block(*this, data.openGroup(id, false), id);
}
Block File::getBlock(size_t index) const {
string id = data.objectName(index);
Block b(*this, data.openGroup(id), id);
return b;
}
vector<Block> File::blocks() const {
vector<Block> block_obj;
size_t block_count = data.objectCount();
for (size_t i = 0; i < block_count; i++) {
string id = data.objectName(i);
Block b(*this, data.openGroup(id, false), id);
block_obj.push_back(b);
}
return block_obj;
}
Block File::createBlock(const std::string &name, string type) {
string id = util::createId("block");
while(data.hasObject(id))
id = util::createId("block");
Block b(*this, data.openGroup(id, true), id);
b.name(name);
b.type(type);
return b;
}
bool File::removeBlock(const std::string &id) {
if (data.hasGroup(id)) {
data.removeGroup(id);
return true;
} else {
return false;
}
}
size_t File::blockCount() const {
return data.objectCount();
}
std::vector<Section> File::sections()const{
vector<Section> section_obj;
size_t section_count = metadata.objectCount();
for (size_t i = 0; i < section_count; i++) {
string id = metadata.objectName(i);
Section s(*this,metadata.openGroup(id,false), id);
section_obj.push_back(s);
}
return section_obj;
}
bool File::hasSection(const std::string &id) const{
return metadata.hasGroup(id);
}
Section File::getSection(const std::string &id) const{
return Section(*this, metadata.openGroup(id, false), id);
}
Section File::getSection(size_t index) const{
string id = data.objectName(index);
Section s(*this, metadata.openGroup(id), id);
return s;
}
std::vector<Section> File::findSection(const std::string &id) const{
vector<Section> s = sections();
vector<Section> sects;
for(size_t i = 0; i < s.size(); i++){
if(s[i].id().compare(id)==0){
sects.push_back(s[i]);
return sects;
}
}
for(size_t i = 0; i < s.size(); i++){
sects = s[i].findSections([&](const Section §ion) {
bool found = section.id() == id;
return found;
});
if (sects.size() > 0){
return sects;
}
}
return sects;
}
Section File::createSection(const string &name, const string &type) {
string id = util::createId("section");
while(metadata.hasObject(id))
id = util::createId("section");
Section s(*this, metadata.openGroup(id, true), id);
s.name(name);
s.type(type);
return s;
}
bool File::removeSection(const std::string &id){
bool success = false;
std::vector<Section> sects = findSection(id);
if(!sects.empty()){
metadata.removeGroup(id);
success = true;
}
return success;
}
size_t File::sectionCount() const {
return metadata.objectCount();
}
time_t File::updatedAt() const {
string t;
root.getAttr("updated_at", t);
return util::strToTime(t);
}
void File::setUpdatedAt() {
if (!root.hasAttr("updated_at")) {
time_t t = time(NULL);
root.setAttr("updated_at", util::timeToStr(t));
}
}
void File::forceUpdatedAt() {
time_t t = time(NULL);
root.setAttr("updated_at", util::timeToStr(t));
}
time_t File::createdAt() const {
string t;
root.getAttr("created_at", t);
return util::strToTime(t);
}
void File::setCreatedAt() {
if (!root.hasAttr("created_at")) {
time_t t = time(NULL);
root.setAttr("created_at", util::timeToStr(t));
}
}
void File::forceCreatedAt(time_t t) {
root.setAttr("created_at", util::timeToStr(t));
}
string File::version() const {
string t;
root.getAttr<std::string>("version", t);
return t;
}
string File::format() const {
string t;
root.getAttr("format", t);
return t;
}
bool File::checkHeader() const {
bool check = true;
string str;
// check format
if (root.hasAttr("format")) {
if (!root.getAttr("format", str) || str != FORMAT) {
check = false;
}
} else {
root.setAttr("format", FORMAT);
}
// check version
if (root.hasAttr("version")) {
if (!root.getAttr("version", str) || str != VERSION) {
check = false;
}
} else {
root.setAttr("version", VERSION);
}
return check;
}
bool File::fileExists(string name) const {
ifstream f(name.c_str());
if (f) {
f.close();
return true;
} else {
return false;
}
}
bool File::operator==(const File &other) const {
return h5file.getFileName() == other.h5file.getFileName();
}
bool File::operator!=(const File &other) const {
return h5file.getFileName() != other.h5file.getFileName();
}
File& File::operator=(const File &other) {
if (*this != other) {
this->h5file = other.h5file;
this->root = other.root;
this->metadata = other.metadata;
this->data = other.data;
}
return *this;
}
File::~File() {
setUpdatedAt();
h5file.close();
}
} // end namespace pandora
<commit_msg>fixup...<commit_after>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
/**
* @file File.cpp
* @brief Implementation of all methods from the class File.
*/
#include <fstream>
#include <vector>
#include <pandora/Util.hpp>
#include <pandora/File.hpp>
#include <pandora/Block.hpp>
#include <pandora/Section.hpp>
#include <pandora/SectionIterator.hpp>
#include <pandora/SectionTreeIterator.hpp>
using namespace std;
namespace pandora {
// Format definition
const string File::VERSION = "1.0";
const string File::FORMAT = "pandora";
static unsigned int map_file_mode(FileMode mode) {
switch (mode) {
case FileMode::ReadWrite:
return H5F_ACC_RDWR;
case FileMode::ReadOnly:
return H5F_ACC_RDONLY;
case FileMode::Overwrite:
return H5F_ACC_TRUNC;
default:
return H5F_ACC_DEFAULT;
}
}
File::File(string name, FileMode mode)
{
if (!fileExists(name)) {
mode = FileMode::Overwrite;
}
unsigned int h5mode = map_file_mode(mode);
h5file = H5::H5File(name.c_str(), h5mode);
root = Group(h5file.openGroup("/"));
metadata = root.openGroup("metadata");
data = root.openGroup("data");
setCreatedAt();
setUpdatedAt();
if(!checkHeader()) {
/// TODO throw an exception here
}
}
File::File(const File &file)
: h5file(file.h5file), root(file.root), metadata(file.metadata), data(file.data)
{}
bool File::hasBlock(const std::string &id) const {
return data.hasGroup(id);
}
Block File::getBlock(const std::string &id) const {
return Block(*this, data.openGroup(id, false), id);
}
Block File::getBlock(size_t index) const {
string id = data.objectName(index);
Block b(*this, data.openGroup(id), id);
return b;
}
vector<Block> File::blocks() const {
vector<Block> block_obj;
size_t block_count = data.objectCount();
for (size_t i = 0; i < block_count; i++) {
string id = data.objectName(i);
Block b(*this, data.openGroup(id, false), id);
block_obj.push_back(b);
}
return block_obj;
}
Block File::createBlock(const std::string &name, string type) {
string id = util::createId("block");
while(data.hasObject(id))
id = util::createId("block");
Block b(*this, data.openGroup(id, true), id);
b.name(name);
b.type(type);
return b;
}
bool File::removeBlock(const std::string &id) {
if (data.hasGroup(id)) {
data.removeGroup(id);
return true;
} else {
return false;
}
}
size_t File::blockCount() const {
return data.objectCount();
}
std::vector<Section> File::sections()const{
vector<Section> section_obj;
size_t section_count = metadata.objectCount();
for (size_t i = 0; i < section_count; i++) {
string id = metadata.objectName(i);
Section s(*this,metadata.openGroup(id,false), id);
section_obj.push_back(s);
}
return section_obj;
}
bool File::hasSection(const std::string &id) const{
return metadata.hasGroup(id);
}
Section File::getSection(const std::string &id) const{
return Section(*this, metadata.openGroup(id, false), id);
}
Section File::getSection(size_t index) const{
string id = data.objectName(index);
Section s(*this, metadata.openGroup(id), id);
return s;
}
std::vector<Section> File::findSection(const std::string &id) const{
vector<Section> s = sections();
vector<Section> sects;
for(size_t i = 0; i < s.size(); i++){
if(s[i].id().compare(id)==0){
sects.push_back(s[i]);
return sects;
}
}
for(size_t i = 0; i < s.size(); i++){
sects = s[i].findSections([&](const Section §ion) {
bool found = section.id() == id;
return found;
});
if (sects.size() > 0){
return sects;
}
}
return sects;
}
Section File::createSection(const string &name, const string &type) {
string id = util::createId("section");
while(metadata.hasObject(id))
id = util::createId("section");
Section s(*this, metadata.openGroup(id, true), id);
s.name(name);
s.type(type);
return s;
}
bool File::removeSection(const std::string &id){
bool success = false;
std::vector<Section> sects = findSection(id);
if(!sects.empty()){
metadata.removeGroup(id);
success = true;
}
return success;
}
size_t File::sectionCount() const {
return metadata.objectCount();
}
time_t File::updatedAt() const {
string t;
root.getAttr("updated_at", t);
return util::strToTime(t);
}
void File::setUpdatedAt() {
if (!root.hasAttr("updated_at")) {
time_t t = time(NULL);
root.setAttr("updated_at", util::timeToStr(t));
}
}
void File::forceUpdatedAt() {
time_t t = time(NULL);
root.setAttr("updated_at", util::timeToStr(t));
}
time_t File::createdAt() const {
string t;
root.getAttr("created_at", t);
return util::strToTime(t);
}
void File::setCreatedAt() {
if (!root.hasAttr("created_at")) {
time_t t = time(NULL);
root.setAttr("created_at", util::timeToStr(t));
}
}
void File::forceCreatedAt(time_t t) {
root.setAttr("created_at", util::timeToStr(t));
}
string File::version() const {
string t;
root.getAttr<std::string>("version", t);
return t;
}
string File::format() const {
string t;
root.getAttr("format", t);
return t;
}
bool File::checkHeader() const {
bool check = true;
string str;
// check format
if (root.hasAttr("format")) {
if (!root.getAttr("format", str) || str != FORMAT) {
check = false;
}
} else {
root.setAttr("format", FORMAT);
}
// check version
if (root.hasAttr("version")) {
if (!root.getAttr("version", str) || str != VERSION) {
check = false;
}
} else {
root.setAttr("version", VERSION);
}
return check;
}
bool File::fileExists(string name) const {
ifstream f(name.c_str());
if (f) {
f.close();
return true;
} else {
return false;
}
}
bool File::operator==(const File &other) const {
return h5file.getFileName() == other.h5file.getFileName();
}
bool File::operator!=(const File &other) const {
return h5file.getFileName() != other.h5file.getFileName();
}
File& File::operator=(const File &other) {
if (*this != other) {
this->h5file = other.h5file;
this->root = other.root;
this->metadata = other.metadata;
this->data = other.data;
}
return *this;
}
File::~File() {
setUpdatedAt();
h5file.close();
}
} // end namespace pandora
<|endoftext|> |
<commit_before>#ifndef QRW_PATHFINDING_ASTAR_HPP
#define QRW_PATHFINDING_ASTAR_HPP
#include <set>
#include <map>
#include "engine/pathfinding/abstractpathfinder.hpp"
#include "engine/pathfinding/path.hpp"
#include "engine/pathfinding/node.hpp"
#include "engine/coordinates.hpp"
namespace qrw
{
namespace pathfinding
{
template<typename TSpatialRepresentation>
class AStar : public AbstractPathfinder<TSpatialRepresentation>
{
public:
AStar() = default;
~AStar() override { clear(); }
Path* findPath(const TSpatialRepresentation& start, const TSpatialRepresentation& end) override;
private:
TSpatialRepresentation findLowestF();
void clear();
std::map<TSpatialRepresentation, Node<TSpatialRepresentation>*> _nodemap;
std::set<Coordinates> _openlist;
std::set<Coordinates> _closedlist;
};
template<class TSpatialRepresentation>
Path* AStar<TSpatialRepresentation>::findPath(const TSpatialRepresentation& start, const TSpatialRepresentation& end)
{
if(!AbstractPathfinder<TSpatialRepresentation>::worldAdapter_->isAccessible(end))
return nullptr;
if(start == end)
return nullptr;
// Clear everything that remained from previous steps
clear();
// Initialize the algorithm
TSpatialRepresentation currentcoords = start;
auto currentnode = new Node<TSpatialRepresentation>(currentcoords);
Node<TSpatialRepresentation>* tmpnode = 0;
currentnode->setG(0);
currentnode->setH(currentcoords.distanceTo(end));
_nodemap[currentcoords] = currentnode;
_openlist.insert(currentcoords);
currentnode = nullptr;
// Run the algorithm
while(!_openlist.empty() && _closedlist.find(end) == _closedlist.end())
{
currentcoords = findLowestF();
_openlist.erase(currentcoords);
currentnode = _nodemap[currentcoords];
_closedlist.insert(currentcoords);
// Check the neighbors
for(const auto& neighbor : AbstractPathfinder<TSpatialRepresentation>::worldAdapter_->getNeighborLocationsFor(currentcoords))
{
// If the sqare is accessible but was not added to closedlist yet
if(_closedlist.find(neighbor) == _closedlist.end()
&& AbstractPathfinder<TSpatialRepresentation>::worldAdapter_->isAccessible(neighbor))
{
// Coordinates are not put into openlist
if(_openlist.find(neighbor) == _openlist.end())
{
tmpnode = new Node(neighbor);
tmpnode->setG(currentnode->getG() + 1);
tmpnode->setH(neighbor.distanceTo(end));
tmpnode->setParent(currentnode);
_nodemap[neighbor] = tmpnode;
_openlist.insert(neighbor);
}
else
{
tmpnode = _nodemap[neighbor];
if(currentnode->getG() + 1 < tmpnode->getG())
{
tmpnode->setParent(currentnode);
tmpnode->setG(currentnode->getG() + 1);
}
}
} // if(accessible && not on closedlist)
} // for(directions)
} // for(openlist not empty && end not reached)
// Build the Path
if(_closedlist.find(end) == _closedlist.end())
return nullptr;
auto path = new Path();
for(currentnode = _nodemap[end];
currentnode->getParent() != 0;
currentnode = currentnode->getParent())
{
path->prependStep(currentnode->getLocation());
}
path->prependStep(start);
return path;
}
template<class TSpatialRepresentation>
TSpatialRepresentation AStar<TSpatialRepresentation>::findLowestF()
{
if(_openlist.size() == 0)
return Coordinates(0, 0);
else if(_openlist.size() == 1)
return *_openlist.begin();
TSpatialRepresentation lowestcoordinate = *_openlist.begin();
Node<TSpatialRepresentation>* lowestfnode = _nodemap[lowestcoordinate];
Node<TSpatialRepresentation>* currentnode = 0;
for(auto coordinate : _openlist)
{
currentnode = _nodemap[coordinate];
if(currentnode->getF() < lowestfnode->getF())
{
lowestcoordinate = coordinate;
lowestfnode = currentnode;
}
}
return lowestcoordinate;
}
template<class TSpatialRepresentation>
void AStar<TSpatialRepresentation>::clear()
{
for(auto nodemapiter : _nodemap)
{
delete nodemapiter.second;
}
_nodemap.clear();
for(auto coordinate : _openlist)
{
// Erase coordinate from closed list so it is not deleted twice.
_closedlist.erase(coordinate);
}
_openlist.clear();
_closedlist.clear();
}
} // namespace pathfinding
} // namespace qrw
#endif // QRW_PATHFINDING_ASTAR_HPP
<commit_msg>Use this-> to get rid of full qualified naming in template astar<commit_after>#ifndef QRW_PATHFINDING_ASTAR_HPP
#define QRW_PATHFINDING_ASTAR_HPP
#include <set>
#include <map>
#include "engine/pathfinding/abstractpathfinder.hpp"
#include "engine/pathfinding/path.hpp"
#include "engine/pathfinding/node.hpp"
#include "engine/coordinates.hpp"
namespace qrw
{
namespace pathfinding
{
template<typename TSpatialRepresentation>
class AStar : public AbstractPathfinder<TSpatialRepresentation>
{
public:
AStar() = default;
~AStar() override { clear(); }
Path* findPath(const TSpatialRepresentation& start, const TSpatialRepresentation& end) override;
private:
TSpatialRepresentation findLowestF();
void clear();
std::map<TSpatialRepresentation, Node<TSpatialRepresentation>*> _nodemap;
std::set<Coordinates> _openlist;
std::set<Coordinates> _closedlist;
};
template<class TSpatialRepresentation>
Path* AStar<TSpatialRepresentation>::findPath(const TSpatialRepresentation& start, const TSpatialRepresentation& end)
{
if(!this->worldAdapter_->isAccessible(end))
return nullptr;
if(start == end)
return nullptr;
// Clear everything that remained from previous steps
clear();
// Initialize the algorithm
TSpatialRepresentation currentcoords = start;
auto currentnode = new Node<TSpatialRepresentation>(currentcoords);
Node<TSpatialRepresentation>* tmpnode = 0;
currentnode->setG(0);
currentnode->setH(currentcoords.distanceTo(end));
_nodemap[currentcoords] = currentnode;
_openlist.insert(currentcoords);
currentnode = nullptr;
// Run the algorithm
while(!_openlist.empty() && _closedlist.find(end) == _closedlist.end())
{
currentcoords = findLowestF();
_openlist.erase(currentcoords);
currentnode = _nodemap[currentcoords];
_closedlist.insert(currentcoords);
// Check the neighbors
for(const auto& neighbor : this->worldAdapter_->getNeighborLocationsFor(currentcoords))
{
// If the sqare is accessible but was not added to closedlist yet
if(_closedlist.find(neighbor) == _closedlist.end()
&& this->worldAdapter_->isAccessible(neighbor))
{
// Coordinates are not put into openlist
if(_openlist.find(neighbor) == _openlist.end())
{
tmpnode = new Node(neighbor);
tmpnode->setG(currentnode->getG() + 1);
tmpnode->setH(neighbor.distanceTo(end));
tmpnode->setParent(currentnode);
_nodemap[neighbor] = tmpnode;
_openlist.insert(neighbor);
}
else
{
tmpnode = _nodemap[neighbor];
if(currentnode->getG() + 1 < tmpnode->getG())
{
tmpnode->setParent(currentnode);
tmpnode->setG(currentnode->getG() + 1);
}
}
} // if(accessible && not on closedlist)
} // for(directions)
} // for(openlist not empty && end not reached)
// Build the Path
if(_closedlist.find(end) == _closedlist.end())
return nullptr;
auto path = new Path();
for(currentnode = _nodemap[end];
currentnode->getParent() != 0;
currentnode = currentnode->getParent())
{
path->prependStep(currentnode->getLocation());
}
path->prependStep(start);
return path;
}
template<class TSpatialRepresentation>
TSpatialRepresentation AStar<TSpatialRepresentation>::findLowestF()
{
if(_openlist.size() == 0)
return Coordinates(0, 0);
else if(_openlist.size() == 1)
return *_openlist.begin();
TSpatialRepresentation lowestcoordinate = *_openlist.begin();
Node<TSpatialRepresentation>* lowestfnode = _nodemap[lowestcoordinate];
Node<TSpatialRepresentation>* currentnode = 0;
for(auto coordinate : _openlist)
{
currentnode = _nodemap[coordinate];
if(currentnode->getF() < lowestfnode->getF())
{
lowestcoordinate = coordinate;
lowestfnode = currentnode;
}
}
return lowestcoordinate;
}
template<class TSpatialRepresentation>
void AStar<TSpatialRepresentation>::clear()
{
for(auto nodemapiter : _nodemap)
{
delete nodemapiter.second;
}
_nodemap.clear();
for(auto coordinate : _openlist)
{
// Erase coordinate from closed list so it is not deleted twice.
_closedlist.erase(coordinate);
}
_openlist.clear();
_closedlist.clear();
}
} // namespace pathfinding
} // namespace qrw
#endif // QRW_PATHFINDING_ASTAR_HPP
<|endoftext|> |
<commit_before>#include "Font.h"
#include <iostream>
#include <algorithm>
#include <vector>
#include "Renderer.h"
#include <boost/filesystem.hpp>
#include "Log.h"
FT_Library Font::sLibrary;
bool Font::libraryInitialized = false;
int Font::getDpiX() { return 96; }
int Font::getDpiY() { return 96; }
int Font::getSize() { return mSize; }
std::string Font::getDefaultPath()
{
const int fontCount = 4;
std::string fonts[fontCount] = { "/usr/share/fonts/truetype/ttf-dejavu/DejaVuSerif.ttf",
"/usr/share/fonts/TTF/DejaVuSerif.ttf",
"/usr/share/fonts/dejavu/DejaVuSerif.ttf",
"font.ttf" };
for(int i = 0; i < fontCount; i++)
{
if(boost::filesystem::exists(fonts[i]))
return fonts[i];
}
LOG(LogError) << "Error - could not find a font!";
return "";
}
void Font::initLibrary()
{
if(FT_Init_FreeType(&sLibrary))
{
LOG(LogError) << "Error initializing FreeType!";
}else{
libraryInitialized = true;
}
}
Font::Font(std::string path, int size)
{
mPath = path;
mSize = size;
init();
}
void Font::init()
{
if(!libraryInitialized)
initLibrary();
mMaxGlyphHeight = 0;
if(FT_New_Face(sLibrary, mPath.c_str(), 0, &face))
{
LOG(LogError) << "Error creating font face! (path: " << mPath.c_str();
return;
}
//FT_Set_Char_Size(face, 0, size * 64, getDpiX(), getDpiY());
FT_Set_Pixel_Sizes(face, 0, mSize);
buildAtlas();
FT_Done_Face(face);
}
void Font::deinit()
{
if(textureID)
glDeleteTextures(1, &textureID);
}
void Font::buildAtlas()
{
//find the size we should use
FT_GlyphSlot g = face->glyph;
int w = 0;
int h = 0;
/*for(int i = 32; i < 128; i++)
{
if(FT_Load_Char(face, i, FT_LOAD_RENDER))
{
fprintf(stderr, "Loading character %c failed!\n", i);
continue;
}
w += g->bitmap.width;
h = std::max(h, g->bitmap.rows);
}*/
//the max size (GL_MAX_TEXTURE_SIZE) is like 3300
w = 2048;
h = 512;
textureWidth = w;
textureHeight = h;
//create the texture
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_2D, textureID);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, w, h, 0, GL_ALPHA, GL_UNSIGNED_BYTE, NULL);
//copy the glyphs into the texture
int x = 0;
int y = 0;
int maxHeight = 0;
for(int i = 32; i < 128; i++)
{
if(FT_Load_Char(face, i, FT_LOAD_RENDER))
continue;
//prints rendered texture to the console
/*std::cout << "uploading at x: " << x << ", w: " << g->bitmap.width << " h: " << g->bitmap.rows << "\n";
for(int k = 0; k < g->bitmap.rows; k++)
{
for(int j = 0; j < g->bitmap.width; j++)
{
if(g->bitmap.buffer[g->bitmap.width * k + j])
std::cout << ".";
else
std::cout << " ";
}
std::cout << "\n";
}*/
if(x + g->bitmap.width >= textureWidth)
{
x = 0;
y += maxHeight;
maxHeight = 0;
}
if(g->bitmap.rows > maxHeight)
maxHeight = g->bitmap.rows;
glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, g->bitmap.width, g->bitmap.rows, GL_ALPHA, GL_UNSIGNED_BYTE, g->bitmap.buffer);
charData[i].texX = x;
charData[i].texY = y;
charData[i].texW = g->bitmap.width;
charData[i].texH = g->bitmap.rows;
charData[i].advX = g->metrics.horiAdvance >> 6;
charData[i].advY = g->advance.y >> 6;
charData[i].bearingY = g->metrics.horiBearingY >> 6;
if(charData[i].texH > mMaxGlyphHeight)
mMaxGlyphHeight = charData[i].texH;
x += g->bitmap.width;
}
if(y >= textureHeight)
{
LOG(LogError) << "Error - font size exceeded texture size! If you were doing something reasonable, tell Aloshi to fix it!";
}
glBindTexture(GL_TEXTURE_2D, 0);
//std::cout << "generated texture \"" << textureID << "\" (w: " << w << " h: " << h << ")" << std::endl;
}
Font::~Font()
{
if(textureID)
glDeleteTextures(1, &textureID);
}
//why these aren't in an array:
//openGL reads these in the order they are in memory
//if I use an array, it will be 4 x values then 4 y values
//it'll read XX, XX, YY instead of XY, XY, XY
//...
//that was the thinking at the time and honestly an array would have been smarter wow I'm dumb
struct point {
GLfloat pos0x;
GLfloat pos0y;
GLfloat pos1x;
GLfloat pos1y;
GLfloat pos2x;
GLfloat pos2y;
};
struct tex {
GLfloat tex0x;
GLfloat tex0y;
GLfloat tex1x;
GLfloat tex1y;
GLfloat tex2x;
GLfloat tex2y;
};
void Font::drawText(std::string text, int startx, int starty, int color)
{
if(!textureID)
{
LOG(LogError) << "Error - tried to draw with Font that has no texture loaded!";
return;
}
starty += mMaxGlyphHeight;
//padding (another 0.5% is added to the bottom through the sizeText function)
starty += (int)(mMaxGlyphHeight * 0.1f);
int pointCount = text.length() * 2;
point* points = new point[pointCount];
tex* texs = new tex[pointCount];
GLubyte* colors = new GLubyte[pointCount * 3 * 4];
glBindTexture(GL_TEXTURE_2D, textureID);
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
//texture atlas width/height
float tw = (float)textureWidth;
float th = (float)textureHeight;
int p = 0;
int i = 0;
float x = (float)startx;
float y = (float)starty;
for(; p < pointCount; i++, p++)
{
unsigned char letter = text[i];
if(letter < 32 || letter >= 128)
letter = 127; //print [X] if character is not standard ASCII
points[p].pos0x = x; points[p].pos0y = y + charData[letter].texH - charData[letter].bearingY;
points[p].pos1x = x + charData[letter].texW; points[p].pos1y = y - charData[letter].bearingY;
points[p].pos2x = x; points[p].pos2y = y - charData[letter].bearingY;
texs[p].tex0x = charData[letter].texX / tw; texs[p].tex0y = (charData[letter].texY + charData[letter].texH) / th;
texs[p].tex1x = (charData[letter].texX + charData[letter].texW) / tw; texs[p].tex1y = charData[letter].texY / th;
texs[p].tex2x = charData[letter].texX / tw; texs[p].tex2y = charData[letter].texY / th;
p++;
points[p].pos0x = x; points[p].pos0y = y + charData[letter].texH - charData[letter].bearingY;
points[p].pos1x = x + charData[letter].texW; points[p].pos1y = y - charData[letter].bearingY;
points[p].pos2x = x + charData[letter].texW; points[p].pos2y = y + charData[letter].texH - charData[letter].bearingY;
texs[p].tex0x = charData[letter].texX / tw; texs[p].tex0y = (charData[letter].texY + charData[letter].texH) / th;
texs[p].tex1x = (charData[letter].texX + charData[letter].texW) / tw; texs[p].tex1y = charData[letter].texY / th;
texs[p].tex2x = texs[p].tex1x; texs[p].tex2y = texs[p].tex0y;
x += charData[letter].advX;
}
Renderer::buildGLColorArray(colors, color, pointCount * 3);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glVertexPointer(2, GL_FLOAT, 0, points);
glTexCoordPointer(2, GL_FLOAT, 0, texs);
glColorPointer(4, GL_UNSIGNED_BYTE, 0, colors);
glDrawArrays(GL_TRIANGLES, 0, pointCount * 3);
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);
glDisable(GL_TEXTURE_2D);
glDisable(GL_BLEND);
delete[] points;
delete[] texs;
delete[] colors;
}
void Font::sizeText(std::string text, int* w, int* h)
{
int cwidth = 0;
for(unsigned int i = 0; i < text.length(); i++)
{
unsigned char letter = text[i];
if(letter < 32 || letter >= 128)
letter = 127;
cwidth += charData[letter].advX;
}
if(w != NULL)
*w = cwidth;
if(h != NULL)
*h = (int)(mMaxGlyphHeight + mMaxGlyphHeight * 0.5f);
}
int Font::getHeight()
{
return (int)(mMaxGlyphHeight * 1.5f);
}
<commit_msg>Find proper font path in Windows<commit_after>#include "Font.h"
#include <iostream>
#include <algorithm>
#include <vector>
#include "Renderer.h"
#include <boost/filesystem.hpp>
#include "Log.h"
FT_Library Font::sLibrary;
bool Font::libraryInitialized = false;
int Font::getDpiX() { return 96; }
int Font::getDpiY() { return 96; }
int Font::getSize() { return mSize; }
std::string Font::getDefaultPath()
{
const int fontCount = 4;
#ifdef WIN32
std::string fonts[] = {"DejaVuSerif.ttf",
"Arial.ttf",
"Verdana.ttf",
"Tahoma.ttf" };
//build full font path
TCHAR winDir[MAX_PATH];
GetWindowsDirectory(winDir, MAX_PATH);
#ifdef UNICODE
char winDirChar[MAX_PATH*2];
char DefChar = ' ';
WideCharToMultiByte(CP_ACP, 0, winDir, -1, winDirChar, MAX_PATH, &DefChar, NULL);
std::string fontPath(winDirChar);
#else
std::string fontPath(winDir);
#endif
fontPath += "\\Fonts\\";
//prepend to font file names
for(int i = 0; i < fontCount; i++)
{
fonts[i] = fontPath + fonts[i];
}
#else
std::string fonts[] = {"/usr/share/fonts/truetype/ttf-dejavu/DejaVuSerif.ttf",
"/usr/share/fonts/TTF/DejaVuSerif.ttf",
"/usr/share/fonts/dejavu/DejaVuSerif.ttf",
"font.ttf" };
#endif
for(int i = 0; i < fontCount; i++)
{
if(boost::filesystem::exists(fonts[i]))
return fonts[i];
}
LOG(LogError) << "Error - could not find a font!";
return "";
}
void Font::initLibrary()
{
if(FT_Init_FreeType(&sLibrary))
{
LOG(LogError) << "Error initializing FreeType!";
}else{
libraryInitialized = true;
}
}
Font::Font(std::string path, int size)
{
mPath = path;
mSize = size;
init();
}
void Font::init()
{
if(!libraryInitialized)
initLibrary();
mMaxGlyphHeight = 0;
if(FT_New_Face(sLibrary, mPath.c_str(), 0, &face))
{
LOG(LogError) << "Error creating font face! (path: " << mPath.c_str();
return;
}
//FT_Set_Char_Size(face, 0, size * 64, getDpiX(), getDpiY());
FT_Set_Pixel_Sizes(face, 0, mSize);
buildAtlas();
FT_Done_Face(face);
}
void Font::deinit()
{
if(textureID)
glDeleteTextures(1, &textureID);
}
void Font::buildAtlas()
{
//find the size we should use
FT_GlyphSlot g = face->glyph;
int w = 0;
int h = 0;
/*for(int i = 32; i < 128; i++)
{
if(FT_Load_Char(face, i, FT_LOAD_RENDER))
{
fprintf(stderr, "Loading character %c failed!\n", i);
continue;
}
w += g->bitmap.width;
h = std::max(h, g->bitmap.rows);
}*/
//the max size (GL_MAX_TEXTURE_SIZE) is like 3300
w = 2048;
h = 512;
textureWidth = w;
textureHeight = h;
//create the texture
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_2D, textureID);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, w, h, 0, GL_ALPHA, GL_UNSIGNED_BYTE, NULL);
//copy the glyphs into the texture
int x = 0;
int y = 0;
int maxHeight = 0;
for(int i = 32; i < 128; i++)
{
if(FT_Load_Char(face, i, FT_LOAD_RENDER))
continue;
//prints rendered texture to the console
/*std::cout << "uploading at x: " << x << ", w: " << g->bitmap.width << " h: " << g->bitmap.rows << "\n";
for(int k = 0; k < g->bitmap.rows; k++)
{
for(int j = 0; j < g->bitmap.width; j++)
{
if(g->bitmap.buffer[g->bitmap.width * k + j])
std::cout << ".";
else
std::cout << " ";
}
std::cout << "\n";
}*/
if(x + g->bitmap.width >= textureWidth)
{
x = 0;
y += maxHeight;
maxHeight = 0;
}
if(g->bitmap.rows > maxHeight)
maxHeight = g->bitmap.rows;
glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, g->bitmap.width, g->bitmap.rows, GL_ALPHA, GL_UNSIGNED_BYTE, g->bitmap.buffer);
charData[i].texX = x;
charData[i].texY = y;
charData[i].texW = g->bitmap.width;
charData[i].texH = g->bitmap.rows;
charData[i].advX = g->metrics.horiAdvance >> 6;
charData[i].advY = g->advance.y >> 6;
charData[i].bearingY = g->metrics.horiBearingY >> 6;
if(charData[i].texH > mMaxGlyphHeight)
mMaxGlyphHeight = charData[i].texH;
x += g->bitmap.width;
}
if(y >= textureHeight)
{
LOG(LogError) << "Error - font size exceeded texture size! If you were doing something reasonable, tell Aloshi to fix it!";
}
glBindTexture(GL_TEXTURE_2D, 0);
//std::cout << "generated texture \"" << textureID << "\" (w: " << w << " h: " << h << ")" << std::endl;
}
Font::~Font()
{
if(textureID)
glDeleteTextures(1, &textureID);
}
//why these aren't in an array:
//openGL reads these in the order they are in memory
//if I use an array, it will be 4 x values then 4 y values
//it'll read XX, XX, YY instead of XY, XY, XY
//...
//that was the thinking at the time and honestly an array would have been smarter wow I'm dumb
struct point {
GLfloat pos0x;
GLfloat pos0y;
GLfloat pos1x;
GLfloat pos1y;
GLfloat pos2x;
GLfloat pos2y;
};
struct tex {
GLfloat tex0x;
GLfloat tex0y;
GLfloat tex1x;
GLfloat tex1y;
GLfloat tex2x;
GLfloat tex2y;
};
void Font::drawText(std::string text, int startx, int starty, int color)
{
if(!textureID)
{
LOG(LogError) << "Error - tried to draw with Font that has no texture loaded!";
return;
}
starty += mMaxGlyphHeight;
//padding (another 0.5% is added to the bottom through the sizeText function)
starty += (int)(mMaxGlyphHeight * 0.1f);
int pointCount = text.length() * 2;
point* points = new point[pointCount];
tex* texs = new tex[pointCount];
GLubyte* colors = new GLubyte[pointCount * 3 * 4];
glBindTexture(GL_TEXTURE_2D, textureID);
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
//texture atlas width/height
float tw = (float)textureWidth;
float th = (float)textureHeight;
int p = 0;
int i = 0;
float x = (float)startx;
float y = (float)starty;
for(; p < pointCount; i++, p++)
{
unsigned char letter = text[i];
if(letter < 32 || letter >= 128)
letter = 127; //print [X] if character is not standard ASCII
points[p].pos0x = x; points[p].pos0y = y + charData[letter].texH - charData[letter].bearingY;
points[p].pos1x = x + charData[letter].texW; points[p].pos1y = y - charData[letter].bearingY;
points[p].pos2x = x; points[p].pos2y = y - charData[letter].bearingY;
texs[p].tex0x = charData[letter].texX / tw; texs[p].tex0y = (charData[letter].texY + charData[letter].texH) / th;
texs[p].tex1x = (charData[letter].texX + charData[letter].texW) / tw; texs[p].tex1y = charData[letter].texY / th;
texs[p].tex2x = charData[letter].texX / tw; texs[p].tex2y = charData[letter].texY / th;
p++;
points[p].pos0x = x; points[p].pos0y = y + charData[letter].texH - charData[letter].bearingY;
points[p].pos1x = x + charData[letter].texW; points[p].pos1y = y - charData[letter].bearingY;
points[p].pos2x = x + charData[letter].texW; points[p].pos2y = y + charData[letter].texH - charData[letter].bearingY;
texs[p].tex0x = charData[letter].texX / tw; texs[p].tex0y = (charData[letter].texY + charData[letter].texH) / th;
texs[p].tex1x = (charData[letter].texX + charData[letter].texW) / tw; texs[p].tex1y = charData[letter].texY / th;
texs[p].tex2x = texs[p].tex1x; texs[p].tex2y = texs[p].tex0y;
x += charData[letter].advX;
}
Renderer::buildGLColorArray(colors, color, pointCount * 3);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glVertexPointer(2, GL_FLOAT, 0, points);
glTexCoordPointer(2, GL_FLOAT, 0, texs);
glColorPointer(4, GL_UNSIGNED_BYTE, 0, colors);
glDrawArrays(GL_TRIANGLES, 0, pointCount * 3);
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);
glDisable(GL_TEXTURE_2D);
glDisable(GL_BLEND);
delete[] points;
delete[] texs;
delete[] colors;
}
void Font::sizeText(std::string text, int* w, int* h)
{
int cwidth = 0;
for(unsigned int i = 0; i < text.length(); i++)
{
unsigned char letter = text[i];
if(letter < 32 || letter >= 128)
letter = 127;
cwidth += charData[letter].advX;
}
if(w != NULL)
*w = cwidth;
if(h != NULL)
*h = (int)(mMaxGlyphHeight + mMaxGlyphHeight * 0.5f);
}
int Font::getHeight()
{
return (int)(mMaxGlyphHeight * 1.5f);
}
<|endoftext|> |
<commit_before>#ifndef MAP_MAP_HPP
#define MAP_MAP_HPP
#include <unordered_map>
#include <utility>
#include "Area.hpp"
#include "Tile.hpp"
#include "std_hash.hpp"
#include "AreaManager.hpp"
#include <SFML/Graphics.hpp>
/* Store all the map (Areas)
* and allaow you to load/unload piece of the map on the fly +
* get +/- index for the map minimum cell (Tile)
*/
namespace map
{
/* T is a tile class */
template<class T>
class Map
{
public:
explicit Map();
~Map();
Map(const Map&)=delete;
Map& operator=(const Map&) = delete;
T* operator()(const int& X,const int& Y);
void draw(sf::RenderTarget& target, sf::RenderStates states= sf::RenderStates::Default);
//void draw_areas(sf::RenderTarget& target, sf::RenderStates states= sf::RenderStates::Default);
template <typename ... Args>
inline static sf::Vector2i mapPixelToCoords(const Args&... args){
return T::mapPixelToCoords(args...);
};
template <typename ... Args>
inline static sf::Vector2f mapCoordsToPixel(Args&&... args){
return T::mapCoordsToPixel(args...);
};
private:
friend AreaManager<T>;
std::unordered_map<std::pair<int,int>,Area<T>*> areas;
AreaManager<T> areaManager;
/* To optimise operator(int X, int Y) acces */
Area<T>* _last_area;
int _last_area_X;
int _last_area_Y;
bool remove(Area<T>* area);
std::mutex mutex;
Area<T>& getOrCreateArea(const int& X,const int& Y);
};
};
#include "Map.tpl"
#endif
<commit_msg>add class keyword<commit_after>#ifndef MAP_MAP_HPP
#define MAP_MAP_HPP
#include <unordered_map>
#include <utility>
#include "Area.hpp"
#include "Tile.hpp"
#include "std_hash.hpp"
#include "AreaManager.hpp"
#include <SFML/Graphics.hpp>
/* Store all the map (Areas)
* and allaow you to load/unload piece of the map on the fly +
* get +/- index for the map minimum cell (Tile)
*/
namespace map
{
/* T is a tile class */
template<class T>
class Map
{
public:
explicit Map();
~Map();
Map(const Map&)=delete;
Map& operator=(const Map&) = delete;
T* operator()(const int& X,const int& Y);
void draw(sf::RenderTarget& target, sf::RenderStates states= sf::RenderStates::Default);
//void draw_areas(sf::RenderTarget& target, sf::RenderStates states= sf::RenderStates::Default);
template <typename ... Args>
inline static sf::Vector2i mapPixelToCoords(const Args&... args){
return T::mapPixelToCoords(args...);
};
template <typename ... Args>
inline static sf::Vector2f mapCoordsToPixel(Args&&... args){
return T::mapCoordsToPixel(args...);
};
private:
friend class AreaManager<T>;
std::unordered_map<std::pair<int,int>,Area<T>*> areas;
AreaManager<T> areaManager;
/* To optimise operator(int X, int Y) acces */
Area<T>* _last_area;
int _last_area_X;
int _last_area_Y;
bool remove(Area<T>* area);
std::mutex mutex;
Area<T>& getOrCreateArea(const int& X,const int& Y);
};
};
#include "Map.tpl"
#endif
<|endoftext|> |
<commit_before>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved.
This file is part of Navitia,
the software to build cool stuff with public transport.
Hope you'll enjoy and contribute to this project,
powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
a non ending quest to the responsive locomotion way of traveling!
LICENCE: This program 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.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Stay tuned using
twitter @navitia
IRC #navitia on freenode
https://groups.google.com/d/forum/navitia
www.navitia.io
*/
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE test_street_network
#include "georef/georef.h"
#include "builder.h"
#include "type/data.h"
#include "type/pt_data.h"
#include "georef/street_network.h"
#include <boost/test/unit_test.hpp>
using namespace navitia::georef;
using namespace navitia;
namespace bt = boost::posix_time;
using dir = ProjectionData::Direction;
namespace {
struct computation_results {
navitia::time_duration duration; // asked duration
std::vector<navitia::time_duration> durations_matrix; // duration matrix
std::vector<vertex_t> predecessor;
computation_results(navitia::time_duration d, const PathFinder& worker)
: duration(d), durations_matrix(worker.distances), predecessor(worker.predecessors) {}
bool operator==(const computation_results& other) {
BOOST_CHECK_EQUAL(other.duration, duration);
BOOST_REQUIRE_EQUAL(other.durations_matrix.size(), durations_matrix.size());
for (size_t i = 0; i < durations_matrix.size(); ++i) {
BOOST_CHECK_EQUAL(other.durations_matrix.at(i), durations_matrix.at(i));
}
BOOST_CHECK(predecessor == other.predecessor);
return true;
}
};
std::string get_name(int i, int j) {
std::stringstream ss;
ss << i << "_" << j;
return ss.str();
}
const ProjectionData build_data(GraphBuilder& b, type::Data& data) {
// graph creation
size_t square_size(10);
// we build a dumb square graph
for (size_t i = 0; i < square_size; ++i) {
for (size_t j = 0; j < square_size; ++j) {
std::string name(get_name(i, j));
b(name, i, j);
}
}
for (size_t i = 0; i < square_size - 1; ++i) {
for (size_t j = 0; j < square_size - 1; ++j) {
std::string name(get_name(i, j));
// we add edge to the next vertex (the value is not important)
b.add_edge(name, get_name(i, j + 1), navitia::seconds((i + j) * j));
b.add_edge(name, get_name(i + 1, j), navitia::seconds((i + j) * i));
}
}
type::StopPoint* sp = new type::StopPoint();
sp->coord.set_xy(8., 8.);
sp->idx = 0;
data.pt_data->stop_points.push_back(sp);
b.geo_ref.init();
b.geo_ref.project_stop_points(data.pt_data->stop_points);
const GeoRef::ProjectionByMode& projections = b.geo_ref.projected_stop_points[sp->idx];
const ProjectionData proj = projections[type::Mode_e::Walking];
BOOST_REQUIRE(proj.found); // we have to be able to project this point (on the walking graph)
b.geo_ref.build_proximity_list();
return proj;
}
} // namespace
/**
* The aim of the test is to check that the street network answer give the same answer
* to multiple get_distance question
*
**/
BOOST_AUTO_TEST_CASE(djikstra_idempotence) {
GraphBuilder b;
type::Data data;
auto proj = build_data(b, data);
// we project 2 stations
type::GeographicalCoord start;
start.set_xy(2., 2.);
DijkstraPathFinder worker(b.geo_ref);
worker.init(start, type::Mode_e::Walking, georef::default_speed[type::Mode_e::Walking]);
auto const target_idx = data.pt_data->stop_points.front()->idx;
auto distance = worker.get_distance(target_idx);
// we have to find a way to get there
BOOST_REQUIRE_NE(distance, bt::pos_infin);
std::cout << "distance " << distance << " proj distance to source " << proj.distances[dir::Source]
<< " proj distance to target " << proj.distances[dir::Target] << " distance to source "
<< worker.distances[proj[dir::Source]] << " distance to target " << worker.distances[proj[dir::Target]]
<< std::endl;
// the distance matrix also has to be updated
BOOST_CHECK(
worker.distances[proj[dir::Source]]
+ navitia::seconds(proj.distances[dir::Source] / double(default_speed[type::Mode_e::Walking]))
== distance // we have to take into account the projection distance
|| worker.distances[proj[dir::Target]]
+ navitia::seconds(proj.distances[dir::Target] / double(default_speed[type::Mode_e::Walking]))
== distance);
computation_results first_res{distance, worker};
// we ask again with the init again
{
worker.init(start, type::Mode_e::Walking, georef::default_speed[type::Mode_e::Walking]);
auto other_distance = worker.get_distance(target_idx);
computation_results other_res{other_distance, worker};
// we have to find a way to get there
BOOST_REQUIRE_NE(other_distance, bt::pos_infin);
// the distance matrix also has to be updated
BOOST_CHECK(
worker.distances[proj[dir::Source]]
+ navitia::seconds(proj.distances[dir::Source] / double(default_speed[type::Mode_e::Walking]))
== other_distance
|| worker.distances[proj[dir::Target]]
+ navitia::seconds(proj.distances[dir::Target] / double(default_speed[type::Mode_e::Walking]))
== other_distance);
BOOST_REQUIRE(first_res == other_res);
}
// we ask again without a init
{
auto other_distance = worker.get_distance(target_idx);
computation_results other_res{other_distance, worker};
// we have to find a way to get there
BOOST_CHECK_NE(other_distance, bt::pos_infin);
BOOST_CHECK(
worker.distances[proj[dir::Source]]
+ navitia::seconds(proj.distances[dir::Source] / double(default_speed[type::Mode_e::Walking]))
== other_distance
|| worker.distances[proj[dir::Target]]
+ navitia::seconds(proj.distances[dir::Target] / double(default_speed[type::Mode_e::Walking]))
== other_distance);
BOOST_CHECK(first_res == other_res);
}
}
BOOST_AUTO_TEST_CASE(astar_init) {
GraphBuilder b;
type::Data data;
auto proj_stop_point = build_data(b, data);
type::GeographicalCoord start;
start.set_xy(2., 2.);
type::GeographicalCoord destination;
start.set_xy(8., 6.);
AstarPathFinder worker(b.geo_ref);
worker.init(start, destination, type::Mode_e::Walking, georef::default_speed[type::Mode_e::Walking]);
auto const speed = georef::default_speed[type::Mode_e::Walking] * georef::default_speed[type::Mode_e::Walking];
BOOST_CHECK_EQUAL(worker.costs[proj_stop_point[dir::Source]], bt::pos_infin);
BOOST_CHECK_EQUAL(worker.costs[proj_stop_point[dir::Target]], bt::pos_infin);
// Distance is 10
BOOST_CHECK_EQUAL(worker.costs[worker.starting_edge[dir::Source]], navitia::seconds(10 / speed));
BOOST_CHECK_EQUAL(worker.costs[worker.starting_edge[dir::Target]], navitia::seconds(10 / speed));
}
<commit_msg>Revert "I am in pain..."<commit_after>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved.
This file is part of Navitia,
the software to build cool stuff with public transport.
Hope you'll enjoy and contribute to this project,
powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
a non ending quest to the responsive locomotion way of traveling!
LICENCE: This program 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.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Stay tuned using
twitter @navitia
IRC #navitia on freenode
https://groups.google.com/d/forum/navitia
www.navitia.io
*/
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE test_street_network
#include "georef/georef.h"
#include "builder.h"
#include "type/data.h"
#include "type/pt_data.h"
#include "georef/street_network.h"
#include <boost/test/unit_test.hpp>
using namespace navitia::georef;
using namespace navitia;
namespace bt = boost::posix_time;
using dir = ProjectionData::Direction;
namespace {
struct computation_results {
navitia::time_duration duration; // asked duration
std::vector<navitia::time_duration> durations_matrix; // duration matrix
std::vector<vertex_t> predecessor;
computation_results(navitia::time_duration d, const PathFinder& worker)
: duration(d), durations_matrix(worker.distances), predecessor(worker.predecessors) {}
bool operator==(const computation_results& other) {
BOOST_CHECK_EQUAL(other.duration, duration);
BOOST_REQUIRE_EQUAL(other.durations_matrix.size(), durations_matrix.size());
for (size_t i = 0; i < durations_matrix.size(); ++i) {
BOOST_CHECK_EQUAL(other.durations_matrix.at(i), durations_matrix.at(i));
}
BOOST_CHECK(predecessor == other.predecessor);
return true;
}
};
std::string get_name(int i, int j) {
std::stringstream ss;
ss << i << "_" << j;
return ss.str();
}
const ProjectionData build_data(GraphBuilder& b, type::Data& data, type::StopPoint* sp) {
// graph creation
size_t square_size(10);
// we build a dumb square graph
for (size_t i = 0; i < square_size; ++i) {
for (size_t j = 0; j < square_size; ++j) {
std::string name(get_name(i, j));
b(name, i, j);
}
}
for (size_t i = 0; i < square_size - 1; ++i) {
for (size_t j = 0; j < square_size - 1; ++j) {
std::string name(get_name(i, j));
// we add edge to the next vertex (the value is not important)
b.add_edge(name, get_name(i, j + 1), navitia::seconds((i + j) * j));
b.add_edge(name, get_name(i + 1, j), navitia::seconds((i + j) * i));
}
}
sp->coord.set_xy(8., 8.);
sp->idx = 0;
data.pt_data->stop_points.push_back(sp);
b.geo_ref.init();
b.geo_ref.project_stop_points(data.pt_data->stop_points);
const GeoRef::ProjectionByMode& projections = b.geo_ref.projected_stop_points[sp->idx];
const ProjectionData proj = projections[type::Mode_e::Walking];
BOOST_REQUIRE(proj.found); // we have to be able to project this point (on the walking graph)
b.geo_ref.build_proximity_list();
return proj;
}
} // namespace
/**
* The aim of the test is to check that the street network answer give the same answer
* to multiple get_distance question
*
**/
BOOST_AUTO_TEST_CASE(djikstra_idempotence) {
GraphBuilder b;
type::Data data;
auto sp = std::make_unique<type::StopPoint>();
auto proj = build_data(b, data, sp.get());
// we project 2 stations
type::GeographicalCoord start;
start.set_xy(2., 2.);
DijkstraPathFinder worker(b.geo_ref);
worker.init(start, type::Mode_e::Walking, georef::default_speed[type::Mode_e::Walking]);
type::idx_t target_idx(sp->idx);
auto distance = worker.get_distance(target_idx);
// we have to find a way to get there
BOOST_REQUIRE_NE(distance, bt::pos_infin);
std::cout << "distance " << distance << " proj distance to source " << proj.distances[dir::Source]
<< " proj distance to target " << proj.distances[dir::Target] << " distance to source "
<< worker.distances[proj[dir::Source]] << " distance to target " << worker.distances[proj[dir::Target]]
<< std::endl;
// the distance matrix also has to be updated
BOOST_CHECK(
worker.distances[proj[dir::Source]]
+ navitia::seconds(proj.distances[dir::Source] / double(default_speed[type::Mode_e::Walking]))
== distance // we have to take into account the projection distance
|| worker.distances[proj[dir::Target]]
+ navitia::seconds(proj.distances[dir::Target] / double(default_speed[type::Mode_e::Walking]))
== distance);
computation_results first_res{distance, worker};
// we ask again with the init again
{
worker.init(start, type::Mode_e::Walking, georef::default_speed[type::Mode_e::Walking]);
auto other_distance = worker.get_distance(target_idx);
computation_results other_res{other_distance, worker};
// we have to find a way to get there
BOOST_REQUIRE_NE(other_distance, bt::pos_infin);
// the distance matrix also has to be updated
BOOST_CHECK(
worker.distances[proj[dir::Source]]
+ navitia::seconds(proj.distances[dir::Source] / double(default_speed[type::Mode_e::Walking]))
== other_distance
|| worker.distances[proj[dir::Target]]
+ navitia::seconds(proj.distances[dir::Target] / double(default_speed[type::Mode_e::Walking]))
== other_distance);
BOOST_REQUIRE(first_res == other_res);
}
// we ask again without a init
{
auto other_distance = worker.get_distance(target_idx);
computation_results other_res{other_distance, worker};
// we have to find a way to get there
BOOST_CHECK_NE(other_distance, bt::pos_infin);
BOOST_CHECK(
worker.distances[proj[dir::Source]]
+ navitia::seconds(proj.distances[dir::Source] / double(default_speed[type::Mode_e::Walking]))
== other_distance
|| worker.distances[proj[dir::Target]]
+ navitia::seconds(proj.distances[dir::Target] / double(default_speed[type::Mode_e::Walking]))
== other_distance);
BOOST_CHECK(first_res == other_res);
}
}
BOOST_AUTO_TEST_CASE(astar_init) {
GraphBuilder b;
type::Data data;
auto sp = std::make_unique<type::StopPoint>();
auto proj_stop_point = build_data(b, data, sp.get());
type::GeographicalCoord start;
start.set_xy(2., 2.);
type::GeographicalCoord destination;
start.set_xy(8., 6.);
AstarPathFinder worker(b.geo_ref);
worker.init(start, destination, type::Mode_e::Walking, georef::default_speed[type::Mode_e::Walking]);
auto const speed = georef::default_speed[type::Mode_e::Walking] * georef::default_speed[type::Mode_e::Walking];
BOOST_CHECK_EQUAL(worker.costs[proj_stop_point[dir::Source]], bt::pos_infin);
BOOST_CHECK_EQUAL(worker.costs[proj_stop_point[dir::Target]], bt::pos_infin);
// Distance is 10
BOOST_CHECK_EQUAL(worker.costs[worker.starting_edge[dir::Source]], navitia::seconds(10 / speed));
BOOST_CHECK_EQUAL(worker.costs[worker.starting_edge[dir::Target]], navitia::seconds(10 / speed));
}
<|endoftext|> |
<commit_before>#ifndef KGR_INCLUDE_KANGARU_DETAIL_LAZY_BASE_HPP
#define KGR_INCLUDE_KANGARU_DETAIL_LAZY_BASE_HPP
#include "../container.hpp"
namespace kgr {
namespace detail {
template<typename T>
struct LazyHelper {
using type = T;
protected:
using ref = T&;
using rref = T&&;
using ptr = T*;
T&& assign_value(T&& service) {
return std::move(service);
}
T& value(T& service) {
return service;
}
};
template<typename T>
struct LazyHelper<T&> {
using type = T*;
protected:
using ref = T&;
using rref = T&&;
using ptr = T*;
T* assign_value(T& service) {
return &service;
}
T& value(T* service) {
return *service;
}
};
template<typename CRTP, typename T, template<typename, typename, typename = void> class... Bases>
struct LazyCrtpHelper : Bases<CRTP, T>... {};
template<typename CRTP, typename T, typename = void>
struct LazyCopyConstruct {
LazyCopyConstruct(const LazyCopyConstruct&) = delete;
LazyCopyConstruct() = default;
LazyCopyConstruct& operator=(const LazyCopyConstruct&) = default;
LazyCopyConstruct(LazyCopyConstruct&&) = default;
LazyCopyConstruct& operator=(LazyCopyConstruct&&) = default;
};
template<typename CRTP, typename T>
struct LazyCopyConstruct<CRTP, T, detail::enable_if_t<std::is_copy_constructible<T>::value>> {
LazyCopyConstruct(const LazyCopyConstruct& other) {
auto& o = static_cast<const CRTP&>(other);
if (o._initialized) {
static_cast<CRTP&>(*this).emplace(o.data());
}
}
LazyCopyConstruct() = default;
LazyCopyConstruct& operator=(const LazyCopyConstruct&) = default;
LazyCopyConstruct(LazyCopyConstruct&&) = default;
LazyCopyConstruct& operator=(LazyCopyConstruct&&) = default;
};
template<typename CRTP, typename T, typename = void>
struct LazyCopyAssign {
LazyCopyAssign& operator=(const LazyCopyAssign&) = delete;
LazyCopyAssign() = default;
LazyCopyAssign(LazyCopyAssign&&) = default;
LazyCopyAssign& operator=(LazyCopyAssign&&) = default;
LazyCopyAssign(const LazyCopyAssign&) = default;
};
template<typename CRTP, typename T>
struct LazyCopyAssign<CRTP, T, detail::enable_if_t<std::is_copy_assignable<T>::value && std::is_copy_constructible<T>::value>> {
LazyCopyAssign& operator=(const LazyCopyAssign& other) {
auto& o = static_cast<const CRTP&>(other);
auto& self = static_cast<CRTP&>(*this);
if (o._initialized) {
self.assign(o.data());
} else {
self.destroy();
}
return *this;
}
LazyCopyAssign() = default;
LazyCopyAssign(LazyCopyAssign&&) = default;
LazyCopyAssign& operator=(LazyCopyAssign&&) = default;
LazyCopyAssign(const LazyCopyAssign&) = default;
};
template<typename CRTP, typename T, typename = void>
struct LazyMoveConstruct {
LazyMoveConstruct(LazyMoveConstruct&&) = delete;
LazyMoveConstruct() = default;
LazyMoveConstruct& operator=(const LazyMoveConstruct&) = default;
LazyMoveConstruct& operator=(LazyMoveConstruct&&) = default;
LazyMoveConstruct(const LazyMoveConstruct&) = default;
};
template<typename CRTP, typename T>
struct LazyMoveConstruct<CRTP, T, detail::enable_if_t<std::is_move_constructible<T>::value>> {
LazyMoveConstruct(LazyMoveConstruct&& other) {
auto& o = static_cast<CRTP&>(other);
if (o._initialized) {
static_cast<CRTP&>(*this).emplace(std::move(o.data()));
}
}
LazyMoveConstruct() = default;
LazyMoveConstruct& operator=(const LazyMoveConstruct&) = default;
LazyMoveConstruct& operator=(LazyMoveConstruct&&) = default;
LazyMoveConstruct(const LazyMoveConstruct&) = default;
};
template<typename CRTP, typename T, typename = void>
struct LazyMoveAssign {
LazyMoveAssign& operator=(LazyMoveAssign&&) = delete;
LazyMoveAssign() = default;
LazyMoveAssign& operator=(const LazyMoveAssign&) = default;
LazyMoveAssign(LazyMoveAssign&&) = default;
LazyMoveAssign(const LazyMoveAssign&) = default;
};
template<typename CRTP, typename T>
struct LazyMoveAssign<CRTP, T, detail::enable_if_t<std::is_move_assignable<T>::value && std::is_move_constructible<T>::value>> {
LazyMoveAssign& operator=(LazyMoveAssign&& other) {
auto& o = static_cast<CRTP&>(other);
auto& self = static_cast<CRTP&>(*this);
if (o._initialized) {
self.assign(std::move(o.data()));
} else {
self.destroy();
}
return *this;
}
LazyMoveAssign() = default;
LazyMoveAssign& operator=(const LazyMoveAssign&) = default;
LazyMoveAssign(LazyMoveAssign&&) = default;
LazyMoveAssign(const LazyMoveAssign&) = default;
};
template<typename CRTP, typename T>
struct LazyBase :
LazyHelper<ServiceType<T>>,
LazyCrtpHelper<LazyBase<CRTP, T>, typename detail::LazyHelper<ServiceType<T>>::type, LazyCopyConstruct, LazyCopyAssign, LazyMoveAssign, LazyMoveConstruct> {
private:
using typename detail::LazyHelper<ServiceType<T>>::type;
using typename detail::LazyHelper<ServiceType<T>>::ref;
using typename detail::LazyHelper<ServiceType<T>>::rref;
using typename detail::LazyHelper<ServiceType<T>>::ptr;
template<typename, typename, typename> friend struct LazyCopyConstruct;
template<typename, typename, typename> friend struct LazyCopyAssign;
template<typename, typename, typename> friend struct LazyMoveAssign;
template<typename, typename, typename> friend struct LazyMoveConstruct;
public:
LazyBase() = default;
LazyBase& operator=(LazyBase&&) = default;
LazyBase& operator=(const LazyBase&) = default;
LazyBase(LazyBase&&) = default;
LazyBase(const LazyBase&) = default;
~LazyBase() {
destroy();
}
ref operator*() & {
return get();
}
ptr operator->() {
return &get();
}
rref operator*() && {
return std::move(get());
}
ref get() {
if (!_initialized) {
emplace(this->assign_value(static_cast<CRTP*>(this)->_container.template service<T>()));
}
return this->value(data());
}
private:
type& data() {
return *reinterpret_cast<type*>(&_service);
}
const type& data() const {
return *reinterpret_cast<const type*>(&_service);
}
template<typename... Args>
void emplace(Args&&... args) {
destroy();
_initialized = true;
new (&_service) type(std::forward<Args>(args)...);
}
void destroy() {
if (_initialized) {
_initialized = false;
data().~type();
}
}
template<typename Arg>
void assign(Arg&& arg) {
if (!_initialized) {
emplace(std::forward<Arg>(arg));
} else {
data() = std::forward<Arg>(arg);
}
}
bool _initialized = false;
typename std::aligned_storage<sizeof(type), alignof(type)>::type _service;
};
} // namespace detail
} // namespace kgr
#endif // KGR_INCLUDE_KANGARU_DETAIL_LAZY_BASE_HPP
<commit_msg>reordered classes to enhance lisibility<commit_after>#ifndef KGR_INCLUDE_KANGARU_DETAIL_LAZY_BASE_HPP
#define KGR_INCLUDE_KANGARU_DETAIL_LAZY_BASE_HPP
#include "../container.hpp"
namespace kgr {
namespace detail {
template<typename T>
struct LazyHelper {
using type = T;
protected:
using ref = T&;
using rref = T&&;
using ptr = T*;
T&& assign_value(T&& service) {
return std::move(service);
}
T& value(T& service) {
return service;
}
};
template<typename T>
struct LazyHelper<T&> {
using type = T*;
protected:
using ref = T&;
using rref = T&&;
using ptr = T*;
T* assign_value(T& service) {
return &service;
}
T& value(T* service) {
return *service;
}
};
template<typename CRTP, typename T, template<typename, typename, typename = void> class... Bases>
struct LazyCrtpHelper : Bases<CRTP, T>... {};
template<typename CRTP, typename T, typename = void>
struct LazyCopyConstruct {
LazyCopyConstruct(const LazyCopyConstruct&) = delete;
LazyCopyConstruct() = default;
LazyCopyConstruct& operator=(const LazyCopyConstruct&) = default;
LazyCopyConstruct(LazyCopyConstruct&&) = default;
LazyCopyConstruct& operator=(LazyCopyConstruct&&) = default;
};
template<typename CRTP, typename T, typename = void>
struct LazyMoveAssign {
LazyMoveAssign& operator=(LazyMoveAssign&&) = delete;
LazyMoveAssign() = default;
LazyMoveAssign(const LazyMoveAssign&) = default;
LazyMoveAssign& operator=(const LazyMoveAssign&) = default;
LazyMoveAssign(LazyMoveAssign&&) = default;
};
template<typename CRTP, typename T, typename = void>
struct LazyCopyAssign {
LazyCopyAssign& operator=(const LazyCopyAssign&) = delete;
LazyCopyAssign() = default;
LazyCopyAssign(const LazyCopyAssign&) = default;
LazyCopyAssign(LazyCopyAssign&&) = default;
LazyCopyAssign& operator=(LazyCopyAssign&&) = default;
};
template<typename CRTP, typename T, typename = void>
struct LazyMoveConstruct {
LazyMoveConstruct(LazyMoveConstruct&&) = delete;
LazyMoveConstruct() = default;
LazyMoveConstruct(const LazyMoveConstruct&) = default;
LazyMoveConstruct& operator=(const LazyMoveConstruct&) = default;
LazyMoveConstruct& operator=(LazyMoveConstruct&&) = default;
};
template<typename CRTP, typename T>
struct LazyCopyConstruct<CRTP, T, detail::enable_if_t<std::is_copy_constructible<T>::value>> {
LazyCopyConstruct(const LazyCopyConstruct& other) {
auto& o = static_cast<const CRTP&>(other);
if (o._initialized) {
static_cast<CRTP&>(*this).emplace(o.data());
}
}
LazyCopyConstruct() = default;
LazyCopyConstruct& operator=(const LazyCopyConstruct&) = default;
LazyCopyConstruct(LazyCopyConstruct&&) = default;
LazyCopyConstruct& operator=(LazyCopyConstruct&&) = default;
};
template<typename CRTP, typename T>
struct LazyCopyAssign<CRTP, T, detail::enable_if_t<std::is_copy_assignable<T>::value && std::is_copy_constructible<T>::value>> {
LazyCopyAssign& operator=(const LazyCopyAssign& other) {
auto& o = static_cast<const CRTP&>(other);
auto& self = static_cast<CRTP&>(*this);
if (o._initialized) {
self.assign(o.data());
} else {
self.destroy();
}
return *this;
}
LazyCopyAssign() = default;
LazyCopyAssign(const LazyCopyAssign&) = default;
LazyCopyAssign(LazyCopyAssign&&) = default;
LazyCopyAssign& operator=(LazyCopyAssign&&) = default;
};
template<typename CRTP, typename T>
struct LazyMoveConstruct<CRTP, T, detail::enable_if_t<std::is_move_constructible<T>::value>> {
LazyMoveConstruct(LazyMoveConstruct&& other) {
auto& o = static_cast<CRTP&>(other);
if (o._initialized) {
static_cast<CRTP&>(*this).emplace(std::move(o.data()));
}
}
LazyMoveConstruct() = default;
LazyMoveConstruct(const LazyMoveConstruct&) = default;
LazyMoveConstruct& operator=(LazyMoveConstruct&&) = default;
LazyMoveConstruct& operator=(const LazyMoveConstruct&) = default;
};
template<typename CRTP, typename T>
struct LazyMoveAssign<CRTP, T, detail::enable_if_t<std::is_move_assignable<T>::value && std::is_move_constructible<T>::value>> {
LazyMoveAssign& operator=(LazyMoveAssign&& other) {
auto& o = static_cast<CRTP&>(other);
auto& self = static_cast<CRTP&>(*this);
if (o._initialized) {
self.assign(std::move(o.data()));
} else {
self.destroy();
}
return *this;
}
LazyMoveAssign() = default;
LazyMoveAssign(const LazyMoveAssign&) = default;
LazyMoveAssign& operator=(const LazyMoveAssign&) = default;
LazyMoveAssign(LazyMoveAssign&&) = default;
};
template<typename CRTP, typename T>
struct LazyBase :
LazyHelper<ServiceType<T>>,
LazyCrtpHelper<LazyBase<CRTP, T>, typename detail::LazyHelper<ServiceType<T>>::type, LazyCopyConstruct, LazyCopyAssign, LazyMoveAssign, LazyMoveConstruct> {
private:
using typename detail::LazyHelper<ServiceType<T>>::type;
using typename detail::LazyHelper<ServiceType<T>>::ref;
using typename detail::LazyHelper<ServiceType<T>>::rref;
using typename detail::LazyHelper<ServiceType<T>>::ptr;
template<typename, typename, typename> friend struct LazyCopyConstruct;
template<typename, typename, typename> friend struct LazyCopyAssign;
template<typename, typename, typename> friend struct LazyMoveAssign;
template<typename, typename, typename> friend struct LazyMoveConstruct;
public:
LazyBase() = default;
LazyBase& operator=(LazyBase&&) = default;
LazyBase& operator=(const LazyBase&) = default;
LazyBase(LazyBase&&) = default;
LazyBase(const LazyBase&) = default;
~LazyBase() {
destroy();
}
ref operator*() & {
return get();
}
ptr operator->() {
return &get();
}
rref operator*() && {
return std::move(get());
}
ref get() {
if (!_initialized) {
emplace(this->assign_value(static_cast<CRTP*>(this)->_container.template service<T>()));
}
return this->value(data());
}
private:
type& data() {
return *reinterpret_cast<type*>(&_service);
}
const type& data() const {
return *reinterpret_cast<const type*>(&_service);
}
template<typename... Args>
void emplace(Args&&... args) {
destroy();
_initialized = true;
new (&_service) type(std::forward<Args>(args)...);
}
void destroy() {
if (_initialized) {
_initialized = false;
data().~type();
}
}
template<typename Arg>
void assign(Arg&& arg) {
if (!_initialized) {
emplace(std::forward<Arg>(arg));
} else {
data() = std::forward<Arg>(arg);
}
}
bool _initialized = false;
typename std::aligned_storage<sizeof(type), alignof(type)>::type _service;
};
} // namespace detail
} // namespace kgr
#endif // KGR_INCLUDE_KANGARU_DETAIL_LAZY_BASE_HPP
<|endoftext|> |
<commit_before>#include <stdlib.h>
#include <math.h>
#include "gason.h"
static unsigned char ctype[256];
static const struct ctype_init_t
{
ctype_init_t()
{
for (int i : "\t\n\v\f\r\x20") ctype[i] |= 001;
for (int i : ",:]}") ctype[i] |= 002;
for (int i : "+-") ctype[i] |= 004;
for (int i : "0123456789") ctype[i] |= 010;
for (int i : "ABCDEF" "abcdef") ctype[i] |= 020;
}
} ctype_init;
inline bool is_space(char c) { return (ctype[(int)(unsigned char)c] & 001) != 0; }
inline bool is_delim(char c) { return (ctype[(int)(unsigned char)c] & 003) != 0; }
inline bool is_sign(char c) { return (ctype[(int)(unsigned char)c] & 004) != 0; }
inline bool is_dec(char c) { return (ctype[(int)(unsigned char)c] & 010) != 0; }
inline bool is_hex(char c) { return (ctype[(int)(unsigned char)c] & 030) != 0; }
inline int char2int(char c)
{
if (c >= 'a') return c - 'a' + 10;
if (c >= 'A') return c - 'A' + 10;
return c - '0';
}
static double str2float(const char *str, char **endptr)
{
double sign = 1;
if (is_sign(*str)) sign = ',' - *str++;
double result = 0;
while (is_dec(*str)) result = (result * 10) + (*str++ - '0');
if (*str == '.')
{
++str;
double base = 1;
while (is_dec(*str)) base *= 0.1, result += (*str++ - '0') * base;
}
double exponent = 0;
if (*str == 'e' || *str == 'E')
{
++str;
double sign = 1;
if (is_sign(*str)) sign = ',' - *str++;
while (is_dec(*str)) exponent = (exponent * 10) + (*str++ - '0');
exponent *= sign;
}
*endptr = (char *)str;
return sign * result * pow(10, exponent);
}
JsonAllocator::~JsonAllocator()
{
while (head)
{
Zone *temp = head->next;
free(head);
head = temp;
}
}
inline void *align_pointer(void *x, size_t align) { return (void *)(((uintptr_t)x + (align - 1)) & ~(align - 1)); }
void *JsonAllocator::allocate(size_t n, size_t align)
{
if (head)
{
char *p = (char *)align_pointer(head->end, align);
if (p + n <= (char *)head + JSON_ZONE_SIZE)
{
head->end = p + n;
return p;
}
}
size_t zone_size = sizeof(Zone) + n + align;
Zone *z = (Zone *)malloc(zone_size <= JSON_ZONE_SIZE ? JSON_ZONE_SIZE : zone_size);
char *p = (char *)align_pointer(z + 1, align);
z->end = p + n;
if (zone_size <= JSON_ZONE_SIZE || head == nullptr)
{
z->next = head;
head = z;
}
else
{
z->next = head->next;
head->next = z;
}
return p;
}
struct JsonList
{
JsonTag tag;
JsonValue node;
char *key;
void grow_the_tail(JsonNode *p)
{
JsonNode *tail = (JsonNode *)node.getPayload();
if (tail)
{
p->next = tail->next;
tail->next = p;
}
else
{
p->next = p;
}
node = JsonValue(tag, p);
}
JsonValue cut_the_head()
{
JsonNode *tail = (JsonNode *)node.getPayload();
if (tail)
{
JsonNode *head = tail->next;
tail->next = nullptr;
return JsonValue(tag, head);
}
return node;
}
};
JsonParseStatus json_parse(char *str, char **endptr, JsonValue *value, JsonAllocator &allocator)
{
JsonList stack[JSON_STACK_SIZE];
int top = -1;
bool separator = true;
while (*str)
{
JsonValue o;
while (*str && is_space(*str)) ++str;
*endptr = str++;
switch (**endptr)
{
case '\0':
continue;
case '-':
if (!is_dec(*str) && *str != '.') return *endptr = str, JSON_PARSE_BAD_NUMBER;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
o = JsonValue(str2float(*endptr, &str));
if (!is_delim(*str)) return *endptr = str, JSON_PARSE_BAD_NUMBER;
break;
case '"':
o = JsonValue(JSON_TAG_STRING, str);
for (char *s = str; *str; ++s, ++str)
{
int c = *s = *str;
if (c == '\\')
{
c = *++str;
switch (c)
{
case '\\':
case '"':
case '/': *s = c; break;
case 'b': *s = '\b'; break;
case 'f': *s = '\f'; break;
case 'n': *s = '\n'; break;
case 'r': *s = '\r'; break;
case 't': *s = '\t'; break;
case 'u':
c = 0;
for (int i = 0; i < 4; ++i)
{
if (!is_hex(*++str)) return *endptr = str, JSON_PARSE_BAD_STRING;
c = c * 16 + char2int(*str);
}
if (c < 0x80)
{
*s = c;
}
else if (c < 0x800)
{
*s++ = 0xC0 | (c >> 6);
*s = 0x80 | (c & 0x3F);
}
else
{
*s++ = 0xE0 | (c >> 12);
*s++ = 0x80 | ((c >> 6) & 0x3F);
*s = 0x80 | (c & 0x3F);
}
break;
default:
return *endptr = str, JSON_PARSE_BAD_STRING;
}
}
else if (c == '"')
{
*s = 0;
++str;
break;
}
}
if (!is_delim(*str)) return *endptr = str, JSON_PARSE_BAD_STRING;
break;
case 't':
for (const char *s = "rue"; *s; ++s, ++str)
{
if (*s != *str) return JSON_PARSE_BAD_IDENTIFIER;
}
if (!is_delim(*str)) return JSON_PARSE_BAD_IDENTIFIER;
o = JsonValue(JSON_TAG_BOOL, (void *)true);
break;
case 'f':
for (const char *s = "alse"; *s; ++s, ++str)
{
if (*s != *str) return JSON_PARSE_BAD_IDENTIFIER;
}
if (!is_delim(*str)) return JSON_PARSE_BAD_IDENTIFIER;
o = JsonValue(JSON_TAG_BOOL, (void *)false);
break;
case 'n':
for (const char *s = "ull"; *s; ++s, ++str)
{
if (*s != *str) return JSON_PARSE_BAD_IDENTIFIER;
}
if (!is_delim(*str)) return JSON_PARSE_BAD_IDENTIFIER;
break;
case ']':
if (top == -1) return JSON_PARSE_STACK_UNDERFLOW;
if (stack[top].tag != JSON_TAG_ARRAY) return JSON_PARSE_MISMATCH_BRACKET;
o = stack[top--].cut_the_head();
break;
case '}':
if (top == -1) return JSON_PARSE_STACK_UNDERFLOW;
if (stack[top].tag != JSON_TAG_OBJECT) return JSON_PARSE_MISMATCH_BRACKET;
o = stack[top--].cut_the_head();
break;
case '[':
if (++top == JSON_STACK_SIZE) return JSON_PARSE_STACK_OVERFLOW;
stack[top] = {JSON_TAG_ARRAY, JsonValue(JSON_TAG_ARRAY, nullptr), nullptr};
continue;
case '{':
if (++top == JSON_STACK_SIZE) return JSON_PARSE_STACK_OVERFLOW;
stack[top] = {JSON_TAG_OBJECT, JsonValue(JSON_TAG_OBJECT, nullptr), nullptr};
continue;
case ':':
if (separator || stack[top].key == nullptr) return JSON_PARSE_UNEXPECTED_CHARACTER;
separator = true;
continue;
case ',':
if (separator || stack[top].key != nullptr) return JSON_PARSE_UNEXPECTED_CHARACTER;
separator = true;
continue;
default:
return JSON_PARSE_UNEXPECTED_CHARACTER;
}
separator = false;
if (top == -1)
{
*endptr = str;
*value = o;
return JSON_PARSE_OK;
}
if (stack[top].tag == JSON_TAG_OBJECT)
{
if (!stack[top].key)
{
if (o.getTag() != JSON_TAG_STRING) return JSON_PARSE_UNQUOTED_KEY;
stack[top].key = o.toString();
continue;
}
JsonNode *p = (JsonNode *)allocator.allocate(sizeof(JsonNode));
p->value = o;
p->key = stack[top].key;
stack[top].key = nullptr;
stack[top].grow_the_tail((JsonNode *)p);
continue;
}
JsonNode *p = (JsonNode *)allocator.allocate(sizeof(JsonNode) - sizeof(char *));
p->value = o;
stack[top].grow_the_tail(p);
}
return JSON_PARSE_BREAKING_BAD;
}
<commit_msg>new exponent pow calc<commit_after>#include <stdlib.h>
#include "gason.h"
static unsigned char ctype[256];
static const struct ctype_init_t
{
ctype_init_t()
{
for (int i : "\t\n\v\f\r\x20") ctype[i] |= 001;
for (int i : ",:]}") ctype[i] |= 002;
for (int i : "+-") ctype[i] |= 004;
for (int i : "0123456789") ctype[i] |= 010;
for (int i : "ABCDEF" "abcdef") ctype[i] |= 020;
}
} ctype_init;
inline bool is_space(char c) { return (ctype[(int)(unsigned char)c] & 001) != 0; }
inline bool is_delim(char c) { return (ctype[(int)(unsigned char)c] & 003) != 0; }
inline bool is_sign(char c) { return (ctype[(int)(unsigned char)c] & 004) != 0; }
inline bool is_dec(char c) { return (ctype[(int)(unsigned char)c] & 010) != 0; }
inline bool is_hex(char c) { return (ctype[(int)(unsigned char)c] & 030) != 0; }
inline int char2int(char c)
{
if (c >= 'a') return c - 'a' + 10;
if (c >= 'A') return c - 'A' + 10;
return c - '0';
}
static double str2float(const char *str, char **endptr)
{
double sign = 1;
if (is_sign(*str)) sign = ',' - *str++;
double result = 0;
while (is_dec(*str)) result = (result * 10) + (*str++ - '0');
if (*str == '.')
{
++str;
double fraction = 1;
while (is_dec(*str)) fraction *= 0.1, result += (*str++ - '0') * fraction;
}
if (*str == 'e' || *str == 'E')
{
++str;
double base = 10;
if (is_sign(*str) && *str++ == '-') base = 0.1;
int exponent = 0;
while (is_dec(*str)) exponent = (exponent * 10) + (*str++ - '0');
double power = 1;
while (exponent)
{
if (exponent & 1) power *= base;
exponent >>= 1;
base *= base;
}
result *= power;
}
*endptr = (char *)str;
return sign * result;
}
JsonAllocator::~JsonAllocator()
{
while (head)
{
Zone *temp = head->next;
free(head);
head = temp;
}
}
inline void *align_pointer(void *x, size_t align) { return (void *)(((uintptr_t)x + (align - 1)) & ~(align - 1)); }
void *JsonAllocator::allocate(size_t n, size_t align)
{
if (head)
{
char *p = (char *)align_pointer(head->end, align);
if (p + n <= (char *)head + JSON_ZONE_SIZE)
{
head->end = p + n;
return p;
}
}
size_t zone_size = sizeof(Zone) + n + align;
Zone *z = (Zone *)malloc(zone_size <= JSON_ZONE_SIZE ? JSON_ZONE_SIZE : zone_size);
char *p = (char *)align_pointer(z + 1, align);
z->end = p + n;
if (zone_size <= JSON_ZONE_SIZE || head == nullptr)
{
z->next = head;
head = z;
}
else
{
z->next = head->next;
head->next = z;
}
return p;
}
struct JsonList
{
JsonTag tag;
JsonValue node;
char *key;
void grow_the_tail(JsonNode *p)
{
JsonNode *tail = (JsonNode *)node.getPayload();
if (tail)
{
p->next = tail->next;
tail->next = p;
}
else
{
p->next = p;
}
node = JsonValue(tag, p);
}
JsonValue cut_the_head()
{
JsonNode *tail = (JsonNode *)node.getPayload();
if (tail)
{
JsonNode *head = tail->next;
tail->next = nullptr;
return JsonValue(tag, head);
}
return node;
}
};
JsonParseStatus json_parse(char *str, char **endptr, JsonValue *value, JsonAllocator &allocator)
{
JsonList stack[JSON_STACK_SIZE];
int top = -1;
bool separator = true;
while (*str)
{
JsonValue o;
while (*str && is_space(*str)) ++str;
*endptr = str++;
switch (**endptr)
{
case '\0':
continue;
case '-':
if (!is_dec(*str) && *str != '.') return *endptr = str, JSON_PARSE_BAD_NUMBER;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
o = JsonValue(str2float(*endptr, &str));
if (!is_delim(*str)) return *endptr = str, JSON_PARSE_BAD_NUMBER;
break;
case '"':
o = JsonValue(JSON_TAG_STRING, str);
for (char *s = str; *str; ++s, ++str)
{
int c = *s = *str;
if (c == '\\')
{
c = *++str;
switch (c)
{
case '\\':
case '"':
case '/': *s = c; break;
case 'b': *s = '\b'; break;
case 'f': *s = '\f'; break;
case 'n': *s = '\n'; break;
case 'r': *s = '\r'; break;
case 't': *s = '\t'; break;
case 'u':
c = 0;
for (int i = 0; i < 4; ++i)
{
if (!is_hex(*++str)) return *endptr = str, JSON_PARSE_BAD_STRING;
c = c * 16 + char2int(*str);
}
if (c < 0x80)
{
*s = c;
}
else if (c < 0x800)
{
*s++ = 0xC0 | (c >> 6);
*s = 0x80 | (c & 0x3F);
}
else
{
*s++ = 0xE0 | (c >> 12);
*s++ = 0x80 | ((c >> 6) & 0x3F);
*s = 0x80 | (c & 0x3F);
}
break;
default:
return *endptr = str, JSON_PARSE_BAD_STRING;
}
}
else if (c == '"')
{
*s = 0;
++str;
break;
}
}
if (!is_delim(*str)) return *endptr = str, JSON_PARSE_BAD_STRING;
break;
case 't':
for (const char *s = "rue"; *s; ++s, ++str)
{
if (*s != *str) return JSON_PARSE_BAD_IDENTIFIER;
}
if (!is_delim(*str)) return JSON_PARSE_BAD_IDENTIFIER;
o = JsonValue(JSON_TAG_BOOL, (void *)true);
break;
case 'f':
for (const char *s = "alse"; *s; ++s, ++str)
{
if (*s != *str) return JSON_PARSE_BAD_IDENTIFIER;
}
if (!is_delim(*str)) return JSON_PARSE_BAD_IDENTIFIER;
o = JsonValue(JSON_TAG_BOOL, (void *)false);
break;
case 'n':
for (const char *s = "ull"; *s; ++s, ++str)
{
if (*s != *str) return JSON_PARSE_BAD_IDENTIFIER;
}
if (!is_delim(*str)) return JSON_PARSE_BAD_IDENTIFIER;
break;
case ']':
if (top == -1) return JSON_PARSE_STACK_UNDERFLOW;
if (stack[top].tag != JSON_TAG_ARRAY) return JSON_PARSE_MISMATCH_BRACKET;
o = stack[top--].cut_the_head();
break;
case '}':
if (top == -1) return JSON_PARSE_STACK_UNDERFLOW;
if (stack[top].tag != JSON_TAG_OBJECT) return JSON_PARSE_MISMATCH_BRACKET;
o = stack[top--].cut_the_head();
break;
case '[':
if (++top == JSON_STACK_SIZE) return JSON_PARSE_STACK_OVERFLOW;
stack[top] = {JSON_TAG_ARRAY, JsonValue(JSON_TAG_ARRAY, nullptr), nullptr};
continue;
case '{':
if (++top == JSON_STACK_SIZE) return JSON_PARSE_STACK_OVERFLOW;
stack[top] = {JSON_TAG_OBJECT, JsonValue(JSON_TAG_OBJECT, nullptr), nullptr};
continue;
case ':':
if (separator || stack[top].key == nullptr) return JSON_PARSE_UNEXPECTED_CHARACTER;
separator = true;
continue;
case ',':
if (separator || stack[top].key != nullptr) return JSON_PARSE_UNEXPECTED_CHARACTER;
separator = true;
continue;
default:
return JSON_PARSE_UNEXPECTED_CHARACTER;
}
separator = false;
if (top == -1)
{
*endptr = str;
*value = o;
return JSON_PARSE_OK;
}
if (stack[top].tag == JSON_TAG_OBJECT)
{
if (!stack[top].key)
{
if (o.getTag() != JSON_TAG_STRING) return JSON_PARSE_UNQUOTED_KEY;
stack[top].key = o.toString();
continue;
}
JsonNode *p = (JsonNode *)allocator.allocate(sizeof(JsonNode));
p->value = o;
p->key = stack[top].key;
stack[top].key = nullptr;
stack[top].grow_the_tail((JsonNode *)p);
continue;
}
JsonNode *p = (JsonNode *)allocator.allocate(sizeof(JsonNode) - sizeof(char *));
p->value = o;
stack[top].grow_the_tail(p);
}
return JSON_PARSE_BREAKING_BAD;
}
<|endoftext|> |
<commit_before>#include "StableHeaders.h"
#include "NaaliRenderWindow.h"
#include <QWidget>
#include <QImage>
#include <utility>
#ifdef Q_WS_X11
#include <QX11Info>
#endif
using namespace std;
namespace
{
const char rttTextureName[] = "MainWindow RTT";
const char rttMaterialName[] = "MainWindow Material";
}
NaaliRenderWindow::NaaliRenderWindow()
:renderWindow(0),
overlay(0),
overlayContainer(0)
{
}
void NaaliRenderWindow::CreateRenderWindow(QWidget *targetWindow, const QString &name, int width, int height, int left, int top, bool fullscreen)
{
Ogre::NameValuePairList params;
#ifdef WIN32
params["externalWindowHandle"] = Ogre::StringConverter::toString((unsigned int)targetWindow->winId());
#elif Q_WS_MAC
// qt docs say it's a HIViewRef on carbon,
// carbon docs say HIViewGetWindow gets a WindowRef out of it
#if 0
HIViewRef vref = (HIViewRef) nativewin-> winId ();
WindowRef wref = HIViewGetWindow(vref);
winhandle = Ogre::StringConverter::toString(
(unsigned long) (HIViewGetRoot(wref)));
#else
// according to
// http://www.ogre3d.org/forums/viewtopic.php?f=2&t=27027 does
winhandle = Ogre::StringConverter::toString(
(unsigned long) nativewin->winId());
#endif
//Add the external window handle parameters to the existing params set.
params["externalWindowHandle"] = winhandle;
#endif
#ifdef Q_WS_X11
QWidget *parent = targetWindow;
while(parent->parentWidget())
parent = parent->parentWidget();
// GLX - According to Ogre Docs:
// poslong:posint:poslong:poslong (display*:screen:windowHandle:XVisualInfo*)
QX11Info info = targetWindow->x11Info();
winhandle = Ogre::StringConverter::toString((unsigned long)(info.display()));
winhandle += ":" + Ogre::StringConverter::toString((unsigned int)(info.screen()));
winhandle += ":" + Ogre::StringConverter::toString((unsigned long)parent->winId());
//Add the external window handle parameters to the existing params set.
params["parentWindowHandle"] = winhandle;
#endif
// Window position to params
if (left != -1)
params["left"] = ToString(left);
if (top != -1)
params["top"] = ToString(top);
#ifdef USE_NVIDIA_PERFHUD
params["useNVPerfHUD"] = "true";
params["Rendering Device"] = "NVIDIA PerfHUD";
#endif
renderWindow = Ogre::Root::getSingletonPtr()->createRenderWindow(name.toStdString().c_str(), width, height, fullscreen, ¶ms);
renderWindow->setDeactivateOnFocusChange(false);
CreateRenderTargetOverlay(width, height);
}
void NaaliRenderWindow::CreateRenderTargetOverlay(int width, int height)
{
width = max(1, width);
height = max(1, height);
Ogre::TexturePtr renderTarget = Ogre::TextureManager::getSingleton().createManual(
rttTextureName, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
Ogre::TEX_TYPE_2D, width, height, 0, Ogre::PF_A8R8G8B8, Ogre::TU_DYNAMIC_WRITE_ONLY_DISCARDABLE);
Ogre::MaterialPtr rttMaterial = Ogre::MaterialManager::getSingleton().create(
rttMaterialName, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
Ogre::TextureUnitState *rttTuState = rttMaterial->getTechnique(0)->getPass(0)->createTextureUnitState();
rttTuState->setTextureName(rttTextureName);
rttTuState->setTextureFiltering(Ogre::TFO_NONE);
rttTuState->setNumMipmaps(1);
rttTuState->setTextureAddressingMode(Ogre::TextureUnitState::TAM_CLAMP);
rttMaterial->setFog(true, Ogre::FOG_NONE); ///\todo Check, shouldn't here be false?
rttMaterial->setReceiveShadows(false);
rttMaterial->setTransparencyCastsShadows(false);
rttMaterial->getTechnique(0)->getPass(0)->setSceneBlending(Ogre::SBF_SOURCE_ALPHA, Ogre::SBF_ONE_MINUS_SOURCE_ALPHA);
rttMaterial->getTechnique(0)->getPass(0)->setDepthWriteEnabled(false);
rttMaterial->getTechnique(0)->getPass(0)->setDepthCheckEnabled(false);
rttMaterial->getTechnique(0)->getPass(0)->setLightingEnabled(false);
rttMaterial->getTechnique(0)->getPass(0)->setCullingMode(Ogre::CULL_NONE);
overlayContainer = Ogre::OverlayManager::getSingleton().createOverlayElement("Panel", "MainWindow Overlay Panel");
overlayContainer->setMaterialName(rttMaterialName);
overlayContainer->setMetricsMode(Ogre::GMM_PIXELS);
overlayContainer->setPosition(0, 0);
overlay = Ogre::OverlayManager::getSingleton().create("MainWindow Overlay");
overlay->add2D(static_cast<Ogre::OverlayContainer *>(overlayContainer));
overlay->setZOrder(500);
overlay->show();
// ResizeOverlay(width, height);
}
Ogre::RenderWindow *NaaliRenderWindow::OgreRenderWindow()
{
return renderWindow;
}
Ogre::Overlay *NaaliRenderWindow::OgreOverlay()
{
return overlay;
}
#if 0
void NaaliRenderWindow::RenderFrame()
{
PROFILE(NaaliRenderWindow_RenderFrame);
/*
if (applyFPSLimit && targetFpsLimit > 0.f)
{
Core::tick_t timeNow = Core::GetCurrentClockTime();
double msecsSpentInFrame = (double)(timeNow - lastPresentTime) / timerFrequency * 1000.0;
const double msecsPerFrame = 1000.0 / targetFpsLimit;
if (msecsSpentInFrame < msecsPerFrame)
{
PROFILE(FPSLimitSleep);
while(msecsSpentInFrame >= 0 && msecsSpentInFrame < msecsPerFrame)
{
if (msecsSpentInFrame + 1 < msecsPerFrame)
Sleep(1);
msecsSpentInFrame = (double)(Core::GetCurrentClockTime() - lastPresentTime) / timerFrequency * 1000.0;
}
// Busy-wait the rest of the time slice to avoid jittering and to produce smoother updates.
while(msecsSpentInFrame >= 0 && msecsSpentInFrame < msecsPerFrame)
msecsSpentInFrame = (double)(Core::GetCurrentClockTime() - lastPresentTime) / timerFrequency * 1000.0;
}
lastPresentTime = Core::GetCurrentClockTime();
timeSleptLastFrame = (float)((timeNow - lastPresentTime) * 1000.0 / timerFrequency);
}
else
timeSleptLastFrame = 0.f;
*/
}
#endif
void NaaliRenderWindow::UpdateOverlayImage(const QImage &src)
{
PROFILE(NaaliRenderWindow_UpdateOverlayImage);
Ogre::Box bounds(0, 0, src.width(), src.height());
Ogre::PixelBox bufbox(bounds, Ogre::PF_A8R8G8B8, (void *)src.bits());
Ogre::TextureManager &mgr = Ogre::TextureManager::getSingleton();
Ogre::TexturePtr texture = mgr.getByName(rttTextureName);
assert(texture.get());
texture->getBuffer()->blitFromMemory(bufbox);
}
void NaaliRenderWindow::Resize(int width, int height)
{
renderWindow->resize(width, height);
renderWindow->windowMovedOrResized();
if (Ogre::TextureManager::getSingletonPtr() && Ogre::OverlayManager::getSingletonPtr())
{
PROFILE(NaaliRenderWindow_Resize);
// recenter the overlay
// int left = (renderWindow->getWidth() - width) / 2;
// int top = (renderWindow->getHeight() - height) / 2;
// resize the container
// overlayContainer->setDimensions(width, height);
// overlayContainer->setPosition(left, top);
overlayContainer->setDimensions(width, height);
overlayContainer->setPosition(0,0);
// resize the backing texture
Ogre::TextureManager &mgr = Ogre::TextureManager::getSingleton();
Ogre::TexturePtr texture = mgr.getByName(rttTextureName);
assert(texture.get());
texture->freeInternalResources();
texture->setWidth(width);
texture->setHeight(height);
texture->createInternalResources();
}
}<commit_msg>Fixed syntax error in previous commit.<commit_after>#include "StableHeaders.h"
#include "NaaliRenderWindow.h"
#include <QWidget>
#include <QImage>
#include <utility>
#ifdef Q_WS_X11
#include <QX11Info>
#endif
using namespace std;
namespace
{
const char rttTextureName[] = "MainWindow RTT";
const char rttMaterialName[] = "MainWindow Material";
}
NaaliRenderWindow::NaaliRenderWindow()
:renderWindow(0),
overlay(0),
overlayContainer(0)
{
}
void NaaliRenderWindow::CreateRenderWindow(QWidget *targetWindow, const QString &name, int width, int height, int left, int top, bool fullscreen)
{
Ogre::NameValuePairList params;
#ifdef WIN32
params["externalWindowHandle"] = Ogre::StringConverter::toString((unsigned int)targetWindow->winId());
#elif Q_WS_MAC
// qt docs say it's a HIViewRef on carbon,
// carbon docs say HIViewGetWindow gets a WindowRef out of it
#if 0
HIViewRef vref = (HIViewRef) nativewin-> winId ();
WindowRef wref = HIViewGetWindow(vref);
winhandle = Ogre::StringConverter::toString(
(unsigned long) (HIViewGetRoot(wref)));
#else
// according to
// http://www.ogre3d.org/forums/viewtopic.php?f=2&t=27027 does
winhandle = Ogre::StringConverter::toString(
(unsigned long) nativewin->winId());
#endif
//Add the external window handle parameters to the existing params set.
params["externalWindowHandle"] = winhandle;
#endif
#ifdef Q_WS_X11
QWidget *parent = targetWindow;
while(parent->parentWidget())
parent = parent->parentWidget();
// GLX - According to Ogre Docs:
// poslong:posint:poslong:poslong (display*:screen:windowHandle:XVisualInfo*)
QX11Info info = targetWindow->x11Info();
Ogre::String winhandle = Ogre::StringConverter::toString((unsigned long)(info.display()));
winhandle += ":" + Ogre::StringConverter::toString((unsigned int)(info.screen()));
winhandle += ":" + Ogre::StringConverter::toString((unsigned long)parent->winId());
//Add the external window handle parameters to the existing params set.
params["parentWindowHandle"] = winhandle;
#endif
// Window position to params
if (left != -1)
params["left"] = ToString(left);
if (top != -1)
params["top"] = ToString(top);
#ifdef USE_NVIDIA_PERFHUD
params["useNVPerfHUD"] = "true";
params["Rendering Device"] = "NVIDIA PerfHUD";
#endif
renderWindow = Ogre::Root::getSingletonPtr()->createRenderWindow(name.toStdString().c_str(), width, height, fullscreen, ¶ms);
renderWindow->setDeactivateOnFocusChange(false);
CreateRenderTargetOverlay(width, height);
}
void NaaliRenderWindow::CreateRenderTargetOverlay(int width, int height)
{
width = max(1, width);
height = max(1, height);
Ogre::TexturePtr renderTarget = Ogre::TextureManager::getSingleton().createManual(
rttTextureName, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
Ogre::TEX_TYPE_2D, width, height, 0, Ogre::PF_A8R8G8B8, Ogre::TU_DYNAMIC_WRITE_ONLY_DISCARDABLE);
Ogre::MaterialPtr rttMaterial = Ogre::MaterialManager::getSingleton().create(
rttMaterialName, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
Ogre::TextureUnitState *rttTuState = rttMaterial->getTechnique(0)->getPass(0)->createTextureUnitState();
rttTuState->setTextureName(rttTextureName);
rttTuState->setTextureFiltering(Ogre::TFO_NONE);
rttTuState->setNumMipmaps(1);
rttTuState->setTextureAddressingMode(Ogre::TextureUnitState::TAM_CLAMP);
rttMaterial->setFog(true, Ogre::FOG_NONE); ///\todo Check, shouldn't here be false?
rttMaterial->setReceiveShadows(false);
rttMaterial->setTransparencyCastsShadows(false);
rttMaterial->getTechnique(0)->getPass(0)->setSceneBlending(Ogre::SBF_SOURCE_ALPHA, Ogre::SBF_ONE_MINUS_SOURCE_ALPHA);
rttMaterial->getTechnique(0)->getPass(0)->setDepthWriteEnabled(false);
rttMaterial->getTechnique(0)->getPass(0)->setDepthCheckEnabled(false);
rttMaterial->getTechnique(0)->getPass(0)->setLightingEnabled(false);
rttMaterial->getTechnique(0)->getPass(0)->setCullingMode(Ogre::CULL_NONE);
overlayContainer = Ogre::OverlayManager::getSingleton().createOverlayElement("Panel", "MainWindow Overlay Panel");
overlayContainer->setMaterialName(rttMaterialName);
overlayContainer->setMetricsMode(Ogre::GMM_PIXELS);
overlayContainer->setPosition(0, 0);
overlay = Ogre::OverlayManager::getSingleton().create("MainWindow Overlay");
overlay->add2D(static_cast<Ogre::OverlayContainer *>(overlayContainer));
overlay->setZOrder(500);
overlay->show();
// ResizeOverlay(width, height);
}
Ogre::RenderWindow *NaaliRenderWindow::OgreRenderWindow()
{
return renderWindow;
}
Ogre::Overlay *NaaliRenderWindow::OgreOverlay()
{
return overlay;
}
#if 0
void NaaliRenderWindow::RenderFrame()
{
PROFILE(NaaliRenderWindow_RenderFrame);
/*
if (applyFPSLimit && targetFpsLimit > 0.f)
{
Core::tick_t timeNow = Core::GetCurrentClockTime();
double msecsSpentInFrame = (double)(timeNow - lastPresentTime) / timerFrequency * 1000.0;
const double msecsPerFrame = 1000.0 / targetFpsLimit;
if (msecsSpentInFrame < msecsPerFrame)
{
PROFILE(FPSLimitSleep);
while(msecsSpentInFrame >= 0 && msecsSpentInFrame < msecsPerFrame)
{
if (msecsSpentInFrame + 1 < msecsPerFrame)
Sleep(1);
msecsSpentInFrame = (double)(Core::GetCurrentClockTime() - lastPresentTime) / timerFrequency * 1000.0;
}
// Busy-wait the rest of the time slice to avoid jittering and to produce smoother updates.
while(msecsSpentInFrame >= 0 && msecsSpentInFrame < msecsPerFrame)
msecsSpentInFrame = (double)(Core::GetCurrentClockTime() - lastPresentTime) / timerFrequency * 1000.0;
}
lastPresentTime = Core::GetCurrentClockTime();
timeSleptLastFrame = (float)((timeNow - lastPresentTime) * 1000.0 / timerFrequency);
}
else
timeSleptLastFrame = 0.f;
*/
}
#endif
void NaaliRenderWindow::UpdateOverlayImage(const QImage &src)
{
PROFILE(NaaliRenderWindow_UpdateOverlayImage);
Ogre::Box bounds(0, 0, src.width(), src.height());
Ogre::PixelBox bufbox(bounds, Ogre::PF_A8R8G8B8, (void *)src.bits());
Ogre::TextureManager &mgr = Ogre::TextureManager::getSingleton();
Ogre::TexturePtr texture = mgr.getByName(rttTextureName);
assert(texture.get());
texture->getBuffer()->blitFromMemory(bufbox);
}
void NaaliRenderWindow::Resize(int width, int height)
{
renderWindow->resize(width, height);
renderWindow->windowMovedOrResized();
if (Ogre::TextureManager::getSingletonPtr() && Ogre::OverlayManager::getSingletonPtr())
{
PROFILE(NaaliRenderWindow_Resize);
// recenter the overlay
// int left = (renderWindow->getWidth() - width) / 2;
// int top = (renderWindow->getHeight() - height) / 2;
// resize the container
// overlayContainer->setDimensions(width, height);
// overlayContainer->setPosition(left, top);
overlayContainer->setDimensions(width, height);
overlayContainer->setPosition(0,0);
// resize the backing texture
Ogre::TextureManager &mgr = Ogre::TextureManager::getSingleton();
Ogre::TexturePtr texture = mgr.getByName(rttTextureName);
assert(texture.get());
texture->freeInternalResources();
texture->setWidth(width);
texture->setHeight(height);
texture->createInternalResources();
}
}<|endoftext|> |
<commit_before>/*
---------------------------------------------------------------------
The template library textwolf implements an input iterator on
a set of XML path expressions without backward references on an
STL conforming input iterator as source. It does no buffering
or read ahead and is dedicated for stream processing of XML
for a small set of XML queries.
Stream processing in this Object refers to processing the
document without buffering anything but the current result token
processed with its tag hierarchy information.
Copyright (C) 2010,2011,2012,2013,2014 Patrick Frey
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 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
--------------------------------------------------------------------
The latest version of textwolf can be found at 'http://github.com/patrickfrey/textwolf'
For documentation see 'http://patrickfrey.github.com/textwolf'
--------------------------------------------------------------------
*/
/// \file textwolf/istreamiterator.hpp
/// \brief Definition of iterators for textwolf on STL input streams (std::istream)
#ifndef __TEXTWOLF_ISTREAM_ITERATOR_HPP__
#define __TEXTWOLF_ISTREAM_ITERATOR_HPP__
#include <iostream>
#include <fstream>
#include <iterator>
#include <cstdlib>
#include <stdexcept>
#include <stdint.h>
/// \namespace textwolf
/// \brief Toplevel namespace of the library
namespace textwolf {
/// \class IStreamIterator
/// \brief Input iterator on an STL input stream
class IStreamIterator
{
public:
/// \brief Default constructor
IStreamIterator(){}
/// \brief Destructor
~IStreamIterator()
{
std::free(m_buf);
}
/// \brief Constructor
/// \param [in] input input to iterate on
IStreamIterator( std::istream& input, std::size_t bufsize=4096)
:m_input(&input),m_buf((char*)std::malloc(bufsize)),m_bufsize(bufsize),m_readsize(0),m_readpos(0),m_abspos(0)
{
input.unsetf( std::ios::skipws);
input.exceptions ( std::ifstream::failbit | std::ifstream::badbit | std::ifstream::eofbit );
fillbuf();
}
/// \brief Copy constructor
/// \param [in] o iterator to copy
IStreamIterator( const IStreamIterator& o)
:m_input(o.m_input),m_buf((char*)std::malloc(o.m_bufsize)),m_bufsize(o.m_bufsize),m_readsize(o.m_readsize),m_readpos(o.m_readpos),m_abspos(o.m_abspos)
{
std::memcpy( m_buf, o.m_buf, o.m_readsize);
}
/// \brief Element access
/// \return current character
inline char operator* ()
{
return (m_readpos < m_readsize)?m_buf[m_readpos]:0;
}
/// \brief Pre increment
inline IStreamIterator& operator++()
{
if (m_readpos+1 >= m_readsize)
{
fillbuf();
}
else
{
++m_readpos;
}
return *this;
}
int operator - (const IStreamIterator& o) const
{
return (int)m_readpos - o.m_readpos;
}
uint64_t position() const
{
return m_abspos + m_readpos;
}
private:
bool fillbuf()
{
try
{
m_input->read( m_buf, m_bufsize);
m_abspos += m_readsize;
m_readsize = m_input->gcount();
m_readpos = 0;
return true;
}
catch (const std::istream::failure& err)
{
if (m_input->eof())
{
m_readsize = m_input->gcount();
m_readpos = 0;
return (m_readsize > 0);
}
throw std::runtime_error( std::string( "file read error: ") + err.what());
}
catch (const std::exception& err)
{
throw std::runtime_error( std::string( "file read error: ") + err.what());
}
catch (...)
{
throw std::runtime_error( std::string( "file read error"));
}
}
private:
std::istream* m_input;
char* m_buf;
std::size_t m_bufsize;
std::size_t m_readsize;
std::size_t m_readpos;
uint64_t m_abspos;
};
}//namespace
#endif
<commit_msg>fixed wrong counting of position in istreamiterator<commit_after>/*
---------------------------------------------------------------------
The template library textwolf implements an input iterator on
a set of XML path expressions without backward references on an
STL conforming input iterator as source. It does no buffering
or read ahead and is dedicated for stream processing of XML
for a small set of XML queries.
Stream processing in this Object refers to processing the
document without buffering anything but the current result token
processed with its tag hierarchy information.
Copyright (C) 2010,2011,2012,2013,2014 Patrick Frey
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 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
--------------------------------------------------------------------
The latest version of textwolf can be found at 'http://github.com/patrickfrey/textwolf'
For documentation see 'http://patrickfrey.github.com/textwolf'
--------------------------------------------------------------------
*/
/// \file textwolf/istreamiterator.hpp
/// \brief Definition of iterators for textwolf on STL input streams (std::istream)
#ifndef __TEXTWOLF_ISTREAM_ITERATOR_HPP__
#define __TEXTWOLF_ISTREAM_ITERATOR_HPP__
#include <iostream>
#include <fstream>
#include <iterator>
#include <cstdlib>
#include <stdexcept>
#include <stdint.h>
/// \namespace textwolf
/// \brief Toplevel namespace of the library
namespace textwolf {
/// \class IStreamIterator
/// \brief Input iterator on an STL input stream
class IStreamIterator
{
public:
/// \brief Default constructor
IStreamIterator(){}
/// \brief Destructor
~IStreamIterator()
{
std::free(m_buf);
}
/// \brief Constructor
/// \param [in] input input to iterate on
IStreamIterator( std::istream& input, std::size_t bufsize=4096)
:m_input(&input),m_buf((char*)std::malloc(bufsize)),m_bufsize(bufsize),m_readsize(0),m_readpos(0),m_abspos(0)
{
input.unsetf( std::ios::skipws);
input.exceptions ( std::ifstream::failbit | std::ifstream::badbit | std::ifstream::eofbit );
fillbuf();
}
/// \brief Copy constructor
/// \param [in] o iterator to copy
IStreamIterator( const IStreamIterator& o)
:m_input(o.m_input),m_buf((char*)std::malloc(o.m_bufsize)),m_bufsize(o.m_bufsize),m_readsize(o.m_readsize),m_readpos(o.m_readpos),m_abspos(o.m_abspos)
{
std::memcpy( m_buf, o.m_buf, o.m_readsize);
}
/// \brief Element access
/// \return current character
inline char operator* ()
{
return (m_readpos < m_readsize)?m_buf[m_readpos]:0;
}
/// \brief Pre increment
inline IStreamIterator& operator++()
{
if (m_readpos+1 >= m_readsize)
{
fillbuf();
}
else
{
++m_readpos;
}
return *this;
}
int operator - (const IStreamIterator& o) const
{
return (int)m_readpos - o.m_readpos;
}
uint64_t position() const
{
return m_abspos + m_readpos;
}
private:
bool fillbuf()
{
try
{
m_input->read( m_buf, m_bufsize);
m_abspos += m_readsize;
m_readsize = m_input->gcount();
m_readpos = 0;
return true;
}
catch (const std::istream::failure& err)
{
if (m_input->eof())
{
m_abspos += m_readsize;
m_readsize = m_input->gcount();
m_readpos = 0;
return (m_readsize > 0);
}
throw std::runtime_error( std::string( "file read error: ") + err.what());
}
catch (const std::exception& err)
{
throw std::runtime_error( std::string( "file read error: ") + err.what());
}
catch (...)
{
throw std::runtime_error( std::string( "file read error"));
}
}
private:
std::istream* m_input;
char* m_buf;
std::size_t m_bufsize;
std::size_t m_readsize;
std::size_t m_readpos;
uint64_t m_abspos;
};
}//namespace
#endif
<|endoftext|> |
<commit_before>#ifndef VSMC_HELPER_PARALLEL_TBB_HPP
#define VSMC_HELPER_PARALLEL_TBB_HPP
#include <vsmc/internal/common.hpp>
#include <vsmc/helper/sequential.hpp>
#include <tbb/tbb.h>
/// \defgroup TBB Intel Threading Buidling Block
/// \ingroup Helper
/// \brief Parallelized samplers with Intel TBB
namespace vsmc {
/// \brief Particle::value_type subtype
/// \ingroup TBB
///
/// \tparam Dim The dimension of the state parameter vector
/// \tparam T The type of the value of the state parameter vector
/// \tparam Profiler class The profiler used for profiling run_parallel().
/// The default is NullProfiler, which does nothing but provide the compatible
/// inteferce. Profiler::start() and Profiler::stop() are called automatically
/// when entering and exiting run_parallel(). This shall provide how much
/// time are spent on the parallel code (plus a small overhead of scheduling).
template <unsigned Dim, typename T, typename Profiler>
class StateTBB : public internal::StateBase<Dim, T>
#if !VSMC_HAS_CXX11_DECLTYPE || !VSMC_HAS_CXX11_AUTO_TYPE
, public internal::ParallelTag
#endif
{
public :
typedef VSMC_SIZE_TYPE size_type;
typedef T state_type;
typedef Profiler profiler_type;
explicit StateTBB (size_type N) :
internal::StateBase<Dim, T>(N), size_(N), copy_(N) {}
virtual ~StateTBB () {}
/// \brief Run a worker in parallel with tbb::parallel_for
///
/// \param work The worker object
///
/// \note The kernel shall implement
/// \code
/// void operator () (const tbb::blocked_range<size_type> &range) const
/// \endcode
/// where \c size_type is StateTBB::size_type. There are equivalent
/// typedefs in InitializeTBB etc.
///
/// \note The range form of tbb::parallel_for is used by run_parallel.
/// This is the most commonly used in the context of SMC. The range is
/// constructed as <tt>tbb::blocked_range<size_type>(0, size())</tt>. For
/// more complex parallel patterns, users need to call Intel TBB API
/// themselves.
template <typename Work>
void run_parallel (const Work &work) const
{
profiler_.start();
tbb::parallel_for(tbb::blocked_range<size_type>(0, size_), work);
profiler_.stop();
}
/// \brief Run a worker in parallel with tbb::parallel_for
///
/// \param work The worker object
/// \param part The affinity partitioner
template <typename Work>
void run_parallel (const Work &work, tbb::affinity_partitioner &part) const
{
profiler_.start();
tbb::parallel_for(tbb::blocked_range<size_type>(0, size_), work, part);
profiler_.stop();
}
Profiler &profiler () const
{
return profiler_;
}
void copy (size_type from, size_type to)
{
copy_[to] = from;
}
void pre_resampling ()
{
for (size_type i = 0; i != this->size(); ++i)
copy_[i] = i;
}
void post_resampling ()
{
run_parallel(copy_work_(this, copy_.data()));
}
private :
size_type size_;
std::vector<size_type> copy_;
profiler_type profiler_;
class copy_work_
{
public :
copy_work_ (StateTBB<Dim, T> *state, const size_type *from) :
state_(state), from_(from) {}
void operator () (const tbb::blocked_range<size_type> &range) const
{
for (size_type i = range.begin(); i != range.end(); ++i) {
size_type from = from_[i];
if (from != i)
state_->state().col(i) = state_->state().col(from);
}
}
private :
StateTBB<Dim, T> *const state_;
const size_type *const from_;
}; // class work_
}; // class StateTBB
/// \brief Sampler<T>::init_type subtype
/// \ingroup TBB
///
/// \tparam T A subtype of StateBase
template <typename T>
class InitializeTBB
{
public :
typedef VSMC_SIZE_TYPE size_type;
typedef T value_type;
virtual ~InitializeTBB () {}
unsigned operator() (Particle<T> &particle, void *param)
{
this->initialize_param(particle, param);
this->pre_processor(particle);
accept_.resize(particle.size());
particle.value().run_parallel(work_(this, &particle, accept_.data()));
this->post_processor(particle);
return accept_.sum();
}
virtual unsigned initialize_state (SingleParticle<T> part) = 0;
virtual void initialize_param (Particle<T> &particle, void *param) {}
virtual void pre_processor (Particle<T> &particle) {}
virtual void post_processor (Particle<T> &particle) {}
private :
Eigen::Matrix<unsigned, Eigen::Dynamic, 1> accept_;
class work_
{
public :
work_ (InitializeTBB<T> *init,
Particle<T> *particle, unsigned *accept) :
init_(init), particle_(particle), accept_(accept) {}
void operator() (const tbb::blocked_range<size_type> &range) const
{
for (size_type i = range.begin(); i != range.end(); ++i) {
accept_[i] = init_->initialize_state(
SingleParticle<T>(i, particle_));
}
}
private :
InitializeTBB<T> *const init_;
Particle<T> *const particle_;
unsigned *const accept_;
}; // class work_
}; // class InitializeTBB
/// \brief Sampler<T>::move_type subtype
/// \ingroup TBB
///
/// \tparam T A subtype of StateBase
template <typename T>
class MoveTBB
{
public :
typedef VSMC_SIZE_TYPE size_type;
typedef T value_type;
virtual ~MoveTBB () {}
unsigned operator() (unsigned iter, Particle<T> &particle)
{
this->pre_processor(iter, particle);
accept_.resize(particle.size());
particle.value().run_parallel(
work_(this, iter, &particle, accept_.data()));
this->post_processor(iter, particle);
return accept_.sum();
}
virtual unsigned move_state (unsigned iter, SingleParticle<T> part) = 0;
virtual void pre_processor (unsigned iter, Particle<T> &particle) {}
virtual void post_processor (unsigned iter, Particle<T> &particle) {}
private :
Eigen::Matrix<unsigned, Eigen::Dynamic, 1> accept_;
class work_
{
public :
work_ (MoveTBB<T> *move, unsigned iter,
Particle<T> *particle, unsigned *accept) :
move_(move), iter_(iter), particle_(particle), accept_(accept) {}
void operator() (const tbb::blocked_range<size_type> &range) const
{
for (size_type i = range.begin(); i != range.end(); ++i) {
accept_[i] = move_->move_state(iter_,
SingleParticle<T>(i, particle_));
}
}
private :
MoveTBB<T> *const move_;
const unsigned iter_;
Particle<T> *const particle_;
unsigned *const accept_;
}; // class work_
}; // class MoveTBB
/// \brief Monitor<T>::eval_type subtype
/// \ingroup TBB
///
/// \tparam T A subtype of StateBase
/// \tparam Dim The dimension of the monitor
template <typename T, unsigned Dim>
class MonitorTBB
{
public :
typedef VSMC_SIZE_TYPE size_type;
typedef T value_type;
virtual ~MonitorTBB () {}
void operator() (unsigned iter, const Particle<T> &particle, double *res)
{
this->pre_processor(iter, particle);
particle.value().run_parallel(work_(this, iter, &particle, res));
this->post_processor(iter, particle);
}
virtual void monitor_state (unsigned iter, ConstSingleParticle<T> part,
double *res) = 0;
virtual void pre_processor (unsigned iter, const Particle<T> &particle) {}
virtual void post_processor (unsigned iter, const Particle<T> &particle) {}
static unsigned dim ()
{
return Dim;
}
private :
class work_
{
public :
work_ (MonitorTBB<T, Dim> *monitor, unsigned iter,
const Particle<T> *particle, double *res) :
monitor_(monitor), iter_(iter), particle_(particle), res_(res) {}
void operator() (const tbb::blocked_range<size_type> &range) const
{
for (size_type i = range.begin(); i != range.end(); ++i) {
monitor_->monitor_state(iter_,
ConstSingleParticle<T>(i, particle_), res_ + i * Dim);
}
}
private :
MonitorTBB<T, Dim> *const monitor_;
const unsigned iter_;
const Particle<T> *const particle_;
double *const res_;
}; // class work_
}; // class MonitorTBB
/// \brief Path<T>::eval_type subtype
/// \ingroup TBB
///
/// \tparam T A subtype of StateBase
template <typename T>
class PathTBB
{
public :
typedef VSMC_SIZE_TYPE size_type;
typedef T value_type;
virtual ~PathTBB () {}
double operator() (unsigned iter, const Particle<T> &particle, double *res)
{
this->pre_processor(iter, particle);
particle.value().run_parallel(work_(this, iter, &particle, res));
this->post_processor(iter, particle);
return this->width_state(iter, particle);
}
virtual double path_state (unsigned iter,
ConstSingleParticle<T> part) = 0;
virtual double width_state (unsigned iter,
const Particle<T> &particle) = 0;
virtual void pre_processor (unsigned iter, const Particle<T> &particle) {}
virtual void post_processor (unsigned iter, const Particle<T> &particle) {}
private :
class work_
{
public :
work_ (PathTBB<T> *path, unsigned iter,
const Particle<T> *particle, double *res) :
path_(path), iter_(iter), particle_(particle), res_(res) {}
void operator() (const tbb::blocked_range<size_type> &range) const
{
for (size_type i = range.begin(); i != range.end(); ++i) {
res_[i] = path_->path_state(iter_,
ConstSingleParticle<T>(i, particle_));
}
}
private :
PathTBB<T> *const path_;
const unsigned iter_;
const Particle<T> *const particle_;
double *const res_;
}; // class work_
}; // PathTBB
} // namespace vsmc
#endif // VSMC_HELPER_PARALLEL_TBB_HPP
<commit_msg>Localize some loop variables<commit_after>#ifndef VSMC_HELPER_PARALLEL_TBB_HPP
#define VSMC_HELPER_PARALLEL_TBB_HPP
#include <vsmc/internal/common.hpp>
#include <vsmc/helper/sequential.hpp>
#include <tbb/tbb.h>
/// \defgroup TBB Intel Threading Buidling Block
/// \ingroup Helper
/// \brief Parallelized samplers with Intel TBB
namespace vsmc {
/// \brief Particle::value_type subtype
/// \ingroup TBB
///
/// \tparam Dim The dimension of the state parameter vector
/// \tparam T The type of the value of the state parameter vector
/// \tparam Profiler class The profiler used for profiling run_parallel().
/// The default is NullProfiler, which does nothing but provide the compatible
/// inteferce. Profiler::start() and Profiler::stop() are called automatically
/// when entering and exiting run_parallel(). This shall provide how much
/// time are spent on the parallel code (plus a small overhead of scheduling).
template <unsigned Dim, typename T, typename Profiler>
class StateTBB : public internal::StateBase<Dim, T>
#if !VSMC_HAS_CXX11_DECLTYPE || !VSMC_HAS_CXX11_AUTO_TYPE
, public internal::ParallelTag
#endif
{
public :
typedef VSMC_SIZE_TYPE size_type;
typedef T state_type;
typedef Profiler profiler_type;
explicit StateTBB (size_type N) :
internal::StateBase<Dim, T>(N), size_(N), copy_(N) {}
virtual ~StateTBB () {}
/// \brief Run a worker in parallel with tbb::parallel_for
///
/// \param work The worker object
///
/// \note The kernel shall implement
/// \code
/// void operator () (const tbb::blocked_range<size_type> &range) const
/// \endcode
/// where \c size_type is StateTBB::size_type. There are equivalent
/// typedefs in InitializeTBB etc.
///
/// \note The range form of tbb::parallel_for is used by run_parallel.
/// This is the most commonly used in the context of SMC. The range is
/// constructed as <tt>tbb::blocked_range<size_type>(0, size())</tt>. For
/// more complex parallel patterns, users need to call Intel TBB API
/// themselves.
template <typename Work>
void run_parallel (const Work &work) const
{
profiler_.start();
tbb::parallel_for(tbb::blocked_range<size_type>(0, size_), work);
profiler_.stop();
}
/// \brief Run a worker in parallel with tbb::parallel_for
///
/// \param work The worker object
/// \param part The affinity partitioner
template <typename Work>
void run_parallel (const Work &work, tbb::affinity_partitioner &part) const
{
profiler_.start();
tbb::parallel_for(tbb::blocked_range<size_type>(0, size_), work, part);
profiler_.stop();
}
Profiler &profiler () const
{
return profiler_;
}
void copy (size_type from, size_type to)
{
copy_[to] = from;
}
void pre_resampling ()
{
for (size_type i = 0; i != this->size(); ++i)
copy_[i] = i;
}
void post_resampling ()
{
run_parallel(copy_work_(this, copy_.data()));
}
private :
size_type size_;
std::vector<size_type> copy_;
profiler_type profiler_;
class copy_work_
{
public :
copy_work_ (StateTBB<Dim, T> *state, const size_type *from) :
state_(state), from_(from) {}
void operator () (const tbb::blocked_range<size_type> &range) const
{
for (size_type i = range.begin(); i != range.end(); ++i) {
size_type from = from_[i];
if (from != i)
state_->state().col(i) = state_->state().col(from);
}
}
private :
StateTBB<Dim, T> *const state_;
const size_type *const from_;
}; // class work_
}; // class StateTBB
/// \brief Sampler<T>::init_type subtype
/// \ingroup TBB
///
/// \tparam T A subtype of StateBase
template <typename T>
class InitializeTBB
{
public :
typedef VSMC_SIZE_TYPE size_type;
typedef T value_type;
virtual ~InitializeTBB () {}
unsigned operator() (Particle<T> &particle, void *param)
{
this->initialize_param(particle, param);
this->pre_processor(particle);
accept_.resize(particle.size());
particle.value().run_parallel(work_(this, &particle, accept_.data()));
this->post_processor(particle);
return accept_.sum();
}
virtual unsigned initialize_state (SingleParticle<T> part) = 0;
virtual void initialize_param (Particle<T> &particle, void *param) {}
virtual void pre_processor (Particle<T> &particle) {}
virtual void post_processor (Particle<T> &particle) {}
private :
Eigen::Matrix<unsigned, Eigen::Dynamic, 1> accept_;
class work_
{
public :
work_ (InitializeTBB<T> *init,
Particle<T> *particle, unsigned *accept) :
init_(init), particle_(particle), accept_(accept) {}
void operator() (const tbb::blocked_range<size_type> &range) const
{
for (size_type i = range.begin(); i != range.end(); ++i) {
unsigned *const acc = accept_;
Particle<T> *const part = particle_;
acc[i] = init_->initialize_state(SingleParticle<T>(i, part));
}
}
private :
InitializeTBB<T> *const init_;
Particle<T> *const particle_;
unsigned *const accept_;
}; // class work_
}; // class InitializeTBB
/// \brief Sampler<T>::move_type subtype
/// \ingroup TBB
///
/// \tparam T A subtype of StateBase
template <typename T>
class MoveTBB
{
public :
typedef VSMC_SIZE_TYPE size_type;
typedef T value_type;
virtual ~MoveTBB () {}
unsigned operator() (unsigned iter, Particle<T> &particle)
{
this->pre_processor(iter, particle);
accept_.resize(particle.size());
particle.value().run_parallel(
work_(this, iter, &particle, accept_.data()));
this->post_processor(iter, particle);
return accept_.sum();
}
virtual unsigned move_state (unsigned iter, SingleParticle<T> part) = 0;
virtual void pre_processor (unsigned iter, Particle<T> &particle) {}
virtual void post_processor (unsigned iter, Particle<T> &particle) {}
private :
Eigen::Matrix<unsigned, Eigen::Dynamic, 1> accept_;
class work_
{
public :
work_ (MoveTBB<T> *move, unsigned iter,
Particle<T> *particle, unsigned *accept) :
move_(move), iter_(iter), particle_(particle), accept_(accept) {}
void operator() (const tbb::blocked_range<size_type> &range) const
{
for (size_type i = range.begin(); i != range.end(); ++i) {
unsigned *const acc = accept_;
Particle<T> *const part = particle_;
acc[i] = move_->move_state(iter_, SingleParticle<T>(i, part));
}
}
private :
MoveTBB<T> *const move_;
const unsigned iter_;
Particle<T> *const particle_;
unsigned *const accept_;
}; // class work_
}; // class MoveTBB
/// \brief Monitor<T>::eval_type subtype
/// \ingroup TBB
///
/// \tparam T A subtype of StateBase
/// \tparam Dim The dimension of the monitor
template <typename T, unsigned Dim>
class MonitorTBB
{
public :
typedef VSMC_SIZE_TYPE size_type;
typedef T value_type;
virtual ~MonitorTBB () {}
void operator() (unsigned iter, const Particle<T> &particle, double *res)
{
this->pre_processor(iter, particle);
particle.value().run_parallel(work_(this, iter, &particle, res));
this->post_processor(iter, particle);
}
virtual void monitor_state (unsigned iter, ConstSingleParticle<T> part,
double *res) = 0;
virtual void pre_processor (unsigned iter, const Particle<T> &particle) {}
virtual void post_processor (unsigned iter, const Particle<T> &particle) {}
static unsigned dim ()
{
return Dim;
}
private :
class work_
{
public :
work_ (MonitorTBB<T, Dim> *monitor, unsigned iter,
const Particle<T> *particle, double *res) :
monitor_(monitor), iter_(iter), particle_(particle), res_(res) {}
void operator() (const tbb::blocked_range<size_type> &range) const
{
for (size_type i = range.begin(); i != range.end(); ++i) {
double *const r = res_ + i * Dim;
const Particle<T> *const part = particle_;
monitor_->monitor_state(iter_,
ConstSingleParticle<T>(i, part), r);
}
}
private :
MonitorTBB<T, Dim> *const monitor_;
const unsigned iter_;
const Particle<T> *const particle_;
double *const res_;
}; // class work_
}; // class MonitorTBB
/// \brief Path<T>::eval_type subtype
/// \ingroup TBB
///
/// \tparam T A subtype of StateBase
template <typename T>
class PathTBB
{
public :
typedef VSMC_SIZE_TYPE size_type;
typedef T value_type;
virtual ~PathTBB () {}
double operator() (unsigned iter, const Particle<T> &particle, double *res)
{
this->pre_processor(iter, particle);
particle.value().run_parallel(work_(this, iter, &particle, res));
this->post_processor(iter, particle);
return this->width_state(iter, particle);
}
virtual double path_state (unsigned iter,
ConstSingleParticle<T> part) = 0;
virtual double width_state (unsigned iter,
const Particle<T> &particle) = 0;
virtual void pre_processor (unsigned iter, const Particle<T> &particle) {}
virtual void post_processor (unsigned iter, const Particle<T> &particle) {}
private :
class work_
{
public :
work_ (PathTBB<T> *path, unsigned iter,
const Particle<T> *particle, double *res) :
path_(path), iter_(iter), particle_(particle), res_(res) {}
void operator() (const tbb::blocked_range<size_type> &range) const
{
for (size_type i = range.begin(); i != range.end(); ++i) {
const Particle<T> *const part = particle_;
res_[i] = path_->path_state(iter_,
ConstSingleParticle<T>(i, part));
}
}
private :
PathTBB<T> *const path_;
const unsigned iter_;
const Particle<T> *const particle_;
double *const res_;
}; // class work_
}; // PathTBB
} // namespace vsmc
#endif // VSMC_HELPER_PARALLEL_TBB_HPP
<|endoftext|> |
<commit_before>/**
* This file is part of the "libfnord" project
* Copyright (c) 2015 Paul Asmuth
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <unistd.h>
#include <fnord-base/io/file.h>
#include <fnord-base/io/fileutil.h>
#include <fnord-base/io/mmappedfile.h>
#include <fnord-base/logging.h>
#include <fnord-base/io/fileutil.h>
#include <fnord-dproc/LocalScheduler.h>
namespace fnord {
namespace dproc {
LocalScheduler::LocalScheduler(
const String& tempdir /* = "/tmp" */,
size_t max_threads /* = 8 */,
size_t max_requests /* = 32 */) :
tempdir_(tempdir),
tpool_(max_threads),
req_tpool_(max_requests) {}
void LocalScheduler::start() {
req_tpool_.start();
tpool_.start();
}
void LocalScheduler::stop() {
req_tpool_.stop();
tpool_.stop();
}
RefPtr<TaskResult> LocalScheduler::run(
RefPtr<Application> app,
const TaskSpec& task) {
RefPtr<TaskResult> result(new TaskResult());
try {
auto instance = mkRef(
new LocalTaskRef(
app,
task.task_name(),
Buffer(task.params().data(), task.params().size())));
req_tpool_.run([this, app, result, instance] () {
try {
LocalTaskPipeline pipeline;
pipeline.tasks.push_back(instance);
run(app.get(), &pipeline);
result->returnResult(
new io::MmappedFile(
File::openFile(instance->output_filename, File::O_READ)));
} catch (const StandardException& e) {
fnord::logError("dproc.scheduler", e, "task failed");
result->returnError(e);
}
});
} catch (const StandardException& e) {
fnord::logError("dproc.scheduler", e, "task failed");
result->returnError(e);
}
return result;
}
void LocalScheduler::run(
Application* app,
LocalTaskPipeline* pipeline) {
fnord::logInfo(
"fnord.dproc",
"Starting local pipeline id=$0 tasks=$1",
(void*) pipeline,
pipeline->tasks.size());
std::unique_lock<std::mutex> lk(pipeline->mutex);
while (pipeline->tasks.size() > 0) {
bool waiting = true;
size_t num_waiting = 0;
size_t num_running = 0;
size_t num_completed = 0;
for (auto& taskref : pipeline->tasks) {
if (taskref->finished) {
++num_completed;
continue;
}
if (taskref->running) {
++num_running;
continue;
}
if (!taskref->expanded) {
taskref->expanded = true;
auto parent_task = taskref;
for (const auto& dep : taskref->task->dependencies()) {
RefPtr<LocalTaskRef> depref(new LocalTaskRef(app, dep.task_name, dep.params));
parent_task->dependencies.emplace_back(depref);
pipeline->tasks.emplace_back(depref);
}
waiting = false;
break;
}
bool deps_finished = true;
for (const auto& dep : taskref->dependencies) {
if (!dep->finished) {
deps_finished = false;
}
}
if (!deps_finished) {
++num_waiting;
continue;
}
taskref->running = true;
tpool_.run(std::bind(&LocalScheduler::runTask, this, pipeline, taskref));
waiting = false;
}
fnord::logInfo(
"fnord.dproc",
"Running local pipeline... id=$0 tasks=$1, running=$2, waiting=$3, completed=$4",
(void*) pipeline,
pipeline->tasks.size(),
num_running,
num_waiting,
num_completed);
if (waiting) {
pipeline->wakeup.wait(lk);
}
while (pipeline->tasks.size() > 0 && pipeline->tasks.back()->finished) {
pipeline->tasks.pop_back();
}
}
fnord::logInfo(
"fnord.dproc",
"Completed local pipeline id=$0",
(void*) pipeline);
}
void LocalScheduler::runTask(
LocalTaskPipeline* pipeline,
RefPtr<LocalTaskRef> task) {
auto cache_key = task->task->cacheKey();
String output_file;
if (cache_key.isEmpty()) {
auto tmpid = Random::singleton()->hex128();
output_file = FileUtil::joinPaths(
tempdir_,
StringUtil::format("tmp_$0", tmpid));
} else {
output_file = FileUtil::joinPaths(
tempdir_,
StringUtil::format("cache_$0", cache_key.get()));
}
auto cached = !cache_key.isEmpty() && FileUtil::exists(output_file);
fnord::logDebug(
"fnord.dproc",
"Running task: $0 (cached=$1)",
task->debug_name,
cached);
if (!cached) {
try {
auto res = task->task->run(task.get());
auto file = File::openFile(
output_file + "~",
File::O_CREATEOROPEN | File::O_WRITE);
file.write(res->data(), res->size());
FileUtil::mv(output_file + "~", output_file);
} catch (const std::exception& e) {
fnord::logError("fnord.dproc", e, "error");
}
}
std::unique_lock<std::mutex> lk(pipeline->mutex);
task->output_filename = output_file;
task->finished = true;
lk.unlock();
pipeline->wakeup.notify_all();
}
LocalScheduler::LocalTaskRef::LocalTaskRef(
RefPtr<Application> app,
const String& task_name,
const Buffer& params) :
task(app->getTaskInstance(task_name, params)),
running(false),
expanded(false),
finished(false) {}
RefPtr<VFSFile> LocalScheduler::LocalTaskRef::getDependency(size_t index) {
if (index >= dependencies.size()) {
RAISEF(kIndexError, "invalid dependecy index: $0", index);
}
const auto& dep = dependencies[index];
if (!FileUtil::exists(dep->output_filename)) {
RAISEF(kRuntimeError, "missing upstream output: $0", dep->output_filename);
}
return RefPtr<VFSFile>(
new io::MmappedFile(
File::openFile(dep->output_filename, File::O_READ)));
}
size_t LocalScheduler::LocalTaskRef::numDependencies() const {
return dependencies.size();
}
} // namespace dproc
} // namespace fnord
<commit_msg>task debug name<commit_after>/**
* This file is part of the "libfnord" project
* Copyright (c) 2015 Paul Asmuth
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <unistd.h>
#include <fnord-base/io/file.h>
#include <fnord-base/io/fileutil.h>
#include <fnord-base/io/mmappedfile.h>
#include <fnord-base/logging.h>
#include <fnord-base/io/fileutil.h>
#include <fnord-dproc/LocalScheduler.h>
namespace fnord {
namespace dproc {
LocalScheduler::LocalScheduler(
const String& tempdir /* = "/tmp" */,
size_t max_threads /* = 8 */,
size_t max_requests /* = 32 */) :
tempdir_(tempdir),
tpool_(max_threads),
req_tpool_(max_requests) {}
void LocalScheduler::start() {
req_tpool_.start();
tpool_.start();
}
void LocalScheduler::stop() {
req_tpool_.stop();
tpool_.stop();
}
RefPtr<TaskResult> LocalScheduler::run(
RefPtr<Application> app,
const TaskSpec& task) {
RefPtr<TaskResult> result(new TaskResult());
try {
auto instance = mkRef(
new LocalTaskRef(
app,
task.task_name(),
Buffer(task.params().data(), task.params().size())));
req_tpool_.run([this, app, result, instance] () {
try {
LocalTaskPipeline pipeline;
pipeline.tasks.push_back(instance);
run(app.get(), &pipeline);
result->returnResult(
new io::MmappedFile(
File::openFile(instance->output_filename, File::O_READ)));
} catch (const StandardException& e) {
fnord::logError("dproc.scheduler", e, "task failed");
result->returnError(e);
}
});
} catch (const StandardException& e) {
fnord::logError("dproc.scheduler", e, "task failed");
result->returnError(e);
}
return result;
}
void LocalScheduler::run(
Application* app,
LocalTaskPipeline* pipeline) {
fnord::logInfo(
"fnord.dproc",
"Starting local pipeline id=$0 tasks=$1",
(void*) pipeline,
pipeline->tasks.size());
std::unique_lock<std::mutex> lk(pipeline->mutex);
while (pipeline->tasks.size() > 0) {
bool waiting = true;
size_t num_waiting = 0;
size_t num_running = 0;
size_t num_completed = 0;
for (auto& taskref : pipeline->tasks) {
if (taskref->finished) {
++num_completed;
continue;
}
if (taskref->running) {
++num_running;
continue;
}
if (!taskref->expanded) {
taskref->expanded = true;
auto parent_task = taskref;
for (const auto& dep : taskref->task->dependencies()) {
RefPtr<LocalTaskRef> depref(new LocalTaskRef(app, dep.task_name, dep.params));
parent_task->dependencies.emplace_back(depref);
pipeline->tasks.emplace_back(depref);
}
waiting = false;
break;
}
bool deps_finished = true;
for (const auto& dep : taskref->dependencies) {
if (!dep->finished) {
deps_finished = false;
}
}
if (!deps_finished) {
++num_waiting;
continue;
}
taskref->running = true;
tpool_.run(std::bind(&LocalScheduler::runTask, this, pipeline, taskref));
waiting = false;
}
fnord::logInfo(
"fnord.dproc",
"Running local pipeline... id=$0 tasks=$1, running=$2, waiting=$3, completed=$4",
(void*) pipeline,
pipeline->tasks.size(),
num_running,
num_waiting,
num_completed);
if (waiting) {
pipeline->wakeup.wait(lk);
}
while (pipeline->tasks.size() > 0 && pipeline->tasks.back()->finished) {
pipeline->tasks.pop_back();
}
}
fnord::logInfo(
"fnord.dproc",
"Completed local pipeline id=$0",
(void*) pipeline);
}
void LocalScheduler::runTask(
LocalTaskPipeline* pipeline,
RefPtr<LocalTaskRef> task) {
auto cache_key = task->task->cacheKey();
String output_file;
if (cache_key.isEmpty()) {
auto tmpid = Random::singleton()->hex128();
output_file = FileUtil::joinPaths(
tempdir_,
StringUtil::format("tmp_$0", tmpid));
} else {
output_file = FileUtil::joinPaths(
tempdir_,
StringUtil::format("cache_$0", cache_key.get()));
}
auto cached = !cache_key.isEmpty() && FileUtil::exists(output_file);
fnord::logDebug(
"fnord.dproc",
"Running task: $0 (cached=$1)",
task->debug_name,
cached);
if (!cached) {
try {
auto res = task->task->run(task.get());
auto file = File::openFile(
output_file + "~",
File::O_CREATEOROPEN | File::O_WRITE);
file.write(res->data(), res->size());
FileUtil::mv(output_file + "~", output_file);
} catch (const std::exception& e) {
fnord::logError("fnord.dproc", e, "error");
}
}
std::unique_lock<std::mutex> lk(pipeline->mutex);
task->output_filename = output_file;
task->finished = true;
lk.unlock();
pipeline->wakeup.notify_all();
}
LocalScheduler::LocalTaskRef::LocalTaskRef(
RefPtr<Application> app,
const String& task_name,
const Buffer& params) :
task(app->getTaskInstance(task_name, params)),
debug_name(StringUtil::format("$0#$1", app->name(), task_name)),
running(false),
expanded(false),
finished(false) {}
RefPtr<VFSFile> LocalScheduler::LocalTaskRef::getDependency(size_t index) {
if (index >= dependencies.size()) {
RAISEF(kIndexError, "invalid dependecy index: $0", index);
}
const auto& dep = dependencies[index];
if (!FileUtil::exists(dep->output_filename)) {
RAISEF(kRuntimeError, "missing upstream output: $0", dep->output_filename);
}
return RefPtr<VFSFile>(
new io::MmappedFile(
File::openFile(dep->output_filename, File::O_READ)));
}
size_t LocalScheduler::LocalTaskRef::numDependencies() const {
return dependencies.size();
}
} // namespace dproc
} // namespace fnord
<|endoftext|> |
<commit_before>/**
* This file is part of the "libfnord" project
* Copyright (c) 2015 Paul Asmuth
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <unistd.h>
#include <fnord-base/io/file.h>
#include <fnord-base/io/fileutil.h>
#include <fnord-base/io/mmappedfile.h>
#include <fnord-base/logging.h>
#include <fnord-base/io/fileutil.h>
#include <fnord-dproc/LocalScheduler.h>
namespace fnord {
namespace dproc {
LocalScheduler::LocalScheduler(
const String& tempdir /* = "/tmp" */,
size_t max_threads /* = 8 */,
size_t max_requests /* = 32 */) :
tempdir_(tempdir),
tpool_(max_threads),
req_tpool_(max_requests) {}
void LocalScheduler::start() {
req_tpool_.start();
tpool_.start();
}
void LocalScheduler::stop() {
req_tpool_.stop();
tpool_.stop();
}
RefPtr<TaskResult> LocalScheduler::run(
RefPtr<Application> app,
const TaskSpec& task) {
RefPtr<TaskResult> result(new TaskResult());
try {
auto instance = mkRef(
new LocalTaskRef(
app,
task.task_name(),
Buffer(task.params().data(), task.params().size())));
req_tpool_.run([this, app, result, instance] () {
try {
LocalTaskPipeline pipeline;
pipeline.tasks.push_back(instance);
runPipeline(app.get(), &pipeline, result);
result->returnResult(
new io::MmappedFile(
File::openFile(instance->output_filename, File::O_READ)));
} catch (const StandardException& e) {
fnord::logError("dproc.scheduler", e, "task failed");
result->returnError(e);
}
});
} catch (const StandardException& e) {
fnord::logError("dproc.scheduler", e, "task failed");
result->returnError(e);
}
return result;
}
void LocalScheduler::runPipeline(
Application* app,
LocalTaskPipeline* pipeline,
RefPtr<TaskResult> result) {
fnord::logInfo(
"fnord.dproc",
"Starting local pipeline id=$0 tasks=$1",
(void*) pipeline,
pipeline->tasks.size());
std::unique_lock<std::mutex> lk(pipeline->mutex);
result->updateStatus([&pipeline] (TaskStatus* status) {
status->num_subtasks_total = pipeline->tasks.size();
});
while (pipeline->tasks.size() > 0) {
bool waiting = true;
size_t num_waiting = 0;
size_t num_running = 0;
size_t num_completed = 0;
for (auto& taskref : pipeline->tasks) {
if (taskref->failed) {
RAISE(kRuntimeError, "task failed");
}
if (taskref->finished) {
++num_completed;
continue;
}
if (taskref->running) {
++num_running;
continue;
}
if (!taskref->expanded) {
taskref->expanded = true;
auto cache_key = taskref->task->cacheKey();
if (cache_key.isEmpty()) {
auto tmpid = Random::singleton()->hex128();
taskref->output_filename = FileUtil::joinPaths(
tempdir_,
StringUtil::format("tmp_$0", tmpid));
} else {
taskref->output_filename = FileUtil::joinPaths(
tempdir_,
StringUtil::format("cache_$0", cache_key.get()));
}
auto cached =
!cache_key.isEmpty() &&
FileUtil::exists(taskref->output_filename);
if (cached) {
fnord::logDebug(
"fnord.dproc",
"Running task [cached]: $0",
taskref->debug_name);
result->updateStatus([&pipeline] (TaskStatus* status) {
++status->num_subtasks_completed;
});
taskref->finished = true;
waiting = false;
break;
}
auto parent_task = taskref;
size_t numdeps = 0;
for (const auto& dep : taskref->task->dependencies()) {
RefPtr<LocalTaskRef> depref(new LocalTaskRef(app, dep.task_name, dep.params));
parent_task->dependencies.emplace_back(depref);
pipeline->tasks.emplace_back(depref);
++numdeps;
}
if (numdeps > 0) {
result->updateStatus([numdeps] (TaskStatus* status) {
status->num_subtasks_total += numdeps;
});
}
waiting = false;
break;
}
bool deps_finished = true;
for (const auto& dep : taskref->dependencies) {
if (dep->failed) {
RAISE(kRuntimeError, "task failed");
}
if (!dep->finished) {
deps_finished = false;
}
}
if (!deps_finished) {
++num_waiting;
continue;
}
fnord::logDebug("fnord.dproc", "Running task: $0", taskref->debug_name);
taskref->running = true;
tpool_.run(std::bind(
&LocalScheduler::runTask,
this,
pipeline,
taskref,
result));
waiting = false;
}
fnord::logDebug(
"fnord.dproc",
"Running local pipeline id=$0: $1",
(void*) pipeline,
result->status().toString());
if (waiting) {
pipeline->wakeup.wait(lk);
}
while (pipeline->tasks.size() > 0 && pipeline->tasks.back()->finished) {
pipeline->tasks.pop_back();
}
}
fnord::logDebug(
"fnord.dproc",
"Completed local pipeline id=$0",
(void*) pipeline);
}
void LocalScheduler::runTask(
LocalTaskPipeline* pipeline,
RefPtr<LocalTaskRef> task,
RefPtr<TaskResult> result) {
auto output_file = task->output_filename;
try {
auto res = task->task->run(task.get());
auto file = File::openFile(
output_file + "~",
File::O_CREATEOROPEN | File::O_WRITE);
file.write(res->data(), res->size());
FileUtil::mv(output_file + "~", output_file);
} catch (const std::exception& e) {
task->failed = true;
fnord::logError("fnord.dproc", e, "error");
}
result->updateStatus([&pipeline] (TaskStatus* status) {
++status->num_subtasks_completed;
});
std::unique_lock<std::mutex> lk(pipeline->mutex);
task->finished = true;
lk.unlock();
pipeline->wakeup.notify_all();
}
LocalScheduler::LocalTaskRef::LocalTaskRef(
RefPtr<Application> app,
const String& task_name,
const Buffer& params) :
task(app->getTaskInstance(task_name, params)),
debug_name(StringUtil::format("$0#$1", app->name(), task_name)),
running(false),
expanded(false),
finished(false),
failed(false) {}
RefPtr<VFSFile> LocalScheduler::LocalTaskRef::getDependency(size_t index) {
if (index >= dependencies.size()) {
RAISEF(kIndexError, "invalid dependecy index: $0", index);
}
const auto& dep = dependencies[index];
if (!FileUtil::exists(dep->output_filename)) {
RAISEF(kRuntimeError, "missing upstream output: $0", dep->output_filename);
}
return RefPtr<VFSFile>(
new io::MmappedFile(
File::openFile(dep->output_filename, File::O_READ)));
}
size_t LocalScheduler::LocalTaskRef::numDependencies() const {
return dependencies.size();
}
} // namespace dproc
} // namespace fnord
<commit_msg>fail tasks...<commit_after>/**
* This file is part of the "libfnord" project
* Copyright (c) 2015 Paul Asmuth
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <unistd.h>
#include <fnord-base/io/file.h>
#include <fnord-base/io/fileutil.h>
#include <fnord-base/io/mmappedfile.h>
#include <fnord-base/logging.h>
#include <fnord-base/io/fileutil.h>
#include <fnord-dproc/LocalScheduler.h>
namespace fnord {
namespace dproc {
LocalScheduler::LocalScheduler(
const String& tempdir /* = "/tmp" */,
size_t max_threads /* = 8 */,
size_t max_requests /* = 32 */) :
tempdir_(tempdir),
tpool_(max_threads),
req_tpool_(max_requests) {}
void LocalScheduler::start() {
req_tpool_.start();
tpool_.start();
}
void LocalScheduler::stop() {
req_tpool_.stop();
tpool_.stop();
}
RefPtr<TaskResult> LocalScheduler::run(
RefPtr<Application> app,
const TaskSpec& task) {
RefPtr<TaskResult> result(new TaskResult());
try {
auto instance = mkRef(
new LocalTaskRef(
app,
task.task_name(),
Buffer(task.params().data(), task.params().size())));
req_tpool_.run([this, app, result, instance] () {
try {
LocalTaskPipeline pipeline;
pipeline.tasks.push_back(instance);
runPipeline(app.get(), &pipeline, result);
result->returnResult(
new io::MmappedFile(
File::openFile(instance->output_filename, File::O_READ)));
} catch (const StandardException& e) {
fnord::logError("dproc.scheduler", e, "task failed");
result->returnError(e);
}
});
} catch (const StandardException& e) {
fnord::logError("dproc.scheduler", e, "task failed");
result->returnError(e);
}
return result;
}
void LocalScheduler::runPipeline(
Application* app,
LocalTaskPipeline* pipeline,
RefPtr<TaskResult> result) {
fnord::logInfo(
"fnord.dproc",
"Starting local pipeline id=$0 tasks=$1",
(void*) pipeline,
pipeline->tasks.size());
std::unique_lock<std::mutex> lk(pipeline->mutex);
result->updateStatus([&pipeline] (TaskStatus* status) {
status->num_subtasks_total = pipeline->tasks.size();
});
while (pipeline->tasks.size() > 0) {
bool waiting = true;
size_t num_waiting = 0;
size_t num_running = 0;
size_t num_completed = 0;
for (auto& taskref : pipeline->tasks) {
if (taskref->finished) {
++num_completed;
continue;
}
if (taskref->running) {
++num_running;
continue;
}
if (!taskref->expanded) {
taskref->expanded = true;
auto cache_key = taskref->task->cacheKey();
if (cache_key.isEmpty()) {
auto tmpid = Random::singleton()->hex128();
taskref->output_filename = FileUtil::joinPaths(
tempdir_,
StringUtil::format("tmp_$0", tmpid));
} else {
taskref->output_filename = FileUtil::joinPaths(
tempdir_,
StringUtil::format("cache_$0", cache_key.get()));
}
auto cached =
!cache_key.isEmpty() &&
FileUtil::exists(taskref->output_filename);
if (cached) {
fnord::logDebug(
"fnord.dproc",
"Running task [cached]: $0",
taskref->debug_name);
result->updateStatus([&pipeline] (TaskStatus* status) {
++status->num_subtasks_completed;
});
taskref->finished = true;
waiting = false;
break;
}
auto parent_task = taskref;
size_t numdeps = 0;
for (const auto& dep : taskref->task->dependencies()) {
RefPtr<LocalTaskRef> depref(new LocalTaskRef(app, dep.task_name, dep.params));
parent_task->dependencies.emplace_back(depref);
pipeline->tasks.emplace_back(depref);
++numdeps;
}
if (numdeps > 0) {
result->updateStatus([numdeps] (TaskStatus* status) {
status->num_subtasks_total += numdeps;
});
}
waiting = false;
break;
}
bool deps_finished = true;
for (const auto& dep : taskref->dependencies) {
if (dep->failed) {
taskref->failed = true;
taskref->finished = true;
waiting = false;
}
if (!dep->finished) {
deps_finished = false;
}
}
if (!taskref->finished) {
if (!deps_finished) {
++num_waiting;
continue;
}
fnord::logDebug("fnord.dproc", "Running task: $0", taskref->debug_name);
taskref->running = true;
tpool_.run(std::bind(
&LocalScheduler::runTask,
this,
pipeline,
taskref,
result));
waiting = false;
}
}
fnord::logDebug(
"fnord.dproc",
"Running local pipeline id=$0: $1",
(void*) pipeline,
result->status().toString());
if (waiting) {
pipeline->wakeup.wait(lk);
}
while (pipeline->tasks.size() > 0 && pipeline->tasks.back()->finished) {
pipeline->tasks.pop_back();
}
}
fnord::logDebug(
"fnord.dproc",
"Completed local pipeline id=$0",
(void*) pipeline);
}
void LocalScheduler::runTask(
LocalTaskPipeline* pipeline,
RefPtr<LocalTaskRef> task,
RefPtr<TaskResult> result) {
auto output_file = task->output_filename;
try {
auto res = task->task->run(task.get());
auto file = File::openFile(
output_file + "~",
File::O_CREATEOROPEN | File::O_WRITE);
file.write(res->data(), res->size());
FileUtil::mv(output_file + "~", output_file);
} catch (const std::exception& e) {
task->failed = true;
fnord::logError("fnord.dproc", e, "error");
}
result->updateStatus([&pipeline] (TaskStatus* status) {
++status->num_subtasks_completed;
});
std::unique_lock<std::mutex> lk(pipeline->mutex);
task->finished = true;
lk.unlock();
pipeline->wakeup.notify_all();
}
LocalScheduler::LocalTaskRef::LocalTaskRef(
RefPtr<Application> app,
const String& task_name,
const Buffer& params) :
task(app->getTaskInstance(task_name, params)),
debug_name(StringUtil::format("$0#$1", app->name(), task_name)),
running(false),
expanded(false),
finished(false),
failed(false) {}
RefPtr<VFSFile> LocalScheduler::LocalTaskRef::getDependency(size_t index) {
if (index >= dependencies.size()) {
RAISEF(kIndexError, "invalid dependecy index: $0", index);
}
const auto& dep = dependencies[index];
if (!FileUtil::exists(dep->output_filename)) {
RAISEF(kRuntimeError, "missing upstream output: $0", dep->output_filename);
}
return RefPtr<VFSFile>(
new io::MmappedFile(
File::openFile(dep->output_filename, File::O_READ)));
}
size_t LocalScheduler::LocalTaskRef::numDependencies() const {
return dependencies.size();
}
} // namespace dproc
} // namespace fnord
<|endoftext|> |
<commit_before>//
// Copyright (C) 2006-2007 SIPez LLC.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// Copyright (C) 2004-2007 SIPfoundry Inc.
// Licensed by SIPfoundry under the LGPL license.
//
// Copyright (C) 2004-2006 Pingtel Corp. All rights reserved.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// $$
///////////////////////////////////////////////////////////////////////////////
// SYSTEM INCLUDES
#include <assert.h>
// APPLICATION INCLUDES
#include <mp/MpMediaTask.h>
#include <mp/MpRtpInputAudioConnection.h>
#include <mp/MpFlowGraphBase.h>
#include <mp/MprFromNet.h>
#include <mp/MprDejitter.h>
#include <mp/MprDecode.h>
#include <mp/JB/JB_API.h>
#include <mp/MpResourceMsg.h>
#include <mp/MprRtpStartReceiveMsg.h>
#include <sdp/SdpCodec.h>
#include <os/OsLock.h>
#ifdef RTL_ENABLED
# include <rtl_macro.h>
#endif
// EXTERNAL FUNCTIONS
// EXTERNAL VARIABLES
// CONSTANTS
// STATIC VARIABLE INITIALIZATIONS
/* //////////////////////////// PUBLIC //////////////////////////////////// */
/* ============================ CREATORS ================================== */
// Constructor
MpRtpInputAudioConnection::MpRtpInputAudioConnection(const UtlString& resourceName,
MpConnectionID myID,
int samplesPerFrame,
int samplesPerSec)
: MpRtpInputConnection(resourceName,
myID,
#ifdef INCLUDE_RTCP // [
NULL // TODO: pParent->getRTCPSessionPtr()
#else // INCLUDE_RTCP ][
NULL
#endif // INCLUDE_RTCP ]
)
, mpDecode(NULL)
, mpJB_inst(NULL)
{
char name[50];
int i;
sprintf(name, "Decode-%d", myID);
mpDecode = new MprDecode(name, this, samplesPerFrame, samplesPerSec);
//memset((char*)mpPayloadMap, 0, (NUM_PAYLOAD_TYPES*sizeof(MpDecoderBase*)));
for (i=0; i<NUM_PAYLOAD_TYPES; i++) {
mpPayloadMap[i] = NULL;
}
// decoder does not get added to the flowgraph, this connection
// gets added to do the decoding frameprocessing.
//////////////////////////////////////////////////////////////////////////
// connect Dejitter -> Decode (Non synchronous resources)
mpDecode->setMyDejitter(mpDejitter);
// This got moved to the call flowgraph when the connection is
// added to the flowgraph. Not sure it is still needed there either
//pParent->synchronize("new Connection, before enable(), %dx%X\n");
//enable();
//pParent->synchronize("new Connection, after enable(), %dx%X\n");
}
// Destructor
MpRtpInputAudioConnection::~MpRtpInputAudioConnection()
{
if (mpDecode != NULL)
delete mpDecode;
if (NULL != mpJB_inst) {
JB_free(mpJB_inst);
mpJB_inst = NULL;
}
}
/* ============================ MANIPULATORS ============================== */
UtlBoolean MpRtpInputAudioConnection::processFrame(void)
{
UtlBoolean result;
#ifdef RTL_ENABLED
RTL_BLOCK((UtlString)*this);
#endif
assert(mpDecode);
if(mpDecode)
{
// call doProcessFrame to do any "real" work
result = mpDecode->doProcessFrame(mpInBufs,
mpOutBufs,
mMaxInputs,
mMaxOutputs,
mpDecode->mIsEnabled,
mpDecode->getSamplesPerFrame(),
mpDecode->getSamplesPerSec());
}
// No input buffers to release
assert(mMaxInputs == 0);
// Push the output buffer to the next resource
assert(mMaxOutputs == 1);
pushBufferDownsream(0, mpOutBufs[0]);
// release the output buffer
mpOutBufs[0].release();
return(result);
}
UtlBoolean MpRtpInputAudioConnection::doProcessFrame(MpBufPtr inBufs[],
MpBufPtr outBufs[],
int inBufsSize,
int outBufsSize,
UtlBoolean isEnabled,
int samplesPerFrame,
int samplesPerSecond)
{
// Not currently used
assert(0);
UtlBoolean result = FALSE;
assert(mpDecode);
if(mpDecode)
{
result = mpDecode->doProcessFrame(inBufs,
outBufs,
inBufsSize,
outBufsSize,
isEnabled,
samplesPerFrame,
samplesPerSecond);
}
return(result);
}
UtlBoolean MpRtpInputAudioConnection::handleMessage(MpResourceMsg& rMsg)
{
UtlBoolean result = FALSE;
unsigned char messageSubtype = rMsg.getMsgSubType();
switch(messageSubtype)
{
case MpResourceMsg::MPRM_START_RECEIVE_RTP:
{
MprRtpStartReceiveMsg* startMessage = (MprRtpStartReceiveMsg*) &rMsg;
SdpCodec** codecArray = NULL;
int numCodecs;
startMessage->getCodecArray(numCodecs, codecArray);
OsSocket* rtpSocket = startMessage->getRtpSocket();
OsSocket* rtcpSocket = startMessage->getRtcpSocket();
handleStartReceiveRtp(codecArray, numCodecs, *rtpSocket, *rtcpSocket);
result = TRUE;
}
break;
case MpResourceMsg::MPRM_STOP_RECEIVE_RTP:
printf("MpRtpInputAudioConnection::handleMessage MPRM_STOP_RECEIVE_RTP\n");
handleStopReceiveRtp();
result = TRUE;
break;
default:
result = MpResource::handleMessage(rMsg);
break;
}
return(result);
}
// Disables the input path of the connection.
// Resources on the path(s) will also be disabled by these calls.
// If the flow graph is not "started", this call takes effect
// immediately. Otherwise, the call takes effect at the start of the
// next frame processing interval.
//!retcode: OS_SUCCESS - for now, these methods always return success
UtlBoolean MpRtpInputAudioConnection::handleDisable()
{
mpDecode->disable();
return(MpResource::handleDisable());
}
// Enables the input path of the connection.
// Resources on the path(s) will also be enabled by these calls.
// Resources may allocate needed data (e.g. output path reframe buffer)
// during this operation.
// If the flow graph is not "started", this call takes effect
// immediately. Otherwise, the call takes effect at the start of the
// next frame processing interval.
//!retcode: OS_SUCCESS - for now, these methods always return success
UtlBoolean MpRtpInputAudioConnection::handleEnable()
{
mpDecode->enable();
return(MpResource::handleEnable());
}
// Start receiving RTP and RTCP packets.
OsStatus MpRtpInputAudioConnection::startReceiveRtp(OsMsgQ& messageQueue,
const UtlString& resourceName,
SdpCodec* codecArray[],
int numCodecs,
OsSocket& rRtpSocket,
OsSocket& rRtcpSocket)
{
OsStatus result = OS_INVALID_ARGUMENT;
if(numCodecs > 0 && codecArray)
{
// Create a message to contain the startRecieveRtp data
MprRtpStartReceiveMsg msg(resourceName,
codecArray,
numCodecs,
rRtpSocket,
rRtcpSocket);
// Send the message in the queue.
result = messageQueue.send(msg);
}
return(result);
}
void MpRtpInputAudioConnection::handleStartReceiveRtp(SdpCodec* pCodecs[],
int numCodecs,
OsSocket& rRtpSocket,
OsSocket& rRtcpSocket)
{
if (numCodecs)
{
mpDecode->selectCodecs(pCodecs, numCodecs);
}
// No need to synchronize as the decoder is not part of the
// flowgraph. It is part of this connection/resource
//mpFlowGraph->synchronize();
prepareStartReceiveRtp(rRtpSocket, rRtcpSocket);
// No need to synchronize as the decoder is not part of the
// flowgraph. It is part of this connection/resource
//mpFlowGraph->synchronize();
if (numCodecs)
{
mpDecode->enable();
}
}
OsStatus MpRtpInputAudioConnection::stopReceiveRtp(OsMsgQ& messageQueue,
const UtlString& resourceName)
{
MpResourceMsg stopReceiveMsg(MpResourceMsg::MPRM_STOP_RECEIVE_RTP,
resourceName);
// Send the message in the queue.
OsStatus result = messageQueue.send(stopReceiveMsg);
return(result);
}
// Stop receiving RTP and RTCP packets.
void MpRtpInputAudioConnection::handleStopReceiveRtp()
{
prepareStopReceiveRtp();
JB_inst* pJB_inst;
// No need to synchronize as the decoder is not part of the
// flowgraph. It is part of this connection/resource
//mpFlowGraph->synchronize();
mpDecode->deselectCodec();
// No need to synchronize as the decoder is not part of the
// flowgraph. It is part of this connection/resource
//mpFlowGraph->synchronize();
pJB_inst = getJBinst(TRUE); // get NULL if not allocated
mpJB_inst = NULL;
// No need to synchronize as the decoder is not part of the
// flowgraph. It is part of this connection/resource
//mpFlowGraph->synchronize();
if (NULL != pJB_inst) {
JB_free(pJB_inst);
}
mpDecode->disable();
}
void MpRtpInputAudioConnection::addPayloadType(int payloadType, MpDecoderBase* decoder)
{
OsLock lock(mLock);
// Check that payloadType is valid.
if ((payloadType < 0) || (payloadType >= NUM_PAYLOAD_TYPES))
{
OsSysLog::add(FAC_MP, PRI_ERR,
"MpRtpInputAudioConnection::addPayloadType Attempting to add an invalid payload type %d", payloadType);
}
// Check to see if we already have a decoder for this payload type.
else if (!(NULL == mpPayloadMap[payloadType]))
{
// This condition probably indicates that the sender of SDP specified
// two decoders for the same payload type number.
OsSysLog::add(FAC_MP, PRI_ERR,
"MpRtpInputAudioConnection::addPayloadType Attempting to add a second decoder for payload type %d",
payloadType);
}
else
{
mpPayloadMap[payloadType] = decoder;
}
}
void MpRtpInputAudioConnection::deletePayloadType(int payloadType)
{
OsLock lock(mLock);
// Check that payloadType is valid.
if ((payloadType < 0) || (payloadType >= NUM_PAYLOAD_TYPES))
{
OsSysLog::add(FAC_MP, PRI_ERR,
"MpRtpInputAudioConnection::deletePayloadType Attempting to delete an invalid payload type %d", payloadType);
}
// Check to see if this entry has already been deleted.
else if (NULL == mpPayloadMap[payloadType])
{
// Either this payload type was doubly-added (and reported by
// addPayloadType) or we've hit the race condtion in XMR-29.
OsSysLog::add(FAC_MP, PRI_ERR,
"MpRtpInputAudioConnection::deletePayloadType Attempting to delete again payload type %d",
payloadType);
OsSysLog::add(FAC_MP, PRI_ERR,
"MpRtpInputAudioConnection::deletePayloadType If there is no message from MpRtpInputAudioConnection::addPayloadType above, see XMR-29");
}
else
{
mpPayloadMap[payloadType] = NULL;
}
}
void MpRtpInputAudioConnection::setPremiumSound(PremiumSoundOptions op)
{
#ifdef HAVE_GIPS /* [ */
int NetEqOp = NETEQ_PLAYOUT_MODE_OFF;
// this must only be called in the context of the Media Task
assert(OsTask::getCurrentTask() == MpMediaTask::getMediaTask(0));
if (EnablePremiumSound == op) {
NetEqOp = NETEQ_PLAYOUT_MODE_ON;
}
if (NULL != mpJB_inst) {
#ifndef __pingtel_on_posix__
NETEQ_GIPS_10MS16B_SetPlayoutMode(mpJB_inst, NetEqOp);
#endif
/*
osPrintf("MpRtpInputAudioConnection::setPremiumSound: %sabling Premium Sound on #%d\n",
(EnablePremiumSound == op) ? "En" : "Dis", mMyID);
*/
}
#endif /* HAVE_GIPS ] */
}
/* ============================ ACCESSORS ================================= */
//:Returns a pointer to the Jitter Buffer instance, creating it if necessary
// If the instance has not been created, but the argument "optional" is
// TRUE, then do not create it, just return NULL.
JB_inst* MpRtpInputAudioConnection::getJBinst(UtlBoolean optional) {
if ((NULL == mpJB_inst) && (!optional)) {
int res;
res = JB_create(&mpJB_inst);
/*
osPrintf("MpRtpInputAudioConnection::getJBinst: JB_create=>0x%X\n",
(int) mpJB_inst);
*/
assert(NULL != mpJB_inst);
//Here it is hard coded to use 8000 Hz sampling frequency
//This number is only relevant until any packet has arrived
//When packet arrives the codec determines the output samp.freq.
res |= JB_init(mpJB_inst, 8000);
if (0 != res) { //just in case
osPrintf("MpRtpInputAudioConnection::getJBinst: Jitter Buffer init failure!\n");
if (NULL != mpJB_inst) {
JB_free(mpJB_inst);
mpJB_inst = NULL;
}
}
if (NULL != mpJB_inst) {
/*
UtlBoolean on = mpFlowGraph->isPremiumSoundEnabled();
osPrintf("MpRtpInputAudioConnection::getJBinst: %sabling Premium Sound on #%d\n",
on ? "En" : "Dis", mMyID);
setPremiumSound(on ? EnablePremiumSound : DisablePremiumSound);
*/
}
}
return(mpJB_inst);
}
MpDecoderBase* MpRtpInputAudioConnection::mapPayloadType(int payloadType)
{
OsLock lock(mLock);
if ((payloadType < 0) || (payloadType >= NUM_PAYLOAD_TYPES))
{
OsSysLog::add(FAC_MP, PRI_ERR,
"MpRtpInputAudioConnection::mapPayloadType Attempting to map an invalid payload type %d", payloadType);
return NULL;
}
else
{
return mpPayloadMap[payloadType];
}
}
/* ============================ INQUIRY =================================== */
/* //////////////////////////// PROTECTED ///////////////////////////////// */
UtlBoolean MpRtpInputAudioConnection::handleSetDtmfNotify(OsNotification* pNotify)
{
return mpDecode->handleSetDtmfNotify(pNotify);
}
UtlBoolean MpRtpInputAudioConnection::setDtmfTerm(MprRecorder *pRecorders)
{
return mpDecode->setDtmfTerm(pRecorders);
}
/* //////////////////////////// PRIVATE /////////////////////////////////// */
/* ============================ FUNCTIONS ================================= */
<commit_msg>Remove chatty debug output from MpRtpInputAudioConnection::handleMessage().<commit_after>//
// Copyright (C) 2006-2007 SIPez LLC.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// Copyright (C) 2004-2007 SIPfoundry Inc.
// Licensed by SIPfoundry under the LGPL license.
//
// Copyright (C) 2004-2006 Pingtel Corp. All rights reserved.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// $$
///////////////////////////////////////////////////////////////////////////////
// SYSTEM INCLUDES
#include <assert.h>
// APPLICATION INCLUDES
#include <mp/MpMediaTask.h>
#include <mp/MpRtpInputAudioConnection.h>
#include <mp/MpFlowGraphBase.h>
#include <mp/MprFromNet.h>
#include <mp/MprDejitter.h>
#include <mp/MprDecode.h>
#include <mp/JB/JB_API.h>
#include <mp/MpResourceMsg.h>
#include <mp/MprRtpStartReceiveMsg.h>
#include <sdp/SdpCodec.h>
#include <os/OsLock.h>
#ifdef RTL_ENABLED
# include <rtl_macro.h>
#endif
// EXTERNAL FUNCTIONS
// EXTERNAL VARIABLES
// CONSTANTS
// STATIC VARIABLE INITIALIZATIONS
/* //////////////////////////// PUBLIC //////////////////////////////////// */
/* ============================ CREATORS ================================== */
// Constructor
MpRtpInputAudioConnection::MpRtpInputAudioConnection(const UtlString& resourceName,
MpConnectionID myID,
int samplesPerFrame,
int samplesPerSec)
: MpRtpInputConnection(resourceName,
myID,
#ifdef INCLUDE_RTCP // [
NULL // TODO: pParent->getRTCPSessionPtr()
#else // INCLUDE_RTCP ][
NULL
#endif // INCLUDE_RTCP ]
)
, mpDecode(NULL)
, mpJB_inst(NULL)
{
char name[50];
int i;
sprintf(name, "Decode-%d", myID);
mpDecode = new MprDecode(name, this, samplesPerFrame, samplesPerSec);
//memset((char*)mpPayloadMap, 0, (NUM_PAYLOAD_TYPES*sizeof(MpDecoderBase*)));
for (i=0; i<NUM_PAYLOAD_TYPES; i++) {
mpPayloadMap[i] = NULL;
}
// decoder does not get added to the flowgraph, this connection
// gets added to do the decoding frameprocessing.
//////////////////////////////////////////////////////////////////////////
// connect Dejitter -> Decode (Non synchronous resources)
mpDecode->setMyDejitter(mpDejitter);
// This got moved to the call flowgraph when the connection is
// added to the flowgraph. Not sure it is still needed there either
//pParent->synchronize("new Connection, before enable(), %dx%X\n");
//enable();
//pParent->synchronize("new Connection, after enable(), %dx%X\n");
}
// Destructor
MpRtpInputAudioConnection::~MpRtpInputAudioConnection()
{
if (mpDecode != NULL)
delete mpDecode;
if (NULL != mpJB_inst) {
JB_free(mpJB_inst);
mpJB_inst = NULL;
}
}
/* ============================ MANIPULATORS ============================== */
UtlBoolean MpRtpInputAudioConnection::processFrame(void)
{
UtlBoolean result;
#ifdef RTL_ENABLED
RTL_BLOCK((UtlString)*this);
#endif
assert(mpDecode);
if(mpDecode)
{
// call doProcessFrame to do any "real" work
result = mpDecode->doProcessFrame(mpInBufs,
mpOutBufs,
mMaxInputs,
mMaxOutputs,
mpDecode->mIsEnabled,
mpDecode->getSamplesPerFrame(),
mpDecode->getSamplesPerSec());
}
// No input buffers to release
assert(mMaxInputs == 0);
// Push the output buffer to the next resource
assert(mMaxOutputs == 1);
pushBufferDownsream(0, mpOutBufs[0]);
// release the output buffer
mpOutBufs[0].release();
return(result);
}
UtlBoolean MpRtpInputAudioConnection::doProcessFrame(MpBufPtr inBufs[],
MpBufPtr outBufs[],
int inBufsSize,
int outBufsSize,
UtlBoolean isEnabled,
int samplesPerFrame,
int samplesPerSecond)
{
// Not currently used
assert(0);
UtlBoolean result = FALSE;
assert(mpDecode);
if(mpDecode)
{
result = mpDecode->doProcessFrame(inBufs,
outBufs,
inBufsSize,
outBufsSize,
isEnabled,
samplesPerFrame,
samplesPerSecond);
}
return(result);
}
UtlBoolean MpRtpInputAudioConnection::handleMessage(MpResourceMsg& rMsg)
{
UtlBoolean result = FALSE;
unsigned char messageSubtype = rMsg.getMsgSubType();
switch(messageSubtype)
{
case MpResourceMsg::MPRM_START_RECEIVE_RTP:
{
MprRtpStartReceiveMsg* startMessage = (MprRtpStartReceiveMsg*) &rMsg;
SdpCodec** codecArray = NULL;
int numCodecs;
startMessage->getCodecArray(numCodecs, codecArray);
OsSocket* rtpSocket = startMessage->getRtpSocket();
OsSocket* rtcpSocket = startMessage->getRtcpSocket();
handleStartReceiveRtp(codecArray, numCodecs, *rtpSocket, *rtcpSocket);
result = TRUE;
}
break;
case MpResourceMsg::MPRM_STOP_RECEIVE_RTP:
handleStopReceiveRtp();
result = TRUE;
break;
default:
result = MpResource::handleMessage(rMsg);
break;
}
return(result);
}
// Disables the input path of the connection.
// Resources on the path(s) will also be disabled by these calls.
// If the flow graph is not "started", this call takes effect
// immediately. Otherwise, the call takes effect at the start of the
// next frame processing interval.
//!retcode: OS_SUCCESS - for now, these methods always return success
UtlBoolean MpRtpInputAudioConnection::handleDisable()
{
mpDecode->disable();
return(MpResource::handleDisable());
}
// Enables the input path of the connection.
// Resources on the path(s) will also be enabled by these calls.
// Resources may allocate needed data (e.g. output path reframe buffer)
// during this operation.
// If the flow graph is not "started", this call takes effect
// immediately. Otherwise, the call takes effect at the start of the
// next frame processing interval.
//!retcode: OS_SUCCESS - for now, these methods always return success
UtlBoolean MpRtpInputAudioConnection::handleEnable()
{
mpDecode->enable();
return(MpResource::handleEnable());
}
// Start receiving RTP and RTCP packets.
OsStatus MpRtpInputAudioConnection::startReceiveRtp(OsMsgQ& messageQueue,
const UtlString& resourceName,
SdpCodec* codecArray[],
int numCodecs,
OsSocket& rRtpSocket,
OsSocket& rRtcpSocket)
{
OsStatus result = OS_INVALID_ARGUMENT;
if(numCodecs > 0 && codecArray)
{
// Create a message to contain the startRecieveRtp data
MprRtpStartReceiveMsg msg(resourceName,
codecArray,
numCodecs,
rRtpSocket,
rRtcpSocket);
// Send the message in the queue.
result = messageQueue.send(msg);
}
return(result);
}
void MpRtpInputAudioConnection::handleStartReceiveRtp(SdpCodec* pCodecs[],
int numCodecs,
OsSocket& rRtpSocket,
OsSocket& rRtcpSocket)
{
if (numCodecs)
{
mpDecode->selectCodecs(pCodecs, numCodecs);
}
// No need to synchronize as the decoder is not part of the
// flowgraph. It is part of this connection/resource
//mpFlowGraph->synchronize();
prepareStartReceiveRtp(rRtpSocket, rRtcpSocket);
// No need to synchronize as the decoder is not part of the
// flowgraph. It is part of this connection/resource
//mpFlowGraph->synchronize();
if (numCodecs)
{
mpDecode->enable();
}
}
OsStatus MpRtpInputAudioConnection::stopReceiveRtp(OsMsgQ& messageQueue,
const UtlString& resourceName)
{
MpResourceMsg stopReceiveMsg(MpResourceMsg::MPRM_STOP_RECEIVE_RTP,
resourceName);
// Send the message in the queue.
OsStatus result = messageQueue.send(stopReceiveMsg);
return(result);
}
// Stop receiving RTP and RTCP packets.
void MpRtpInputAudioConnection::handleStopReceiveRtp()
{
prepareStopReceiveRtp();
JB_inst* pJB_inst;
// No need to synchronize as the decoder is not part of the
// flowgraph. It is part of this connection/resource
//mpFlowGraph->synchronize();
mpDecode->deselectCodec();
// No need to synchronize as the decoder is not part of the
// flowgraph. It is part of this connection/resource
//mpFlowGraph->synchronize();
pJB_inst = getJBinst(TRUE); // get NULL if not allocated
mpJB_inst = NULL;
// No need to synchronize as the decoder is not part of the
// flowgraph. It is part of this connection/resource
//mpFlowGraph->synchronize();
if (NULL != pJB_inst) {
JB_free(pJB_inst);
}
mpDecode->disable();
}
void MpRtpInputAudioConnection::addPayloadType(int payloadType, MpDecoderBase* decoder)
{
OsLock lock(mLock);
// Check that payloadType is valid.
if ((payloadType < 0) || (payloadType >= NUM_PAYLOAD_TYPES))
{
OsSysLog::add(FAC_MP, PRI_ERR,
"MpRtpInputAudioConnection::addPayloadType Attempting to add an invalid payload type %d", payloadType);
}
// Check to see if we already have a decoder for this payload type.
else if (!(NULL == mpPayloadMap[payloadType]))
{
// This condition probably indicates that the sender of SDP specified
// two decoders for the same payload type number.
OsSysLog::add(FAC_MP, PRI_ERR,
"MpRtpInputAudioConnection::addPayloadType Attempting to add a second decoder for payload type %d",
payloadType);
}
else
{
mpPayloadMap[payloadType] = decoder;
}
}
void MpRtpInputAudioConnection::deletePayloadType(int payloadType)
{
OsLock lock(mLock);
// Check that payloadType is valid.
if ((payloadType < 0) || (payloadType >= NUM_PAYLOAD_TYPES))
{
OsSysLog::add(FAC_MP, PRI_ERR,
"MpRtpInputAudioConnection::deletePayloadType Attempting to delete an invalid payload type %d", payloadType);
}
// Check to see if this entry has already been deleted.
else if (NULL == mpPayloadMap[payloadType])
{
// Either this payload type was doubly-added (and reported by
// addPayloadType) or we've hit the race condtion in XMR-29.
OsSysLog::add(FAC_MP, PRI_ERR,
"MpRtpInputAudioConnection::deletePayloadType Attempting to delete again payload type %d",
payloadType);
OsSysLog::add(FAC_MP, PRI_ERR,
"MpRtpInputAudioConnection::deletePayloadType If there is no message from MpRtpInputAudioConnection::addPayloadType above, see XMR-29");
}
else
{
mpPayloadMap[payloadType] = NULL;
}
}
void MpRtpInputAudioConnection::setPremiumSound(PremiumSoundOptions op)
{
#ifdef HAVE_GIPS /* [ */
int NetEqOp = NETEQ_PLAYOUT_MODE_OFF;
// this must only be called in the context of the Media Task
assert(OsTask::getCurrentTask() == MpMediaTask::getMediaTask(0));
if (EnablePremiumSound == op) {
NetEqOp = NETEQ_PLAYOUT_MODE_ON;
}
if (NULL != mpJB_inst) {
#ifndef __pingtel_on_posix__
NETEQ_GIPS_10MS16B_SetPlayoutMode(mpJB_inst, NetEqOp);
#endif
/*
osPrintf("MpRtpInputAudioConnection::setPremiumSound: %sabling Premium Sound on #%d\n",
(EnablePremiumSound == op) ? "En" : "Dis", mMyID);
*/
}
#endif /* HAVE_GIPS ] */
}
/* ============================ ACCESSORS ================================= */
//:Returns a pointer to the Jitter Buffer instance, creating it if necessary
// If the instance has not been created, but the argument "optional" is
// TRUE, then do not create it, just return NULL.
JB_inst* MpRtpInputAudioConnection::getJBinst(UtlBoolean optional) {
if ((NULL == mpJB_inst) && (!optional)) {
int res;
res = JB_create(&mpJB_inst);
/*
osPrintf("MpRtpInputAudioConnection::getJBinst: JB_create=>0x%X\n",
(int) mpJB_inst);
*/
assert(NULL != mpJB_inst);
//Here it is hard coded to use 8000 Hz sampling frequency
//This number is only relevant until any packet has arrived
//When packet arrives the codec determines the output samp.freq.
res |= JB_init(mpJB_inst, 8000);
if (0 != res) { //just in case
osPrintf("MpRtpInputAudioConnection::getJBinst: Jitter Buffer init failure!\n");
if (NULL != mpJB_inst) {
JB_free(mpJB_inst);
mpJB_inst = NULL;
}
}
if (NULL != mpJB_inst) {
/*
UtlBoolean on = mpFlowGraph->isPremiumSoundEnabled();
osPrintf("MpRtpInputAudioConnection::getJBinst: %sabling Premium Sound on #%d\n",
on ? "En" : "Dis", mMyID);
setPremiumSound(on ? EnablePremiumSound : DisablePremiumSound);
*/
}
}
return(mpJB_inst);
}
MpDecoderBase* MpRtpInputAudioConnection::mapPayloadType(int payloadType)
{
OsLock lock(mLock);
if ((payloadType < 0) || (payloadType >= NUM_PAYLOAD_TYPES))
{
OsSysLog::add(FAC_MP, PRI_ERR,
"MpRtpInputAudioConnection::mapPayloadType Attempting to map an invalid payload type %d", payloadType);
return NULL;
}
else
{
return mpPayloadMap[payloadType];
}
}
/* ============================ INQUIRY =================================== */
/* //////////////////////////// PROTECTED ///////////////////////////////// */
UtlBoolean MpRtpInputAudioConnection::handleSetDtmfNotify(OsNotification* pNotify)
{
return mpDecode->handleSetDtmfNotify(pNotify);
}
UtlBoolean MpRtpInputAudioConnection::setDtmfTerm(MprRecorder *pRecorders)
{
return mpDecode->setDtmfTerm(pRecorders);
}
/* //////////////////////////// PRIVATE /////////////////////////////////// */
/* ============================ FUNCTIONS ================================= */
<|endoftext|> |
<commit_before>/**
* @file llfoldertype.cpp
* @brief Implementation of LLViewerFolderType functionality.
*
* $LicenseInfo:firstyear=2001&license=viewergpl$
*
* Copyright (c) 2001-2009, Linden Research, Inc.
*
* Second Life Viewer Source Code
* The source code in this file ("Source Code") is provided by Linden Lab
* to you under the terms of the GNU General Public License, version 2.0
* ("GPL"), unless you have obtained a separate licensing agreement
* ("Other License"), formally executed by you and Linden Lab. Terms of
* the GPL can be found in doc/GPL-license.txt in this distribution, or
* online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
*
* There are special exceptions to the terms and conditions of the GPL as
* it is applied to this Source Code. View the full text of the exception
* in the file doc/FLOSS-exception.txt in this software distribution, or
* online at
* http://secondlifegrid.net/programs/open_source/licensing/flossexception
*
* By copying, modifying or distributing this software, you acknowledge
* that you have read and understood your obligations described above,
* and agree to abide by those obligations.
*
* ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
* WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
* COMPLETENESS OR PERFORMANCE.
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
#include "llviewerfoldertype.h"
#include "lldictionary.h"
#include "llmemory.h"
#include "llvisualparam.h"
static const std::string empty_string;
struct ViewerFolderEntry : public LLDictionaryEntry
{
// Constructor for non-ensembles
ViewerFolderEntry(const std::string &new_category_name, // default name when creating a new category of this type
const std::string &icon_name_open, // name of the folder icon
const std::string &icon_name_closed,
BOOL is_quiet, // folder doesn't need a UI update when changed
const std::string &dictionary_name = empty_string // no reverse lookup needed on non-ensembles, so in most cases just leave this blank
)
:
LLDictionaryEntry(dictionary_name),
mNewCategoryName(new_category_name),
mIconNameOpen(icon_name_open),
mIconNameClosed(icon_name_closed),
mIsQuiet(is_quiet)
{
mAllowedNames.clear();
}
// Constructor for ensembles
ViewerFolderEntry(const std::string &xui_name, // name of the xui menu item
const std::string &new_category_name, // default name when creating a new category of this type
const std::string &icon_name, // name of the folder icon
const std::string allowed_names // allowed item typenames for this folder type
)
:
LLDictionaryEntry(xui_name),
/* Just use default icons until we actually support ensembles
mIconNameOpen(icon_name),
mIconNameClosed(icon_name),
*/
mIconNameOpen("Inv_FolderOpen"), mIconNameClosed("Inv_FolderClosed"),
mNewCategoryName(new_category_name),
mIsQuiet(FALSE)
{
const std::string delims (",");
LLStringUtilBase<char>::getTokens(allowed_names, mAllowedNames, delims);
}
bool getIsAllowedName(const std::string &name) const
{
if (mAllowedNames.empty())
return false;
for (name_vec_t::const_iterator iter = mAllowedNames.begin();
iter != mAllowedNames.end();
iter++)
{
if (name == (*iter))
return true;
}
return false;
}
const std::string mIconNameOpen;
const std::string mIconNameClosed;
const std::string mNewCategoryName;
typedef std::vector<std::string> name_vec_t;
name_vec_t mAllowedNames;
BOOL mIsQuiet;
};
class LLViewerFolderDictionary : public LLSingleton<LLViewerFolderDictionary>,
public LLDictionary<LLFolderType::EType, ViewerFolderEntry>
{
public:
LLViewerFolderDictionary();
protected:
bool initEnsemblesFromFile(); // Reads in ensemble information from foldertypes.xml
};
LLViewerFolderDictionary::LLViewerFolderDictionary()
{
initEnsemblesFromFile();
// NEW CATEGORY NAME FOLDER OPEN FOLDER CLOSED QUIET?
// |-------------------------|-----------------------|----------------------|-----------|
addEntry(LLFolderType::FT_TEXTURE, new ViewerFolderEntry("Textures", "Inv_SysOpen", "Inv_SysClosed", FALSE));
addEntry(LLFolderType::FT_SOUND, new ViewerFolderEntry("Sounds", "Inv_SysOpen", "Inv_SysClosed", FALSE));
addEntry(LLFolderType::FT_CALLINGCARD, new ViewerFolderEntry("Calling Cards", "Inv_SysOpen", "Inv_SysClosed", FALSE));
addEntry(LLFolderType::FT_LANDMARK, new ViewerFolderEntry("Landmarks", "Inv_SysOpen", "Inv_SysClosed", FALSE));
addEntry(LLFolderType::FT_CLOTHING, new ViewerFolderEntry("Clothing", "Inv_SysOpen", "Inv_SysClosed", FALSE));
addEntry(LLFolderType::FT_OBJECT, new ViewerFolderEntry("Objects", "Inv_SysOpen", "Inv_SysClosed", FALSE));
addEntry(LLFolderType::FT_NOTECARD, new ViewerFolderEntry("Notecards", "Inv_SysOpen", "Inv_SysClosed", FALSE));
addEntry(LLFolderType::FT_ROOT_INVENTORY, new ViewerFolderEntry("My Inventory", "Inv_SysOpen", "Inv_SysClosed", FALSE));
addEntry(LLFolderType::FT_LSL_TEXT, new ViewerFolderEntry("Scripts", "Inv_SysOpen", "Inv_SysClosed", FALSE));
addEntry(LLFolderType::FT_BODYPART, new ViewerFolderEntry("Body Parts", "Inv_SysOpen", "Inv_SysClosed", FALSE));
addEntry(LLFolderType::FT_TRASH, new ViewerFolderEntry("Trash", "Inv_TrashOpen", "Inv_TrashClosed", TRUE));
addEntry(LLFolderType::FT_SNAPSHOT_CATEGORY, new ViewerFolderEntry("Photo Album", "Inv_SysOpen", "Inv_SysClosed", FALSE));
addEntry(LLFolderType::FT_LOST_AND_FOUND, new ViewerFolderEntry("Lost And Found", "Inv_LostOpen", "Inv_LostClosed", TRUE));
addEntry(LLFolderType::FT_ANIMATION, new ViewerFolderEntry("Animations", "Inv_SysOpen", "Inv_SysClosed", FALSE));
addEntry(LLFolderType::FT_GESTURE, new ViewerFolderEntry("Gestures", "Inv_SysOpen", "Inv_SysClosed", FALSE));
addEntry(LLFolderType::FT_FAVORITE, new ViewerFolderEntry("Favorites", "Inv_SysOpen", "Inv_SysClosed", FALSE));
addEntry(LLFolderType::FT_CURRENT_OUTFIT, new ViewerFolderEntry("Current Outfit", "Inv_SysOpen", "Inv_SysClosed", TRUE));
addEntry(LLFolderType::FT_OUTFIT, new ViewerFolderEntry("New Outfit", "Inv_LookFolderOpen", "Inv_LookFolderClosed", TRUE));
addEntry(LLFolderType::FT_MY_OUTFITS, new ViewerFolderEntry("My Outfits", "Inv_SysOpen", "Inv_SysClosed", TRUE));
addEntry(LLFolderType::FT_INBOX, new ViewerFolderEntry("Inbox", "Inv_SysOpen", "Inv_SysClosed", FALSE));
addEntry(LLFolderType::FT_NONE, new ViewerFolderEntry("New Folder", "Inv_FolderOpen", "Inv_FolderClosed", FALSE, "default"));
}
bool LLViewerFolderDictionary::initEnsemblesFromFile()
{
std::string xml_filename = gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS,"foldertypes.xml");
LLXmlTree folder_def;
if (!folder_def.parseFile(xml_filename))
{
llerrs << "Failed to parse folders file " << xml_filename << llendl;
return false;
}
LLXmlTreeNode* rootp = folder_def.getRoot();
for (LLXmlTreeNode* ensemble = rootp->getFirstChild();
ensemble;
ensemble = rootp->getNextChild())
{
if (!ensemble->hasName("ensemble"))
{
llwarns << "Invalid ensemble definition node " << ensemble->getName() << llendl;
continue;
}
S32 ensemble_type;
static LLStdStringHandle ensemble_num_string = LLXmlTree::addAttributeString("foldertype_num");
if (!ensemble->getFastAttributeS32(ensemble_num_string, ensemble_type))
{
llwarns << "No ensemble type defined" << llendl;
continue;
}
if (ensemble_type < S32(LLFolderType::FT_ENSEMBLE_START) || ensemble_type > S32(LLFolderType::FT_ENSEMBLE_END))
{
llwarns << "Exceeded maximum ensemble index" << LLFolderType::FT_ENSEMBLE_END << llendl;
break;
}
std::string xui_name;
static LLStdStringHandle xui_name_string = LLXmlTree::addAttributeString("xui_name");
if (!ensemble->getFastAttributeString(xui_name_string, xui_name))
{
llwarns << "No xui name defined" << llendl;
continue;
}
std::string icon_name;
static LLStdStringHandle icon_name_string = LLXmlTree::addAttributeString("icon_name");
if (!ensemble->getFastAttributeString(icon_name_string, icon_name))
{
llwarns << "No ensemble icon name defined" << llendl;
continue;
}
std::string allowed_names;
static LLStdStringHandle allowed_names_string = LLXmlTree::addAttributeString("allowed");
if (!ensemble->getFastAttributeString(allowed_names_string, allowed_names))
{
}
// Add the entry and increment the asset number.
const static std::string new_ensemble_name = "New Ensemble";
addEntry(LLFolderType::EType(ensemble_type), new ViewerFolderEntry(xui_name, new_ensemble_name, icon_name, allowed_names));
}
return true;
}
const std::string &LLViewerFolderType::lookupXUIName(LLFolderType::EType folder_type)
{
const ViewerFolderEntry *entry = LLViewerFolderDictionary::getInstance()->lookup(folder_type);
if (entry)
{
return entry->mName;
}
return badLookup();
}
LLFolderType::EType LLViewerFolderType::lookupTypeFromXUIName(const std::string &name)
{
return LLViewerFolderDictionary::getInstance()->lookup(name);
}
const std::string &LLViewerFolderType::lookupIconName(LLFolderType::EType folder_type, BOOL is_open)
{
const ViewerFolderEntry *entry = LLViewerFolderDictionary::getInstance()->lookup(folder_type);
if (entry)
{
if (is_open)
return entry->mIconNameOpen;
else
return entry->mIconNameClosed;
}
return badLookup();
}
BOOL LLViewerFolderType::lookupIsQuietType(LLFolderType::EType folder_type)
{
const ViewerFolderEntry *entry = LLViewerFolderDictionary::getInstance()->lookup(folder_type);
if (entry)
{
return entry->mIsQuiet;
}
return FALSE;
}
const std::string &LLViewerFolderType::lookupNewCategoryName(LLFolderType::EType folder_type)
{
const ViewerFolderEntry *entry = LLViewerFolderDictionary::getInstance()->lookup(folder_type);
if (entry)
{
return entry->mNewCategoryName;
}
return badLookup();
}
LLFolderType::EType LLViewerFolderType::lookupTypeFromNewCategoryName(const std::string& name)
{
for (LLViewerFolderDictionary::const_iterator iter = LLViewerFolderDictionary::getInstance()->begin();
iter != LLViewerFolderDictionary::getInstance()->end();
iter++)
{
const ViewerFolderEntry *entry = iter->second;
if (entry->mNewCategoryName == name)
{
return iter->first;
}
}
return FT_NONE;
}
U64 LLViewerFolderType::lookupValidFolderTypes(const std::string& item_name)
{
U64 matching_folders = 0;
for (LLViewerFolderDictionary::const_iterator iter = LLViewerFolderDictionary::getInstance()->begin();
iter != LLViewerFolderDictionary::getInstance()->end();
iter++)
{
const ViewerFolderEntry *entry = iter->second;
if (entry->getIsAllowedName(item_name))
{
matching_folders |= 1LL << iter->first;
}
}
return matching_folders;
}
<commit_msg>EXT-7829 FIXED Corrupted graphics in inventory side panel (gray box)<commit_after>/**
* @file llfoldertype.cpp
* @brief Implementation of LLViewerFolderType functionality.
*
* $LicenseInfo:firstyear=2001&license=viewergpl$
*
* Copyright (c) 2001-2009, Linden Research, Inc.
*
* Second Life Viewer Source Code
* The source code in this file ("Source Code") is provided by Linden Lab
* to you under the terms of the GNU General Public License, version 2.0
* ("GPL"), unless you have obtained a separate licensing agreement
* ("Other License"), formally executed by you and Linden Lab. Terms of
* the GPL can be found in doc/GPL-license.txt in this distribution, or
* online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
*
* There are special exceptions to the terms and conditions of the GPL as
* it is applied to this Source Code. View the full text of the exception
* in the file doc/FLOSS-exception.txt in this software distribution, or
* online at
* http://secondlifegrid.net/programs/open_source/licensing/flossexception
*
* By copying, modifying or distributing this software, you acknowledge
* that you have read and understood your obligations described above,
* and agree to abide by those obligations.
*
* ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
* WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
* COMPLETENESS OR PERFORMANCE.
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
#include "llviewerfoldertype.h"
#include "lldictionary.h"
#include "llmemory.h"
#include "llvisualparam.h"
static const std::string empty_string;
struct ViewerFolderEntry : public LLDictionaryEntry
{
// Constructor for non-ensembles
ViewerFolderEntry(const std::string &new_category_name, // default name when creating a new category of this type
const std::string &icon_name_open, // name of the folder icon
const std::string &icon_name_closed,
BOOL is_quiet, // folder doesn't need a UI update when changed
const std::string &dictionary_name = empty_string // no reverse lookup needed on non-ensembles, so in most cases just leave this blank
)
:
LLDictionaryEntry(dictionary_name),
mNewCategoryName(new_category_name),
mIconNameOpen(icon_name_open),
mIconNameClosed(icon_name_closed),
mIsQuiet(is_quiet)
{
mAllowedNames.clear();
}
// Constructor for ensembles
ViewerFolderEntry(const std::string &xui_name, // name of the xui menu item
const std::string &new_category_name, // default name when creating a new category of this type
const std::string &icon_name, // name of the folder icon
const std::string allowed_names // allowed item typenames for this folder type
)
:
LLDictionaryEntry(xui_name),
/* Just use default icons until we actually support ensembles
mIconNameOpen(icon_name),
mIconNameClosed(icon_name),
*/
mIconNameOpen("Inv_FolderOpen"), mIconNameClosed("Inv_FolderClosed"),
mNewCategoryName(new_category_name),
mIsQuiet(FALSE)
{
const std::string delims (",");
LLStringUtilBase<char>::getTokens(allowed_names, mAllowedNames, delims);
}
bool getIsAllowedName(const std::string &name) const
{
if (mAllowedNames.empty())
return false;
for (name_vec_t::const_iterator iter = mAllowedNames.begin();
iter != mAllowedNames.end();
iter++)
{
if (name == (*iter))
return true;
}
return false;
}
const std::string mIconNameOpen;
const std::string mIconNameClosed;
const std::string mNewCategoryName;
typedef std::vector<std::string> name_vec_t;
name_vec_t mAllowedNames;
BOOL mIsQuiet;
};
class LLViewerFolderDictionary : public LLSingleton<LLViewerFolderDictionary>,
public LLDictionary<LLFolderType::EType, ViewerFolderEntry>
{
public:
LLViewerFolderDictionary();
protected:
bool initEnsemblesFromFile(); // Reads in ensemble information from foldertypes.xml
};
LLViewerFolderDictionary::LLViewerFolderDictionary()
{
// NEW CATEGORY NAME FOLDER OPEN FOLDER CLOSED QUIET?
// |-------------------------|-----------------------|----------------------|-----------|
addEntry(LLFolderType::FT_TEXTURE, new ViewerFolderEntry("Textures", "Inv_SysOpen", "Inv_SysClosed", FALSE));
addEntry(LLFolderType::FT_SOUND, new ViewerFolderEntry("Sounds", "Inv_SysOpen", "Inv_SysClosed", FALSE));
addEntry(LLFolderType::FT_CALLINGCARD, new ViewerFolderEntry("Calling Cards", "Inv_SysOpen", "Inv_SysClosed", FALSE));
addEntry(LLFolderType::FT_LANDMARK, new ViewerFolderEntry("Landmarks", "Inv_SysOpen", "Inv_SysClosed", FALSE));
addEntry(LLFolderType::FT_CLOTHING, new ViewerFolderEntry("Clothing", "Inv_SysOpen", "Inv_SysClosed", FALSE));
addEntry(LLFolderType::FT_OBJECT, new ViewerFolderEntry("Objects", "Inv_SysOpen", "Inv_SysClosed", FALSE));
addEntry(LLFolderType::FT_NOTECARD, new ViewerFolderEntry("Notecards", "Inv_SysOpen", "Inv_SysClosed", FALSE));
addEntry(LLFolderType::FT_ROOT_INVENTORY, new ViewerFolderEntry("My Inventory", "Inv_SysOpen", "Inv_SysClosed", FALSE));
addEntry(LLFolderType::FT_LSL_TEXT, new ViewerFolderEntry("Scripts", "Inv_SysOpen", "Inv_SysClosed", FALSE));
addEntry(LLFolderType::FT_BODYPART, new ViewerFolderEntry("Body Parts", "Inv_SysOpen", "Inv_SysClosed", FALSE));
addEntry(LLFolderType::FT_TRASH, new ViewerFolderEntry("Trash", "Inv_TrashOpen", "Inv_TrashClosed", TRUE));
addEntry(LLFolderType::FT_SNAPSHOT_CATEGORY, new ViewerFolderEntry("Photo Album", "Inv_SysOpen", "Inv_SysClosed", FALSE));
addEntry(LLFolderType::FT_LOST_AND_FOUND, new ViewerFolderEntry("Lost And Found", "Inv_LostOpen", "Inv_LostClosed", TRUE));
addEntry(LLFolderType::FT_ANIMATION, new ViewerFolderEntry("Animations", "Inv_SysOpen", "Inv_SysClosed", FALSE));
addEntry(LLFolderType::FT_GESTURE, new ViewerFolderEntry("Gestures", "Inv_SysOpen", "Inv_SysClosed", FALSE));
addEntry(LLFolderType::FT_FAVORITE, new ViewerFolderEntry("Favorites", "Inv_SysOpen", "Inv_SysClosed", FALSE));
addEntry(LLFolderType::FT_CURRENT_OUTFIT, new ViewerFolderEntry("Current Outfit", "Inv_SysOpen", "Inv_SysClosed", TRUE));
addEntry(LLFolderType::FT_OUTFIT, new ViewerFolderEntry("New Outfit", "Inv_LookFolderOpen", "Inv_LookFolderClosed", TRUE));
addEntry(LLFolderType::FT_MY_OUTFITS, new ViewerFolderEntry("My Outfits", "Inv_SysOpen", "Inv_SysClosed", TRUE));
addEntry(LLFolderType::FT_INBOX, new ViewerFolderEntry("Inbox", "Inv_SysOpen", "Inv_SysClosed", FALSE));
addEntry(LLFolderType::FT_NONE, new ViewerFolderEntry("New Folder", "Inv_FolderOpen", "Inv_FolderClosed", FALSE, "default"));
#if SUPPORT_ENSEMBLES
initEnsemblesFromFile();
#else
for (U32 type = (U32)LLFolderType::FT_ENSEMBLE_START; type <= (U32)LLFolderType::FT_ENSEMBLE_END; ++type)
{
addEntry((LLFolderType::EType)type, new ViewerFolderEntry("New Folder", "Inv_FolderOpen", "Inv_FolderClosed", FALSE));
}
#endif
}
bool LLViewerFolderDictionary::initEnsemblesFromFile()
{
std::string xml_filename = gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS,"foldertypes.xml");
LLXmlTree folder_def;
if (!folder_def.parseFile(xml_filename))
{
llerrs << "Failed to parse folders file " << xml_filename << llendl;
return false;
}
LLXmlTreeNode* rootp = folder_def.getRoot();
for (LLXmlTreeNode* ensemble = rootp->getFirstChild();
ensemble;
ensemble = rootp->getNextChild())
{
if (!ensemble->hasName("ensemble"))
{
llwarns << "Invalid ensemble definition node " << ensemble->getName() << llendl;
continue;
}
S32 ensemble_type;
static LLStdStringHandle ensemble_num_string = LLXmlTree::addAttributeString("foldertype_num");
if (!ensemble->getFastAttributeS32(ensemble_num_string, ensemble_type))
{
llwarns << "No ensemble type defined" << llendl;
continue;
}
if (ensemble_type < S32(LLFolderType::FT_ENSEMBLE_START) || ensemble_type > S32(LLFolderType::FT_ENSEMBLE_END))
{
llwarns << "Exceeded maximum ensemble index" << LLFolderType::FT_ENSEMBLE_END << llendl;
break;
}
std::string xui_name;
static LLStdStringHandle xui_name_string = LLXmlTree::addAttributeString("xui_name");
if (!ensemble->getFastAttributeString(xui_name_string, xui_name))
{
llwarns << "No xui name defined" << llendl;
continue;
}
std::string icon_name;
static LLStdStringHandle icon_name_string = LLXmlTree::addAttributeString("icon_name");
if (!ensemble->getFastAttributeString(icon_name_string, icon_name))
{
llwarns << "No ensemble icon name defined" << llendl;
continue;
}
std::string allowed_names;
static LLStdStringHandle allowed_names_string = LLXmlTree::addAttributeString("allowed");
if (!ensemble->getFastAttributeString(allowed_names_string, allowed_names))
{
}
// Add the entry and increment the asset number.
const static std::string new_ensemble_name = "New Ensemble";
addEntry(LLFolderType::EType(ensemble_type), new ViewerFolderEntry(xui_name, new_ensemble_name, icon_name, allowed_names));
}
return true;
}
const std::string &LLViewerFolderType::lookupXUIName(LLFolderType::EType folder_type)
{
const ViewerFolderEntry *entry = LLViewerFolderDictionary::getInstance()->lookup(folder_type);
if (entry)
{
return entry->mName;
}
return badLookup();
}
LLFolderType::EType LLViewerFolderType::lookupTypeFromXUIName(const std::string &name)
{
return LLViewerFolderDictionary::getInstance()->lookup(name);
}
const std::string &LLViewerFolderType::lookupIconName(LLFolderType::EType folder_type, BOOL is_open)
{
const ViewerFolderEntry *entry = LLViewerFolderDictionary::getInstance()->lookup(folder_type);
if (entry)
{
if (is_open)
return entry->mIconNameOpen;
else
return entry->mIconNameClosed;
}
// Error condition. Return something so that we don't show a grey box in inventory view.
const ViewerFolderEntry *default_entry = LLViewerFolderDictionary::getInstance()->lookup(LLFolderType::FT_NONE);
if (default_entry)
{
return default_entry->mIconNameClosed;
}
// Should not get here unless there's something corrupted with the FT_NONE entry.
return badLookup();
}
BOOL LLViewerFolderType::lookupIsQuietType(LLFolderType::EType folder_type)
{
const ViewerFolderEntry *entry = LLViewerFolderDictionary::getInstance()->lookup(folder_type);
if (entry)
{
return entry->mIsQuiet;
}
return FALSE;
}
const std::string &LLViewerFolderType::lookupNewCategoryName(LLFolderType::EType folder_type)
{
const ViewerFolderEntry *entry = LLViewerFolderDictionary::getInstance()->lookup(folder_type);
if (entry)
{
return entry->mNewCategoryName;
}
return badLookup();
}
LLFolderType::EType LLViewerFolderType::lookupTypeFromNewCategoryName(const std::string& name)
{
for (LLViewerFolderDictionary::const_iterator iter = LLViewerFolderDictionary::getInstance()->begin();
iter != LLViewerFolderDictionary::getInstance()->end();
iter++)
{
const ViewerFolderEntry *entry = iter->second;
if (entry->mNewCategoryName == name)
{
return iter->first;
}
}
return FT_NONE;
}
U64 LLViewerFolderType::lookupValidFolderTypes(const std::string& item_name)
{
U64 matching_folders = 0;
for (LLViewerFolderDictionary::const_iterator iter = LLViewerFolderDictionary::getInstance()->begin();
iter != LLViewerFolderDictionary::getInstance()->end();
iter++)
{
const ViewerFolderEntry *entry = iter->second;
if (entry->getIsAllowedName(item_name))
{
matching_folders |= 1LL << iter->first;
}
}
return matching_folders;
}
<|endoftext|> |
<commit_before>#include "Game.hpp"
namespace swift
{
const std::string errorLog = "./data/log.txt";
const std::string defaultFontFile = "./data/fonts/DejaVuSansMono.ttf";
Game::Game()
: logger("Alpha", errorLog),
console(500, 200, defaultFont, "[swift2]:")
{
graphics = Quality::Medium;
smoothing = false;
verticalSync = true;
fullScreen = false;
resolution.x = 800;
resolution.y = 600;
running = false;
// engine integral settings
ticksPerSecond = 60;
defaultFont.loadFromFile(defaultFontFile);
}
Game::~Game()
{
if(currentState)
delete currentState;
}
// Do any pre-game data loading
// Such as setting up the scripting virtual machine
// and setting game quality settings.
// That's about it
void Game::Start(int c, char** args)
{
// c is the total arguments
// args is the arguments
// loads settings from the settings file
loadSettings("./data/settings/settings.ini");
handleLaunchOps(c, args);
// Window set up.
if(fullScreen)
window.create(sf::VideoMode(resolution.x, resolution.y, 32), "Swift Engine", sf::Style::Fullscreen, contextSettings);
else
window.create(sf::VideoMode(resolution.x, resolution.y, 32), "Swift Engine", sf::Style::Titlebar | sf::Style::Close, contextSettings);
//window.setIcon(SwiftEngineIcon.width, SwiftEngineIcon.height, SwiftEngineIcon.pixel_data);
window.setVerticalSyncEnabled(verticalSync);
window.setKeyRepeatEnabled(false);
assets.setSmooth(smoothing);
assets.loadResourceFolder("./data/fonts");
assets.loadResourceFolder("./data/textures");
assets.loadResourceFolder("./data/music");
assets.loadResourceFolder("./data/scripts");
assets.loadResourceFolder("./data/skeletons");
assets.loadResourceFolder("./data/sounds");
mods.loadMods("./data/mods");
for(auto &m : mods.getMods())
{
assets.loadMod(m.second.mod);
}
// add some default keybindings
keyboard.newBinding("toggleTerminal", sf::Keyboard::BackSlash, [&]()
{
console.activate(!console.isActivated());
});
keyboard.newBinding("exit", sf::Keyboard::Escape, [&]()
{
running = false;
});
// add some console commands
console.addCommand("hello", [](ArgVec args)
{
return "Hello to you too!";
});
console.addCommand("exit", [&](ArgVec args)
{
running = false;
return "Exiting";
});
running = true;
// fps display
if(debug)
{
FPS.setFont(defaultFont);
FPS.setScale(0.7, 0.7);
FPS.setString("00");
FPS.setPosition(window.getSize().x - (FPS.getGlobalBounds().width + 2), 0);
}
// setup Script static variables
Script::setWindow(window);
Script::setAssetManager(assets);
Script::setClock(GameTime);
// state setup
currentState = new MainMenu(window, assets);
currentState->setup();
}
void Game::GameLoop()
{
const sf::Time dt = sf::seconds(1 / ticksPerSecond);
sf::Time currentTime = GameTime.getElapsedTime();
sf::Time lag = sf::seconds(0);
while(running)
{
sf::Time newTime = GameTime.getElapsedTime();
sf::Time frameTime = newTime - currentTime;
if(frameTime > sf::seconds(0.25))
frameTime = sf::seconds(0.25);
currentTime = newTime;
lag += frameTime;
while(lag >= dt)
{
Update(dt);
lag -= dt;
}
Draw(lag.asSeconds() / dt.asSeconds());
}
}
void Game::Update(sf::Time dt)
{
sf::Event event;
while(window.pollEvent(event))
{
keyboard(event);
mouse(event);
// avoid having the console type the key that toggles it
if(event.type == sf::Event::TextEntered && event.text.unicode != '\\')
console.update(event);
if(event.type == sf::Event::Closed)
running = false;
currentState->handleEvent(event);
}
if(debug)
FPS.setString(std::to_string(1 / dt.asSeconds()).substr(0, 2));
currentState->update(dt);
manageStates();
}
void Game::manageStates()
{
if(currentState->switchFrom())
{
State::Type nextState = currentState->finish();
delete currentState;
currentState = nullptr;
switch(nextState)
{
case State::Type::MainMenu:
currentState = new MainMenu(window, assets);
currentState->setup();
break;
case State::Type::Play:
currentState = new Play(window, assets);
currentState->setup();
break;
case State::Type::Exit:
running = false;
break;
}
}
}
void Game::Draw(float e)
{
if(running)
{
/* clear display */
window.clear(sf::Color::White);
/* state drawing */
currentState->draw(e);
/* other drawing */
window.draw(console);
if(debug)
window.draw(FPS);
/* display drawing */
window.display();
}
}
// Finish cleaning up memory, close cleanly, etc
void Game::Finish()
{
window.close();
}
void Game::handleLaunchOps(int c, char** args)
{
// launch options
editor = false;
debug = false;
fullScreen = false;
// loop through options
int arg = 1; // we skip arg 0 because arg 0 is the executable
while(arg < c)
{
if(args[arg] == std::string("editor"))
{
editor = true;
}
else if(args[arg] == std::string("debug"))
{
debug = true;
}
else if(args[arg] == std::string("fullscreen"))
{
fullScreen = true;
}
else if(args[arg] == std::string("res"))
{
resolution.x = std::stoi(args[arg + 1]);
resolution.y = std::stoi(args[arg + 1]);
arg += 2;
}
else if(args[arg] == std::string("videoModes"))
{
logger << Logger::LogType::INFO << "Supported Fullscreen Video Modes:";
std::vector<sf::VideoMode> modes = sf::VideoMode::getFullscreenModes();
for(std::size_t i = 0; i < modes.size(); ++i)
{
sf::VideoMode mode = modes[i];
logger << Logger::LogType::INFO
<< "Mode #" + std::to_string(i) + ": " + std::to_string(mode.width) + "x" + std::to_string(mode.height)
+ " - " + std::to_string(mode.bitsPerPixel) + " bpp";
// ex: "Mode #0: 1920x1080 - 32 bbp"
}
}
else
{
logger << "\nUnknown launch option: " + std::string(args[arg]) + '\n';
}
arg++;
}
}
void Game::loadSettings(const std::string& file)
{
// settings file settings
if(!settings.loadFile(file))
logger << Logger::LogType::WARNING << "Could not open settings file, default settings will be used\n";
settings.get("quality", graphics);
settings.get("fullScreen", fullScreen);
settings.get("vertSync", verticalSync);
settings.get("res.x", resolution.x);
settings.get("res.y", resolution.y);
settings.get("sound", soundLevel);
settings.get("music", musicLevel);
}
}
<commit_msg>Removed some more out of date code.<commit_after>#include "Game.hpp"
namespace swift
{
const std::string errorLog = "./data/log.txt";
Game::Game()
: logger("Alpha", errorLog),
console(500, 200, defaultFont, "[swift2]:")
{
graphics = Quality::Medium;
smoothing = false;
verticalSync = true;
fullScreen = false;
resolution.x = 800;
resolution.y = 600;
running = false;
// engine integral settings
ticksPerSecond = 60;
}
Game::~Game()
{
if(currentState)
delete currentState;
}
// Do any pre-game data loading
// Such as setting up the scripting virtual machine
// and setting game quality settings.
// That's about it
void Game::Start(int c, char** args)
{
// c is the total arguments
// args is the arguments
// loads settings from the settings file
loadSettings("./data/settings/settings.ini");
handleLaunchOps(c, args);
// Window set up.
if(fullScreen)
window.create(sf::VideoMode(resolution.x, resolution.y, 32), "Swift Engine", sf::Style::Fullscreen, contextSettings);
else
window.create(sf::VideoMode(resolution.x, resolution.y, 32), "Swift Engine", sf::Style::Titlebar | sf::Style::Close, contextSettings);
//window.setIcon(SwiftEngineIcon.width, SwiftEngineIcon.height, SwiftEngineIcon.pixel_data);
window.setVerticalSyncEnabled(verticalSync);
window.setKeyRepeatEnabled(false);
assets.setSmooth(smoothing);
assets.loadResourceFolder("./data/fonts");
assets.loadResourceFolder("./data/textures");
assets.loadResourceFolder("./data/music");
assets.loadResourceFolder("./data/scripts");
assets.loadResourceFolder("./data/skeletons");
assets.loadResourceFolder("./data/sounds");
mods.loadMods("./data/mods");
for(auto &m : mods.getMods())
{
assets.loadMod(m.second.mod);
}
// add some default keybindings
keyboard.newBinding("toggleTerminal", sf::Keyboard::BackSlash, [&]()
{
console.activate(!console.isActivated());
});
keyboard.newBinding("exit", sf::Keyboard::Escape, [&]()
{
running = false;
});
// add some console commands
console.addCommand("hello", [](ArgVec args)
{
return "Hello to you too!";
});
console.addCommand("exit", [&](ArgVec args)
{
running = false;
return "Exiting";
});
running = true;
// fps display
if(debug)
{
FPS.setFont(defaultFont);
FPS.setScale(0.7, 0.7);
FPS.setString("00");
FPS.setPosition(window.getSize().x - (FPS.getGlobalBounds().width + 2), 0);
}
// setup Script static variables
Script::setWindow(window);
Script::setAssetManager(assets);
Script::setClock(GameTime);
// state setup
currentState = new MainMenu(window, assets);
currentState->setup();
}
void Game::GameLoop()
{
const sf::Time dt = sf::seconds(1 / ticksPerSecond);
sf::Time currentTime = GameTime.getElapsedTime();
sf::Time lag = sf::seconds(0);
while(running)
{
sf::Time newTime = GameTime.getElapsedTime();
sf::Time frameTime = newTime - currentTime;
if(frameTime > sf::seconds(0.25))
frameTime = sf::seconds(0.25);
currentTime = newTime;
lag += frameTime;
while(lag >= dt)
{
Update(dt);
lag -= dt;
}
Draw(lag.asSeconds() / dt.asSeconds());
}
}
void Game::Update(sf::Time dt)
{
sf::Event event;
while(window.pollEvent(event))
{
keyboard(event);
mouse(event);
// avoid having the console type the key that toggles it
if(event.type == sf::Event::TextEntered && event.text.unicode != '\\')
console.update(event);
if(event.type == sf::Event::Closed)
running = false;
currentState->handleEvent(event);
}
if(debug)
FPS.setString(std::to_string(1 / dt.asSeconds()).substr(0, 2));
currentState->update(dt);
manageStates();
}
void Game::manageStates()
{
if(currentState->switchFrom())
{
State::Type nextState = currentState->finish();
delete currentState;
currentState = nullptr;
switch(nextState)
{
case State::Type::MainMenu:
currentState = new MainMenu(window, assets);
currentState->setup();
break;
case State::Type::Play:
currentState = new Play(window, assets);
currentState->setup();
break;
case State::Type::Exit:
running = false;
break;
}
}
}
void Game::Draw(float e)
{
if(running)
{
/* clear display */
window.clear(sf::Color::White);
/* state drawing */
currentState->draw(e);
/* other drawing */
window.draw(console);
if(debug)
window.draw(FPS);
/* display drawing */
window.display();
}
}
// Finish cleaning up memory, close cleanly, etc
void Game::Finish()
{
window.close();
}
void Game::handleLaunchOps(int c, char** args)
{
// launch options
editor = false;
debug = false;
fullScreen = false;
// loop through options
int arg = 1; // we skip arg 0 because arg 0 is the executable
while(arg < c)
{
if(args[arg] == std::string("editor"))
{
editor = true;
}
else if(args[arg] == std::string("debug"))
{
debug = true;
}
else if(args[arg] == std::string("fullscreen"))
{
fullScreen = true;
}
else if(args[arg] == std::string("res"))
{
resolution.x = std::stoi(args[arg + 1]);
resolution.y = std::stoi(args[arg + 1]);
arg += 2;
}
else if(args[arg] == std::string("videoModes"))
{
logger << Logger::LogType::INFO << "Supported Fullscreen Video Modes:";
std::vector<sf::VideoMode> modes = sf::VideoMode::getFullscreenModes();
for(std::size_t i = 0; i < modes.size(); ++i)
{
sf::VideoMode mode = modes[i];
logger << Logger::LogType::INFO
<< "Mode #" + std::to_string(i) + ": " + std::to_string(mode.width) + "x" + std::to_string(mode.height)
+ " - " + std::to_string(mode.bitsPerPixel) + " bpp";
// ex: "Mode #0: 1920x1080 - 32 bbp"
}
}
else
{
logger << "\nUnknown launch option: " + std::string(args[arg]) + '\n';
}
arg++;
}
}
void Game::loadSettings(const std::string& file)
{
// settings file settings
if(!settings.loadFile(file))
logger << Logger::LogType::WARNING << "Could not open settings file, default settings will be used\n";
settings.get("quality", graphics);
settings.get("fullScreen", fullScreen);
settings.get("vertSync", verticalSync);
settings.get("res.x", resolution.x);
settings.get("res.y", resolution.y);
settings.get("sound", soundLevel);
settings.get("music", musicLevel);
}
}
<|endoftext|> |
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief 設定ファイル入力 @n
@author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include <boost/format.hpp>
#include "utils/string_utils.hpp"
#include "utils/text_edit.hpp"
namespace utils {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief Def input クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
struct def_in {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief レジスター定義
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
private:
enum class analize_type {
none,
error,
first,
base_in,
base_main,
};
bool verbose_;
utils::text_edit te_;
analize_type analize_type_ = analize_type::none;
std::string last_error_;
std::string make_error_(uint32_t pos, const std::string& line) {
auto ret = (boost::format("(%u)%s") % pos % line).str();
return ret;
}
void analize_base_(const std::string& line, const utils::strings& ss) {
if(ss.empty()) return;
std::cout << ss[0] << std::endl;
}
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
@param[in] verbose 詳細時「true」
*/
//-----------------------------------------------------------------//
def_in(bool verbose = false) : verbose_(verbose) { }
//-----------------------------------------------------------------//
/*!
@brief 設定書式をロード
@param[in] file ファイル名
@return 成功なら「true」
*/
//-----------------------------------------------------------------//
bool load(const std::string& file)
{
auto ret = te_.load(file);
if(ret && verbose_) {
std::cout << "Input: '" << file << "'" << std::endl;
std::cout << "lines: " << te_.get_lines() << std::endl;
}
return ret;
}
//-----------------------------------------------------------------//
/*!
@brief 解析
@return 成功なら「true」
*/
//-----------------------------------------------------------------//
bool analize()
{
last_error_.clear();
analize_type_ = analize_type::first;
te_.loop([this](uint32_t pos, const std::string& line) {
if(!line.empty() && line[0] == '#') return;
if(analize_type_ == analize_type::none |
analize_type_ == analize_type::error) return;
auto ss = utils::split_text(line, " \t", "\"'");
if(ss.empty()) return;
switch(analize_type_) {
case analize_type::first:
if(ss[0] == "base") {
analize_type_ = analize_type::base_in;
} else {
last_error_ = make_error_(pos, line);
last_error_ += (boost::format(", error: '%s'") % ss[0]).str();
if(verbose_) {
std::cerr << last_error_ << std::endl;
}
analize_type_ = analize_type::error;
}
break;
case analize_type::base_in:
if(ss[0] == "{") analize_type_ = analize_type::base_main;
break;
case analize_type::base_main:
if(ss[0] == "}") analize_type_ = analize_type::first;
else {
analize_base_(line, ss);
}
break;
default:
break;
}
} );
return analize_type_ != analize_type::error;
}
//-----------------------------------------------------------------//
/*!
@brief 解析エラーを取得
@return 解析エラー文字列
*/
//-----------------------------------------------------------------//
std::string get_last_error() const { return last_error_; }
};
}
<commit_msg>update analize in file<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief 設定ファイル入力 @n
@author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include <boost/format.hpp>
#include "utils/string_utils.hpp"
#include "utils/text_edit.hpp"
namespace utils {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief Def input クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
struct def_in {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief レジスター定義
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
private:
enum class analize_type {
none,
error,
first,
base_in,
base_main,
};
bool verbose_;
std::string last_error_;
utils::text_edit te_;
analize_type analize_type_ = analize_type::none;
std::string class_;
utils::strings body_;
std::string make_error_(uint32_t pos, const std::string& line) {
auto ret = (boost::format("(%u)%s") % pos % line).str();
return ret;
}
void analize_base_(const std::string& line, const utils::strings& ss) {
if(ss.empty()) return;
std::cout << ss[0] << std::endl;
}
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
@param[in] verbose 詳細時「true」
*/
//-----------------------------------------------------------------//
def_in(bool verbose = false) : verbose_(verbose) { }
//-----------------------------------------------------------------//
/*!
@brief 設定書式をロード
@param[in] file ファイル名
@return 成功なら「true」
*/
//-----------------------------------------------------------------//
bool load(const std::string& file)
{
auto ret = te_.load(file);
if(ret && verbose_) {
std::cout << "Input: '" << file << "'" << std::endl;
std::cout << "lines: " << te_.get_lines() << std::endl;
}
return ret;
}
//-----------------------------------------------------------------//
/*!
@brief 解析
@return 成功なら「true」
*/
//-----------------------------------------------------------------//
bool analize()
{
last_error_.clear();
class_.clear();
body_.clear();
analize_type_ = analize_type::first;
te_.loop([this](uint32_t pos, const std::string& line) {
if(line.empty()) return;
if(line[0] == '#') return;
if(analize_type_ == analize_type::none |
analize_type_ == analize_type::error) return;
auto ss = utils::split_text(line, " \t", "\"'");
if(ss.empty()) return;
} );
return analize_type_ != analize_type::error;
}
#if 0
switch(analize_type_) {
case analize_type::first:
if(ss[0] == "base") {
analize_type_ = analize_type::base_in;
} else {
last_error_ = make_error_(pos, line);
last_error_ += (boost::format(", error: '%s'") % ss[0]).str();
if(verbose_) {
std::cerr << last_error_ << std::endl;
}
analize_type_ = analize_type::error;
}
break;
case analize_type::base_in:
if(ss[0] == "{") analize_type_ = analize_type::base_main;
break;
case analize_type::base_main:
if(ss[0] == "}") analize_type_ = analize_type::first;
else {
analize_base_(line, ss);
}
break;
default:
break;
}
#endif
//-----------------------------------------------------------------//
/*!
@brief 解析エラーを取得
@return 解析エラー文字列
*/
//-----------------------------------------------------------------//
std::string get_last_error() const { return last_error_; }
};
}
<|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright (c) 2012-2015 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file lis3mdl.cpp
*
* Driver for the LIS3MDL magnetometer connected via I2C or SPI.
*
* Based on the hmc5883 driver.
*/
#include <px4_platform_common/time.h>
#include "lis3mdl.h"
LIS3MDL::LIS3MDL(device::Device *interface, enum Rotation rotation, I2CSPIBusOption bus_option, int bus) :
I2CSPIDriver(MODULE_NAME, px4::device_bus_to_wq(interface->get_device_id()), bus_option, bus),
_px4_mag(interface->get_device_id(), interface->external() ? ORB_PRIO_VERY_HIGH : ORB_PRIO_DEFAULT, rotation),
_interface(interface),
_comms_errors(perf_alloc(PC_COUNT, MODULE_NAME": comms_errors")),
_conf_errors(perf_alloc(PC_COUNT, MODULE_NAME": conf_errors")),
_range_errors(perf_alloc(PC_COUNT, MODULE_NAME": range_errors")),
_sample_perf(perf_alloc(PC_ELAPSED, MODULE_NAME": read")),
_continuous_mode_set(false),
_mode(CONTINUOUS),
_measure_interval(0),
_range_ga(4.0f),
_check_state_cnt(0),
_cntl_reg1(
CNTL_REG1_DEFAULT), // 1 11 111 0 0 | temp-en, ultra high performance (XY), fast_odr disabled, self test disabled
_cntl_reg2(CNTL_REG2_DEFAULT), // 4 gauss FS range, reboot settings default
_cntl_reg3(CNTL_REG3_DEFAULT), // operating mode CONTINUOUS!
_cntl_reg4(CNTL_REG4_DEFAULT), // Z-axis ultra high performance mode
_cntl_reg5(CNTL_REG5_DEFAULT), // fast read disabled, continious update disabled (block data update)
_range_bits(0),
_temperature_counter(0),
_temperature_error_count(0)
{
_px4_mag.set_external(_interface->external());
}
LIS3MDL::~LIS3MDL()
{
// free perf counters
perf_free(_sample_perf);
perf_free(_comms_errors);
perf_free(_range_errors);
perf_free(_conf_errors);
}
int LIS3MDL::collect()
{
struct {
uint8_t x[2];
uint8_t y[2];
uint8_t z[2];
} lis_report{};
struct {
int16_t x;
int16_t y;
int16_t z;
int16_t t;
} report{};
uint8_t buf_rx[2] {};
_px4_mag.set_error_count(perf_event_count(_comms_errors));
perf_begin(_sample_perf);
const hrt_abstime timestamp_sample = hrt_absolute_time();
_interface->read(ADDR_OUT_X_L, (uint8_t *)&lis_report, sizeof(lis_report));
/**
* Silicon Bug: the X axis will be read instead of the temperature registers if you do a sequential read through XYZ.
* The temperature registers must be addressed directly.
*/
int ret = _interface->read(ADDR_OUT_T_L, (uint8_t *)&buf_rx, sizeof(buf_rx));
if (ret != OK) {
perf_end(_sample_perf);
perf_count(_comms_errors);
PX4_WARN("Register read error.");
return ret;
}
perf_end(_sample_perf);
report.x = (int16_t)((lis_report.x[1] << 8) | lis_report.x[0]);
report.y = (int16_t)((lis_report.y[1] << 8) | lis_report.y[0]);
report.z = (int16_t)((lis_report.z[1] << 8) | lis_report.z[0]);
report.t = (int16_t)((buf_rx[1] << 8) | buf_rx[0]);
float temperature = 25.0f + (report.t / 8.0f);
_px4_mag.set_temperature(temperature);
_px4_mag.update(timestamp_sample, report.x, report.y, report.z);
return PX4_OK;
}
void LIS3MDL::RunImpl()
{
/* _measure_interval == 0 is used as _task_should_exit */
if (_measure_interval == 0) {
return;
}
/* Collect last measurement at the start of every cycle */
if (collect() != OK) {
PX4_DEBUG("collection error");
/* restart the measurement state machine */
start();
return;
}
if (measure() != OK) {
PX4_DEBUG("measure error");
}
if (_measure_interval > 0) {
/* schedule a fresh cycle call when the measurement is done */
ScheduleDelayed(LIS3MDL_CONVERSION_INTERVAL);
}
}
int LIS3MDL::init()
{
/* reset the device configuration */
reset();
_measure_interval = LIS3MDL_CONVERSION_INTERVAL;
start();
return PX4_OK;
}
int LIS3MDL::measure()
{
int ret = 0;
/* Send the command to begin a measurement. */
if ((_mode == CONTINUOUS) && !_continuous_mode_set) {
ret = write_reg(ADDR_CTRL_REG3, MODE_REG_CONTINOUS_MODE);
_continuous_mode_set = true;
} else if (_mode == SINGLE) {
ret = write_reg(ADDR_CTRL_REG3, MODE_REG_SINGLE_MODE);
_continuous_mode_set = false;
}
if (ret != OK) {
perf_count(_comms_errors);
}
return ret;
}
void LIS3MDL::print_status()
{
I2CSPIDriverBase::print_status();
perf_print_counter(_sample_perf);
perf_print_counter(_comms_errors);
PX4_INFO("poll interval: %u", _measure_interval);
_px4_mag.print_status();
}
int LIS3MDL::reset()
{
int ret = set_default_register_values();
if (ret != OK) {
return PX4_ERROR;
}
ret = set_range(_range_ga);
if (ret != OK) {
return PX4_ERROR;
}
return PX4_OK;
}
int
LIS3MDL::set_default_register_values()
{
write_reg(ADDR_CTRL_REG1, CNTL_REG1_DEFAULT);
write_reg(ADDR_CTRL_REG2, CNTL_REG2_DEFAULT);
write_reg(ADDR_CTRL_REG3, CNTL_REG3_DEFAULT);
write_reg(ADDR_CTRL_REG4, CNTL_REG4_DEFAULT);
write_reg(ADDR_CTRL_REG5, CNTL_REG5_DEFAULT);
return PX4_OK;
}
int LIS3MDL::set_range(unsigned range)
{
if (range <= 4) {
_range_bits = 0x00;
_px4_mag.set_scale(1.0f / 6842.0f);
_range_ga = 4.0f;
} else if (range <= 8) {
_range_bits = 0x01;
_px4_mag.set_scale(1.0f / 3421.0f);
_range_ga = 8.0f;
} else if (range <= 12) {
_range_bits = 0x02;
_px4_mag.set_scale(1.0f / 2281.0f);
_range_ga = 12.0f;
} else {
_range_bits = 0x03;
_px4_mag.set_scale(1.0f / 1711.0f);
_range_ga = 16.0f;
}
/*
* Send the command to set the range
*/
int ret = write_reg(ADDR_CTRL_REG2, (_range_bits << 5));
if (ret != OK) {
perf_count(_comms_errors);
}
uint8_t range_bits_in = 0;
ret = read_reg(ADDR_CTRL_REG2, range_bits_in);
if (ret != OK) {
perf_count(_comms_errors);
}
if (range_bits_in == (_range_bits << 5)) {
return PX4_OK;
} else {
return PX4_ERROR;
}
}
void LIS3MDL::start()
{
set_default_register_values();
/* schedule a cycle to start things */
ScheduleNow();
}
int LIS3MDL::read_reg(uint8_t reg, uint8_t &val)
{
uint8_t buf = val;
int ret = _interface->read(reg, &buf, 1);
val = buf;
return ret;
}
int LIS3MDL::write_reg(uint8_t reg, uint8_t val)
{
uint8_t buf = val;
return _interface->write(reg, &buf, 1);
}
<commit_msg>lis3mdl: cleanup device interface on destruction<commit_after>/****************************************************************************
*
* Copyright (c) 2012-2015 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file lis3mdl.cpp
*
* Driver for the LIS3MDL magnetometer connected via I2C or SPI.
*
* Based on the hmc5883 driver.
*/
#include <px4_platform_common/time.h>
#include "lis3mdl.h"
LIS3MDL::LIS3MDL(device::Device *interface, enum Rotation rotation, I2CSPIBusOption bus_option, int bus) :
I2CSPIDriver(MODULE_NAME, px4::device_bus_to_wq(interface->get_device_id()), bus_option, bus),
_px4_mag(interface->get_device_id(), interface->external() ? ORB_PRIO_VERY_HIGH : ORB_PRIO_DEFAULT, rotation),
_interface(interface),
_comms_errors(perf_alloc(PC_COUNT, MODULE_NAME": comms_errors")),
_conf_errors(perf_alloc(PC_COUNT, MODULE_NAME": conf_errors")),
_range_errors(perf_alloc(PC_COUNT, MODULE_NAME": range_errors")),
_sample_perf(perf_alloc(PC_ELAPSED, MODULE_NAME": read")),
_continuous_mode_set(false),
_mode(CONTINUOUS),
_measure_interval(0),
_range_ga(4.0f),
_check_state_cnt(0),
_cntl_reg1(
CNTL_REG1_DEFAULT), // 1 11 111 0 0 | temp-en, ultra high performance (XY), fast_odr disabled, self test disabled
_cntl_reg2(CNTL_REG2_DEFAULT), // 4 gauss FS range, reboot settings default
_cntl_reg3(CNTL_REG3_DEFAULT), // operating mode CONTINUOUS!
_cntl_reg4(CNTL_REG4_DEFAULT), // Z-axis ultra high performance mode
_cntl_reg5(CNTL_REG5_DEFAULT), // fast read disabled, continious update disabled (block data update)
_range_bits(0),
_temperature_counter(0),
_temperature_error_count(0)
{
_px4_mag.set_external(_interface->external());
}
LIS3MDL::~LIS3MDL()
{
// free perf counters
perf_free(_sample_perf);
perf_free(_comms_errors);
perf_free(_range_errors);
perf_free(_conf_errors);
delete _interface;
}
int LIS3MDL::collect()
{
struct {
uint8_t x[2];
uint8_t y[2];
uint8_t z[2];
} lis_report{};
struct {
int16_t x;
int16_t y;
int16_t z;
int16_t t;
} report{};
uint8_t buf_rx[2] {};
_px4_mag.set_error_count(perf_event_count(_comms_errors));
perf_begin(_sample_perf);
const hrt_abstime timestamp_sample = hrt_absolute_time();
_interface->read(ADDR_OUT_X_L, (uint8_t *)&lis_report, sizeof(lis_report));
/**
* Silicon Bug: the X axis will be read instead of the temperature registers if you do a sequential read through XYZ.
* The temperature registers must be addressed directly.
*/
int ret = _interface->read(ADDR_OUT_T_L, (uint8_t *)&buf_rx, sizeof(buf_rx));
if (ret != OK) {
perf_end(_sample_perf);
perf_count(_comms_errors);
PX4_WARN("Register read error.");
return ret;
}
perf_end(_sample_perf);
report.x = (int16_t)((lis_report.x[1] << 8) | lis_report.x[0]);
report.y = (int16_t)((lis_report.y[1] << 8) | lis_report.y[0]);
report.z = (int16_t)((lis_report.z[1] << 8) | lis_report.z[0]);
report.t = (int16_t)((buf_rx[1] << 8) | buf_rx[0]);
float temperature = 25.0f + (report.t / 8.0f);
_px4_mag.set_temperature(temperature);
_px4_mag.update(timestamp_sample, report.x, report.y, report.z);
return PX4_OK;
}
void LIS3MDL::RunImpl()
{
/* _measure_interval == 0 is used as _task_should_exit */
if (_measure_interval == 0) {
return;
}
/* Collect last measurement at the start of every cycle */
if (collect() != OK) {
PX4_DEBUG("collection error");
/* restart the measurement state machine */
start();
return;
}
if (measure() != OK) {
PX4_DEBUG("measure error");
}
if (_measure_interval > 0) {
/* schedule a fresh cycle call when the measurement is done */
ScheduleDelayed(LIS3MDL_CONVERSION_INTERVAL);
}
}
int LIS3MDL::init()
{
/* reset the device configuration */
reset();
_measure_interval = LIS3MDL_CONVERSION_INTERVAL;
start();
return PX4_OK;
}
int LIS3MDL::measure()
{
int ret = 0;
/* Send the command to begin a measurement. */
if ((_mode == CONTINUOUS) && !_continuous_mode_set) {
ret = write_reg(ADDR_CTRL_REG3, MODE_REG_CONTINOUS_MODE);
_continuous_mode_set = true;
} else if (_mode == SINGLE) {
ret = write_reg(ADDR_CTRL_REG3, MODE_REG_SINGLE_MODE);
_continuous_mode_set = false;
}
if (ret != OK) {
perf_count(_comms_errors);
}
return ret;
}
void LIS3MDL::print_status()
{
I2CSPIDriverBase::print_status();
perf_print_counter(_sample_perf);
perf_print_counter(_comms_errors);
PX4_INFO("poll interval: %u", _measure_interval);
_px4_mag.print_status();
}
int LIS3MDL::reset()
{
int ret = set_default_register_values();
if (ret != OK) {
return PX4_ERROR;
}
ret = set_range(_range_ga);
if (ret != OK) {
return PX4_ERROR;
}
return PX4_OK;
}
int
LIS3MDL::set_default_register_values()
{
write_reg(ADDR_CTRL_REG1, CNTL_REG1_DEFAULT);
write_reg(ADDR_CTRL_REG2, CNTL_REG2_DEFAULT);
write_reg(ADDR_CTRL_REG3, CNTL_REG3_DEFAULT);
write_reg(ADDR_CTRL_REG4, CNTL_REG4_DEFAULT);
write_reg(ADDR_CTRL_REG5, CNTL_REG5_DEFAULT);
return PX4_OK;
}
int LIS3MDL::set_range(unsigned range)
{
if (range <= 4) {
_range_bits = 0x00;
_px4_mag.set_scale(1.0f / 6842.0f);
_range_ga = 4.0f;
} else if (range <= 8) {
_range_bits = 0x01;
_px4_mag.set_scale(1.0f / 3421.0f);
_range_ga = 8.0f;
} else if (range <= 12) {
_range_bits = 0x02;
_px4_mag.set_scale(1.0f / 2281.0f);
_range_ga = 12.0f;
} else {
_range_bits = 0x03;
_px4_mag.set_scale(1.0f / 1711.0f);
_range_ga = 16.0f;
}
/*
* Send the command to set the range
*/
int ret = write_reg(ADDR_CTRL_REG2, (_range_bits << 5));
if (ret != OK) {
perf_count(_comms_errors);
}
uint8_t range_bits_in = 0;
ret = read_reg(ADDR_CTRL_REG2, range_bits_in);
if (ret != OK) {
perf_count(_comms_errors);
}
if (range_bits_in == (_range_bits << 5)) {
return PX4_OK;
} else {
return PX4_ERROR;
}
}
void LIS3MDL::start()
{
set_default_register_values();
/* schedule a cycle to start things */
ScheduleNow();
}
int LIS3MDL::read_reg(uint8_t reg, uint8_t &val)
{
uint8_t buf = val;
int ret = _interface->read(reg, &buf, 1);
val = buf;
return ret;
}
int LIS3MDL::write_reg(uint8_t reg, uint8_t val)
{
uint8_t buf = val;
return _interface->write(reg, &buf, 1);
}
<|endoftext|> |
<commit_before>#include "ObjParser.hpp"
#include "Shaders.hpp"
#include "Viewer.hpp"
#include <GL/freeglut.h>
#include <iostream>
#include <string>
int main(int argc, char** argv) {
if (argc == 1) {
std::cout << "Usage: obj-viewer FILE" << std::endl;
return -1;
}
std::string file = std::string(argv[1]);
ObjParser parser(file);
Viewer viewer("Model Viewer", 1024, 768);
ModelPtr model = parser.parseObj();
viewer.setModel(model);
viewer.initGlut(argc, argv);
viewer.initGl();
std::string prefix = std::string(INSTALL_PREFIX) + "/share/obj-viewer/shaders";
std::string vsFile = prefix + "/lambertian.vs";
std::string fsFile = prefix + "/lambertian.fs";
ShadersPtr shaders = ShadersPtr(new Shaders(vsFile, fsFile));
shaders->setSamplerName("texMap");
model->loadTextures();
model->compileLists();
model->setShaders(shaders);
Viewer::setInstance(&viewer);
viewer.start();
return 0;
}
<commit_msg>More tweaks.<commit_after>#include "ObjParser.hpp"
#include "Shaders.hpp"
#include "Viewer.hpp"
#include <GL/freeglut.h>
#include <iostream>
#include <string>
int main(int argc, char** argv) {
if (argc == 1) {
std::cout << "Usage: obj-viewer FILE" << std::endl;
return -1;
}
std::string file = std::string(argv[1]);
ObjParser parser(file);
Viewer viewer("Model Viewer", 1024, 768);
ModelPtr model = parser.parseObj();
viewer.setModel(model);
viewer.initGlut(argc, argv);
viewer.initGl();
std::string prefix = std::string(INSTALL_PREFIX) + "/share/obj-viewer/shaders";
std::string vsFile = prefix + "/lambertian.vs";
std::string fsFile = prefix + "/lambertian.fs";
ShadersPtr shaders(new Shaders(vsFile, fsFile));
shaders->setSamplerName("texMap");
model->loadTextures();
model->compileLists();
model->setShaders(shaders);
Viewer::setInstance(&viewer);
viewer.start();
return 0;
}
<|endoftext|> |
<commit_before>#ifdef _MSC_VER
#pragma comment(linker, "/SUBSYSTEM:windows /ENTRY:mainCRTStartup")
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "v8_base.lib")
#pragma comment(lib, "v8_snapshot.lib")
#pragma comment(lib, "v8_nosnapshot.lib")
#pragma comment(lib, "winmm.lib")
#pragma comment(lib, "Qt5Cored.lib")
#pragma comment(lib, "Qt5Guid.lib")
#pragma comment(lib, "Qt5Widgetsd.lib")
#endif
#include "JSE.h"
#include "JSEApplication.h"
#include "JSEV8.h"
using namespace JSE;
int main(int argc, char *argv[])
{
JSEApplication app(argc, argv);
JSEV8 v8app(app);
QObject::connect(&app, SIGNAL(start()), &v8app, SLOT(start()));
return app.exec();
}<commit_msg>(Windows only) Test static linkage<commit_after>#ifdef _MSC_VER
#pragma comment(linker, "/SUBSYSTEM:windows /ENTRY:mainCRTStartup")
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "winmm.lib")
#pragma comment(lib, "Opengl32.lib")
#pragma comment(lib, "Imm32.lib")
#pragma comment(lib, "D3d9.lib")
#pragma comment(lib, "dxguid.lib")
#include <d3d9.h>
#include <QtCore/qplugin.h>
Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin)
#ifdef _DEBUG
#pragma comment(lib, "Qt5Cored.lib")
#pragma comment(lib, "Qt5Guid.lib")
#pragma comment(lib, "Qt5Widgetsd.lib")
#pragma comment(lib, "v8_based.lib")
#pragma comment(lib, "v8_snapshotd.lib")
#pragma comment(lib, "v8_nosnapshotd.lib")
#pragma comment(lib, "libEGLd.lib")
#pragma comment(lib, "libGLESv2d.lib")
#pragma comment(lib, "preprocessord.lib")
#pragma comment(lib, "translatord.lib")
#pragma comment(lib, "Qt5PlatformSupportd.lib")
#pragma comment(lib, "platforms/qwindowsd.lib")
#else
#pragma comment(lib, "v8_base.lib")
#pragma comment(lib, "v8_snapshot.lib")
#pragma comment(lib, "v8_nosnapshot.lib")
#pragma comment(lib, "Qt5Core.lib")
#pragma comment(lib, "Qt5Gui.lib")
#pragma comment(lib, "Qt5Widgets.lib")
#pragma comment(lib, "libEGL.lib")
#pragma comment(lib, "libGLESv2.lib")
#pragma comment(lib, "preprocessor.lib")
#pragma comment(lib, "translator.lib")
#pragma comment(lib, "Qt5PlatformSupport.lib")
#pragma comment(lib, "platforms/qwindows.lib")
#endif // DEBUG
#endif // _MSC_VER
#include "JSE.h"
#include "JSEApplication.h"
#include "JSEV8.h"
using namespace JSE;
int main(int argc, char *argv[])
{
JSEApplication app(argc, argv);
JSEV8 v8app(app);
QObject::connect(&app, SIGNAL(start()), &v8app, SLOT(start()));
return app.exec();
}<|endoftext|> |
<commit_before>#include "gpu.h"
#include <cassert>
#include <iostream>
#include <fstream>
static const size_t kBlockWidth = 4;
static const size_t kBlockHeight = 4;
static const size_t kNumComponents = 4;
static const size_t kNumBlockPixels = kBlockWidth * kBlockHeight;
static const size_t kBlockSize = kNumBlockPixels * kNumComponents;
static size_t kLocalWorkSizeX = 16;
static size_t kLocalWorkSizeY = 16;
static inline size_t GetTotalWorkItems() { return kLocalWorkSizeX * kLocalWorkSizeY; }
// We have 16 pixels per work item and 4 bytes per pixel, so each work
// group will need this much local memory.
static inline size_t GetPixelBufferBytes() { return GetTotalWorkItems() * kBlockSize; }
// Thirty-two bytes for the kernel arguments...
static inline size_t GetTotalLocalMemory() { return GetPixelBufferBytes() + 32; }
#ifndef CL_VERSION_1_2
static cl_int clUnloadCompiler11(cl_platform_id) {
return clUnloadCompiler();
}
#endif
typedef cl_int (*clUnloadCompilerFunc)(cl_platform_id);
#ifdef CL_VERSION_1_2
static const clUnloadCompilerFunc gUnloadCompilerFunc = clUnloadPlatformCompiler;
#else
static const clUnloadCompilerFunc gUnloadCompilerFunc = clUnloadCompiler11;
#endif
namespace gpu {
void ContextErrorCallback(const char *errinfo, const void *, size_t, void *) {
fprintf(stderr, "Context error: %s", errinfo);
assert(false);
exit(1);
}
void PrintDeviceInfo(cl_device_id device_id) {
size_t strLen;
const size_t kStrBufSz = 1024;
union {
char strBuf[kStrBufSz];
cl_uint intBuf[kStrBufSz / sizeof(cl_uint)];
size_t sizeBuf[kStrBufSz / sizeof(size_t)];
};
CHECK_CL(clGetDeviceInfo, device_id, CL_DEVICE_NAME, kStrBufSz, strBuf, &strLen);
std::cout << "Device name: " << strBuf << std::endl;
CHECK_CL(clGetDeviceInfo, device_id, CL_DEVICE_PROFILE, kStrBufSz, strBuf, &strLen);
std::cout << "Device profile: " << strBuf << std::endl;
CHECK_CL(clGetDeviceInfo, device_id, CL_DEVICE_VENDOR, kStrBufSz, strBuf, &strLen);
std::cout << "Device vendor: " << strBuf << std::endl;
CHECK_CL(clGetDeviceInfo, device_id, CL_DEVICE_VERSION, kStrBufSz, strBuf, &strLen);
std::cout << "Device version: " << strBuf << std::endl;
CHECK_CL(clGetDeviceInfo, device_id, CL_DRIVER_VERSION, kStrBufSz, strBuf, &strLen);
std::cout << "Device driver version: " << strBuf << std::endl;
CHECK_CL(clGetDeviceInfo, device_id, CL_DEVICE_ADDRESS_BITS, kStrBufSz, strBuf,
&strLen);
std::cout << "Device driver address bits: " << intBuf[0] << std::endl;
CHECK_CL(clGetDeviceInfo, device_id, CL_DEVICE_MAX_WORK_GROUP_SIZE, kStrBufSz,
strBuf, &strLen);
std::cout << "Max work group size: " << sizeBuf[0] << std::endl;
assert(*((size_t *)strBuf) >= GetTotalWorkItems());
CHECK_CL(clGetDeviceInfo, device_id, CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS, kStrBufSz,
strBuf, &strLen);
std::cout << "Max work item dimensions: " << intBuf[0] << std::endl;
assert(*(reinterpret_cast<cl_uint *>(strBuf)) >= 2);
CHECK_CL(clGetDeviceInfo, device_id, CL_DEVICE_GLOBAL_MEM_SIZE, kStrBufSz,
strBuf, &strLen);
std::cout << "Total global bytes available: " << intBuf[0] << std::endl;
CHECK_CL(clGetDeviceInfo, device_id, CL_DEVICE_LOCAL_MEM_SIZE, kStrBufSz,
strBuf, &strLen);
std::cout << "Total local bytes available: " << intBuf[0] << std::endl;
CHECK_CL(clGetDeviceInfo, device_id, CL_DEVICE_MAX_MEM_ALLOC_SIZE, kStrBufSz,
strBuf, &strLen);
std::cout << "Total size of memory allocatable: " << intBuf[0] << std::endl;
CHECK_CL(clGetDeviceInfo, device_id, CL_DEVICE_MAX_WORK_ITEM_SIZES, kStrBufSz, strBuf, &strLen);
size_t nSizeElements = strLen / sizeof(size_t);
std::cout << "Max work item sizes: (";
size_t *dimSizes = (size_t *)(strBuf);
for(size_t j = 0; j < nSizeElements; j++) {
std::cout << dimSizes[j] << ((j == nSizeElements - 1)? "" : ", ");
assert(j != 0 || dimSizes[j] > kLocalWorkSizeX);
assert(j != 1 || dimSizes[j] > kLocalWorkSizeY);
}
std::cout << ")" << std::endl;
CHECK_CL(clGetDeviceInfo, device_id, CL_DEVICE_EXTENSIONS, kStrBufSz, strBuf, &strLen);
std::cout << "Device extensions: " << std::endl;
for (size_t k = 0; k < strLen; ++k) {
if (strBuf[k] == ',' || strBuf[k] == ' ') {
strBuf[k] = '\0';
}
}
std::cout << " " << strBuf << std::endl;
for (size_t k = 1; k < strLen; ++k) {
if (strBuf[k] == '\0' && k < strLen - 1) {
std::cout << " " << (strBuf + k + 1) << std::endl;
}
}
cl_device_type deviceType;
size_t deviceTypeSz;
CHECK_CL(clGetDeviceInfo, device_id, CL_DEVICE_TYPE, sizeof(cl_device_type), &deviceType, &deviceTypeSz);
if(deviceType & CL_DEVICE_TYPE_CPU) {
std::cout << "Device driver type: CPU" << std::endl;
}
if(deviceType & CL_DEVICE_TYPE_GPU) {
std::cout << "Device driver type: GPU" << std::endl;
}
if(deviceType & CL_DEVICE_TYPE_ACCELERATOR) {
std::cout << "Device driver type: ACCELERATOR" << std::endl;
}
if(deviceType & CL_DEVICE_TYPE_DEFAULT) {
std::cout << "Device driver type: DEFAULT" << std::endl;
}
}
std::vector<cl_context_properties> GetSharedCLGLProps() {
std::vector<cl_context_properties> props;
#ifdef __APPLE__
// Get current CGL Context and CGL Share group
CGLContextObj kCGLContext = CGLGetCurrentContext();
CGLShareGroupObj kCGLShareGroup = CGLGetShareGroup(kCGLContext);
props.push_back(CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE);
props.push_back((cl_context_properties)kCGLShareGroup);
props.push_back(0);
#elif defined (_WIN32)
// OpenGL context
props.push_back(CL_GL_CONTEXT_KHR);
props.push_back((cl_context_properties)wglGetCurrentContext());
// HDC used to create the OpenGL context
props.push_back(CL_WGL_HDC_KHR);
props.push_back((cl_context_properties)wglGetCurrentDC());
props.push_back(0);
#else // Linux??
props.push_back(CL_GL_CONTEXT_KHR);
props.push_back((cl_context_properties) glXGetCurrentContext());
props.push_back(CL_GLX_DISPLAY_KHR);
props.push_back((cl_context_properties) glXGetCurrentDisplay());
props.push_back(0);
#endif
return std::move(props);
}
static void CreateCLContext(cl_context *result, const cl_context_properties *props,
cl_device_id device) {
cl_int errCreateContext;
*result = clCreateContext(props, 1, &device, ContextErrorCallback, NULL,
&errCreateContext);
CHECK_CL((cl_int), errCreateContext);
}
cl_context InitializeOpenCL(bool share_opengl) {
const cl_uint kMaxPlatforms = 8;
cl_platform_id platforms[kMaxPlatforms];
cl_uint nPlatforms;
CHECK_CL(clGetPlatformIDs, kMaxPlatforms, platforms, &nPlatforms);
#ifndef NDEBUG
size_t strLen;
fprintf(stdout, "\n");
fprintf(stdout, "Found %d OpenCL platform%s.\n", nPlatforms, nPlatforms == 1? "" : "s");
for(cl_uint i = 0; i < nPlatforms; i++) {
char strBuf[256];
fprintf(stdout, "\n");
fprintf(stdout, "Platform %d info:\n", i);
CHECK_CL(clGetPlatformInfo, platforms[i], CL_PLATFORM_PROFILE, 256, strBuf, &strLen);
fprintf(stdout, "Platform profile: %s\n", strBuf);
CHECK_CL(clGetPlatformInfo, platforms[i], CL_PLATFORM_VERSION, 256, strBuf, &strLen);
fprintf(stdout, "Platform version: %s\n", strBuf);
CHECK_CL(clGetPlatformInfo, platforms[i], CL_PLATFORM_NAME, 256, strBuf, &strLen);
fprintf(stdout, "Platform name: %s\n", strBuf);
CHECK_CL(clGetPlatformInfo, platforms[i], CL_PLATFORM_VENDOR, 256, strBuf, &strLen);
fprintf(stdout, "Platform vendor: %s\n", strBuf);
}
#endif
cl_platform_id platform = platforms[0];
const cl_uint kMaxDevices = 8;
cl_device_id devices[kMaxDevices];
cl_uint nDevices;
CHECK_CL(clGetDeviceIDs, platform, CL_DEVICE_TYPE_GPU, kMaxDevices, devices, &nDevices);
#ifndef NDEBUG
fprintf(stdout, "\n");
fprintf(stdout, "Found %d device%s on platform 0.\n", nDevices, nDevices == 1? "" : "s");
for(cl_uint i = 0; i < nDevices; i++) {
PrintDeviceInfo(devices[i]);
}
std::cout << std::endl;
#endif
// Create OpenCL context...
cl_context ctx;
if (share_opengl) {
std::vector<cl_context_properties> props = GetSharedCLGLProps();
CreateCLContext(&ctx, props.data(), devices[0]);
} else {
cl_context_properties props[] = {
CL_CONTEXT_PLATFORM, (cl_context_properties) platform, 0
};
CreateCLContext(&ctx, props, devices[0]);
}
return ctx;
}
cl_device_id GetDeviceForSharedContext(cl_context ctx) {
std::vector<cl_context_properties> props = GetSharedCLGLProps();
size_t device_id_size_bytes;
cl_device_id device;
typedef CL_API_ENTRY cl_int (CL_API_CALL *CtxInfoFunc)
(const cl_context_properties *properties, cl_gl_context_info param_name,
size_t param_value_size, void *param_value, size_t *param_value_size_ret);
static CtxInfoFunc getCtxInfoFunc = NULL;
if (NULL == getCtxInfoFunc) {
getCtxInfoFunc = (CtxInfoFunc)(clGetExtensionFunctionAddress("clGetGLContextInfoKHR"));
}
assert (getCtxInfoFunc);
CHECK_CL(getCtxInfoFunc, props.data(), CL_CURRENT_DEVICE_FOR_GL_CONTEXT_KHR,
sizeof(device), &device, &device_id_size_bytes);
// If we're sharing an openGL context, there should really only
// be one device ID...
assert (device_id_size_bytes == sizeof(cl_device_id));
return device;
}
std::vector<cl_device_id> GetAllDevicesForContext(cl_context ctx) {
std::vector<cl_device_id> devices(16);
size_t nDeviceIds;
CHECK_CL(clGetContextInfo, ctx, CL_CONTEXT_DEVICES, devices.size() * sizeof(cl_device_id),
devices.data(), &nDeviceIds);
nDeviceIds /= sizeof(cl_device_id);
devices.resize(nDeviceIds);
return std::move(devices);
}
LoadedCLKernel InitializeOpenCLKernel(const char *source_filename, const char *kernel_name,
cl_context ctx, cl_device_id device) {
#ifndef NDEBUG
// If the total local memory required is greater than the minimum specified.. check!
size_t strLen;
cl_ulong totalLocalMemory;
CHECK_CL(clGetDeviceInfo, device, CL_DEVICE_LOCAL_MEM_SIZE, sizeof(cl_ulong),
&totalLocalMemory, &strLen);
assert(strLen == sizeof(cl_ulong));
assert(totalLocalMemory >= 16384);
while(GetTotalLocalMemory() > totalLocalMemory) {
kLocalWorkSizeX >>= 1;
kLocalWorkSizeY >>= 1;
}
#endif
std::ifstream progfs(source_filename);
std::string progStr((std::istreambuf_iterator<char>(progfs)),
std::istreambuf_iterator<char>());
const char *progCStr = progStr.c_str();
cl_int errCreateProgram;
cl_program program;
program = clCreateProgramWithSource(ctx, 1, &progCStr, NULL, &errCreateProgram);
CHECK_CL((cl_int), errCreateProgram);
if(clBuildProgram(program, 1, &device, "-Werror", NULL, NULL) != CL_SUCCESS) {
size_t bufferSz;
clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,
sizeof(size_t), NULL, &bufferSz);
char *buffer = new char[bufferSz + 1];
buffer[bufferSz] = '\0';
clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,
bufferSz, buffer, NULL);
std::cerr << "CL Compilation failed:" << std::endl;
std::cerr << buffer + 1 << std::endl;
abort();
} else {
std::cerr << "CL Kernel compiled successfully!" << std::endl;
}
// !FIXME!
// CHECK_CL(gUnloadCompilerFunc, platform);
LoadedCLKernel kernel;
cl_int errCreateCommandQueue;
kernel._command_queue = clCreateCommandQueue(ctx, device, 0, &errCreateCommandQueue);
CHECK_CL((cl_int), errCreateCommandQueue);
cl_int errCreateKernel;
kernel._kernel = clCreateKernel(program, kernel_name, &errCreateKernel);
CHECK_CL((cl_int), errCreateKernel);
CHECK_CL(clReleaseProgram, program);
return kernel;
}
void DestroyOpenCLKernel(const LoadedCLKernel &kernel) {
CHECK_CL(clReleaseKernel, kernel._kernel);
CHECK_CL(clReleaseCommandQueue, kernel._command_queue);
}
void ShutdownOpenCL(cl_context ctx) {
CHECK_CL(clReleaseContext, ctx);
}
} // namespace gpu
<commit_msg>Fix build on OS X and make sure it runs<commit_after>#include "gpu.h"
#include <cassert>
#include <iostream>
#include <fstream>
static const size_t kBlockWidth = 4;
static const size_t kBlockHeight = 4;
static const size_t kNumComponents = 4;
static const size_t kNumBlockPixels = kBlockWidth * kBlockHeight;
static const size_t kBlockSize = kNumBlockPixels * kNumComponents;
static size_t kLocalWorkSizeX = 16;
static size_t kLocalWorkSizeY = 16;
static inline size_t GetTotalWorkItems() { return kLocalWorkSizeX * kLocalWorkSizeY; }
// We have 16 pixels per work item and 4 bytes per pixel, so each work
// group will need this much local memory.
static inline size_t GetPixelBufferBytes() { return GetTotalWorkItems() * kBlockSize; }
// Thirty-two bytes for the kernel arguments...
static inline size_t GetTotalLocalMemory() { return GetPixelBufferBytes() + 32; }
#ifndef CL_VERSION_1_2
static cl_int clUnloadCompiler11(cl_platform_id) {
return clUnloadCompiler();
}
#endif
typedef cl_int (*clUnloadCompilerFunc)(cl_platform_id);
#ifdef CL_VERSION_1_2
static const clUnloadCompilerFunc gUnloadCompilerFunc = clUnloadPlatformCompiler;
#else
static const clUnloadCompilerFunc gUnloadCompilerFunc = clUnloadCompiler11;
#endif
namespace gpu {
void ContextErrorCallback(const char *errinfo, const void *, size_t, void *) {
fprintf(stderr, "Context error: %s", errinfo);
assert(false);
exit(1);
}
void PrintDeviceInfo(cl_device_id device_id) {
size_t strLen;
const size_t kStrBufSz = 1024;
union {
char strBuf[kStrBufSz];
cl_uint intBuf[kStrBufSz / sizeof(cl_uint)];
size_t sizeBuf[kStrBufSz / sizeof(size_t)];
};
CHECK_CL(clGetDeviceInfo, device_id, CL_DEVICE_NAME, kStrBufSz, strBuf, &strLen);
std::cout << "Device name: " << strBuf << std::endl;
CHECK_CL(clGetDeviceInfo, device_id, CL_DEVICE_PROFILE, kStrBufSz, strBuf, &strLen);
std::cout << "Device profile: " << strBuf << std::endl;
CHECK_CL(clGetDeviceInfo, device_id, CL_DEVICE_VENDOR, kStrBufSz, strBuf, &strLen);
std::cout << "Device vendor: " << strBuf << std::endl;
CHECK_CL(clGetDeviceInfo, device_id, CL_DEVICE_VERSION, kStrBufSz, strBuf, &strLen);
std::cout << "Device version: " << strBuf << std::endl;
CHECK_CL(clGetDeviceInfo, device_id, CL_DRIVER_VERSION, kStrBufSz, strBuf, &strLen);
std::cout << "Device driver version: " << strBuf << std::endl;
CHECK_CL(clGetDeviceInfo, device_id, CL_DEVICE_ADDRESS_BITS, kStrBufSz, strBuf,
&strLen);
std::cout << "Device driver address bits: " << intBuf[0] << std::endl;
CHECK_CL(clGetDeviceInfo, device_id, CL_DEVICE_MAX_WORK_GROUP_SIZE, kStrBufSz,
strBuf, &strLen);
std::cout << "Max work group size: " << sizeBuf[0] << std::endl;
assert(*((size_t *)strBuf) >= GetTotalWorkItems());
CHECK_CL(clGetDeviceInfo, device_id, CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS, kStrBufSz,
strBuf, &strLen);
std::cout << "Max work item dimensions: " << intBuf[0] << std::endl;
assert(*(reinterpret_cast<cl_uint *>(strBuf)) >= 2);
CHECK_CL(clGetDeviceInfo, device_id, CL_DEVICE_GLOBAL_MEM_SIZE, kStrBufSz,
strBuf, &strLen);
std::cout << "Total global bytes available: " << intBuf[0] << std::endl;
CHECK_CL(clGetDeviceInfo, device_id, CL_DEVICE_LOCAL_MEM_SIZE, kStrBufSz,
strBuf, &strLen);
std::cout << "Total local bytes available: " << intBuf[0] << std::endl;
CHECK_CL(clGetDeviceInfo, device_id, CL_DEVICE_MAX_MEM_ALLOC_SIZE, kStrBufSz,
strBuf, &strLen);
std::cout << "Total size of memory allocatable: " << intBuf[0] << std::endl;
CHECK_CL(clGetDeviceInfo, device_id, CL_DEVICE_MAX_WORK_ITEM_SIZES, kStrBufSz, strBuf, &strLen);
size_t nSizeElements = strLen / sizeof(size_t);
std::cout << "Max work item sizes: (";
size_t *dimSizes = (size_t *)(strBuf);
for(size_t j = 0; j < nSizeElements; j++) {
std::cout << dimSizes[j] << ((j == nSizeElements - 1)? "" : ", ");
assert(j != 0 || dimSizes[j] > kLocalWorkSizeX);
assert(j != 1 || dimSizes[j] > kLocalWorkSizeY);
}
std::cout << ")" << std::endl;
CHECK_CL(clGetDeviceInfo, device_id, CL_DEVICE_EXTENSIONS, kStrBufSz, strBuf, &strLen);
std::cout << "Device extensions: " << std::endl;
for (size_t k = 0; k < strLen; ++k) {
if (strBuf[k] == ',' || strBuf[k] == ' ') {
strBuf[k] = '\0';
}
}
std::cout << " " << strBuf << std::endl;
for (size_t k = 1; k < strLen; ++k) {
if (strBuf[k] == '\0' && k < strLen - 1) {
std::cout << " " << (strBuf + k + 1) << std::endl;
}
}
cl_device_type deviceType;
size_t deviceTypeSz;
CHECK_CL(clGetDeviceInfo, device_id, CL_DEVICE_TYPE, sizeof(cl_device_type), &deviceType, &deviceTypeSz);
if(deviceType & CL_DEVICE_TYPE_CPU) {
std::cout << "Device driver type: CPU" << std::endl;
}
if(deviceType & CL_DEVICE_TYPE_GPU) {
std::cout << "Device driver type: GPU" << std::endl;
}
if(deviceType & CL_DEVICE_TYPE_ACCELERATOR) {
std::cout << "Device driver type: ACCELERATOR" << std::endl;
}
if(deviceType & CL_DEVICE_TYPE_DEFAULT) {
std::cout << "Device driver type: DEFAULT" << std::endl;
}
}
std::vector<cl_context_properties> GetSharedCLGLProps() {
std::vector<cl_context_properties> props;
#ifdef __APPLE__
// Get current CGL Context and CGL Share group
CGLContextObj kCGLContext = CGLGetCurrentContext();
CGLShareGroupObj kCGLShareGroup = CGLGetShareGroup(kCGLContext);
props.push_back(CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE);
props.push_back((cl_context_properties)kCGLShareGroup);
props.push_back(0);
#elif defined (_WIN32)
// OpenGL context
props.push_back(CL_GL_CONTEXT_KHR);
props.push_back((cl_context_properties)wglGetCurrentContext());
// HDC used to create the OpenGL context
props.push_back(CL_WGL_HDC_KHR);
props.push_back((cl_context_properties)wglGetCurrentDC());
props.push_back(0);
#else // Linux??
props.push_back(CL_GL_CONTEXT_KHR);
props.push_back((cl_context_properties) glXGetCurrentContext());
props.push_back(CL_GLX_DISPLAY_KHR);
props.push_back((cl_context_properties) glXGetCurrentDisplay());
props.push_back(0);
#endif
return std::move(props);
}
static void CreateCLContext(cl_context *result, const cl_context_properties *props,
cl_device_id device) {
cl_int errCreateContext;
*result = clCreateContext(props, 1, &device, ContextErrorCallback, NULL,
&errCreateContext);
CHECK_CL((cl_int), errCreateContext);
}
cl_context InitializeOpenCL(bool share_opengl) {
const cl_uint kMaxPlatforms = 8;
cl_platform_id platforms[kMaxPlatforms];
cl_uint nPlatforms;
CHECK_CL(clGetPlatformIDs, kMaxPlatforms, platforms, &nPlatforms);
#ifndef NDEBUG
size_t strLen;
fprintf(stdout, "\n");
fprintf(stdout, "Found %d OpenCL platform%s.\n", nPlatforms, nPlatforms == 1? "" : "s");
for(cl_uint i = 0; i < nPlatforms; i++) {
char strBuf[256];
fprintf(stdout, "\n");
fprintf(stdout, "Platform %d info:\n", i);
CHECK_CL(clGetPlatformInfo, platforms[i], CL_PLATFORM_PROFILE, 256, strBuf, &strLen);
fprintf(stdout, "Platform profile: %s\n", strBuf);
CHECK_CL(clGetPlatformInfo, platforms[i], CL_PLATFORM_VERSION, 256, strBuf, &strLen);
fprintf(stdout, "Platform version: %s\n", strBuf);
CHECK_CL(clGetPlatformInfo, platforms[i], CL_PLATFORM_NAME, 256, strBuf, &strLen);
fprintf(stdout, "Platform name: %s\n", strBuf);
CHECK_CL(clGetPlatformInfo, platforms[i], CL_PLATFORM_VENDOR, 256, strBuf, &strLen);
fprintf(stdout, "Platform vendor: %s\n", strBuf);
}
#endif
cl_platform_id platform = platforms[0];
const cl_uint kMaxDevices = 8;
cl_device_id devices[kMaxDevices];
cl_uint nDevices;
CHECK_CL(clGetDeviceIDs, platform, CL_DEVICE_TYPE_GPU, kMaxDevices, devices, &nDevices);
#ifndef NDEBUG
fprintf(stdout, "\n");
fprintf(stdout, "Found %d device%s on platform 0.\n", nDevices, nDevices == 1? "" : "s");
for(cl_uint i = 0; i < nDevices; i++) {
PrintDeviceInfo(devices[i]);
}
std::cout << std::endl;
#endif
// Create OpenCL context...
cl_context ctx;
if (share_opengl) {
std::vector<cl_context_properties> props = GetSharedCLGLProps();
CreateCLContext(&ctx, props.data(), devices[0]);
} else {
cl_context_properties props[] = {
CL_CONTEXT_PLATFORM, (cl_context_properties) platform, 0
};
CreateCLContext(&ctx, props, devices[0]);
}
return ctx;
}
cl_device_id GetDeviceForSharedContext(cl_context ctx) {
size_t device_id_size_bytes;
cl_device_id device;
#ifndef __APPLE__
std::vector<cl_context_properties> props = GetSharedCLGLProps();
typedef CL_API_ENTRY cl_int (CL_API_CALL *CtxInfoFunc)
(const cl_context_properties *properties, cl_gl_context_info param_name,
size_t param_value_size, void *param_value, size_t *param_value_size_ret);
static CtxInfoFunc getCtxInfoFunc = NULL;
if (NULL == getCtxInfoFunc) {
getCtxInfoFunc = (CtxInfoFunc)(clGetExtensionFunctionAddress("clGetGLContextInfoKHR"));
}
assert (getCtxInfoFunc);
CHECK_CL(getCtxInfoFunc, props.data(), CL_CURRENT_DEVICE_FOR_GL_CONTEXT_KHR,
sizeof(device), &device, &device_id_size_bytes);
#else
// Get current CGL Context and CGL Share group
CGLContextObj kCGLContext = CGLGetCurrentContext();
// And now we can ask OpenCL which particular device is being used by
// OpenGL to do the rendering, currently:
clGetGLContextInfoAPPLE(ctx, kCGLContext,
CL_CGL_DEVICE_FOR_CURRENT_VIRTUAL_SCREEN_APPLE,
sizeof(device), &device, &device_id_size_bytes);
#endif
// If we're sharing an openGL context, there should really only
// be one device ID...
assert (device_id_size_bytes == sizeof(cl_device_id));
return device;
}
std::vector<cl_device_id> GetAllDevicesForContext(cl_context ctx) {
std::vector<cl_device_id> devices(16);
size_t nDeviceIds;
CHECK_CL(clGetContextInfo, ctx, CL_CONTEXT_DEVICES, devices.size() * sizeof(cl_device_id),
devices.data(), &nDeviceIds);
nDeviceIds /= sizeof(cl_device_id);
devices.resize(nDeviceIds);
return std::move(devices);
}
LoadedCLKernel InitializeOpenCLKernel(const char *source_filename, const char *kernel_name,
cl_context ctx, cl_device_id device) {
#ifndef NDEBUG
// If the total local memory required is greater than the minimum specified.. check!
size_t strLen;
cl_ulong totalLocalMemory;
CHECK_CL(clGetDeviceInfo, device, CL_DEVICE_LOCAL_MEM_SIZE, sizeof(cl_ulong),
&totalLocalMemory, &strLen);
assert(strLen == sizeof(cl_ulong));
assert(totalLocalMemory >= 16384);
while(GetTotalLocalMemory() > totalLocalMemory) {
kLocalWorkSizeX >>= 1;
kLocalWorkSizeY >>= 1;
}
#endif
std::ifstream progfs(source_filename);
std::string progStr((std::istreambuf_iterator<char>(progfs)),
std::istreambuf_iterator<char>());
const char *progCStr = progStr.c_str();
cl_int errCreateProgram;
cl_program program;
program = clCreateProgramWithSource(ctx, 1, &progCStr, NULL, &errCreateProgram);
CHECK_CL((cl_int), errCreateProgram);
if(clBuildProgram(program, 1, &device, "-Werror", NULL, NULL) != CL_SUCCESS) {
size_t bufferSz;
clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,
sizeof(size_t), NULL, &bufferSz);
char *buffer = new char[bufferSz + 1];
buffer[bufferSz] = '\0';
clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,
bufferSz, buffer, NULL);
std::cerr << "CL Compilation failed:" << std::endl;
std::cerr << buffer + 1 << std::endl;
abort();
} else {
std::cerr << "CL Kernel compiled successfully!" << std::endl;
}
// !FIXME!
// CHECK_CL(gUnloadCompilerFunc, platform);
LoadedCLKernel kernel;
cl_int errCreateCommandQueue;
kernel._command_queue = clCreateCommandQueue(ctx, device, 0, &errCreateCommandQueue);
CHECK_CL((cl_int), errCreateCommandQueue);
cl_int errCreateKernel;
kernel._kernel = clCreateKernel(program, kernel_name, &errCreateKernel);
CHECK_CL((cl_int), errCreateKernel);
CHECK_CL(clReleaseProgram, program);
return kernel;
}
void DestroyOpenCLKernel(const LoadedCLKernel &kernel) {
CHECK_CL(clReleaseKernel, kernel._kernel);
CHECK_CL(clReleaseCommandQueue, kernel._command_queue);
}
void ShutdownOpenCL(cl_context ctx) {
CHECK_CL(clReleaseContext, ctx);
}
} // namespace gpu
<|endoftext|> |
<commit_before>/* vim: set ai et ts=4 sw=4: */
#include <string>
#include <utility>
#include <map>
#include <iostream>
#include <signal.h>
#include <HttpServer.h>
//#include <InMemoryStorage.h>
#include <PersistentStorage.h>
// TODO: describe REST API in README.md or API.md
// TODO: support rangescans
// TODO: support _rev in ::set, ::delete
// TODO: multithread test with _rev
// TODO: script - run under Valgrind
// TODO: script - run under MemorySanitizer + other kinds of sanitizers
// TODO: see `grep -r TODO ./`
// TODO: Keyspaces class
//InMemoryStorage storage;
PersistentStorage storage;
pthread_mutex_t terminate_lock;
static bool terminate = false;
static void httpIndexGetHandler(const HttpRequest&, HttpResponse& resp) {
resp.setStatus(HTTP_STATUS_OK);
resp.setBody("This is HurmaDB!\n\n");
}
static void httpKVGetHandler(const HttpRequest& req, HttpResponse& resp) {
bool found;
const std::string& key = req.getQueryMatch(0);
const std::string& value = storage.get(key, &found);
resp.setStatus(found ? HTTP_STATUS_OK : HTTP_STATUS_NOT_FOUND);
resp.setBody(value);
}
static void httpKVPutHandler(const HttpRequest& req, HttpResponse& resp) {
const std::string& key = req.getQueryMatch(0);
const std::string& value = req.getBody();
storage.set(key, value);
resp.setStatus(HTTP_STATUS_OK);
}
static void httpKVDeleteHandler(const HttpRequest& req, HttpResponse& resp) {
bool found;
const std::string& key = req.getQueryMatch(0);
storage.del(key, &found);
resp.setStatus(found ? HTTP_STATUS_OK : HTTP_STATUS_NOT_FOUND);
}
/* Required for generating code coverage report */
static void httpStopPutHandler(const HttpRequest&, HttpResponse& resp) {
pthread_mutex_lock(&terminate_lock);
terminate = true;
pthread_mutex_unlock(&terminate_lock);
resp.setStatus(HTTP_STATUS_OK);
}
int main(int argc, char** argv) {
if(argc < 2) {
std::cerr << "Usage: " << argv[0] << " <port>" << std::endl;
return 1;
}
int port = atoi(argv[1]);
if(port <= 0 || port >= 65536) {
std::cerr << "Invalid port number!" << std::endl;
return 2;
}
HttpServer server;
server.addHandler(HTTP_GET, "(?i)^/$", &httpIndexGetHandler);
server.addHandler(HTTP_PUT, "(?i)^/v1/_stop/?$", &httpStopPutHandler);
server.addHandler(HTTP_GET, "(?i)^/v1/kv/([\\w-]+)/?$", &httpKVGetHandler);
server.addHandler(HTTP_PUT, "(?i)^/v1/kv/([\\w-]+)/?$", &httpKVPutHandler);
server.addHandler(HTTP_DELETE, "(?i)^/v1/kv/([\\w-]+)/?$", &httpKVDeleteHandler);
server.listen("127.0.0.1", port);
for(;;) {
pthread_mutex_lock(&terminate_lock);
bool term = terminate;
pthread_mutex_unlock(&terminate_lock);
if(term) break;
server.accept();
}
pthread_exit(nullptr);
}
<commit_msg>TODO item added<commit_after>/* vim: set ai et ts=4 sw=4: */
#include <string>
#include <utility>
#include <map>
#include <iostream>
#include <signal.h>
#include <HttpServer.h>
//#include <InMemoryStorage.h>
#include <PersistentStorage.h>
// TODO: plugable porotols, e.g. support Memcached protocol
// TODO: describe REST API in README.md or API.md
// TODO: support rangescans
// TODO: support _rev in ::set, ::delete
// TODO: multithread test with _rev
// TODO: script - run under Valgrind
// TODO: script - run under MemorySanitizer + other kinds of sanitizers
// TODO: see `grep -r TODO ./`
// TODO: Keyspaces class
//InMemoryStorage storage;
PersistentStorage storage;
pthread_mutex_t terminate_lock;
static bool terminate = false;
static void httpIndexGetHandler(const HttpRequest&, HttpResponse& resp) {
resp.setStatus(HTTP_STATUS_OK);
resp.setBody("This is HurmaDB!\n\n");
}
static void httpKVGetHandler(const HttpRequest& req, HttpResponse& resp) {
bool found;
const std::string& key = req.getQueryMatch(0);
const std::string& value = storage.get(key, &found);
resp.setStatus(found ? HTTP_STATUS_OK : HTTP_STATUS_NOT_FOUND);
resp.setBody(value);
}
static void httpKVPutHandler(const HttpRequest& req, HttpResponse& resp) {
const std::string& key = req.getQueryMatch(0);
const std::string& value = req.getBody();
storage.set(key, value);
resp.setStatus(HTTP_STATUS_OK);
}
static void httpKVDeleteHandler(const HttpRequest& req, HttpResponse& resp) {
bool found;
const std::string& key = req.getQueryMatch(0);
storage.del(key, &found);
resp.setStatus(found ? HTTP_STATUS_OK : HTTP_STATUS_NOT_FOUND);
}
/* Required for generating code coverage report */
static void httpStopPutHandler(const HttpRequest&, HttpResponse& resp) {
pthread_mutex_lock(&terminate_lock);
terminate = true;
pthread_mutex_unlock(&terminate_lock);
resp.setStatus(HTTP_STATUS_OK);
}
int main(int argc, char** argv) {
if(argc < 2) {
std::cerr << "Usage: " << argv[0] << " <port>" << std::endl;
return 1;
}
int port = atoi(argv[1]);
if(port <= 0 || port >= 65536) {
std::cerr << "Invalid port number!" << std::endl;
return 2;
}
HttpServer server;
server.addHandler(HTTP_GET, "(?i)^/$", &httpIndexGetHandler);
server.addHandler(HTTP_PUT, "(?i)^/v1/_stop/?$", &httpStopPutHandler);
server.addHandler(HTTP_GET, "(?i)^/v1/kv/([\\w-]+)/?$", &httpKVGetHandler);
server.addHandler(HTTP_PUT, "(?i)^/v1/kv/([\\w-]+)/?$", &httpKVPutHandler);
server.addHandler(HTTP_DELETE, "(?i)^/v1/kv/([\\w-]+)/?$", &httpKVDeleteHandler);
server.listen("127.0.0.1", port);
for(;;) {
pthread_mutex_lock(&terminate_lock);
bool term = terminate;
pthread_mutex_unlock(&terminate_lock);
if(term) break;
server.accept();
}
pthread_exit(nullptr);
}
<|endoftext|> |
<commit_before>/******************************************************************************\
* File: menu.cpp
* Purpose: Implementation of wxExMenu class
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
*
* Copyright (c) 1998-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <map>
#include <wx/extension/menu.h>
#include <wx/extension/art.h>
#include <wx/extension/lexers.h>
#include <wx/extension/tool.h>
#include <wx/extension/util.h> // for wxExEllipsed
#include <wx/extension/vcs.h>
#if wxUSE_GUI
wxExMenu::wxExMenu(long style)
: m_Style(style)
, m_MenuVCSFilled(false)
{
}
wxExMenu::wxExMenu(const wxExMenu& menu)
: m_Style(menu.m_Style)
, m_MenuVCSFilled(menu.m_MenuVCSFilled)
{
}
wxMenuItem* wxExMenu::Append(int id)
{
// Using wxMenu::Append(id)
// also appends the stock item,
// but does not add the bitmap.
wxMenuItem* item = new wxMenuItem(this, id);
const wxExStockArt art(id);
if (art.GetBitmap().IsOk())
{
item->SetBitmap(art.GetBitmap(
wxART_MENU,
wxArtProvider::GetSizeHint(wxART_MENU, true)));
}
return wxMenu::Append(item);
}
wxMenuItem* wxExMenu::Append(
int id,
const wxString& name,
const wxString& helptext,
const wxArtID& artid)
{
wxMenuItem* item = new wxMenuItem(this, id, name, helptext);
if (!artid.empty())
{
const wxBitmap bitmap =
wxArtProvider::GetBitmap(
artid,
wxART_MENU,
wxArtProvider::GetSizeHint(wxART_MENU, true));
if (bitmap.IsOk())
{
item->SetBitmap(bitmap);
}
}
return wxMenu::Append(item);
}
void wxExMenu::AppendBars()
{
#ifndef __WXGTK__
AppendCheckItem(ID_VIEW_MENUBAR, _("&Menubar"));
#endif
AppendCheckItem(ID_VIEW_STATUSBAR, _("&Statusbar"));
AppendCheckItem(ID_VIEW_TOOLBAR, _("&Toolbar"));
AppendCheckItem(ID_VIEW_FINDBAR, _("&Findbar"));
}
void wxExMenu::AppendEdit(bool add_invert)
{
if (!(m_Style & MENU_IS_READ_ONLY) &&
(m_Style & MENU_IS_SELECTED))
{
Append(wxID_CUT);
}
if (m_Style & MENU_IS_SELECTED)
{
Append(wxID_COPY);
}
if (!(m_Style & MENU_IS_READ_ONLY) &&
(m_Style & MENU_CAN_PASTE))
{
Append(wxID_PASTE);
}
if (!(m_Style & MENU_IS_SELECTED) &&
!(m_Style & MENU_IS_EMPTY))
{
Append(wxID_SELECTALL);
}
else
{
if (add_invert && !(m_Style & MENU_IS_EMPTY))
{
Append(ID_EDIT_SELECT_NONE, _("&Deselect All"));
}
}
if (m_Style & MENU_ALLOW_CLEAR)
{
Append(wxID_CLEAR);
}
if (add_invert && !(m_Style & MENU_IS_EMPTY))
{
Append(ID_EDIT_SELECT_INVERT, _("&Invert"));
}
if (!(m_Style & MENU_IS_READ_ONLY) &&
(m_Style & MENU_IS_SELECTED) &&
!(m_Style & MENU_IS_EMPTY))
{
Append(wxID_DELETE);
}
}
void wxExMenu::AppendPrint()
{
Append(wxID_PRINT_SETUP, wxExEllipsed(_("Page &Setup")));
Append(wxID_PREVIEW);
Append(wxID_PRINT);
}
void wxExMenu::AppendSeparator()
{
if (
GetMenuItemCount() == 0 ||
FindItemByPosition(GetMenuItemCount() - 1)->IsSeparator())
{
return;
}
wxMenu::AppendSeparator();
}
void wxExMenu::AppendSubMenu(
wxMenu *submenu,
const wxString& text,
const wxString& help,
int itemid)
{
if (itemid == wxID_ANY)
{
wxMenu::AppendSubMenu(submenu, text, help);
}
else
{
// This one is deprecated, but is necessary if
// we have an explicit itemid.
wxMenu::Append(itemid, text, submenu, help);
}
}
bool wxExMenu::AppendTools(int itemid)
{
if (wxExLexers::Get()->Count() == 0)
{
return false;
}
wxExMenu* menuTool = new wxExMenu(*this);
for (
auto it =
wxExTool::Get()->GetToolInfo().begin();
it != wxExTool::Get()->GetToolInfo().end();
++it)
{
if (!it->second.GetText().empty())
{
const bool vcs_type = wxExTool(it->first).IsRCSType();
if ((vcs_type && !wxExVCS::Get()->Use()) || !vcs_type)
{
menuTool->Append(
it->first,
it->second.GetText(),
it->second.GetHelpText());
}
}
}
AppendSubMenu(menuTool, _("&Tools"), wxEmptyString, itemid);
return true;
}
// This is the VCS submenu, as present on a popup.
// Therefore it is build when clicking, and does not
// need to be destroyed an old one.
void wxExMenu::AppendVCS(const wxExFileName& filename)
{
if (!wxExVCS::Get()->Use())
{
return;
}
const int vcs_offset_id = ID_EDIT_VCS_LOWEST + 1;
wxExMenu* vcsmenu = new wxExMenu;
wxExVCS::Get()->BuildMenu(vcs_offset_id, vcsmenu, filename);
if (vcsmenu->GetMenuItemCount() > 0)
{
AppendSubMenu(vcsmenu, "&VCS");
}
}
// This is the general VCS menu, it is in the main menu,
// and because contents depends on actual VCS used,
// it is rebuild after change of VCS system.
void wxExMenu::BuildVCS(bool fill)
{
if (m_MenuVCSFilled)
{
wxMenuItem* item;
while ((item = FindItem(wxID_SEPARATOR)) != NULL)
{
Destroy(item);
}
for (int id = ID_VCS_LOWEST + 1; id < ID_VCS_HIGHEST; id++)
{
// When using only Destroy, and the item does not exist,
// an assert happens.
if (FindItem(id) != NULL)
{
Destroy(id);
}
}
}
if (fill)
{
const int vcs_offset_id = ID_VCS_LOWEST + 1;
wxExVCS::Get()->BuildMenu(
vcs_offset_id,
this,
wxExFileName(),
false); // no popup
if (GetMenuItemCount() == 0)
{
fill = false;
}
}
m_MenuVCSFilled = fill;
}
#endif // wxUSE_GUI
<commit_msg>added ctrl-b as comment to menu bar<commit_after>/******************************************************************************\
* File: menu.cpp
* Purpose: Implementation of wxExMenu class
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
*
* Copyright (c) 1998-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <map>
#include <wx/extension/menu.h>
#include <wx/extension/art.h>
#include <wx/extension/lexers.h>
#include <wx/extension/tool.h>
#include <wx/extension/util.h> // for wxExEllipsed
#include <wx/extension/vcs.h>
#if wxUSE_GUI
wxExMenu::wxExMenu(long style)
: m_Style(style)
, m_MenuVCSFilled(false)
{
}
wxExMenu::wxExMenu(const wxExMenu& menu)
: m_Style(menu.m_Style)
, m_MenuVCSFilled(menu.m_MenuVCSFilled)
{
}
wxMenuItem* wxExMenu::Append(int id)
{
// Using wxMenu::Append(id)
// also appends the stock item,
// but does not add the bitmap.
wxMenuItem* item = new wxMenuItem(this, id);
const wxExStockArt art(id);
if (art.GetBitmap().IsOk())
{
item->SetBitmap(art.GetBitmap(
wxART_MENU,
wxArtProvider::GetSizeHint(wxART_MENU, true)));
}
return wxMenu::Append(item);
}
wxMenuItem* wxExMenu::Append(
int id,
const wxString& name,
const wxString& helptext,
const wxArtID& artid)
{
wxMenuItem* item = new wxMenuItem(this, id, name, helptext);
if (!artid.empty())
{
const wxBitmap bitmap =
wxArtProvider::GetBitmap(
artid,
wxART_MENU,
wxArtProvider::GetSizeHint(wxART_MENU, true));
if (bitmap.IsOk())
{
item->SetBitmap(bitmap);
}
}
return wxMenu::Append(item);
}
void wxExMenu::AppendBars()
{
#ifndef __WXGTK__
AppendCheckItem(ID_VIEW_MENUBAR, _("&Menubar\tCtrl+B");
#endif
AppendCheckItem(ID_VIEW_STATUSBAR, _("&Statusbar"));
AppendCheckItem(ID_VIEW_TOOLBAR, _("&Toolbar"));
AppendCheckItem(ID_VIEW_FINDBAR, _("&Findbar"));
}
void wxExMenu::AppendEdit(bool add_invert)
{
if (!(m_Style & MENU_IS_READ_ONLY) &&
(m_Style & MENU_IS_SELECTED))
{
Append(wxID_CUT);
}
if (m_Style & MENU_IS_SELECTED)
{
Append(wxID_COPY);
}
if (!(m_Style & MENU_IS_READ_ONLY) &&
(m_Style & MENU_CAN_PASTE))
{
Append(wxID_PASTE);
}
if (!(m_Style & MENU_IS_SELECTED) &&
!(m_Style & MENU_IS_EMPTY))
{
Append(wxID_SELECTALL);
}
else
{
if (add_invert && !(m_Style & MENU_IS_EMPTY))
{
Append(ID_EDIT_SELECT_NONE, _("&Deselect All"));
}
}
if (m_Style & MENU_ALLOW_CLEAR)
{
Append(wxID_CLEAR);
}
if (add_invert && !(m_Style & MENU_IS_EMPTY))
{
Append(ID_EDIT_SELECT_INVERT, _("&Invert"));
}
if (!(m_Style & MENU_IS_READ_ONLY) &&
(m_Style & MENU_IS_SELECTED) &&
!(m_Style & MENU_IS_EMPTY))
{
Append(wxID_DELETE);
}
}
void wxExMenu::AppendPrint()
{
Append(wxID_PRINT_SETUP, wxExEllipsed(_("Page &Setup")));
Append(wxID_PREVIEW);
Append(wxID_PRINT);
}
void wxExMenu::AppendSeparator()
{
if (
GetMenuItemCount() == 0 ||
FindItemByPosition(GetMenuItemCount() - 1)->IsSeparator())
{
return;
}
wxMenu::AppendSeparator();
}
void wxExMenu::AppendSubMenu(
wxMenu *submenu,
const wxString& text,
const wxString& help,
int itemid)
{
if (itemid == wxID_ANY)
{
wxMenu::AppendSubMenu(submenu, text, help);
}
else
{
// This one is deprecated, but is necessary if
// we have an explicit itemid.
wxMenu::Append(itemid, text, submenu, help);
}
}
bool wxExMenu::AppendTools(int itemid)
{
if (wxExLexers::Get()->Count() == 0)
{
return false;
}
wxExMenu* menuTool = new wxExMenu(*this);
for (
auto it =
wxExTool::Get()->GetToolInfo().begin();
it != wxExTool::Get()->GetToolInfo().end();
++it)
{
if (!it->second.GetText().empty())
{
const bool vcs_type = wxExTool(it->first).IsRCSType();
if ((vcs_type && !wxExVCS::Get()->Use()) || !vcs_type)
{
menuTool->Append(
it->first,
it->second.GetText(),
it->second.GetHelpText());
}
}
}
AppendSubMenu(menuTool, _("&Tools"), wxEmptyString, itemid);
return true;
}
// This is the VCS submenu, as present on a popup.
// Therefore it is build when clicking, and does not
// need to be destroyed an old one.
void wxExMenu::AppendVCS(const wxExFileName& filename)
{
if (!wxExVCS::Get()->Use())
{
return;
}
const int vcs_offset_id = ID_EDIT_VCS_LOWEST + 1;
wxExMenu* vcsmenu = new wxExMenu;
wxExVCS::Get()->BuildMenu(vcs_offset_id, vcsmenu, filename);
if (vcsmenu->GetMenuItemCount() > 0)
{
AppendSubMenu(vcsmenu, "&VCS");
}
}
// This is the general VCS menu, it is in the main menu,
// and because contents depends on actual VCS used,
// it is rebuild after change of VCS system.
void wxExMenu::BuildVCS(bool fill)
{
if (m_MenuVCSFilled)
{
wxMenuItem* item;
while ((item = FindItem(wxID_SEPARATOR)) != NULL)
{
Destroy(item);
}
for (int id = ID_VCS_LOWEST + 1; id < ID_VCS_HIGHEST; id++)
{
// When using only Destroy, and the item does not exist,
// an assert happens.
if (FindItem(id) != NULL)
{
Destroy(id);
}
}
}
if (fill)
{
const int vcs_offset_id = ID_VCS_LOWEST + 1;
wxExVCS::Get()->BuildMenu(
vcs_offset_id,
this,
wxExFileName(),
false); // no popup
if (GetMenuItemCount() == 0)
{
fill = false;
}
}
m_MenuVCSFilled = fill;
}
#endif // wxUSE_GUI
<|endoftext|> |
<commit_before>// $Id$
// The libMesh Finite Element Library.
// Copyright (C) 2002-2007 Benjamin S. Kirk, John W. Peterson
// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#include <iostream>
#include <libmesh.h>
// Prototype for generic unit test.
void unit_test ();
int main (int argc, char** argv)
{
// Initialize the library. This is necessary because the library
// may depend on a number of other libraries (i.e. MPI and Petsc)
// that require initialization before use.
libMesh::init(argc, argv);
{
std::cout << "Running";
for (int i=0; i<argc; i++)
std::cout << " " << argv[i];
std::cout << std::endl;
// Run the test. All unit tests are implemented
// in a function called unit_test().
// We link the tests in one at a time.
unit_test();
}
return libMesh::close();
}
<commit_msg>Switched from libMesh::init()/close() to LibMeshInit<commit_after>// $Id$
// The libMesh Finite Element Library.
// Copyright (C) 2002-2007 Benjamin S. Kirk, John W. Peterson
// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#include <iostream>
#include <libmesh.h>
// Prototype for generic unit test.
void unit_test ();
int main (int argc, char** argv)
{
// Initialize the library. This is necessary because the library
// may depend on a number of other libraries (i.e. MPI and Petsc)
// that require initialization before use.
LibMeshInit init(argc, argv);
std::cout << "Running";
for (int i=0; i<argc; i++)
std::cout << " " << argv[i];
std::cout << std::endl;
// Run the test. All unit tests are implemented
// in a function called unit_test().
// We link the tests in one at a time.
unit_test();
return 0;
}
<|endoftext|> |
<commit_before>///
/// @file S2Status.hpp
///
/// Copyright (C) 2015 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef S2STATUS_HPP
#define S2STATUS_HPP
#include <int128.hpp>
namespace primecount {
class S2Status
{
public:
S2Status(maxint_t x);
void print(maxint_t n, maxint_t limit);
void print(maxint_t n, maxint_t limit, double rsd);
private:
double skewed_percent(maxint_t n, maxint_t limit) const;
bool is_print(double time) const;
bool is_print(double time, double percent) const;
double old_percent_;
double old_time_;
double print_threshold_;
int precision_;
int precision_factor_;
};
} // namespace
#endif
<commit_msg>Make skewed_percent() public<commit_after>///
/// @file S2Status.hpp
///
/// Copyright (C) 2015 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef S2STATUS_HPP
#define S2STATUS_HPP
#include <int128.hpp>
namespace primecount {
class S2Status
{
public:
S2Status(maxint_t x);
void print(maxint_t n, maxint_t limit);
void print(maxint_t n, maxint_t limit, double rsd);
double skewed_percent(maxint_t n, maxint_t limit) const;
private:
bool is_print(double time) const;
bool is_print(double time, double percent) const;
double old_percent_;
double old_time_;
double print_threshold_;
int precision_;
int precision_factor_;
};
} // namespace
#endif
<|endoftext|> |
<commit_before>/*
* Date: $Date: 2009-09-30 20:28:45 -0400 (Wed, 30 Sep 2009) $
* Version: $Revision: 243 $
* Author: $Author: kanterae@UPHS.PENNHEALTH.PRV $
* ID: $Id: invertDeformationField.cxx 243 2009-10-01 00:28:45Z kanterae@UPHS.PENNHEALTH.PRV $
*
* File Description
* Compute the inverse deformation field
*
* Copyright (c) 2009 by SBIA, Dept of Radiology, University of Pennsylvania
*
* This software is distributed WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the above copyright notices for more information.
*
**/
#include <iostream>
#include <getopt.h>
#include <sys/stat.h>
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkNiftiImageIO.h"
#include "itkImageIOFactory.h"
#include "itkVector.h"
#include "itkCommand.h"
#include "itkIterativeInverseDeformationFieldImageFilter.h"
#include "sbiaBasicUtilities.h"
#define INDENT "\t"
#define EXEC_NAME "invertDeformationField"
#define SVN_FILE_VERSION "$Id: $"
#ifndef SVN_REV
#define SVN_REV ""
#endif
#ifndef RELEASE_ID
#define RELEASE_ID "0.0_super_alpha"
#endif
using namespace std;
using namespace sbia;
void echoVersion()
{
std::cerr << std::endl << EXEC_NAME << std::endl <<
INDENT << " Release : " << RELEASE_ID << std::endl <<
INDENT << " Svn Revision : " << SVN_REV << std::endl <<
INDENT << " Svn File versions: " << SVN_FILE_VERSION << std::endl
<< std::endl;
}
static int verbose = 0;
static string default_ext;
class CommandProgressUpdate : public itk::Command
{
public:
typedef CommandProgressUpdate Self;
typedef itk::Command Superclass;
typedef itk::SmartPointer<Self> Pointer;
itkNewMacro( Self );
protected:
CommandProgressUpdate() {};
public:
void Execute(itk::Object *caller, const itk::EventObject & event)
{
Execute( (const itk::Object *)caller, event);
}
void Execute(const itk::Object * object, const itk::EventObject & event)
{
const itk::ProcessObject * filter =
dynamic_cast< const itk::ProcessObject * >( object );
if( ! itk::ProgressEvent().CheckEvent( &event ) )
{
return;
}
std::cout << filter->GetProgress() << std::endl;
}
};
// echoUsage:display usage information
void echoUsage() {
std::cerr
<< EXEC_NAME << "--\n"
<< INDENT << EXEC_NAME << " Compute the inverse deformation field using the itk filter.\n\n"
<< "Usage: "<< EXEC_NAME<<" [options]\n"
<< "Required Options:\n"
<< INDENT << "[-d --dataFile] Specify the input deformation field file (required)\n"
<< INDENT << "[-m --MovingFile] Specify a scalar image file to determine the output geometry (required)\n"
<< INDENT << "[-p --prefix] Prefix for result file\n"
<< "Options:\n"
<< INDENT << "[--i terations, -i] Number of iterations\n"
<< INDENT << "[--usage, -u] Display this message\n"
<< INDENT << "[--help, -h] Display this message\n"
<< INDENT << "[--Version, -V] Display version information\n"
<< INDENT << "[--verbose, -v] Turns on verbose output\n\n"
<< INDENT << "[-o --outputDir] The output directory to write the results\n"
<< INDENT << " Defaults to the location of the input file\n\n";
}
template < typename ImageType >
int
runner(string dataFile, string movingImageFile, string outputBasename, unsigned int NumIter)
{
typedef itk::IterativeInverseDeformationFieldImageFilter<ImageType,ImageType>
InverseDeformationImageFilter;
typename InverseDeformationImageFilter::Pointer filter =
InverseDeformationImageFilter::New();
typedef itk::ImageFileReader< ImageType > ImageReaderType;
typedef itk::ImageFileWriter< ImageType > ImageWriterType;
//Load the moving image to get the geometry!
typedef itk::ImageFileReader< itk::Image<float,3> > MovingImageReaderType;
typename MovingImageReaderType::Pointer mImageReader = MovingImageReaderType::New();
mImageReader->SetFileName( movingImageFile );
mImageReader->Update();
typename MovingImageReaderType::OutputImageType::Pointer
mImage = mImageReader->GetOutput();
typename ImageReaderType::Pointer imageReader = ImageReaderType::New();
imageReader->SetFileName( dataFile );
typename ImageWriterType::Pointer imageWriter = ImageWriterType::New();
imageWriter->SetFileName( outputBasename + default_ext );
imageWriter->SetImageIO( itk::NiftiImageIO::New() );
//~ imageWriter->SetFileName( outputBasename + ".mhd" );
imageReader->Update();
filter->SetInput( imageReader->GetOutput() );
if (verbose)
{
std::cout << "Running InverseDeformation filter " << std::endl;
typedef CommandProgressUpdate CommandIterationUpdateType;
typename CommandIterationUpdateType::Pointer observer = CommandIterationUpdateType::New();
filter->AddObserver( itk::IterationEvent(), observer );
}
imageWriter->SetInput( filter->GetOutput() ) ;
// imageWriter->SetInput( imageReader->GetOutput() ) ;
filter->SetNumberOfIterations(NumIter);
filter->Update();
imageWriter->Update();
return EXIT_SUCCESS;
}
int main(int argc, char** argv)
{
string outputDir="";
string dataFile,movingFile,prefix;
int outputDir_flag = 0;
int prefix_flag = 0;
unsigned int NumIter = 5;
static struct option long_options[] =
{
{"usage", no_argument, 0, 'u'},
{"help", no_argument, 0, 'h'},
{"Version", no_argument, 0, 'V'},
{"verbose", no_argument, 0, 'v'},
{"outputDir", required_argument, 0, 'o'},
{"dataFile", required_argument, 0, 'd'},
{"movingFile", required_argument, 0, 'm'},
{"prefix", required_argument, 0, 'p'},
{"iterations", required_argument, 0, 'i'}
};
int c, option_index = 0;
int reqParams = 0;
while ( (c = getopt_long (argc, argv, "uhVvno:d:p:m:i:",
long_options,&option_index)) != -1)
{
switch (c)
{
case 'u':
echoUsage();
return EXIT_SUCCESS;
case 'h':
echoUsage();
return EXIT_SUCCESS;
case 'V':
echoVersion();
return EXIT_SUCCESS;
case 'v':
verbose++;
break;
case 'i':
NumIter = atoi(optarg);
case 'o':
outputDir = optarg;
outputDir_flag = 1;
outputDir += "/";
break;
case 'd':
dataFile = optarg;
++reqParams;
break;
case 'm':
movingFile = optarg;
++reqParams;
break;
case 'p':
prefix = optarg;
prefix_flag = 1;
++reqParams;
break;
case '?':
/* getopt_long already printed an error message. */
break;
default:
abort ();
}
}
if ( reqParams < 3)
{
echoUsage();
cerr << "Please specify all required parameters!\n";
cerr << reqParams << endl;
return EXIT_FAILURE;
}
// filename parsing
std::string extension;
std::string bName;
std::string path;
sbia::splitFileName(dataFile,bName,extension,path);
if (extension == ".img")
{
std::cerr << "Please supply a header as input, not an .img !" << std::endl;
return EXIT_FAILURE;
}
std::string outputBasename = "";
if (outputDir_flag)
outputBasename += outputDir;
else
outputBasename += path;
if (prefix_flag)
outputBasename += prefix;
else
outputBasename += bName;
default_ext = extension;
//check for the existence of the input files.
if (! sbia::fileExists(dataFile))
{
std::cerr << dataFile << " Doesn't exist!!!\nExiting!\n\n" << std::endl;
echoUsage();
return EXIT_FAILURE;
}
if (verbose)
{
std::cerr << "dataFile : " << dataFile << std::endl;
std::cerr << "outputBaseName : " << outputBasename << std::endl;
}
//read in deformationField and figure out the pixeltype, imageDimension and Order
itk::ImageIOBase::Pointer imageIO;
imageIO = itk::ImageIOFactory::CreateImageIO( dataFile.c_str(),
itk::ImageIOFactory::ReadMode);
if ( imageIO )
{
imageIO->SetFileName(dataFile);
imageIO->ReadImageInformation();
//Unused
// itk::ImageIOBase::IOPixelType pixelType = imageIO->GetPixelType();
itk::ImageIOBase::IOComponentType componentType = imageIO->GetComponentType();
// unsigned int imageDimensions = 3; //Will need to get this out somehow?
///TODO should error if not 3
//Get the number of componants per pixel and compute the Order.
unsigned int nComps = imageIO->GetNumberOfComponents();
if (nComps != 3)
{
std::cout << "Unsupported number of componants : " << nComps << std::endl;
std::cout << "Deformation fields should have 3 components" << std::endl;
return EXIT_FAILURE;
}
switch ( componentType )
{
case itk::ImageIOBase::FLOAT:
{
return runner<itk::Image< itk::Vector<float,3>, 3> >(dataFile, movingFile, outputBasename, NumIter);
}
case itk::ImageIOBase::DOUBLE:
{
return runner<itk::Image<itk::Vector<double,3>, 3> >(dataFile, movingFile, outputBasename, NumIter);
}
default:
{
std::cout << "Unsupported componant Type : " << std::endl;
return EXIT_FAILURE;
}
}
}
else
{
std::cout << "Could not read the input image information from " <<
dataFile << std::endl;
return EXIT_FAILURE;
}
}
<commit_msg>Update invertDeformationField.cxx<commit_after>/*
* Date: $Date: 2009-09-30 20:28:45 -0400 (Wed, 30 Sep 2009) $
* Version: $Revision: 243 $
* Author: $Author: kanterae@UPHS.PENNHEALTH.PRV $
* ID: $Id: invertDeformationField.cxx 243 2009-10-01 00:28:45Z kanterae@UPHS.PENNHEALTH.PRV $
*
* File Description
* Compute the inverse deformation field
*
* Copyright 2011 Jihun Hamm and Donghye Ye
*
* This software is distributed WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the above copyright notices for more information.
*
**/
#include <iostream>
#include <getopt.h>
#include <sys/stat.h>
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkNiftiImageIO.h"
#include "itkImageIOFactory.h"
#include "itkVector.h"
#include "itkCommand.h"
#include "itkIterativeInverseDeformationFieldImageFilter.h"
#include "sbiaBasicUtilities.h"
#define INDENT "\t"
#define EXEC_NAME "invertDeformationField"
#define SVN_FILE_VERSION "$Id: $"
#ifndef SVN_REV
#define SVN_REV ""
#endif
#ifndef RELEASE_ID
#define RELEASE_ID "0.0_super_alpha"
#endif
using namespace std;
using namespace sbia;
void echoVersion()
{
std::cerr << std::endl << EXEC_NAME << std::endl <<
INDENT << " Release : " << RELEASE_ID << std::endl <<
INDENT << " Svn Revision : " << SVN_REV << std::endl <<
INDENT << " Svn File versions: " << SVN_FILE_VERSION << std::endl
<< std::endl;
}
static int verbose = 0;
static string default_ext;
class CommandProgressUpdate : public itk::Command
{
public:
typedef CommandProgressUpdate Self;
typedef itk::Command Superclass;
typedef itk::SmartPointer<Self> Pointer;
itkNewMacro( Self );
protected:
CommandProgressUpdate() {};
public:
void Execute(itk::Object *caller, const itk::EventObject & event)
{
Execute( (const itk::Object *)caller, event);
}
void Execute(const itk::Object * object, const itk::EventObject & event)
{
const itk::ProcessObject * filter =
dynamic_cast< const itk::ProcessObject * >( object );
if( ! itk::ProgressEvent().CheckEvent( &event ) )
{
return;
}
std::cout << filter->GetProgress() << std::endl;
}
};
// echoUsage:display usage information
void echoUsage() {
std::cerr
<< EXEC_NAME << "--\n"
<< INDENT << EXEC_NAME << " Compute the inverse deformation field using the itk filter.\n\n"
<< "Usage: "<< EXEC_NAME<<" [options]\n"
<< "Required Options:\n"
<< INDENT << "[-d --dataFile] Specify the input deformation field file (required)\n"
<< INDENT << "[-m --MovingFile] Specify a scalar image file to determine the output geometry (required)\n"
<< INDENT << "[-p --prefix] Prefix for result file\n"
<< "Options:\n"
<< INDENT << "[--i terations, -i] Number of iterations\n"
<< INDENT << "[--usage, -u] Display this message\n"
<< INDENT << "[--help, -h] Display this message\n"
<< INDENT << "[--Version, -V] Display version information\n"
<< INDENT << "[--verbose, -v] Turns on verbose output\n\n"
<< INDENT << "[-o --outputDir] The output directory to write the results\n"
<< INDENT << " Defaults to the location of the input file\n\n";
}
template < typename ImageType >
int
runner(string dataFile, string movingImageFile, string outputBasename, unsigned int NumIter)
{
typedef itk::IterativeInverseDeformationFieldImageFilter<ImageType,ImageType>
InverseDeformationImageFilter;
typename InverseDeformationImageFilter::Pointer filter =
InverseDeformationImageFilter::New();
typedef itk::ImageFileReader< ImageType > ImageReaderType;
typedef itk::ImageFileWriter< ImageType > ImageWriterType;
//Load the moving image to get the geometry!
typedef itk::ImageFileReader< itk::Image<float,3> > MovingImageReaderType;
typename MovingImageReaderType::Pointer mImageReader = MovingImageReaderType::New();
mImageReader->SetFileName( movingImageFile );
mImageReader->Update();
typename MovingImageReaderType::OutputImageType::Pointer
mImage = mImageReader->GetOutput();
typename ImageReaderType::Pointer imageReader = ImageReaderType::New();
imageReader->SetFileName( dataFile );
typename ImageWriterType::Pointer imageWriter = ImageWriterType::New();
imageWriter->SetFileName( outputBasename + default_ext );
imageWriter->SetImageIO( itk::NiftiImageIO::New() );
//~ imageWriter->SetFileName( outputBasename + ".mhd" );
imageReader->Update();
filter->SetInput( imageReader->GetOutput() );
if (verbose)
{
std::cout << "Running InverseDeformation filter " << std::endl;
typedef CommandProgressUpdate CommandIterationUpdateType;
typename CommandIterationUpdateType::Pointer observer = CommandIterationUpdateType::New();
filter->AddObserver( itk::IterationEvent(), observer );
}
imageWriter->SetInput( filter->GetOutput() ) ;
// imageWriter->SetInput( imageReader->GetOutput() ) ;
filter->SetNumberOfIterations(NumIter);
filter->Update();
imageWriter->Update();
return EXIT_SUCCESS;
}
int main(int argc, char** argv)
{
string outputDir="";
string dataFile,movingFile,prefix;
int outputDir_flag = 0;
int prefix_flag = 0;
unsigned int NumIter = 5;
static struct option long_options[] =
{
{"usage", no_argument, 0, 'u'},
{"help", no_argument, 0, 'h'},
{"Version", no_argument, 0, 'V'},
{"verbose", no_argument, 0, 'v'},
{"outputDir", required_argument, 0, 'o'},
{"dataFile", required_argument, 0, 'd'},
{"movingFile", required_argument, 0, 'm'},
{"prefix", required_argument, 0, 'p'},
{"iterations", required_argument, 0, 'i'}
};
int c, option_index = 0;
int reqParams = 0;
while ( (c = getopt_long (argc, argv, "uhVvno:d:p:m:i:",
long_options,&option_index)) != -1)
{
switch (c)
{
case 'u':
echoUsage();
return EXIT_SUCCESS;
case 'h':
echoUsage();
return EXIT_SUCCESS;
case 'V':
echoVersion();
return EXIT_SUCCESS;
case 'v':
verbose++;
break;
case 'i':
NumIter = atoi(optarg);
case 'o':
outputDir = optarg;
outputDir_flag = 1;
outputDir += "/";
break;
case 'd':
dataFile = optarg;
++reqParams;
break;
case 'm':
movingFile = optarg;
++reqParams;
break;
case 'p':
prefix = optarg;
prefix_flag = 1;
++reqParams;
break;
case '?':
/* getopt_long already printed an error message. */
break;
default:
abort ();
}
}
if ( reqParams < 3)
{
echoUsage();
cerr << "Please specify all required parameters!\n";
cerr << reqParams << endl;
return EXIT_FAILURE;
}
// filename parsing
std::string extension;
std::string bName;
std::string path;
sbia::splitFileName(dataFile,bName,extension,path);
if (extension == ".img")
{
std::cerr << "Please supply a header as input, not an .img !" << std::endl;
return EXIT_FAILURE;
}
std::string outputBasename = "";
if (outputDir_flag)
outputBasename += outputDir;
else
outputBasename += path;
if (prefix_flag)
outputBasename += prefix;
else
outputBasename += bName;
default_ext = extension;
//check for the existence of the input files.
if (! sbia::fileExists(dataFile))
{
std::cerr << dataFile << " Doesn't exist!!!\nExiting!\n\n" << std::endl;
echoUsage();
return EXIT_FAILURE;
}
if (verbose)
{
std::cerr << "dataFile : " << dataFile << std::endl;
std::cerr << "outputBaseName : " << outputBasename << std::endl;
}
//read in deformationField and figure out the pixeltype, imageDimension and Order
itk::ImageIOBase::Pointer imageIO;
imageIO = itk::ImageIOFactory::CreateImageIO( dataFile.c_str(),
itk::ImageIOFactory::ReadMode);
if ( imageIO )
{
imageIO->SetFileName(dataFile);
imageIO->ReadImageInformation();
//Unused
// itk::ImageIOBase::IOPixelType pixelType = imageIO->GetPixelType();
itk::ImageIOBase::IOComponentType componentType = imageIO->GetComponentType();
// unsigned int imageDimensions = 3; //Will need to get this out somehow?
///TODO should error if not 3
//Get the number of componants per pixel and compute the Order.
unsigned int nComps = imageIO->GetNumberOfComponents();
if (nComps != 3)
{
std::cout << "Unsupported number of componants : " << nComps << std::endl;
std::cout << "Deformation fields should have 3 components" << std::endl;
return EXIT_FAILURE;
}
switch ( componentType )
{
case itk::ImageIOBase::FLOAT:
{
return runner<itk::Image< itk::Vector<float,3>, 3> >(dataFile, movingFile, outputBasename, NumIter);
}
case itk::ImageIOBase::DOUBLE:
{
return runner<itk::Image<itk::Vector<double,3>, 3> >(dataFile, movingFile, outputBasename, NumIter);
}
default:
{
std::cout << "Unsupported componant Type : " << std::endl;
return EXIT_FAILURE;
}
}
}
else
{
std::cout << "Could not read the input image information from " <<
dataFile << std::endl;
return EXIT_FAILURE;
}
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: TestAMRUtilities.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include <iostream>
#include <sstream>
#include <cassert>
#include <mpi.h>
#include "vtkAMRUtilities.h"
#include "vtkAMRBox.h"
#include "vtkHierarchicalBoxDataSet.h"
#include "vtkMultiProcessController.h"
#include "vtkMPIController.h"
#include "vtkUniformGrid.h"
#include "vtkImageToStructuredGrid.h"
#include "vtkStructuredGridWriter.h"
//-----------------------------------------------------------------------------
// H E L P E R M E T H O D S & M A C R O S
//-----------------------------------------------------------------------------
#define CHECK_TEST( P, testName, rval ) { \
if( !P ) { \
std::cerr << "ERROR:" << testName << " FAILED!\n"; \
std::cerr << "Location:" << __FILE__ << ":" << __LINE__ << std::endl; \
std::cerr.flush(); \
++rval; \
} \
}
#define CHECK_CONDITION( P, shortMessage, status ) { \
if( !P ) { \
std::cerr << "ERROR:" << shortMessage << std::endl; \
std::cerr << "Location: " << __FILE__ << ":" << __LINE__ << std::endl;\
status = 0; \
return status; \
} \
}
//-----------------------------------------------------------------------------
// Description:
// Gets the grid for the given process
void WriteUniformGrid( vtkUniformGrid *myGrid, std::string prefix )
{
assert( "Input Grid is not NULL" && (myGrid != NULL) );
vtkImageToStructuredGrid* myImage2StructuredGridFilter =
vtkImageToStructuredGrid::New();
assert( "Cannot create Image2StructuredGridFilter" &&
(myImage2StructuredGridFilter != NULL) );
myImage2StructuredGridFilter->SetInput( myGrid );
myImage2StructuredGridFilter->Update();
vtkStructuredGrid* myStructuredGrid =
myImage2StructuredGridFilter->GetOutput();
assert( "Structured Grid output is NULL!" &&
(myStructuredGrid != NULL) );
vtkStructuredGridWriter *myWriter = vtkStructuredGridWriter::New();
myWriter->SetFileName( prefix.c_str() );
myWriter->SetInput( myStructuredGrid );
myWriter->Update();
myWriter->Delete();
myImage2StructuredGridFilter->Delete();
}
//-----------------------------------------------------------------------------
// Description:
// Gets the grid for the given process
int CheckMetaData( vtkHierarchicalBoxDataSet *myAMRData )
{
int status = 1;
vtkAMRBox myBox;
// STEP 0: Check metadata @(0,0)
if( myAMRData->GetMetaData( 0, 0, myBox ) == 1 )
{
CHECK_CONDITION((myBox.GetBlockId()==0),"BlockId mismatch", status );
CHECK_CONDITION((myBox.GetLevel()==0),"Level mismatch", status);
}
else
{
std::cerr << "Could not retrieve metadata for item @(0,0)!\n";
std::cerr.flush( );
status = 0;
}
// STEP 1: Check metadata @(1,0)
if( myAMRData->GetMetaData(1,0,myBox) == 1 )
{
}
else
{
std::cerr << "Could not retrieve metadata for item @(0,0)!\n";
std::cerr.flush( );
status = 0;
}
return( status );
}
//-----------------------------------------------------------------------------
// Description:
// Gets the grid for the given process
int CheckProcessData0( vtkHierarchicalBoxDataSet *myAMRData )
{
// Sanity Check
assert( "Input AMR dataset is NULL" && (myAMRData != NULL) );
int status = 1;
if( myAMRData->GetDataSet(0,0) == NULL )
{
std::cerr << "ERROR: Expected data to be non-NULL, but, data is NULL!\n";
std::cerr.flush();
status = 0;
}
else if( myAMRData->GetDataSet(1,0) != NULL )
{
std::cerr << "ERROR: Expected data to be NULL, but, data is NOT NULL!\n";
std::cerr.flush( );
status = 0;
}
else
{
status = CheckMetaData( myAMRData );
}
return status;
}
//-----------------------------------------------------------------------------
// Description:
// Gets the grid for the given process
int CheckProcessData1( vtkHierarchicalBoxDataSet *myAMRData )
{
// Sanity Check
assert( "Input AMR dataset is NULL" && (myAMRData != NULL) );
int status = 1;
if( myAMRData->GetDataSet(0,0) != NULL )
{
std::cerr << "ERROR: Expected data to be NULL, but, data is NOT NULL!\n";
std::cerr.flush();
status = 0;
}
else if( myAMRData->GetDataSet(1,0) == NULL )
{
std::cerr << "ERROR: Expected data to be non-NULL, but, data is NULL!\n";
std::cerr.flush( );
status = 0;
}
else
{
status = CheckMetaData( myAMRData );
}
return status;
}
//-----------------------------------------------------------------------------
// Description:
// Gets the grid for the given process
void GetGrid( vtkUniformGrid *myGrid, int &level, int &index,
vtkMultiProcessController *myController )
{
assert( "Input Grid is not NULL" && (myGrid != NULL) );
assert( "Null Multi-process controller encountered" &&
(myController != NULL) );
switch( myController->GetLocalProcessId() )
{
case 0:
{
level=index=0;
double myOrigin[3] = {0.0,0.0,0.0};
int ndim[3] = {4,4,1};
double spacing[3] = {1,1,1};
myGrid->Initialize();
myGrid->SetOrigin( myOrigin );
myGrid->SetSpacing( spacing );
myGrid->SetDimensions( ndim );
}
break;
case 1:
{
level=1;index=0;
double myOrigin[3] = {1.0,1.0,0.0};
int ndim[3] = {5,3,1};
double spacing[3] = {0.5,0.5,0.5};
myGrid->Initialize();
myGrid->SetOrigin( myOrigin );
myGrid->SetSpacing( spacing );
myGrid->SetDimensions( ndim );
}
break;
default:
std::cerr << "Undefined process!\n";
std::cerr.flush();
myGrid->Delete();
myGrid=NULL;
}
}
//-----------------------------------------------------------------------------
// Description:
// Get the AMR data-structure for the given process
void GetAMRDataSet(
vtkHierarchicalBoxDataSet *amrData,
vtkMultiProcessController *myController )
{
assert( "Input AMR Data is NULL!" && (amrData != NULL) );
assert( "Null Multi-process controller encountered" &&
(myController != NULL) );
int level = -1;
int index = -1;
vtkUniformGrid* myGrid = vtkUniformGrid::New();
GetGrid( myGrid, level, index, myController );
assert( "Invalid level" && (level >= 0) );
assert( "Invalid index" && (index >= 0) );
std::ostringstream oss;
oss.clear();
oss.str("");
oss << "Process_" << myController->GetLocalProcessId() << "_GRID_";
oss << "L" << level << "_" << index << ".vtk";
WriteUniformGrid( myGrid, oss.str( ) );
amrData->SetDataSet( level, index, myGrid );
myGrid->Delete();
}
//-----------------------------------------------------------------------------
// T E S T M E T H O D S
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Description:
// Tests the functionality for computing the global data-set origin.
bool TestComputeDataSetOrigin( vtkMultiProcessController *myController )
{
assert( "Null Multi-process controller encountered" &&
(myController != NULL) );
myController->Barrier();
vtkHierarchicalBoxDataSet* myAMRData = vtkHierarchicalBoxDataSet::New();
GetAMRDataSet( myAMRData, myController );
double origin[3];
vtkAMRUtilities::ComputeDataSetOrigin( origin, myAMRData, myController );
myAMRData->Delete();
int status = 0;
int statusSum = 0;
if( (origin[0] == 0.0) && (origin[1] == 0.0) && (origin[2] == 0.0) )
status = 1;
myController->AllReduce( &status, &statusSum, 1, vtkCommunicator::SUM_OP );
return( ( (statusSum==2)? true : false ) );
}
//-----------------------------------------------------------------------------
// Description:
// Tests the functionality for computing the global data-set origin.
bool TestCollectMetaData( vtkMultiProcessController *myController )
{
assert( "Null Multi-process controller encountered" &&
(myController != NULL) );
myController->Barrier();
vtkHierarchicalBoxDataSet* myAMRData = vtkHierarchicalBoxDataSet::New();
GetAMRDataSet( myAMRData, myController );
vtkAMRUtilities::CollectAMRMetaData( myAMRData, myController );
int status = 0;
int statusSum = 0;
switch( myController->GetLocalProcessId() )
{
case 0:
status = CheckProcessData0( myAMRData );
break;
case 1:
status = CheckProcessData1( myAMRData );
break;
default:
std::cerr << "ERROR: This test must be run with 2 MPI processes!\n";
std::cerr.flush( );
status = 0;
}
myAMRData->Delete();
myController->AllReduce( &status, &statusSum, 1, vtkCommunicator::SUM_OP );
return ( (statusSum==2)? true : false );
}
//-----------------------------------------------------------------------------
// Description:
// Main Test driver
int TestAMRUtilities(int,char*[])
{
vtkMultiProcessController *myController =
vtkMultiProcessController::GetGlobalController();
assert( "Null Multi-process controller encountered" &&
(myController != NULL) );
// Synchronize Processes
myController->Barrier();
int rval=0;
CHECK_TEST( TestComputeDataSetOrigin(myController),"ComputeOrigin", rval );
CHECK_TEST( TestCollectMetaData(myController), "CollectMetaData", rval );
// Synchronize Processes
myController->Barrier();
return( rval );
}
//-----------------------------------------------------------------------------
// P R O G R A M M A I N
//-----------------------------------------------------------------------------
int main( int argc, char **argv )
{
MPI_Init(&argc,&argv);
vtkMPIController* contr = vtkMPIController::New();
contr->Initialize( &argc, &argv, 1);
vtkMultiProcessController::SetGlobalController(contr);
int rc = TestAMRUtilities( argc, argv );
contr->Barrier();
contr->Finalize();
contr->Delete();
return rc;
}
<commit_msg>ENH: More checks for metadata creation/migration<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: TestAMRUtilities.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include <iostream>
#include <sstream>
#include <cassert>
#include <mpi.h>
#include "vtkAMRUtilities.h"
#include "vtkAMRBox.h"
#include "vtkHierarchicalBoxDataSet.h"
#include "vtkMultiProcessController.h"
#include "vtkMPIController.h"
#include "vtkUniformGrid.h"
#include "vtkImageToStructuredGrid.h"
#include "vtkStructuredGridWriter.h"
//-----------------------------------------------------------------------------
// H E L P E R M E T H O D S & M A C R O S
//-----------------------------------------------------------------------------
#define CHECK_TEST( P, testName, rval ) { \
if( !P ) { \
std::cerr << "ERROR:" << testName << " FAILED!\n"; \
std::cerr << "Location:" << __FILE__ << ":" << __LINE__ << std::endl; \
std::cerr.flush(); \
++rval; \
} \
}
#define CHECK_CONDITION( P, shortMessage, status ) { \
if( !P ) { \
std::cerr << "ERROR:" << shortMessage << std::endl; \
std::cerr << "Location: " << __FILE__ << ":" << __LINE__ << std::endl;\
status = 0; \
return status; \
} \
}
//-----------------------------------------------------------------------------
// Description:
// Gets the grid for the given process
void WriteUniformGrid( vtkUniformGrid *myGrid, std::string prefix )
{
assert( "Input Grid is not NULL" && (myGrid != NULL) );
vtkImageToStructuredGrid* myImage2StructuredGridFilter =
vtkImageToStructuredGrid::New();
assert( "Cannot create Image2StructuredGridFilter" &&
(myImage2StructuredGridFilter != NULL) );
myImage2StructuredGridFilter->SetInput( myGrid );
myImage2StructuredGridFilter->Update();
vtkStructuredGrid* myStructuredGrid =
myImage2StructuredGridFilter->GetOutput();
assert( "Structured Grid output is NULL!" &&
(myStructuredGrid != NULL) );
vtkStructuredGridWriter *myWriter = vtkStructuredGridWriter::New();
myWriter->SetFileName( prefix.c_str() );
myWriter->SetInput( myStructuredGrid );
myWriter->Update();
myWriter->Delete();
myImage2StructuredGridFilter->Delete();
}
//-----------------------------------------------------------------------------
// Description:
// Gets the grid for the given process
int CheckMetaData( vtkHierarchicalBoxDataSet *myAMRData )
{
int status = 1;
vtkAMRBox myBox;
// STEP 0: Check metadata @(0,0)
if( myAMRData->GetMetaData( 0, 0, myBox ) == 1 )
{
CHECK_CONDITION((myBox.GetBlockId()==0),"BlockId mismatch", status );
CHECK_CONDITION((myBox.GetLevel()==0),"Level mismatch", status);
CHECK_CONDITION((myBox.GetProcessId()==0),"Process ID mismatch",status);
int lo[3]; int hi[3];
myBox.GetLoCorner( lo );
myBox.GetHiCorner( hi );
CHECK_CONDITION((lo[0]==0),"LoCorner mismatch",status);
CHECK_CONDITION((lo[1]==0),"LoCorner mismatch",status);
CHECK_CONDITION((lo[2]==0),"LoCorner mismatch",status);
CHECK_CONDITION((hi[0]==2),"HiCorner mismatch",status);
CHECK_CONDITION((hi[1]==2),"HiCorner mismatch",status);
CHECK_CONDITION((hi[2]==0),"HiCorner mismatch",status);
double spacing[3];
myBox.GetGridSpacing( spacing );
CHECK_CONDITION((spacing[0]==1.0),"Check grid spacing",status);
CHECK_CONDITION((spacing[1]==1.0),"Check grid spacing",status);
CHECK_CONDITION((spacing[2]==1.0),"Check grid spacing",status);
}
else
{
std::cerr << "Could not retrieve metadata for item @(0,0)!\n";
std::cerr.flush( );
status = 0;
}
// STEP 1: Check metadata @(1,0)
if( myAMRData->GetMetaData(1,0,myBox) == 1 )
{
CHECK_CONDITION((myBox.GetBlockId()==0),"BlockId mismatch", status );
CHECK_CONDITION((myBox.GetLevel()==1),"Level mismatch", status);
CHECK_CONDITION((myBox.GetProcessId()==1),"Process ID mismatch",status);
int lo[3]; int hi[3];
myBox.GetLoCorner( lo );
myBox.GetHiCorner( hi );
CHECK_CONDITION((lo[0]==2),"LoCorner mismatch",status);
CHECK_CONDITION((lo[1]==2),"LoCorner mismatch",status);
CHECK_CONDITION((lo[2]==0),"LoCorner mismatch",status);
CHECK_CONDITION((hi[0]==5),"HiCorner mismatch",status);
CHECK_CONDITION((hi[1]==3),"HiCorner mismatch",status);
CHECK_CONDITION((hi[2]==0),"HiCorner mismatch",status);
double spacing[3];
myBox.GetGridSpacing( spacing );
CHECK_CONDITION((spacing[0]==0.5),"Check grid spacing",status);
CHECK_CONDITION((spacing[1]==0.5),"Check grid spacing",status);
CHECK_CONDITION((spacing[2]==0.5),"Check grid spacing",status);
}
else
{
std::cerr << "Could not retrieve metadata for item @(0,0)!\n";
std::cerr.flush( );
status = 0;
}
return( status );
}
//-----------------------------------------------------------------------------
// Description:
// Gets the grid for the given process
int CheckProcessData0( vtkHierarchicalBoxDataSet *myAMRData )
{
// Sanity Check
assert( "Input AMR dataset is NULL" && (myAMRData != NULL) );
int status = 1;
if( myAMRData->GetDataSet(0,0) == NULL )
{
std::cerr << "ERROR: Expected data to be non-NULL, but, data is NULL!\n";
std::cerr.flush();
status = 0;
}
else if( myAMRData->GetDataSet(1,0) != NULL )
{
std::cerr << "ERROR: Expected data to be NULL, but, data is NOT NULL!\n";
std::cerr.flush( );
status = 0;
}
else
{
status = CheckMetaData( myAMRData );
}
return status;
}
//-----------------------------------------------------------------------------
// Description:
// Gets the grid for the given process
int CheckProcessData1( vtkHierarchicalBoxDataSet *myAMRData )
{
// Sanity Check
assert( "Input AMR dataset is NULL" && (myAMRData != NULL) );
int status = 1;
if( myAMRData->GetDataSet(0,0) != NULL )
{
std::cerr << "ERROR: Expected data to be NULL, but, data is NOT NULL!\n";
std::cerr.flush();
status = 0;
}
else if( myAMRData->GetDataSet(1,0) == NULL )
{
std::cerr << "ERROR: Expected data to be non-NULL, but, data is NULL!\n";
std::cerr.flush( );
status = 0;
}
else
{
status = CheckMetaData( myAMRData );
}
return status;
}
//-----------------------------------------------------------------------------
// Description:
// Gets the grid for the given process
void GetGrid( vtkUniformGrid *myGrid, int &level, int &index,
vtkMultiProcessController *myController )
{
assert( "Input Grid is not NULL" && (myGrid != NULL) );
assert( "Null Multi-process controller encountered" &&
(myController != NULL) );
switch( myController->GetLocalProcessId() )
{
case 0:
{
level=index=0;
double myOrigin[3] = {0.0,0.0,0.0};
int ndim[3] = {4,4,1};
double spacing[3] = {1,1,1};
myGrid->Initialize();
myGrid->SetOrigin( myOrigin );
myGrid->SetSpacing( spacing );
myGrid->SetDimensions( ndim );
}
break;
case 1:
{
level=1;index=0;
double myOrigin[3] = {1.0,1.0,0.0};
int ndim[3] = {5,3,1};
double spacing[3] = {0.5,0.5,0.5};
myGrid->Initialize();
myGrid->SetOrigin( myOrigin );
myGrid->SetSpacing( spacing );
myGrid->SetDimensions( ndim );
}
break;
default:
std::cerr << "Undefined process!\n";
std::cerr.flush();
myGrid->Delete();
myGrid=NULL;
}
}
//-----------------------------------------------------------------------------
// Description:
// Get the AMR data-structure for the given process
void GetAMRDataSet(
vtkHierarchicalBoxDataSet *amrData,
vtkMultiProcessController *myController )
{
assert( "Input AMR Data is NULL!" && (amrData != NULL) );
assert( "Null Multi-process controller encountered" &&
(myController != NULL) );
int level = -1;
int index = -1;
vtkUniformGrid* myGrid = vtkUniformGrid::New();
GetGrid( myGrid, level, index, myController );
assert( "Invalid level" && (level >= 0) );
assert( "Invalid index" && (index >= 0) );
std::ostringstream oss;
oss.clear();
oss.str("");
oss << "Process_" << myController->GetLocalProcessId() << "_GRID_";
oss << "L" << level << "_" << index << ".vtk";
WriteUniformGrid( myGrid, oss.str( ) );
amrData->SetDataSet( level, index, myGrid );
myGrid->Delete();
}
//-----------------------------------------------------------------------------
// T E S T M E T H O D S
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Description:
// Tests the functionality for computing the global data-set origin.
bool TestComputeDataSetOrigin( vtkMultiProcessController *myController )
{
assert( "Null Multi-process controller encountered" &&
(myController != NULL) );
myController->Barrier();
vtkHierarchicalBoxDataSet* myAMRData = vtkHierarchicalBoxDataSet::New();
GetAMRDataSet( myAMRData, myController );
double origin[3];
vtkAMRUtilities::ComputeDataSetOrigin( origin, myAMRData, myController );
myAMRData->Delete();
int status = 0;
int statusSum = 0;
if( (origin[0] == 0.0) && (origin[1] == 0.0) && (origin[2] == 0.0) )
status = 1;
myController->AllReduce( &status, &statusSum, 1, vtkCommunicator::SUM_OP );
return( ( (statusSum==2)? true : false ) );
}
//-----------------------------------------------------------------------------
// Description:
// Tests the functionality for computing the global data-set origin.
bool TestCollectMetaData( vtkMultiProcessController *myController )
{
assert( "Null Multi-process controller encountered" &&
(myController != NULL) );
myController->Barrier();
vtkHierarchicalBoxDataSet* myAMRData = vtkHierarchicalBoxDataSet::New();
GetAMRDataSet( myAMRData, myController );
vtkAMRUtilities::CollectAMRMetaData( myAMRData, myController );
int status = 0;
int statusSum = 0;
switch( myController->GetLocalProcessId() )
{
case 0:
status = CheckProcessData0( myAMRData );
break;
case 1:
status = CheckProcessData1( myAMRData );
break;
default:
std::cerr << "ERROR: This test must be run with 2 MPI processes!\n";
std::cerr.flush( );
status = 0;
}
myAMRData->Delete();
myController->AllReduce( &status, &statusSum, 1, vtkCommunicator::SUM_OP );
return ( (statusSum==2)? true : false );
}
//-----------------------------------------------------------------------------
// Description:
// Main Test driver
int TestAMRUtilities(int,char*[])
{
vtkMultiProcessController *myController =
vtkMultiProcessController::GetGlobalController();
assert( "Null Multi-process controller encountered" &&
(myController != NULL) );
// Synchronize Processes
myController->Barrier();
int rval=0;
CHECK_TEST( TestComputeDataSetOrigin(myController),"ComputeOrigin", rval );
CHECK_TEST( TestCollectMetaData(myController), "CollectMetaData", rval );
// Synchronize Processes
myController->Barrier();
return( rval );
}
//-----------------------------------------------------------------------------
// P R O G R A M M A I N
//-----------------------------------------------------------------------------
int main( int argc, char **argv )
{
MPI_Init(&argc,&argv);
vtkMPIController* contr = vtkMPIController::New();
contr->Initialize( &argc, &argv, 1);
vtkMultiProcessController::SetGlobalController(contr);
int rc = TestAMRUtilities( argc, argv );
contr->Barrier();
contr->Finalize();
contr->Delete();
return rc;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) Aleksey Fedotov
MIT license
*/
#define VK_USE_PLATFORM_WIN32_KHR
#include <vulkan.h>
#include <SDL.h>
#include <SDL_syswm.h>
#include <windows.h>
#include <vector>
int main()
{
SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_EVENTS);
auto window = SDL_CreateWindow("Demo", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_ALLOW_HIGHDPI);
VkApplicationInfo appInfo {};
appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
appInfo.pApplicationName = "";
appInfo.pEngineName = "";
appInfo.apiVersion = VK_API_VERSION_1_0;
std::vector<const char *> enabledExtensions {
VK_KHR_SURFACE_EXTENSION_NAME,
VK_KHR_WIN32_SURFACE_EXTENSION_NAME,
VK_EXT_DEBUG_REPORT_EXTENSION_NAME
};
std::vector<const char *> enabledLayers {
"VK_LAYER_LUNARG_standard_validation",
};
VkInstanceCreateInfo instanceInfo {};
instanceInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
instanceInfo.pNext = nullptr;
instanceInfo.pApplicationInfo = &appInfo;
if (!enabledLayers.empty())
{
instanceInfo.enabledLayerCount = enabledLayers.size();
instanceInfo.ppEnabledLayerNames = enabledLayers.data();
}
if (!enabledExtensions.empty())
{
instanceInfo.enabledExtensionCount = static_cast<uint32_t>(enabledExtensions.size());
instanceInfo.ppEnabledExtensionNames = enabledExtensions.data();
}
VkInstance instance;
vkCreateInstance(&instanceInfo, nullptr, &instance);
SDL_Quit();
return 0;
}
<commit_msg>Basic event loop in Vulkan demo<commit_after>/*
Copyright (c) Aleksey Fedotov
MIT license
*/
#include "Common/Input.h"
#define VK_USE_PLATFORM_WIN32_KHR
#include <vulkan.h>
#include <SDL.h>
#include <SDL_syswm.h>
#include <windows.h>
#include <vector>
int main()
{
SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_EVENTS);
auto window = SDL_CreateWindow("Demo", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_ALLOW_HIGHDPI);
VkApplicationInfo appInfo {};
appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
appInfo.pApplicationName = "";
appInfo.pEngineName = "";
appInfo.apiVersion = VK_API_VERSION_1_0;
std::vector<const char *> enabledExtensions {
VK_KHR_SURFACE_EXTENSION_NAME,
VK_KHR_WIN32_SURFACE_EXTENSION_NAME,
VK_EXT_DEBUG_REPORT_EXTENSION_NAME
};
std::vector<const char *> enabledLayers {
"VK_LAYER_LUNARG_standard_validation",
};
VkInstanceCreateInfo instanceInfo {};
instanceInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
instanceInfo.pNext = nullptr;
instanceInfo.pApplicationInfo = &appInfo;
if (!enabledLayers.empty())
{
instanceInfo.enabledLayerCount = enabledLayers.size();
instanceInfo.ppEnabledLayerNames = enabledLayers.data();
}
if (!enabledExtensions.empty())
{
instanceInfo.enabledExtensionCount = static_cast<uint32_t>(enabledExtensions.size());
instanceInfo.ppEnabledExtensionNames = enabledExtensions.data();
}
VkInstance instance;
vkCreateInstance(&instanceInfo, nullptr, &instance);
Input input;
auto run = true;
auto lastTime = 0.0f;
while (run)
{
input.beginUpdate(window);
SDL_Event evt;
while (SDL_PollEvent(&evt))
{
input.processEvent(evt);
if (evt.type == SDL_QUIT ||
evt.type == SDL_WINDOWEVENT && evt.window.event == SDL_WINDOWEVENT_CLOSE ||
evt.type == SDL_KEYUP && evt.key.keysym.sym == SDLK_ESCAPE)
{
run = false;
}
}
auto time = SDL_GetTicks() / 1000.0f;
auto dt = time - lastTime;
lastTime = time;
}
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
<|endoftext|> |
<commit_before>/* Definitions for the pqxx::result class and support classes.
*
* pqxx::result represents the set of result rows from a database query.
*
* DO NOT INCLUDE THIS FILE DIRECTLY; include pqxx/result instead.
*
* Copyright (c) 2000-2019, Jeroen T. Vermeulen.
*
* See COPYING for copyright license. If you did not receive a file called
* COPYING with this source code, please notify the distributor of this mistake,
* or contact the author.
*/
#ifndef PQXX_H_ROW
#define PQXX_H_ROW
#include "pqxx/compiler-public.hxx"
#include "pqxx/internal/compiler-internal-pre.hxx"
#include "pqxx/except.hxx"
#include "pqxx/field.hxx"
#include "pqxx/result.hxx"
// Methods tested in eg. test module test01 are marked with "//[t01]".
namespace pqxx
{
/// Reference to one row in a result.
/** A row represents one row (also called a row) in a query result set.
* It also acts as a container mapping column numbers or names to field
* values (see below):
*
* @code
* cout << row["date"].c_str() << ": " << row["name"].c_str() << endl;
* @endcode
*
* The row itself acts like a (non-modifyable) container, complete with its
* own const_iterator and const_reverse_iterator.
*/
class PQXX_LIBEXPORT row
{
public:
using size_type = row_size_type;
using difference_type = row_difference_type;
using const_iterator = const_row_iterator;
using iterator = const_iterator;
using reference = field;
using pointer = const_row_iterator;
using const_reverse_iterator = const_reverse_row_iterator;
using reverse_iterator = const_reverse_iterator;
row() =default;
/// @deprecated Do not use this constructor. It will become private.
row(result r, size_t i) noexcept;
/**
* @name Comparison
*/
//@{
PQXX_PURE bool operator==(const row &) const noexcept; //[t75]
bool operator!=(const row &rhs) const noexcept //[t75]
{ return not operator==(rhs); }
//@}
const_iterator begin() const noexcept; //[t82]
const_iterator cbegin() const noexcept;
const_iterator end() const noexcept; //[t82]
const_iterator cend() const noexcept;
/**
* @name Field access
*/
//@{
reference front() const noexcept; //[t74]
reference back() const noexcept; //[t75]
const_reverse_row_iterator rbegin() const; //[t82]
const_reverse_row_iterator crbegin() const;
const_reverse_row_iterator rend() const; //[t82]
const_reverse_row_iterator crend() const;
reference operator[](size_type) const noexcept; //[t11]
reference operator[](int) const noexcept; //[t02]
/** Address field by name.
* @warning This is much slower than indexing by number, or iterating.
*/
reference operator[](const char[]) const; //[t11]
/** Address field by name.
* @warning This is much slower than indexing by number, or iterating.
*/
reference operator[](const std::string &s) const //[t11]
{ return (*this)[s.c_str()]; }
reference at(size_type) const; //[t11]
reference at(int) const; //[t11]
/** Address field by name.
* @warning This is much slower than indexing by number, or iterating.
*/
reference at(const char[]) const; //[t11]
/** Address field by name.
* @warning This is much slower than indexing by number, or iterating.
*/
reference at(const std::string &s) const //[t11]
{ return at(s.c_str()); }
//@}
size_type size() const noexcept //[t11]
{ return m_end-m_begin; }
void swap(row &) noexcept; //[t11]
/// Row number, assuming this is a real row and not end()/rend().
size_t rownumber() const noexcept { return size_t(m_index); } //[t11]
/**
* @name Column information
*/
//@{
/// Number of given column (throws exception if it doesn't exist).
size_type column_number(const std::string &ColName) const //[t30]
{ return column_number(ColName.c_str()); }
/// Number of given column (throws exception if it doesn't exist).
size_type column_number(const char[]) const; //[t30]
/// Return a column's type.
oid column_type(size_type) const; //[t07]
/// Return a column's type.
oid column_type(int ColNum) const //[t07]
{ return column_type(size_type(ColNum)); }
/// Return a column's type.
template<typename STRING>
oid column_type(STRING ColName) const //[t07]
{ return column_type(column_number(ColName)); }
/// What table did this column come from?
oid column_table(size_type ColNum) const; //[t02]
/// What table did this column come from?
oid column_table(int ColNum) const //[t02]
{ return column_table(size_type(ColNum)); }
/// What table did this column come from?
template<typename STRING>
oid column_table(STRING ColName) const //[t02]
{ return column_table(column_number(ColName)); }
/// What column number in its table did this result column come from?
/** A meaningful answer can be given only if the column in question comes
* directly from a column in a table. If the column is computed in any
* other way, a logic_error will be thrown.
*
* @param ColNum a zero-based column number in this result set
* @return a zero-based column number in originating table
*/
size_type table_column(size_type) const; //[t93]
/// What column number in its table did this result column come from?
size_type table_column(int ColNum) const //[t93]
{ return table_column(size_type(ColNum)); }
/// What column number in its table did this result column come from?
template<typename STRING>
size_type table_column(STRING ColName) const //[t93]
{ return table_column(column_number(ColName)); }
//@}
size_t num() const { return rownumber(); } //[t01]
/** Produce a slice of this row, containing the given range of columns.
*
* The slice runs from the range's starting column to the range's end
* column, exclusive. It looks just like a normal result row, except
* slices can be empty.
*
* @warning Slicing is a relatively new feature, and not all software may be
* prepared to deal with empty slices. If there is any chance that your
* program might be creating empty slices and passing them to code that may
* not be designed with the possibility of empty rows in mind, be sure to
* test for that case.
*/
row slice(size_type Begin, size_type End) const;
// Is this an empty slice?
PQXX_PURE bool empty() const noexcept;
protected:
friend class field;
/// Result set of which this is one row.
result m_result;
/// Row number.
/**
* You'd expect this to be a size_t, but due to the way reverse iterators
* are related to regular iterators, it must be allowed to underflow to -1.
*/
long m_index = 0;
/// First column in slice. This row ignores lower-numbered columns.
size_type m_begin = 0;
/// End column in slice. This row only sees lower-numbered columns.
size_type m_end = 0;
};
/// Iterator for fields in a row. Use as row::const_iterator.
class PQXX_LIBEXPORT const_row_iterator : public field
{
public:
using iterator_category = std::random_access_iterator_tag;
using value_type = const field;
using pointer = const field *;
using size_type = row_size_type;
using difference_type = row_difference_type;
using reference = field;
const_row_iterator(const row &T, row_size_type C) noexcept : //[t82]
field{T, C} {}
const_row_iterator(const field &F) noexcept : field{F} {} //[t82]
/**
* @name Dereferencing operators
*/
//@{
pointer operator->() const { return this; } //[t82]
reference operator*() const { return field{*this}; } //[t82]
//@}
/**
* @name Manipulations
*/
//@{
const_row_iterator operator++(int); //[t82]
const_row_iterator &operator++() { ++m_col; return *this; } //[t82]
const_row_iterator operator--(int); //[t82]
const_row_iterator &operator--() { --m_col; return *this; } //[t82]
const_row_iterator &operator+=(difference_type i) //[t82]
{ m_col = size_type(difference_type(m_col) + i); return *this; }
const_row_iterator &operator-=(difference_type i) //[t82]
{ m_col = size_type(difference_type(m_col) - i); return *this; }
//@}
/**
* @name Comparisons
*/
//@{
bool operator==(const const_row_iterator &i) const //[t82]
{return col()==i.col();}
bool operator!=(const const_row_iterator &i) const //[t82]
{return col()!=i.col();}
bool operator<(const const_row_iterator &i) const //[t82]
{return col()<i.col();}
bool operator<=(const const_row_iterator &i) const //[t82]
{return col()<=i.col();}
bool operator>(const const_row_iterator &i) const //[t82]
{return col()>i.col();}
bool operator>=(const const_row_iterator &i) const //[t82]
{return col()>=i.col();}
//@}
/**
* @name Arithmetic operators
*/
//@{
inline const_row_iterator operator+(difference_type) const; //[t82]
friend const_row_iterator operator+( //[t82]
difference_type,
const_row_iterator);
inline const_row_iterator operator-(difference_type) const; //[t82]
inline difference_type operator-(const_row_iterator) const; //[t82]
//@}
};
/// Reverse iterator for a row. Use as row::const_reverse_iterator.
class PQXX_LIBEXPORT const_reverse_row_iterator : private const_row_iterator
{
public:
using super = const_row_iterator;
using iterator_type = const_row_iterator;
using iterator_type::iterator_category;
using iterator_type::difference_type;
using iterator_type::pointer;
using value_type = iterator_type::value_type;
using reference = iterator_type::reference;
const_reverse_row_iterator(const const_reverse_row_iterator &r) : //[t82]
const_row_iterator{r} {}
explicit
const_reverse_row_iterator(const super &rhs) noexcept : //[t82]
const_row_iterator{rhs} { super::operator--(); }
PQXX_PURE iterator_type base() const noexcept; //[t82]
/**
* @name Dereferencing operators
*/
//@{
using iterator_type::operator->; //[t82]
using iterator_type::operator*; //[t82]
//@}
/**
* @name Manipulations
*/
//@{
const_reverse_row_iterator &
operator=(const const_reverse_row_iterator &r) //[t82]
{ iterator_type::operator=(r); return *this; }
const_reverse_row_iterator operator++() //[t82]
{ iterator_type::operator--(); return *this; }
const_reverse_row_iterator operator++(int); //[t82]
const_reverse_row_iterator &operator--() //[t82]
{ iterator_type::operator++(); return *this; }
const_reverse_row_iterator operator--(int); //[t82]
const_reverse_row_iterator &operator+=(difference_type i) //[t82]
{ iterator_type::operator-=(i); return *this; }
const_reverse_row_iterator &operator-=(difference_type i) //[t82]
{ iterator_type::operator+=(i); return *this; }
//@}
/**
* @name Arithmetic operators
*/
//@{
const_reverse_row_iterator operator+(difference_type i) const //[t82]
{ return const_reverse_row_iterator{base()-i}; }
const_reverse_row_iterator operator-(difference_type i) //[t82]
{ return const_reverse_row_iterator{base()+i}; }
difference_type
operator-(const const_reverse_row_iterator &rhs) const //[t82]
{ return rhs.const_row_iterator::operator-(*this); }
//@}
/**
* @name Comparisons
*/
//@{
bool operator==(const const_reverse_row_iterator &rhs) const noexcept //[t82]
{ return iterator_type::operator==(rhs); }
bool operator!=(const const_reverse_row_iterator &rhs) const noexcept //[t82]
{ return !operator==(rhs); }
bool operator<(const const_reverse_row_iterator &rhs) const //[t82]
{ return iterator_type::operator>(rhs); }
bool operator<=(const const_reverse_row_iterator &rhs) const //[t82]
{ return iterator_type::operator>=(rhs); }
bool operator>(const const_reverse_row_iterator &rhs) const //[t82]
{ return iterator_type::operator<(rhs); }
bool operator>=(const const_reverse_row_iterator &rhs) const //[t82]
{ return iterator_type::operator<=(rhs); }
//@}
};
inline const_row_iterator
const_row_iterator::operator+(difference_type o) const
{
return const_row_iterator{
row(home(), idx()),
size_type(difference_type(col()) + o)};
}
inline const_row_iterator
operator+(const_row_iterator::difference_type o, const_row_iterator i)
{ return i + o; }
inline const_row_iterator
const_row_iterator::operator-(difference_type o) const
{
return const_row_iterator{
row(home(), idx()),
size_type(difference_type(col()) - o)};
}
inline const_row_iterator::difference_type
const_row_iterator::operator-(const_row_iterator i) const
{ return difference_type(num() - i.num()); }
} // namespace pqxx
#include "pqxx/internal/compiler-internal-post.hxx"
#endif
<commit_msg>Try exporting members, not classes.<commit_after>/* Definitions for the pqxx::result class and support classes.
*
* pqxx::result represents the set of result rows from a database query.
*
* DO NOT INCLUDE THIS FILE DIRECTLY; include pqxx/result instead.
*
* Copyright (c) 2000-2019, Jeroen T. Vermeulen.
*
* See COPYING for copyright license. If you did not receive a file called
* COPYING with this source code, please notify the distributor of this mistake,
* or contact the author.
*/
#ifndef PQXX_H_ROW
#define PQXX_H_ROW
#include "pqxx/compiler-public.hxx"
#include "pqxx/internal/compiler-internal-pre.hxx"
#include "pqxx/except.hxx"
#include "pqxx/field.hxx"
#include "pqxx/result.hxx"
// Methods tested in eg. test module test01 are marked with "//[t01]".
namespace pqxx
{
/// Reference to one row in a result.
/** A row represents one row (also called a row) in a query result set.
* It also acts as a container mapping column numbers or names to field
* values (see below):
*
* @code
* cout << row["date"].c_str() << ": " << row["name"].c_str() << endl;
* @endcode
*
* The row itself acts like a (non-modifyable) container, complete with its
* own const_iterator and const_reverse_iterator.
*/
class row
{
public:
using size_type = row_size_type;
using difference_type = row_difference_type;
using const_iterator = const_row_iterator;
using iterator = const_iterator;
using reference = field;
using pointer = const_row_iterator;
using const_reverse_iterator = const_reverse_row_iterator;
using reverse_iterator = const_reverse_iterator;
PQXX_LIBEXPORT row() =default;
/// @deprecated Do not use this constructor. It will become private.
PQXX_LIBEXPORT row(result r, size_t i) noexcept;
/**
* @name Comparison
*/
//@{
PQXX_LIBEXPORT PQXX_PURE bool operator==(const row &) const noexcept; //[t75]
bool operator!=(const row &rhs) const noexcept //[t75]
{ return not operator==(rhs); }
//@}
PQXX_LIBEXPORT const_iterator begin() const noexcept; //[t82]
PQXX_LIBEXPORT const_iterator cbegin() const noexcept;
PQXX_LIBEXPORT const_iterator end() const noexcept; //[t82]
PQXX_LIBEXPORT const_iterator cend() const noexcept;
/**
* @name Field access
*/
//@{
PQXX_LIBEXPORT reference front() const noexcept; //[t74]
PQXX_LIBEXPORT reference back() const noexcept; //[t75]
PQXX_LIBEXPORT const_reverse_row_iterator rbegin() const; //[t82]
PQXX_LIBEXPORT const_reverse_row_iterator crbegin() const;
PQXX_LIBEXPORT const_reverse_row_iterator rend() const; //[t82]
PQXX_LIBEXPORT const_reverse_row_iterator crend() const;
PQXX_LIBEXPORT reference operator[](size_type) const noexcept; //[t11]
PQXX_LIBEXPORT reference operator[](int) const noexcept; //[t02]
/** Address field by name.
* @warning This is much slower than indexing by number, or iterating.
*/
PQXX_LIBEXPORT reference operator[](const char[]) const; //[t11]
/** Address field by name.
* @warning This is much slower than indexing by number, or iterating.
*/
reference operator[](const std::string &s) const //[t11]
{ return (*this)[s.c_str()]; }
PQXX_LIBEXPORT reference at(size_type) const; //[t11]
PQXX_LIBEXPORT reference at(int) const; //[t11]
/** Address field by name.
* @warning This is much slower than indexing by number, or iterating.
*/
PQXX_LIBEXPORT reference at(const char[]) const; //[t11]
/** Address field by name.
* @warning This is much slower than indexing by number, or iterating.
*/
reference at(const std::string &s) const //[t11]
{ return at(s.c_str()); }
//@}
size_type size() const noexcept //[t11]
{ return m_end-m_begin; }
PQXX_LIBEXPORT void swap(row &) noexcept; //[t11]
/// Row number, assuming this is a real row and not end()/rend().
size_t rownumber() const noexcept { return size_t(m_index); } //[t11]
/**
* @name Column information
*/
//@{
/// Number of given column (throws exception if it doesn't exist).
size_type column_number(const std::string &ColName) const //[t30]
{ return column_number(ColName.c_str()); }
/// Number of given column (throws exception if it doesn't exist).
PQXX_LIBEXPORT size_type column_number(const char[]) const; //[t30]
/// Return a column's type.
PQXX_LIBEXPORT oid column_type(size_type) const; //[t07]
/// Return a column's type.
oid column_type(int ColNum) const //[t07]
{ return column_type(size_type(ColNum)); }
/// Return a column's type.
template<typename STRING>
oid column_type(STRING ColName) const //[t07]
{ return column_type(column_number(ColName)); }
/// What table did this column come from?
PQXX_LIBEXPORT oid column_table(size_type ColNum) const; //[t02]
/// What table did this column come from?
oid column_table(int ColNum) const //[t02]
{ return column_table(size_type(ColNum)); }
/// What table did this column come from?
template<typename STRING>
oid column_table(STRING ColName) const //[t02]
{ return column_table(column_number(ColName)); }
/// What column number in its table did this result column come from?
/** A meaningful answer can be given only if the column in question comes
* directly from a column in a table. If the column is computed in any
* other way, a logic_error will be thrown.
*
* @param ColNum a zero-based column number in this result set
* @return a zero-based column number in originating table
*/
PQXX_LIBEXPORT size_type table_column(size_type) const; //[t93]
/// What column number in its table did this result column come from?
size_type table_column(int ColNum) const //[t93]
{ return table_column(size_type(ColNum)); }
/// What column number in its table did this result column come from?
template<typename STRING>
size_type table_column(STRING ColName) const //[t93]
{ return table_column(column_number(ColName)); }
//@}
size_t num() const { return rownumber(); } //[t01]
/** Produce a slice of this row, containing the given range of columns.
*
* The slice runs from the range's starting column to the range's end
* column, exclusive. It looks just like a normal result row, except
* slices can be empty.
*
* @warning Slicing is a relatively new feature, and not all software may be
* prepared to deal with empty slices. If there is any chance that your
* program might be creating empty slices and passing them to code that may
* not be designed with the possibility of empty rows in mind, be sure to
* test for that case.
*/
PQXX_LIBEXPORT row slice(size_type Begin, size_type End) const;
// Is this an empty slice?
PQXX_LIBEXPORT PQXX_PURE bool empty() const noexcept;
protected:
friend class field;
/// Result set of which this is one row.
result m_result;
/// Row number.
/**
* You'd expect this to be a size_t, but due to the way reverse iterators
* are related to regular iterators, it must be allowed to underflow to -1.
*/
long m_index = 0;
/// First column in slice. This row ignores lower-numbered columns.
size_type m_begin = 0;
/// End column in slice. This row only sees lower-numbered columns.
size_type m_end = 0;
};
/// Iterator for fields in a row. Use as row::const_iterator.
class PQXX_LIBEXPORT const_row_iterator : public field
{
public:
using iterator_category = std::random_access_iterator_tag;
using value_type = const field;
using pointer = const field *;
using size_type = row_size_type;
using difference_type = row_difference_type;
using reference = field;
const_row_iterator(const row &T, row_size_type C) noexcept : //[t82]
field{T, C} {}
const_row_iterator(const field &F) noexcept : field{F} {} //[t82]
/**
* @name Dereferencing operators
*/
//@{
pointer operator->() const { return this; } //[t82]
reference operator*() const { return field{*this}; } //[t82]
//@}
/**
* @name Manipulations
*/
//@{
const_row_iterator operator++(int); //[t82]
const_row_iterator &operator++() { ++m_col; return *this; } //[t82]
const_row_iterator operator--(int); //[t82]
const_row_iterator &operator--() { --m_col; return *this; } //[t82]
const_row_iterator &operator+=(difference_type i) //[t82]
{ m_col = size_type(difference_type(m_col) + i); return *this; }
const_row_iterator &operator-=(difference_type i) //[t82]
{ m_col = size_type(difference_type(m_col) - i); return *this; }
//@}
/**
* @name Comparisons
*/
//@{
bool operator==(const const_row_iterator &i) const //[t82]
{return col()==i.col();}
bool operator!=(const const_row_iterator &i) const //[t82]
{return col()!=i.col();}
bool operator<(const const_row_iterator &i) const //[t82]
{return col()<i.col();}
bool operator<=(const const_row_iterator &i) const //[t82]
{return col()<=i.col();}
bool operator>(const const_row_iterator &i) const //[t82]
{return col()>i.col();}
bool operator>=(const const_row_iterator &i) const //[t82]
{return col()>=i.col();}
//@}
/**
* @name Arithmetic operators
*/
//@{
inline const_row_iterator operator+(difference_type) const; //[t82]
friend const_row_iterator operator+( //[t82]
difference_type,
const_row_iterator);
inline const_row_iterator operator-(difference_type) const; //[t82]
inline difference_type operator-(const_row_iterator) const; //[t82]
//@}
};
/// Reverse iterator for a row. Use as row::const_reverse_iterator.
class PQXX_LIBEXPORT const_reverse_row_iterator : private const_row_iterator
{
public:
using super = const_row_iterator;
using iterator_type = const_row_iterator;
using iterator_type::iterator_category;
using iterator_type::difference_type;
using iterator_type::pointer;
using value_type = iterator_type::value_type;
using reference = iterator_type::reference;
const_reverse_row_iterator(const const_reverse_row_iterator &r) : //[t82]
const_row_iterator{r} {}
explicit
const_reverse_row_iterator(const super &rhs) noexcept : //[t82]
const_row_iterator{rhs} { super::operator--(); }
PQXX_PURE iterator_type base() const noexcept; //[t82]
/**
* @name Dereferencing operators
*/
//@{
using iterator_type::operator->; //[t82]
using iterator_type::operator*; //[t82]
//@}
/**
* @name Manipulations
*/
//@{
const_reverse_row_iterator &
operator=(const const_reverse_row_iterator &r) //[t82]
{ iterator_type::operator=(r); return *this; }
const_reverse_row_iterator operator++() //[t82]
{ iterator_type::operator--(); return *this; }
const_reverse_row_iterator operator++(int); //[t82]
const_reverse_row_iterator &operator--() //[t82]
{ iterator_type::operator++(); return *this; }
const_reverse_row_iterator operator--(int); //[t82]
const_reverse_row_iterator &operator+=(difference_type i) //[t82]
{ iterator_type::operator-=(i); return *this; }
const_reverse_row_iterator &operator-=(difference_type i) //[t82]
{ iterator_type::operator+=(i); return *this; }
//@}
/**
* @name Arithmetic operators
*/
//@{
const_reverse_row_iterator operator+(difference_type i) const //[t82]
{ return const_reverse_row_iterator{base()-i}; }
const_reverse_row_iterator operator-(difference_type i) //[t82]
{ return const_reverse_row_iterator{base()+i}; }
difference_type
operator-(const const_reverse_row_iterator &rhs) const //[t82]
{ return rhs.const_row_iterator::operator-(*this); }
//@}
/**
* @name Comparisons
*/
//@{
bool operator==(const const_reverse_row_iterator &rhs) const noexcept //[t82]
{ return iterator_type::operator==(rhs); }
bool operator!=(const const_reverse_row_iterator &rhs) const noexcept //[t82]
{ return !operator==(rhs); }
bool operator<(const const_reverse_row_iterator &rhs) const //[t82]
{ return iterator_type::operator>(rhs); }
bool operator<=(const const_reverse_row_iterator &rhs) const //[t82]
{ return iterator_type::operator>=(rhs); }
bool operator>(const const_reverse_row_iterator &rhs) const //[t82]
{ return iterator_type::operator<(rhs); }
bool operator>=(const const_reverse_row_iterator &rhs) const //[t82]
{ return iterator_type::operator<=(rhs); }
//@}
};
inline const_row_iterator
const_row_iterator::operator+(difference_type o) const
{
return const_row_iterator{
row(home(), idx()),
size_type(difference_type(col()) + o)};
}
inline const_row_iterator
operator+(const_row_iterator::difference_type o, const_row_iterator i)
{ return i + o; }
inline const_row_iterator
const_row_iterator::operator-(difference_type o) const
{
return const_row_iterator{
row(home(), idx()),
size_type(difference_type(col()) - o)};
}
inline const_row_iterator::difference_type
const_row_iterator::operator-(const_row_iterator i) const
{ return difference_type(num() - i.num()); }
} // namespace pqxx
#include "pqxx/internal/compiler-internal-post.hxx"
#endif
<|endoftext|> |
<commit_before>// Macro to compare masses in root data base to the values from pdg
// http://pdg.lbl.gov/2009/mcdata/mass_width_2008.mc
//
// the ROOT values are read in by TDatabasePDG from $ROOTSYS/etc/pdg_table.C
//
// Author: Christian.Klein-Boesing@cern.ch
#include <fstream>
#include <iostream>
#include "TDatabasePDG.h"
#include "TParticlePDG.h"
using namespace std;
void CompareMasses(){
char *fn = "mass_width_2008.mc.txt";
FILE* file = fopen(fn,"r");
ifstream in1;
in1.open(fn);
if (!in1.good()){
Printf("Could not open PDG particle file %s",fn);
fclose(file);
return;
}
char c[200];
char cempty;
Int_t pdg[4];
Float_t mass, err1,err2,err;
Int_t ndiff = 0;
while (fgets(&c[0],200,file)) {
if (c[0] != '*' && c[0] !='W') {
// printf("%s",c);
sscanf(&c[1],"%8d",&pdg[0]);
// check emptyness
pdg[1] = 0;
for(int i = 0;i<8;i++){
sscanf(&c[9+i],"%c",&cempty);
if(cempty != ' ')sscanf(&c[9],"%8d",&pdg[1]);
}
pdg[2] = 0;
for(int i = 0;i<8;i++){
sscanf(&c[17+i],"%c",&cempty);
if(cempty != ' ')sscanf(&c[17],"%8d",&pdg[2]);
}
pdg[3] = 0;
for(int i = 0;i<8;i++){
sscanf(&c[25+i],"%c",&cempty);
if(cempty != ' ')sscanf(&c[25],"%8d",&pdg[3]);
}
sscanf(&c[35],"%14f",&mass);
sscanf(&c[50],"%8f",&err1);
sscanf(&c[50],"%8f",&err2);
err = TMath::Max((Double_t)err1,(Double_t)-1.*err2);
for(int ipdg = 0;ipdg < 4;ipdg++){
if(pdg[ipdg]==0)continue;
TParticlePDG *partRoot = TDatabasePDG::Instance()->GetParticle(pdg[ipdg]);
if(partRoot){
Float_t massRoot = partRoot->Mass();
Float_t deltaM = TMath::Abs(massRoot - mass);
// if(deltaM > err){
if(deltaM/mass>1E-05){
ndiff++;
Printf("%10s %8d pdg mass %E pdg err %E root Mass %E >> deltaM %E = %3.3f%%",partRoot->GetName(),pdg[ipdg],mass,err,massRoot,deltaM,100.*deltaM/mass);
}
}
}
}
}// while
fclose(file);
if (ndiff == 0) Printf("Crongratulations !! All particles in ROOT and PDG have identical masses");
}
<commit_msg>Find input file in a less fragile way, so tutorial can be called from outside tutorials/mc. Fixes roottest.<commit_after>// Macro to compare masses in root data base to the values from pdg
// http://pdg.lbl.gov/2009/mcdata/mass_width_2008.mc
//
// the ROOT values are read in by TDatabasePDG from $ROOTSYS/etc/pdg_table.C
//
// Author: Christian.Klein-Boesing@cern.ch
#include <fstream>
#include <iostream>
#include "TDatabasePDG.h"
#include "TParticlePDG.h"
using namespace std;
void CompareMasses(){
TString massWidthFile = gSystem->UnixPathName(gInterpreter->GetCurrentMacroName());
massWidthFile.ReplaceAll("tasks.C","mass_width_2008.mc.txt");
FILE* file = fopen(massWidthFile.Data(),"r");
ifstream in1;
in1.open(massWidthFile);
if (!in1.good()){
Printf("Could not open PDG particle file %s",massWidthFile.Data());
fclose(file);
return;
}
char c[200];
char cempty;
Int_t pdg[4];
Float_t mass, err1,err2,err;
Int_t ndiff = 0;
while (fgets(&c[0],200,file)) {
if (c[0] != '*' && c[0] !='W') {
// printf("%s",c);
sscanf(&c[1],"%8d",&pdg[0]);
// check emptyness
pdg[1] = 0;
for(int i = 0;i<8;i++){
sscanf(&c[9+i],"%c",&cempty);
if(cempty != ' ')sscanf(&c[9],"%8d",&pdg[1]);
}
pdg[2] = 0;
for(int i = 0;i<8;i++){
sscanf(&c[17+i],"%c",&cempty);
if(cempty != ' ')sscanf(&c[17],"%8d",&pdg[2]);
}
pdg[3] = 0;
for(int i = 0;i<8;i++){
sscanf(&c[25+i],"%c",&cempty);
if(cempty != ' ')sscanf(&c[25],"%8d",&pdg[3]);
}
sscanf(&c[35],"%14f",&mass);
sscanf(&c[50],"%8f",&err1);
sscanf(&c[50],"%8f",&err2);
err = TMath::Max((Double_t)err1,(Double_t)-1.*err2);
for(int ipdg = 0;ipdg < 4;ipdg++){
if(pdg[ipdg]==0)continue;
TParticlePDG *partRoot = TDatabasePDG::Instance()->GetParticle(pdg[ipdg]);
if(partRoot){
Float_t massRoot = partRoot->Mass();
Float_t deltaM = TMath::Abs(massRoot - mass);
// if(deltaM > err){
if(deltaM/mass>1E-05){
ndiff++;
Printf("%10s %8d pdg mass %E pdg err %E root Mass %E >> deltaM %E = %3.3f%%",partRoot->GetName(),pdg[ipdg],mass,err,massRoot,deltaM,100.*deltaM/mass);
}
}
}
}
}// while
fclose(file);
if (ndiff == 0) Printf("Crongratulations !! All particles in ROOT and PDG have identical masses");
}
<|endoftext|> |
<commit_before>#include "echomesh/audio/GetReader.h"
namespace echomesh {
namespace {
AudioFormatManager* makeManager() {
AudioFormatManager* manager = new AudioFormatManager();
manager->registerBasicFormats();
return manager;
}
unique_ptr<AudioFormatManager> MANAGER(makeManager());
} // namespace
PositionableAudioSource* getReader(const String& name,
SampleTime begin, SampleTime end) {
unique_ptr<AudioFormatReader> reader(MANAGER->createReaderFor(File(name)));
if (not reader.get()) {
LOG(ERROR) << "Can't read file " << name.toStdString();
return nullptr;
}
if (end < 0)
end = reader->lengthInSamples;
if (begin or end < reader->lengthInSamples)
reader.reset(new AudioSubsectionReader(
reader.release(), begin, end, true));
return new AudioFormatReaderSource(reader.release(), true);
}
} // namespace echomesh
<commit_msg>Added a new print statement.<commit_after>#include "echomesh/audio/GetReader.h"
namespace echomesh {
namespace {
AudioFormatManager* makeManager() {
AudioFormatManager* manager = new AudioFormatManager();
manager->registerBasicFormats();
return manager;
}
unique_ptr<AudioFormatManager> MANAGER(makeManager());
} // namespace
PositionableAudioSource* getReader(const String& name,
SampleTime begin, SampleTime end) {
unique_ptr<AudioFormatReader> reader(MANAGER->createReaderFor(File(name)));
if (not reader.get()) {
LOG(ERROR) << "Can't read file " << name.toStdString();
std::cerr << "Can't read file " << name.toStdString();
return nullptr;
}
if (end < 0)
end = reader->lengthInSamples;
if (begin or end < reader->lengthInSamples)
reader.reset(new AudioSubsectionReader(
reader.release(), begin, end, true));
return new AudioFormatReaderSource(reader.release(), true);
}
} // namespace echomesh
<|endoftext|> |
<commit_before>/*
* RudeSkinnedMesh.cpp
* golf
*
* Created by Robert Rose on 9/20/08.
* Copyright 2008 Bork 3D LLC. All rights reserved.
*
*/
#include "RudeSkinnedMesh.h"
#include "RudeDebug.h"
#include "RudeGL.h"
#include "RudeFile.h"
#include "RudePerf.h"
#include "RudeTextureManager.h"
#include "RudeTweaker.h"
#include <OpenGLES/ES1/gl.h>
#include <OpenGLES/ES1/glext.h>
bool gDebugAnim = false;
RUDE_TWEAK(DebugAnim, kBool, gDebugAnim);
float gDebugAnimFrame = 0;
RUDE_TWEAK(DebugAnimFrame, kFloat, gDebugAnimFrame);
RudeSkinnedMesh::RudeSkinnedMesh(RudeObject *owner)
: RudeMesh(owner)
, m_frame(0.0f)
, m_fps(24.0f)
, m_toFrame(0.0f)
, m_animateTo(false)
{
}
RudeSkinnedMesh::~RudeSkinnedMesh()
{
}
int RudeSkinnedMesh::Load(const char *name)
{
RUDE_REPORT("RudeSkinnedMesh::Load %s\n", name);
if(RudeMesh::Load(name))
return -1;
for(int i = 0; i < m_model.nNumMesh; i++)
{
SPODMesh *mesh = &m_model.pMesh[i];
for(int b = 0; b < mesh->sBoneBatches.nBatchCnt; b++)
{
int offset = mesh->sBoneBatches.pnBatchOffset[b];
int end = mesh->sBoneBatches.pnBatchOffset[b+1];
if(b == (mesh->sBoneBatches.nBatchCnt - 1))
end = mesh->nNumFaces;
int numfaces = (end - offset);
RUDE_REPORT(" Mesh %d-%d: %d tris\n", i, b, numfaces);
}
}
return 0;
}
void RudeSkinnedMesh::SetFrame(float f)
{
m_animateTo = false;
m_frame = f;
}
void RudeSkinnedMesh::AnimateTo(float f)
{
m_animateTo = true;
m_toFrame = f;
}
void RudeSkinnedMesh::NextFrame(float delta)
{
if(m_animateTo)
{
if(m_toFrame > m_frame)
{
m_frame += delta * m_fps;
if(m_frame > m_toFrame)
{
m_frame = m_toFrame;
m_animateTo = false;
}
}
else
{
m_frame -= delta * m_fps;
if(m_frame < m_toFrame)
{
m_frame = m_toFrame;
m_animateTo = false;
}
}
}
m_model.SetFrame(m_frame);
if(gDebugAnim)
m_model.SetFrame(gDebugAnimFrame);
}
void RudeSkinnedMesh::Render()
{
RUDE_PERF_START(kPerfRudeSkinMeshRender);
//int numbonemats;
//glGetIntegerv(GL_MAX_PALETTE_MATRICES_OES, &numbonemats);
//printf("bonemats %d\n", numbonemats);
glMatrixMode(GL_MODELVIEW);
PVRTMATRIX viewmat;
glGetFloatv(GL_MODELVIEW_MATRIX, viewmat.f);
RGL.Enable(kBackfaceCull, true);
glCullFace(GL_FRONT);
glFrontFace(GL_CW);
//glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
//glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
RGL.EnableClient(kVertexArray, true);
RGL.EnableClient(kTextureCoordArray, true);
//glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_MODULATE);
if(m_animate)
{
glEnable(GL_MATRIX_PALETTE_OES);
glEnableClientState(GL_MATRIX_INDEX_ARRAY_OES);
glEnableClientState(GL_WEIGHT_ARRAY_OES);
}
//glScalef(m_scale.x(), m_scale.y(), m_scale.z());
for(int i = 0; i < m_model.nNumNode; i++)
{
SPODNode *node = &m_model.pNode[i];
if(!node->pszName)
continue;
if(node->pszName[0] != 'M')
continue;
SPODMaterial *material = &m_model.pMaterial[node->nIdxMaterial];
SPODMesh *mesh = &m_model.pMesh[node->nIdx];
RUDE_ASSERT(mesh->sBoneIdx.eType == EPODDataUnsignedByte, "Bone indices must be unsigned byte (mesh '%s')", node->pszName);
RUDE_ASSERT(mesh->sBoneWeight.eType == EPODDataFloat, "Bone weight must be float");
if(m_animate)
{
glMatrixIndexPointerOES(mesh->sBoneIdx.n, GL_UNSIGNED_BYTE, mesh->sBoneIdx.nStride, mesh->pInterleaved + (long) mesh->sBoneIdx.pData);
glWeightPointerOES(mesh->sBoneWeight.n, GL_FLOAT, mesh->sBoneWeight.nStride, mesh->pInterleaved + (long) mesh->sBoneWeight.pData);
}
int textureid = material->nIdxTexDiffuse;
if(textureid >= 0)
RudeTextureManager::GetInstance()->SetTexture(m_textures[textureid]);
unsigned short *indices = (unsigned short*) mesh->sFaces.pData;
if(mesh->sVertex.eType == EPODDataFixed16_16)
{
glVertexPointer(3, GL_FIXED, mesh->sVertex.nStride, mesh->pInterleaved + (long)mesh->sVertex.pData);
}
else if(mesh->sVertex.eType == EPODDataShortNorm)
{
float s = 1.0f / 1000.0f;
glMatrixMode(GL_MODELVIEW);
glScalef(s, s, s);
glVertexPointer(3, GL_UNSIGNED_SHORT, mesh->sVertex.nStride, mesh->pInterleaved + (long)mesh->sVertex.pData);
}
else if(mesh->sVertex.eType == EPODDataShort)
{
glVertexPointer(3, GL_SHORT, mesh->sVertex.nStride, mesh->pInterleaved + (long)mesh->sVertex.pData);
}
else
{
glVertexPointer(3, GL_FLOAT, mesh->sVertex.nStride, mesh->pInterleaved + (long)mesh->sVertex.pData);
}
glTexCoordPointer(2, GL_FLOAT, mesh->psUVW->nStride, mesh->pInterleaved + (long)mesh->psUVW->pData);
if((mesh->sVtxColours.n > 0) && (mesh->sVtxColours.eType == EPODDataRGBA))
{
RGL.EnableClient(kColorArray, true);
glColorPointer(4, GL_UNSIGNED_BYTE, mesh->sVtxColours.nStride, mesh->pInterleaved + (long)mesh->sVtxColours.pData);
}
else
RGL.EnableClient(kColorArray, false);
int totalbatchcnt = 0;
for(int b = 0; b < mesh->sBoneBatches.nBatchCnt; b++)
{
int batchcnt = mesh->sBoneBatches.pnBatchBoneCnt[b];
if(m_animate)
{
glMatrixMode(GL_MATRIX_PALETTE_OES);
for(int j = 0; j < batchcnt; ++j)
{
glCurrentPaletteMatrixOES(j);
// Generates the world matrix for the given bone in this batch.
PVRTMATRIX mBoneWorld;
int i32NodeID = mesh->sBoneBatches.pnBatches[j + totalbatchcnt];
m_model.GetBoneWorldMatrix(mBoneWorld, *node, m_model.pNode[i32NodeID]);
// Multiply the bone's world matrix by the view matrix to put it in view space
PVRTMatrixMultiply(mBoneWorld, mBoneWorld, viewmat);
// Load the bone matrix into the current palette matrix.
glLoadMatrixf(mBoneWorld.f);
}
}
totalbatchcnt += batchcnt;
int offset = mesh->sBoneBatches.pnBatchOffset[b] * 3;
int end = mesh->sBoneBatches.pnBatchOffset[b+1] * 3;
if(b == (mesh->sBoneBatches.nBatchCnt - 1))
end = mesh->nNumFaces*3;
int numidx = (end - offset);
glDrawElements(GL_TRIANGLES, numidx, GL_UNSIGNED_SHORT, &indices[offset]);
}
}
glDisable(GL_MATRIX_PALETTE_OES);
glDisableClientState(GL_MATRIX_INDEX_ARRAY_OES);
glDisableClientState(GL_WEIGHT_ARRAY_OES);
RUDE_PERF_STOP(kPerfRudeSkinMeshRender);
}
<commit_msg>moved skin render asserts to load time<commit_after>/*
* RudeSkinnedMesh.cpp
* golf
*
* Created by Robert Rose on 9/20/08.
* Copyright 2008 Bork 3D LLC. All rights reserved.
*
*/
#include "RudeSkinnedMesh.h"
#include "RudeDebug.h"
#include "RudeGL.h"
#include "RudeFile.h"
#include "RudePerf.h"
#include "RudeTextureManager.h"
#include "RudeTweaker.h"
#include <OpenGLES/ES1/gl.h>
#include <OpenGLES/ES1/glext.h>
bool gDebugAnim = false;
RUDE_TWEAK(DebugAnim, kBool, gDebugAnim);
float gDebugAnimFrame = 0;
RUDE_TWEAK(DebugAnimFrame, kFloat, gDebugAnimFrame);
RudeSkinnedMesh::RudeSkinnedMesh(RudeObject *owner)
: RudeMesh(owner)
, m_frame(0.0f)
, m_fps(24.0f)
, m_toFrame(0.0f)
, m_animateTo(false)
{
}
RudeSkinnedMesh::~RudeSkinnedMesh()
{
}
int RudeSkinnedMesh::Load(const char *name)
{
RUDE_REPORT("RudeSkinnedMesh::Load %s\n", name);
if(RudeMesh::Load(name))
return -1;
for(int i = 0; i < m_model.nNumMesh; i++)
{
SPODMesh *mesh = &m_model.pMesh[i];
for(int b = 0; b < mesh->sBoneBatches.nBatchCnt; b++)
{
int offset = mesh->sBoneBatches.pnBatchOffset[b];
int end = mesh->sBoneBatches.pnBatchOffset[b+1];
if(b == (mesh->sBoneBatches.nBatchCnt - 1))
end = mesh->nNumFaces;
int numfaces = (end - offset);
RUDE_REPORT(" Mesh %d-%d: %d tris\n", i, b, numfaces);
}
RUDE_ASSERT(mesh->sBoneIdx.eType == EPODDataUnsignedByte, "Bone indices must be unsigned byte");
RUDE_ASSERT(mesh->sBoneWeight.eType == EPODDataFloat, "Bone weight must be float");
RUDE_ASSERT(mesh->sVertex.eType == EPODDataFloat, "Mesh verts should be float");
}
return 0;
}
void RudeSkinnedMesh::SetFrame(float f)
{
m_animateTo = false;
m_frame = f;
}
void RudeSkinnedMesh::AnimateTo(float f)
{
m_animateTo = true;
m_toFrame = f;
}
void RudeSkinnedMesh::NextFrame(float delta)
{
if(m_animateTo)
{
if(m_toFrame > m_frame)
{
m_frame += delta * m_fps;
if(m_frame > m_toFrame)
{
m_frame = m_toFrame;
m_animateTo = false;
}
}
else
{
m_frame -= delta * m_fps;
if(m_frame < m_toFrame)
{
m_frame = m_toFrame;
m_animateTo = false;
}
}
}
m_model.SetFrame(m_frame);
if(gDebugAnim)
m_model.SetFrame(gDebugAnimFrame);
}
void RudeSkinnedMesh::Render()
{
RUDE_PERF_START(kPerfRudeSkinMeshRender);
//int numbonemats;
//glGetIntegerv(GL_MAX_PALETTE_MATRICES_OES, &numbonemats);
//printf("bonemats %d\n", numbonemats);
glMatrixMode(GL_MODELVIEW);
PVRTMATRIX viewmat;
glGetFloatv(GL_MODELVIEW_MATRIX, viewmat.f);
RGL.Enable(kBackfaceCull, true);
glCullFace(GL_FRONT);
glFrontFace(GL_CW);
//glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
//glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
RGL.EnableClient(kVertexArray, true);
RGL.EnableClient(kTextureCoordArray, true);
//glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_MODULATE);
if(m_animate)
{
glEnable(GL_MATRIX_PALETTE_OES);
glEnableClientState(GL_MATRIX_INDEX_ARRAY_OES);
glEnableClientState(GL_WEIGHT_ARRAY_OES);
}
//glScalef(m_scale.x(), m_scale.y(), m_scale.z());
for(int i = 0; i < m_model.nNumNode; i++)
{
SPODNode *node = &m_model.pNode[i];
if(!node->pszName)
continue;
if(node->pszName[0] != 'M')
continue;
SPODMaterial *material = &m_model.pMaterial[node->nIdxMaterial];
SPODMesh *mesh = &m_model.pMesh[node->nIdx];
if(m_animate)
{
glMatrixIndexPointerOES(mesh->sBoneIdx.n, GL_UNSIGNED_BYTE, mesh->sBoneIdx.nStride, mesh->pInterleaved + (long) mesh->sBoneIdx.pData);
glWeightPointerOES(mesh->sBoneWeight.n, GL_FLOAT, mesh->sBoneWeight.nStride, mesh->pInterleaved + (long) mesh->sBoneWeight.pData);
}
int textureid = material->nIdxTexDiffuse;
if(textureid >= 0)
RudeTextureManager::GetInstance()->SetTexture(m_textures[textureid]);
unsigned short *indices = (unsigned short*) mesh->sFaces.pData;
glVertexPointer(3, GL_FLOAT, mesh->sVertex.nStride, mesh->pInterleaved + (long)mesh->sVertex.pData);
glTexCoordPointer(2, GL_FLOAT, mesh->psUVW->nStride, mesh->pInterleaved + (long)mesh->psUVW->pData);
if((mesh->sVtxColours.n > 0) && (mesh->sVtxColours.eType == EPODDataRGBA))
{
RGL.EnableClient(kColorArray, true);
glColorPointer(4, GL_UNSIGNED_BYTE, mesh->sVtxColours.nStride, mesh->pInterleaved + (long)mesh->sVtxColours.pData);
}
else
RGL.EnableClient(kColorArray, false);
int totalbatchcnt = 0;
for(int b = 0; b < mesh->sBoneBatches.nBatchCnt; b++)
{
int batchcnt = mesh->sBoneBatches.pnBatchBoneCnt[b];
if(m_animate)
{
glMatrixMode(GL_MATRIX_PALETTE_OES);
for(int j = 0; j < batchcnt; ++j)
{
glCurrentPaletteMatrixOES(j);
// Generates the world matrix for the given bone in this batch.
PVRTMATRIX mBoneWorld;
int i32NodeID = mesh->sBoneBatches.pnBatches[j + totalbatchcnt];
m_model.GetBoneWorldMatrix(mBoneWorld, *node, m_model.pNode[i32NodeID]);
// Multiply the bone's world matrix by the view matrix to put it in view space
PVRTMatrixMultiply(mBoneWorld, mBoneWorld, viewmat);
// Load the bone matrix into the current palette matrix.
glLoadMatrixf(mBoneWorld.f);
}
}
totalbatchcnt += batchcnt;
int offset = mesh->sBoneBatches.pnBatchOffset[b] * 3;
int end = mesh->sBoneBatches.pnBatchOffset[b+1] * 3;
if(b == (mesh->sBoneBatches.nBatchCnt - 1))
end = mesh->nNumFaces*3;
int numidx = (end - offset);
glDrawElements(GL_TRIANGLES, numidx, GL_UNSIGNED_SHORT, &indices[offset]);
}
}
glDisable(GL_MATRIX_PALETTE_OES);
glDisableClientState(GL_MATRIX_INDEX_ARRAY_OES);
glDisableClientState(GL_WEIGHT_ARRAY_OES);
RUDE_PERF_STOP(kPerfRudeSkinMeshRender);
}
<|endoftext|> |
<commit_before>//==- IdempotentOperationChecker.cpp - Idempotent Operations ----*- C++ -*-==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines a set of path-sensitive checks for idempotent and/or
// tautological operations. Each potential operation is checked along all paths
// to see if every path results in a pointless operation.
// +-------------------------------------------+
// |Table of idempotent/tautological operations|
// +-------------------------------------------+
//+--------------------------------------------------------------------------+
//|Operator | x op x | x op 1 | 1 op x | x op 0 | 0 op x | x op ~0 | ~0 op x |
//+--------------------------------------------------------------------------+
// +, += | | | | x | x | |
// -, -= | | | | x | -x | |
// *, *= | | x | x | 0 | 0 | |
// /, /= | 1 | x | | N/A | 0 | |
// &, &= | x | | | 0 | 0 | x | x
// |, |= | x | | | x | x | ~0 | ~0
// ^, ^= | 0 | | | x | x | |
// <<, <<= | | | | x | 0 | |
// >>, >>= | | | | x | 0 | |
// || | 1 | 1 | 1 | x | x | 1 | 1
// && | 1 | x | x | 0 | 0 | x | x
// = | x | | | | | |
// == | 1 | | | | | |
// >= | 1 | | | | | |
// <= | 1 | | | | | |
// > | 0 | | | | | |
// < | 0 | | | | | |
// != | 0 | | | | | |
//===----------------------------------------------------------------------===//
//
// Ways to reduce false positives (that need to be implemented):
// - Don't flag downsizing casts
// - Improved handling of static/global variables
// - Per-block marking of incomplete analysis
// - Handling ~0 values
// - False positives involving silencing unused variable warnings
//
// Other things TODO:
// - Improved error messages
// - Handle mixed assumptions (which assumptions can belong together?)
// - Finer grained false positive control (levels)
#include "GRExprEngineInternalChecks.h"
#include "clang/Checker/BugReporter/BugType.h"
#include "clang/Checker/PathSensitive/CheckerHelpers.h"
#include "clang/Checker/PathSensitive/CheckerVisitor.h"
#include "clang/Checker/PathSensitive/SVals.h"
#include "clang/AST/Stmt.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/Support/ErrorHandling.h"
using namespace clang;
namespace {
class IdempotentOperationChecker
: public CheckerVisitor<IdempotentOperationChecker> {
public:
static void *getTag();
void PreVisitBinaryOperator(CheckerContext &C, const BinaryOperator *B);
void VisitEndAnalysis(ExplodedGraph &G, BugReporter &B,
bool hasWorkRemaining);
private:
// Our assumption about a particular operation.
enum Assumption { Possible, Impossible, Equal, LHSis1, RHSis1, LHSis0,
RHSis0 };
void UpdateAssumption(Assumption &A, const Assumption &New);
/// contains* - Useful recursive methods to see if a statement contains an
/// element somewhere. Used in static analysis to reduce false positives.
static bool isParameterSelfAssign(const Expr *LHS, const Expr *RHS);
static bool isTruncationExtensionAssignment(const Expr *LHS,
const Expr *RHS);
static bool containsZeroConstant(const Stmt *S);
static bool containsOneConstant(const Stmt *S);
// Hash table
typedef llvm::DenseMap<const BinaryOperator *, Assumption> AssumptionMap;
AssumptionMap hash;
};
}
void *IdempotentOperationChecker::getTag() {
static int x = 0;
return &x;
}
void clang::RegisterIdempotentOperationChecker(GRExprEngine &Eng) {
Eng.registerCheck(new IdempotentOperationChecker());
}
void IdempotentOperationChecker::PreVisitBinaryOperator(
CheckerContext &C,
const BinaryOperator *B) {
// Find or create an entry in the hash for this BinaryOperator instance
AssumptionMap::iterator i = hash.find(B);
Assumption &A = i == hash.end() ? hash[B] : i->second;
// If we had to create an entry, initialise the value to Possible
if (i == hash.end())
A = Possible;
// If we already have visited this node on a path that does not contain an
// idempotent operation, return immediately.
if (A == Impossible)
return;
// Skip binary operators containing common false positives
if (containsMacro(B) || containsEnum(B) || containsStmt<SizeOfAlignOfExpr>(B)
|| containsZeroConstant(B) || containsOneConstant(B)
|| containsBuiltinOffsetOf(B) || containsStaticLocal(B)) {
A = Impossible;
return;
}
const Expr *LHS = B->getLHS();
const Expr *RHS = B->getRHS();
const GRState *state = C.getState();
SVal LHSVal = state->getSVal(LHS);
SVal RHSVal = state->getSVal(RHS);
// If either value is unknown, we can't be 100% sure of all paths.
if (LHSVal.isUnknownOrUndef() || RHSVal.isUnknownOrUndef()) {
A = Impossible;
return;
}
BinaryOperator::Opcode Op = B->getOpcode();
// Dereference the LHS SVal if this is an assign operation
switch (Op) {
default:
break;
// Fall through intentional
case BinaryOperator::AddAssign:
case BinaryOperator::SubAssign:
case BinaryOperator::MulAssign:
case BinaryOperator::DivAssign:
case BinaryOperator::AndAssign:
case BinaryOperator::OrAssign:
case BinaryOperator::XorAssign:
case BinaryOperator::ShlAssign:
case BinaryOperator::ShrAssign:
case BinaryOperator::Assign:
// Assign statements have one extra level of indirection
if (!isa<Loc>(LHSVal)) {
A = Impossible;
return;
}
LHSVal = state->getSVal(cast<Loc>(LHSVal));
}
// We now check for various cases which result in an idempotent operation.
// x op x
switch (Op) {
default:
break; // We don't care about any other operators.
// Fall through intentional
case BinaryOperator::Assign:
// x Assign x has a few more false positives we can check for
if (isParameterSelfAssign(RHS, LHS)
|| isTruncationExtensionAssignment(RHS, LHS)) {
A = Impossible;
return;
}
case BinaryOperator::SubAssign:
case BinaryOperator::DivAssign:
case BinaryOperator::AndAssign:
case BinaryOperator::OrAssign:
case BinaryOperator::XorAssign:
case BinaryOperator::Sub:
case BinaryOperator::Div:
case BinaryOperator::And:
case BinaryOperator::Or:
case BinaryOperator::Xor:
case BinaryOperator::LOr:
case BinaryOperator::LAnd:
if (LHSVal != RHSVal)
break;
UpdateAssumption(A, Equal);
return;
}
// x op 1
switch (Op) {
default:
break; // We don't care about any other operators.
// Fall through intentional
case BinaryOperator::MulAssign:
case BinaryOperator::DivAssign:
case BinaryOperator::Mul:
case BinaryOperator::Div:
case BinaryOperator::LOr:
case BinaryOperator::LAnd:
if (!RHSVal.isConstant(1))
break;
UpdateAssumption(A, RHSis1);
return;
}
// 1 op x
switch (Op) {
default:
break; // We don't care about any other operators.
// Fall through intentional
case BinaryOperator::MulAssign:
case BinaryOperator::Mul:
case BinaryOperator::LOr:
case BinaryOperator::LAnd:
if (!LHSVal.isConstant(1))
break;
UpdateAssumption(A, LHSis1);
return;
}
// x op 0
switch (Op) {
default:
break; // We don't care about any other operators.
// Fall through intentional
case BinaryOperator::AddAssign:
case BinaryOperator::SubAssign:
case BinaryOperator::MulAssign:
case BinaryOperator::AndAssign:
case BinaryOperator::OrAssign:
case BinaryOperator::XorAssign:
case BinaryOperator::Add:
case BinaryOperator::Sub:
case BinaryOperator::Mul:
case BinaryOperator::And:
case BinaryOperator::Or:
case BinaryOperator::Xor:
case BinaryOperator::Shl:
case BinaryOperator::Shr:
case BinaryOperator::LOr:
case BinaryOperator::LAnd:
if (!RHSVal.isConstant(0))
break;
UpdateAssumption(A, RHSis0);
return;
}
// 0 op x
switch (Op) {
default:
break; // We don't care about any other operators.
// Fall through intentional
//case BinaryOperator::AddAssign: // Common false positive
case BinaryOperator::SubAssign: // Check only if unsigned
case BinaryOperator::MulAssign:
case BinaryOperator::DivAssign:
case BinaryOperator::AndAssign:
//case BinaryOperator::OrAssign: // Common false positive
//case BinaryOperator::XorAssign: // Common false positive
case BinaryOperator::ShlAssign:
case BinaryOperator::ShrAssign:
case BinaryOperator::Add:
case BinaryOperator::Sub:
case BinaryOperator::Mul:
case BinaryOperator::Div:
case BinaryOperator::And:
case BinaryOperator::Or:
case BinaryOperator::Xor:
case BinaryOperator::Shl:
case BinaryOperator::Shr:
case BinaryOperator::LOr:
case BinaryOperator::LAnd:
if (!LHSVal.isConstant(0))
break;
UpdateAssumption(A, LHSis0);
return;
}
// If we get to this point, there has been a valid use of this operation.
A = Impossible;
}
void IdempotentOperationChecker::VisitEndAnalysis(ExplodedGraph &G,
BugReporter &BR,
bool hasWorkRemaining) {
// If there is any work remaining we cannot be 100% sure about our warnings
// if (hasWorkRemaining)
// return;
// Iterate over the hash to see if we have any paths with definite
// idempotent operations.
for (AssumptionMap::const_iterator i =
hash.begin(); i != hash.end(); ++i) {
if (i->second != Impossible) {
// Select the error message.
const BinaryOperator *B = i->first;
llvm::SmallString<128> buf;
llvm::raw_svector_ostream os(buf);
switch (i->second) {
case Equal:
if (B->getOpcode() == BinaryOperator::Assign)
os << "Assigned value is always the same as the existing value";
else
os << "Both operands to '" << B->getOpcodeStr()
<< "' always have the same value";
break;
case LHSis1:
os << "The left operand to '" << B->getOpcodeStr() << "' is always 1";
break;
case RHSis1:
os << "The right operand to '" << B->getOpcodeStr() << "' is always 1";
break;
case LHSis0:
os << "The left operand to '" << B->getOpcodeStr() << "' is always 0";
break;
case RHSis0:
os << "The right operand to '" << B->getOpcodeStr() << "' is always 0";
break;
case Possible:
llvm_unreachable("Operation was never marked with an assumption");
case Impossible:
llvm_unreachable(0);
}
// Create the SourceRange Arrays
SourceRange S[2] = { i->first->getLHS()->getSourceRange(),
i->first->getRHS()->getSourceRange() };
BR.EmitBasicReport("Idempotent operation", "Dead code",
os.str(), i->first->getOperatorLoc(), S, 2);
}
}
}
// Updates the current assumption given the new assumption
inline void IdempotentOperationChecker::UpdateAssumption(Assumption &A,
const Assumption &New) {
switch (A) {
// If we don't currently have an assumption, set it
case Possible:
A = New;
return;
// If we have determined that a valid state happened, ignore the new
// assumption.
case Impossible:
return;
// Any other case means that we had a different assumption last time. We don't
// currently support mixing assumptions for diagnostic reasons, so we set
// our assumption to be impossible.
default:
A = Impossible;
return;
}
}
// Check for a statement were a parameter is self assigned (to avoid an unused
// variable warning)
bool IdempotentOperationChecker::isParameterSelfAssign(const Expr *LHS,
const Expr *RHS) {
LHS = LHS->IgnoreParenCasts();
RHS = RHS->IgnoreParenCasts();
const DeclRefExpr *LHS_DR = dyn_cast<DeclRefExpr>(LHS);
if (!LHS_DR)
return false;
const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(LHS_DR->getDecl());
if (!PD)
return false;
const DeclRefExpr *RHS_DR = dyn_cast<DeclRefExpr>(RHS);
if (!RHS_DR)
return false;
return PD == RHS_DR->getDecl();
}
// Check for self casts truncating/extending a variable
bool IdempotentOperationChecker::isTruncationExtensionAssignment(
const Expr *LHS,
const Expr *RHS) {
const DeclRefExpr *LHS_DR = dyn_cast<DeclRefExpr>(LHS->IgnoreParenCasts());
if (!LHS_DR)
return false;
const VarDecl *VD = dyn_cast<VarDecl>(LHS_DR->getDecl());
if (!VD)
return false;
const DeclRefExpr *RHS_DR = dyn_cast<DeclRefExpr>(RHS->IgnoreParenCasts());
if (!RHS_DR)
return false;
if (VD != RHS_DR->getDecl())
return false;
return dyn_cast<DeclRefExpr>(RHS->IgnoreParens()) == NULL;
}
// Check for a integer or float constant of 0
bool IdempotentOperationChecker::containsZeroConstant(const Stmt *S) {
const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(S);
if (IL && IL->getValue() == 0)
return true;
const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(S);
if (FL && FL->getValue().isZero())
return true;
for (Stmt::const_child_iterator I = S->child_begin(); I != S->child_end();
++I)
if (const Stmt *child = *I)
if (containsZeroConstant(child))
return true;
return false;
}
// Check for an integer or float constant of 1
bool IdempotentOperationChecker::containsOneConstant(const Stmt *S) {
const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(S);
if (IL && IL->getValue() == 1)
return true;
if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(S)) {
const llvm::APFloat &val = FL->getValue();
const llvm::APFloat one(val.getSemantics(), 1);
if (val.compare(one) == llvm::APFloat::cmpEqual)
return true;
}
for (Stmt::const_child_iterator I = S->child_begin(); I != S->child_end();
++I)
if (const Stmt *child = *I)
if (containsOneConstant(child))
return true;
return false;
}
<commit_msg>Uncomment unfinished work bailout in IdempotentOperationsChecker.<commit_after>//==- IdempotentOperationChecker.cpp - Idempotent Operations ----*- C++ -*-==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines a set of path-sensitive checks for idempotent and/or
// tautological operations. Each potential operation is checked along all paths
// to see if every path results in a pointless operation.
// +-------------------------------------------+
// |Table of idempotent/tautological operations|
// +-------------------------------------------+
//+--------------------------------------------------------------------------+
//|Operator | x op x | x op 1 | 1 op x | x op 0 | 0 op x | x op ~0 | ~0 op x |
//+--------------------------------------------------------------------------+
// +, += | | | | x | x | |
// -, -= | | | | x | -x | |
// *, *= | | x | x | 0 | 0 | |
// /, /= | 1 | x | | N/A | 0 | |
// &, &= | x | | | 0 | 0 | x | x
// |, |= | x | | | x | x | ~0 | ~0
// ^, ^= | 0 | | | x | x | |
// <<, <<= | | | | x | 0 | |
// >>, >>= | | | | x | 0 | |
// || | 1 | 1 | 1 | x | x | 1 | 1
// && | 1 | x | x | 0 | 0 | x | x
// = | x | | | | | |
// == | 1 | | | | | |
// >= | 1 | | | | | |
// <= | 1 | | | | | |
// > | 0 | | | | | |
// < | 0 | | | | | |
// != | 0 | | | | | |
//===----------------------------------------------------------------------===//
//
// Ways to reduce false positives (that need to be implemented):
// - Don't flag downsizing casts
// - Improved handling of static/global variables
// - Per-block marking of incomplete analysis
// - Handling ~0 values
// - False positives involving silencing unused variable warnings
//
// Other things TODO:
// - Improved error messages
// - Handle mixed assumptions (which assumptions can belong together?)
// - Finer grained false positive control (levels)
#include "GRExprEngineInternalChecks.h"
#include "clang/Checker/BugReporter/BugType.h"
#include "clang/Checker/PathSensitive/CheckerHelpers.h"
#include "clang/Checker/PathSensitive/CheckerVisitor.h"
#include "clang/Checker/PathSensitive/SVals.h"
#include "clang/AST/Stmt.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/Support/ErrorHandling.h"
using namespace clang;
namespace {
class IdempotentOperationChecker
: public CheckerVisitor<IdempotentOperationChecker> {
public:
static void *getTag();
void PreVisitBinaryOperator(CheckerContext &C, const BinaryOperator *B);
void VisitEndAnalysis(ExplodedGraph &G, BugReporter &B,
bool hasWorkRemaining);
private:
// Our assumption about a particular operation.
enum Assumption { Possible, Impossible, Equal, LHSis1, RHSis1, LHSis0,
RHSis0 };
void UpdateAssumption(Assumption &A, const Assumption &New);
/// contains* - Useful recursive methods to see if a statement contains an
/// element somewhere. Used in static analysis to reduce false positives.
static bool isParameterSelfAssign(const Expr *LHS, const Expr *RHS);
static bool isTruncationExtensionAssignment(const Expr *LHS,
const Expr *RHS);
static bool containsZeroConstant(const Stmt *S);
static bool containsOneConstant(const Stmt *S);
// Hash table
typedef llvm::DenseMap<const BinaryOperator *, Assumption> AssumptionMap;
AssumptionMap hash;
};
}
void *IdempotentOperationChecker::getTag() {
static int x = 0;
return &x;
}
void clang::RegisterIdempotentOperationChecker(GRExprEngine &Eng) {
Eng.registerCheck(new IdempotentOperationChecker());
}
void IdempotentOperationChecker::PreVisitBinaryOperator(
CheckerContext &C,
const BinaryOperator *B) {
// Find or create an entry in the hash for this BinaryOperator instance
AssumptionMap::iterator i = hash.find(B);
Assumption &A = i == hash.end() ? hash[B] : i->second;
// If we had to create an entry, initialise the value to Possible
if (i == hash.end())
A = Possible;
// If we already have visited this node on a path that does not contain an
// idempotent operation, return immediately.
if (A == Impossible)
return;
// Skip binary operators containing common false positives
if (containsMacro(B) || containsEnum(B) || containsStmt<SizeOfAlignOfExpr>(B)
|| containsZeroConstant(B) || containsOneConstant(B)
|| containsBuiltinOffsetOf(B) || containsStaticLocal(B)) {
A = Impossible;
return;
}
const Expr *LHS = B->getLHS();
const Expr *RHS = B->getRHS();
const GRState *state = C.getState();
SVal LHSVal = state->getSVal(LHS);
SVal RHSVal = state->getSVal(RHS);
// If either value is unknown, we can't be 100% sure of all paths.
if (LHSVal.isUnknownOrUndef() || RHSVal.isUnknownOrUndef()) {
A = Impossible;
return;
}
BinaryOperator::Opcode Op = B->getOpcode();
// Dereference the LHS SVal if this is an assign operation
switch (Op) {
default:
break;
// Fall through intentional
case BinaryOperator::AddAssign:
case BinaryOperator::SubAssign:
case BinaryOperator::MulAssign:
case BinaryOperator::DivAssign:
case BinaryOperator::AndAssign:
case BinaryOperator::OrAssign:
case BinaryOperator::XorAssign:
case BinaryOperator::ShlAssign:
case BinaryOperator::ShrAssign:
case BinaryOperator::Assign:
// Assign statements have one extra level of indirection
if (!isa<Loc>(LHSVal)) {
A = Impossible;
return;
}
LHSVal = state->getSVal(cast<Loc>(LHSVal));
}
// We now check for various cases which result in an idempotent operation.
// x op x
switch (Op) {
default:
break; // We don't care about any other operators.
// Fall through intentional
case BinaryOperator::Assign:
// x Assign x has a few more false positives we can check for
if (isParameterSelfAssign(RHS, LHS)
|| isTruncationExtensionAssignment(RHS, LHS)) {
A = Impossible;
return;
}
case BinaryOperator::SubAssign:
case BinaryOperator::DivAssign:
case BinaryOperator::AndAssign:
case BinaryOperator::OrAssign:
case BinaryOperator::XorAssign:
case BinaryOperator::Sub:
case BinaryOperator::Div:
case BinaryOperator::And:
case BinaryOperator::Or:
case BinaryOperator::Xor:
case BinaryOperator::LOr:
case BinaryOperator::LAnd:
if (LHSVal != RHSVal)
break;
UpdateAssumption(A, Equal);
return;
}
// x op 1
switch (Op) {
default:
break; // We don't care about any other operators.
// Fall through intentional
case BinaryOperator::MulAssign:
case BinaryOperator::DivAssign:
case BinaryOperator::Mul:
case BinaryOperator::Div:
case BinaryOperator::LOr:
case BinaryOperator::LAnd:
if (!RHSVal.isConstant(1))
break;
UpdateAssumption(A, RHSis1);
return;
}
// 1 op x
switch (Op) {
default:
break; // We don't care about any other operators.
// Fall through intentional
case BinaryOperator::MulAssign:
case BinaryOperator::Mul:
case BinaryOperator::LOr:
case BinaryOperator::LAnd:
if (!LHSVal.isConstant(1))
break;
UpdateAssumption(A, LHSis1);
return;
}
// x op 0
switch (Op) {
default:
break; // We don't care about any other operators.
// Fall through intentional
case BinaryOperator::AddAssign:
case BinaryOperator::SubAssign:
case BinaryOperator::MulAssign:
case BinaryOperator::AndAssign:
case BinaryOperator::OrAssign:
case BinaryOperator::XorAssign:
case BinaryOperator::Add:
case BinaryOperator::Sub:
case BinaryOperator::Mul:
case BinaryOperator::And:
case BinaryOperator::Or:
case BinaryOperator::Xor:
case BinaryOperator::Shl:
case BinaryOperator::Shr:
case BinaryOperator::LOr:
case BinaryOperator::LAnd:
if (!RHSVal.isConstant(0))
break;
UpdateAssumption(A, RHSis0);
return;
}
// 0 op x
switch (Op) {
default:
break; // We don't care about any other operators.
// Fall through intentional
//case BinaryOperator::AddAssign: // Common false positive
case BinaryOperator::SubAssign: // Check only if unsigned
case BinaryOperator::MulAssign:
case BinaryOperator::DivAssign:
case BinaryOperator::AndAssign:
//case BinaryOperator::OrAssign: // Common false positive
//case BinaryOperator::XorAssign: // Common false positive
case BinaryOperator::ShlAssign:
case BinaryOperator::ShrAssign:
case BinaryOperator::Add:
case BinaryOperator::Sub:
case BinaryOperator::Mul:
case BinaryOperator::Div:
case BinaryOperator::And:
case BinaryOperator::Or:
case BinaryOperator::Xor:
case BinaryOperator::Shl:
case BinaryOperator::Shr:
case BinaryOperator::LOr:
case BinaryOperator::LAnd:
if (!LHSVal.isConstant(0))
break;
UpdateAssumption(A, LHSis0);
return;
}
// If we get to this point, there has been a valid use of this operation.
A = Impossible;
}
void IdempotentOperationChecker::VisitEndAnalysis(ExplodedGraph &G,
BugReporter &BR,
bool hasWorkRemaining) {
// If there is any work remaining we cannot be 100% sure about our warnings
if (hasWorkRemaining)
return;
// Iterate over the hash to see if we have any paths with definite
// idempotent operations.
for (AssumptionMap::const_iterator i =
hash.begin(); i != hash.end(); ++i) {
if (i->second != Impossible) {
// Select the error message.
const BinaryOperator *B = i->first;
llvm::SmallString<128> buf;
llvm::raw_svector_ostream os(buf);
switch (i->second) {
case Equal:
if (B->getOpcode() == BinaryOperator::Assign)
os << "Assigned value is always the same as the existing value";
else
os << "Both operands to '" << B->getOpcodeStr()
<< "' always have the same value";
break;
case LHSis1:
os << "The left operand to '" << B->getOpcodeStr() << "' is always 1";
break;
case RHSis1:
os << "The right operand to '" << B->getOpcodeStr() << "' is always 1";
break;
case LHSis0:
os << "The left operand to '" << B->getOpcodeStr() << "' is always 0";
break;
case RHSis0:
os << "The right operand to '" << B->getOpcodeStr() << "' is always 0";
break;
case Possible:
llvm_unreachable("Operation was never marked with an assumption");
case Impossible:
llvm_unreachable(0);
}
// Create the SourceRange Arrays
SourceRange S[2] = { i->first->getLHS()->getSourceRange(),
i->first->getRHS()->getSourceRange() };
BR.EmitBasicReport("Idempotent operation", "Dead code",
os.str(), i->first->getOperatorLoc(), S, 2);
}
}
}
// Updates the current assumption given the new assumption
inline void IdempotentOperationChecker::UpdateAssumption(Assumption &A,
const Assumption &New) {
switch (A) {
// If we don't currently have an assumption, set it
case Possible:
A = New;
return;
// If we have determined that a valid state happened, ignore the new
// assumption.
case Impossible:
return;
// Any other case means that we had a different assumption last time. We don't
// currently support mixing assumptions for diagnostic reasons, so we set
// our assumption to be impossible.
default:
A = Impossible;
return;
}
}
// Check for a statement were a parameter is self assigned (to avoid an unused
// variable warning)
bool IdempotentOperationChecker::isParameterSelfAssign(const Expr *LHS,
const Expr *RHS) {
LHS = LHS->IgnoreParenCasts();
RHS = RHS->IgnoreParenCasts();
const DeclRefExpr *LHS_DR = dyn_cast<DeclRefExpr>(LHS);
if (!LHS_DR)
return false;
const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(LHS_DR->getDecl());
if (!PD)
return false;
const DeclRefExpr *RHS_DR = dyn_cast<DeclRefExpr>(RHS);
if (!RHS_DR)
return false;
return PD == RHS_DR->getDecl();
}
// Check for self casts truncating/extending a variable
bool IdempotentOperationChecker::isTruncationExtensionAssignment(
const Expr *LHS,
const Expr *RHS) {
const DeclRefExpr *LHS_DR = dyn_cast<DeclRefExpr>(LHS->IgnoreParenCasts());
if (!LHS_DR)
return false;
const VarDecl *VD = dyn_cast<VarDecl>(LHS_DR->getDecl());
if (!VD)
return false;
const DeclRefExpr *RHS_DR = dyn_cast<DeclRefExpr>(RHS->IgnoreParenCasts());
if (!RHS_DR)
return false;
if (VD != RHS_DR->getDecl())
return false;
return dyn_cast<DeclRefExpr>(RHS->IgnoreParens()) == NULL;
}
// Check for a integer or float constant of 0
bool IdempotentOperationChecker::containsZeroConstant(const Stmt *S) {
const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(S);
if (IL && IL->getValue() == 0)
return true;
const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(S);
if (FL && FL->getValue().isZero())
return true;
for (Stmt::const_child_iterator I = S->child_begin(); I != S->child_end();
++I)
if (const Stmt *child = *I)
if (containsZeroConstant(child))
return true;
return false;
}
// Check for an integer or float constant of 1
bool IdempotentOperationChecker::containsOneConstant(const Stmt *S) {
const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(S);
if (IL && IL->getValue() == 1)
return true;
if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(S)) {
const llvm::APFloat &val = FL->getValue();
const llvm::APFloat one(val.getSemantics(), 1);
if (val.compare(one) == llvm::APFloat::cmpEqual)
return true;
}
for (Stmt::const_child_iterator I = S->child_begin(); I != S->child_end();
++I)
if (const Stmt *child = *I)
if (containsOneConstant(child))
return true;
return false;
}
<|endoftext|> |
<commit_before>/*!
@file
@author Albert Semenov
@date 12/2008
*/
#include "Precompiled.h"
#include "State.h"
namespace demo
{
State::State(const std::string& _layout, ControllerType _type) :
wraps::BaseLayout(_layout),
mFrameAdvise(false)
{
mType = _type;
assignWidget(mButton1, "Button1");
assignWidget(mButton2, "Button2");
assignWidget(mButton3, "Button3");
assignWidget(mButton4, "Button4");
mMainWidget->setVisible(false);
mButton1->setVisible(false);
mButton2->setVisible(false);
mButton3->setVisible(false);
mButton4->setVisible(false);
mButton1->eventMouseButtonClick += MyGUI::newDelegate(this, &State::notifyMouseButtonClick);
mButton2->eventMouseButtonClick += MyGUI::newDelegate(this, &State::notifyMouseButtonClick);
mButton3->eventMouseButtonClick += MyGUI::newDelegate(this, &State::notifyMouseButtonClick);
mButton4->eventMouseButtonClick += MyGUI::newDelegate(this, &State::notifyMouseButtonClick);
}
State::~State()
{
FrameAdvise(false);
}
void State::setVisible(bool _visible)
{
if (_visible)
{
mMainWidget->setVisible(false);
mButton1->setVisible(false);
mButton2->setVisible(false);
mButton3->setVisible(false);
mButton4->setVisible(false);
MyGUI::LayerManager::getInstance().upLayerItem(mMainWidget);
MyGUI::LayerManager::getInstance().upLayerItem(mButton1);
MyGUI::LayerManager::getInstance().upLayerItem(mButton2);
MyGUI::LayerManager::getInstance().upLayerItem(mButton3);
MyGUI::LayerManager::getInstance().upLayerItem(mButton4);
FrameAdvise(true);
mCountTime = 0;
}
else
{
MyGUI::ControllerManager& manager = MyGUI::ControllerManager::getInstance();
MyGUI::ControllerFadeAlpha* controller = createControllerFadeAlpha(0, 3, true);
manager.addItem(mMainWidget, controller);
controller = createControllerFadeAlpha(0, 3, true);
manager.addItem(mButton1, controller);
controller = createControllerFadeAlpha(0, 3, true);
manager.addItem(mButton2, controller);
controller = createControllerFadeAlpha(0, 3, true);
manager.addItem(mButton3, controller);
controller = createControllerFadeAlpha(0, 3, true);
manager.addItem(mButton4, controller);
}
}
void State::notifyMouseButtonClick(MyGUI::Widget* _sender)
{
if (_sender == mButton1) eventButtonPress(ControllerType::Inertional, false);
else if (_sender == mButton2) eventButtonPress(ControllerType::Accelerated, false);
else if (_sender == mButton3) eventButtonPress(ControllerType::Slowed, false);
else if (_sender == mButton4) eventButtonPress(ControllerType::Jump, false);
}
void State::notifyFrameEvent(float _time)
{
mCountTime += _time;
const int offset = 30;
const float time_diff = 0.3;
const MyGUI::IntSize& view = MyGUI::RenderManager::getInstance().getViewSize();
if (!mMainWidget->getVisible())
{
mMainWidget->setPosition(-mMainWidget->getWidth(), view.height - mMainWidget->getHeight() - offset);
mMainWidget->setVisible(true);
mMainWidget->setAlpha(1);
MyGUI::IntPoint point(offset, view.height - mMainWidget->getHeight() - offset);
MyGUI::ControllerManager::getInstance().addItem(mMainWidget, createControllerPosition(point));
}
if (!mButton1->getVisible())
{
mButton1->setPosition(view.width, offset);
mButton1->setVisible(true);
mButton1->setAlpha(1);
MyGUI::IntPoint point(view.width - mButton1->getWidth() - offset, offset);
MyGUI::ControllerManager::getInstance().addItem(mButton1, createControllerPosition(point));
}
if (mCountTime > time_diff)
{
if (!mButton2->getVisible())
{
mButton2->setPosition(view.width, (mButton2->getHeight() + offset) + offset);
mButton2->setVisible(true);
mButton2->setAlpha(1);
MyGUI::IntPoint point(view.width - mButton1->getWidth() - offset, (mButton2->getHeight() + offset) + offset);
MyGUI::ControllerManager::getInstance().addItem(mButton2, createControllerPosition(point));
}
}
if (mCountTime > time_diff * 2)
{
if (!mButton3->getVisible())
{
mButton3->setPosition(view.width, (mButton3->getHeight() + offset) * 2 + offset);
mButton3->setVisible(true);
mButton3->setAlpha(1);
MyGUI::IntPoint point(view.width - mButton3->getWidth() - offset, (mButton3->getHeight() + offset) * 2 + offset);
MyGUI::ControllerManager::getInstance().addItem(mButton3, createControllerPosition(point));
}
}
if (mCountTime > time_diff * 3)
{
if (!mButton4->getVisible())
{
mButton4->setPosition(view.width, (mButton4->getHeight() + offset) * 3 + offset);
mButton4->setVisible(true);
mButton4->setAlpha(1);
MyGUI::IntPoint point(view.width - mButton4->getWidth() - offset, (mButton4->getHeight() + offset) * 3 + offset);
MyGUI::ControllerPosition* controller = createControllerPosition(point);
MyGUI::ControllerManager::getInstance().addItem(mButton4, controller);
controller->eventPostAction += MyGUI::newDelegate(this, &State::notifyPostAction);
}
FrameAdvise(false);
}
}
void State::notifyPostAction(MyGUI::Widget* _sender, MyGUI::ControllerItem* _controller)
{
eventButtonPress(ControllerType::Slowed, true);
}
void State::FrameAdvise(bool _advise)
{
if (_advise)
{
if (!mFrameAdvise)
{
mFrameAdvise = true;
MyGUI::Gui::getInstance().eventFrameStart += MyGUI::newDelegate(this, &State::notifyFrameEvent);
}
}
else
{
if (mFrameAdvise)
{
mFrameAdvise = false;
MyGUI::Gui::getInstance().eventFrameStart -= MyGUI::newDelegate(this, &State::notifyFrameEvent);
}
}
}
MyGUI::ControllerPosition* State::createControllerPosition(const MyGUI::IntPoint& _point)
{
MyGUI::ControllerItem* item = MyGUI::ControllerManager::getInstance().createItem(MyGUI::ControllerPosition::getClassTypeName());
MyGUI::ControllerPosition* controller = item->castType<MyGUI::ControllerPosition>();
controller->setPosition(_point);
controller->setTime(0.5);
if (mType == ControllerType::Inertional) controller->setAction(MyGUI::newDelegate(MyGUI::action::inertionalMoveFunction));
else if (mType == ControllerType::Accelerated) controller->setAction(MyGUI::newDelegate(MyGUI::action::acceleratedMoveFunction<30>));
else if (mType == ControllerType::Slowed) controller->setAction(MyGUI::newDelegate(MyGUI::action::acceleratedMoveFunction<4>));
else controller->setAction(MyGUI::newDelegate(MyGUI::action::jumpMoveFunction<5>));
return controller;
}
MyGUI::ControllerFadeAlpha* State::createControllerFadeAlpha(float _alpha, float _coef, bool _enable)
{
MyGUI::ControllerItem* item = MyGUI::ControllerManager::getInstance().createItem(MyGUI::ControllerFadeAlpha::getClassTypeName());
MyGUI::ControllerFadeAlpha* controller = item->castType<MyGUI::ControllerFadeAlpha>();
controller->setAlpha(_alpha);
controller->setCoef(_coef);
controller->setEnabled(_enable);
return controller;
}
MyGUI::Widget* State::getClient()
{
return mMainWidget->getClientWidget();
}
} // namespace demo
<commit_msg>fix warning<commit_after>/*!
@file
@author Albert Semenov
@date 12/2008
*/
#include "Precompiled.h"
#include "State.h"
namespace demo
{
State::State(const std::string& _layout, ControllerType _type) :
wraps::BaseLayout(_layout),
mFrameAdvise(false)
{
mType = _type;
assignWidget(mButton1, "Button1");
assignWidget(mButton2, "Button2");
assignWidget(mButton3, "Button3");
assignWidget(mButton4, "Button4");
mMainWidget->setVisible(false);
mButton1->setVisible(false);
mButton2->setVisible(false);
mButton3->setVisible(false);
mButton4->setVisible(false);
mButton1->eventMouseButtonClick += MyGUI::newDelegate(this, &State::notifyMouseButtonClick);
mButton2->eventMouseButtonClick += MyGUI::newDelegate(this, &State::notifyMouseButtonClick);
mButton3->eventMouseButtonClick += MyGUI::newDelegate(this, &State::notifyMouseButtonClick);
mButton4->eventMouseButtonClick += MyGUI::newDelegate(this, &State::notifyMouseButtonClick);
}
State::~State()
{
FrameAdvise(false);
}
void State::setVisible(bool _visible)
{
if (_visible)
{
mMainWidget->setVisible(false);
mButton1->setVisible(false);
mButton2->setVisible(false);
mButton3->setVisible(false);
mButton4->setVisible(false);
MyGUI::LayerManager::getInstance().upLayerItem(mMainWidget);
MyGUI::LayerManager::getInstance().upLayerItem(mButton1);
MyGUI::LayerManager::getInstance().upLayerItem(mButton2);
MyGUI::LayerManager::getInstance().upLayerItem(mButton3);
MyGUI::LayerManager::getInstance().upLayerItem(mButton4);
FrameAdvise(true);
mCountTime = 0;
}
else
{
MyGUI::ControllerManager& manager = MyGUI::ControllerManager::getInstance();
MyGUI::ControllerFadeAlpha* controller = createControllerFadeAlpha(0, 3, true);
manager.addItem(mMainWidget, controller);
controller = createControllerFadeAlpha(0, 3, true);
manager.addItem(mButton1, controller);
controller = createControllerFadeAlpha(0, 3, true);
manager.addItem(mButton2, controller);
controller = createControllerFadeAlpha(0, 3, true);
manager.addItem(mButton3, controller);
controller = createControllerFadeAlpha(0, 3, true);
manager.addItem(mButton4, controller);
}
}
void State::notifyMouseButtonClick(MyGUI::Widget* _sender)
{
if (_sender == mButton1) eventButtonPress(ControllerType::Inertional, false);
else if (_sender == mButton2) eventButtonPress(ControllerType::Accelerated, false);
else if (_sender == mButton3) eventButtonPress(ControllerType::Slowed, false);
else if (_sender == mButton4) eventButtonPress(ControllerType::Jump, false);
}
void State::notifyFrameEvent(float _time)
{
mCountTime += _time;
const int offset = 30;
const float time_diff = 0.3f;
const MyGUI::IntSize& view = MyGUI::RenderManager::getInstance().getViewSize();
if (!mMainWidget->getVisible())
{
mMainWidget->setPosition(-mMainWidget->getWidth(), view.height - mMainWidget->getHeight() - offset);
mMainWidget->setVisible(true);
mMainWidget->setAlpha(1);
MyGUI::IntPoint point(offset, view.height - mMainWidget->getHeight() - offset);
MyGUI::ControllerManager::getInstance().addItem(mMainWidget, createControllerPosition(point));
}
if (!mButton1->getVisible())
{
mButton1->setPosition(view.width, offset);
mButton1->setVisible(true);
mButton1->setAlpha(1);
MyGUI::IntPoint point(view.width - mButton1->getWidth() - offset, offset);
MyGUI::ControllerManager::getInstance().addItem(mButton1, createControllerPosition(point));
}
if (mCountTime > time_diff)
{
if (!mButton2->getVisible())
{
mButton2->setPosition(view.width, (mButton2->getHeight() + offset) + offset);
mButton2->setVisible(true);
mButton2->setAlpha(1);
MyGUI::IntPoint point(view.width - mButton1->getWidth() - offset, (mButton2->getHeight() + offset) + offset);
MyGUI::ControllerManager::getInstance().addItem(mButton2, createControllerPosition(point));
}
}
if (mCountTime > time_diff * 2)
{
if (!mButton3->getVisible())
{
mButton3->setPosition(view.width, (mButton3->getHeight() + offset) * 2 + offset);
mButton3->setVisible(true);
mButton3->setAlpha(1);
MyGUI::IntPoint point(view.width - mButton3->getWidth() - offset, (mButton3->getHeight() + offset) * 2 + offset);
MyGUI::ControllerManager::getInstance().addItem(mButton3, createControllerPosition(point));
}
}
if (mCountTime > time_diff * 3)
{
if (!mButton4->getVisible())
{
mButton4->setPosition(view.width, (mButton4->getHeight() + offset) * 3 + offset);
mButton4->setVisible(true);
mButton4->setAlpha(1);
MyGUI::IntPoint point(view.width - mButton4->getWidth() - offset, (mButton4->getHeight() + offset) * 3 + offset);
MyGUI::ControllerPosition* controller = createControllerPosition(point);
MyGUI::ControllerManager::getInstance().addItem(mButton4, controller);
controller->eventPostAction += MyGUI::newDelegate(this, &State::notifyPostAction);
}
FrameAdvise(false);
}
}
void State::notifyPostAction(MyGUI::Widget* _sender, MyGUI::ControllerItem* _controller)
{
eventButtonPress(ControllerType::Slowed, true);
}
void State::FrameAdvise(bool _advise)
{
if (_advise)
{
if (!mFrameAdvise)
{
mFrameAdvise = true;
MyGUI::Gui::getInstance().eventFrameStart += MyGUI::newDelegate(this, &State::notifyFrameEvent);
}
}
else
{
if (mFrameAdvise)
{
mFrameAdvise = false;
MyGUI::Gui::getInstance().eventFrameStart -= MyGUI::newDelegate(this, &State::notifyFrameEvent);
}
}
}
MyGUI::ControllerPosition* State::createControllerPosition(const MyGUI::IntPoint& _point)
{
MyGUI::ControllerItem* item = MyGUI::ControllerManager::getInstance().createItem(MyGUI::ControllerPosition::getClassTypeName());
MyGUI::ControllerPosition* controller = item->castType<MyGUI::ControllerPosition>();
controller->setPosition(_point);
controller->setTime(0.5);
if (mType == ControllerType::Inertional) controller->setAction(MyGUI::newDelegate(MyGUI::action::inertionalMoveFunction));
else if (mType == ControllerType::Accelerated) controller->setAction(MyGUI::newDelegate(MyGUI::action::acceleratedMoveFunction<30>));
else if (mType == ControllerType::Slowed) controller->setAction(MyGUI::newDelegate(MyGUI::action::acceleratedMoveFunction<4>));
else controller->setAction(MyGUI::newDelegate(MyGUI::action::jumpMoveFunction<5>));
return controller;
}
MyGUI::ControllerFadeAlpha* State::createControllerFadeAlpha(float _alpha, float _coef, bool _enable)
{
MyGUI::ControllerItem* item = MyGUI::ControllerManager::getInstance().createItem(MyGUI::ControllerFadeAlpha::getClassTypeName());
MyGUI::ControllerFadeAlpha* controller = item->castType<MyGUI::ControllerFadeAlpha>();
controller->setAlpha(_alpha);
controller->setCoef(_coef);
controller->setEnabled(_enable);
return controller;
}
MyGUI::Widget* State::getClient()
{
return mMainWidget->getClientWidget();
}
} // namespace demo
<|endoftext|> |
<commit_before>#include <sys/types.h>
#include <sys/stat.h>
#include <cstdio>
#include <cstddef>
#include <cstdlib>
#include <unistd.h>
#include <fcntl.h>
#include <elf.h>
#include <algorithm>
#include <cassert>
// COMPILATION NOTE: Must pass -lseccomp to build
#include <seccomp.h>
#include <set>
#include <string>
#include <seccomp.h>
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#define SUBMITTY_INSTALL_DIRECTORY std::string("__INSTALL__FILLIN__SUBMITTY_INSTALL_DIR__")
#define ALLOW_SYSCALL(name) allow_syscall(sc,SCMP_SYS(name),#name)
inline void allow_syscall(scmp_filter_ctx sc, int syscall, const std::string &syscall_string) {
//std::cout << "allow " << syscall_string << std::endl;
int res = seccomp_rule_add(sc, SCMP_ACT_ALLOW, syscall, 0);
if (res < 0) {
std::cerr << "WARNING: Errno " << res << " installing seccomp rule for " << syscall_string << std::endl;
}
}
// ===========================================================================
// ===========================================================================
//
// This helper file defines one function:
// void allow_system_calls(scmp_filter_ctx sc, const std::set<std::string> &categories) {
//
// It is placed in a separate file, since the helper utility
// system_call_check.cpp parses this function to define the categories.
//
#include "system_call_categories.cpp"
#include "json.hpp"
// ===========================================================================
// ===========================================================================
int install_syscall_filter(bool is_32, const std::string &my_program, std::ofstream &execute_logfile, const nlohmann::json &whole_config) {
int res;
scmp_filter_ctx sc = seccomp_init(SCMP_ACT_KILL);
int target_arch = is_32 ? SCMP_ARCH_X86 : SCMP_ARCH_X86_64;
if (seccomp_arch_native() != target_arch) {
res = seccomp_arch_add(sc, target_arch);
if (res != 0) {
//fprintf(stderr, "seccomp_arch_add failed: %d\n", res);
return 1;
}
}
// libseccomp uses pseudo-syscalls to let us use the 64-bit split
// system call names for SYS_socketcall on 32-bit. The translation
// being on their side means we have no choice in the matter as we
// cannot pass them the number for the target: only for the source.
// We could use raw seccomp-bpf instead.
std::set<std::string> categories;
// grep ' :' grading/system_call_categories.cpp | grep WHITELIST | cut -f 6 -d ' '
// grep ' :' grading/system_call_categories.cpp | grep RESTRICTED | cut -f 6 -d ' '
// grep ' :' grading/system_call_categories.cpp | grep FORBIDDEN | cut -f 6 -d ' '
std::set<std::string> whitelist_categories = {
"PROCESS_CONTROL",
"PROCESS_CONTROL_MEMORY",
"PROCESS_CONTROL_WAITING",
"FILE_MANAGEMENT",
"DEVICE_MANAGEMENT",
"INFORMATION_MAINTENANCE"
};
std::set<std::string> restricted_categories = {
"PROCESS_CONTROL_MEMORY_ADVANCED",
"PROCESS_CONTROL_NEW_PROCESS_THREAD",
"PROCESS_CONTROL_SYNCHRONIZATION",
"PROCESS_CONTROL_SCHEDULING",
"PROCESS_CONTROL_ADVANCED",
"PROCESS_CONTROL_GET_SET_USER_GROUP_ID",
"FILE_MANAGEMENT_MOVE_DELETE_RENAME_FILE_DIRECTORY",
"FILE_MANAGEMENT_PERMISSIONS",
"FILE_MANAGEMENT_CAPABILITIES",
"FILE_MANAGEMENT_EXTENDED_ATTRIBUTES",
"FILE_MANAGEMENT_RARE",
"DEVICE_MANAGEMENT_ADVANCED",
"DEVICE_MANAGEMENT_NEW_DEVICE",
"INFORMATION_MAINTENANCE_ADVANCED",
"COMMUNICATIONS_AND_NETWORKING_SOCKETS_MINIMAL",
"COMMUNICATIONS_AND_NETWORKING_SOCKETS",
"COMMUNICATIONS_AND_NETWORKING_SIGNALS",
"COMMUNICATIONS_AND_NETWORKING_INTERPROCESS_COMMUNICATION",
"TGKILL",
"COMMUNICATIONS_AND_NETWORKING_KILL",
"UNKNOWN",
"UNKNOWN_MODULE",
"UNKNOWN_REMAP_PAGES"
};
std::set<std::string> forbidden_categories = {
"INFORMATION_MAINTENANCE_SET_TIME"
};
// ---------------------------------------------------------------
// READ ALLOWED SYSTEM CALLS FROM CONFIG.JSON
const nlohmann::json &config_whitelist = whole_config.value("allow_system_calls",nlohmann::json());
for (nlohmann::json::const_iterator cwitr = config_whitelist.begin();
cwitr != config_whitelist.end(); cwitr++) {
std::string my_category = *cwitr;
if (my_category.size() > 27 && my_category.substr(0,27) == "ALLOW_SYSTEM_CALL_CATEGORY_") {
my_category = my_category.substr(27,my_category.size()-27);
}
// make sure categories is valid
assert (restricted_categories.find(my_category) != restricted_categories.end());
categories.insert(my_category);
}
// --------------------------------------------------------------
// HELPER UTILTIY PROGRAMS
if (my_program == "/bin/cp") {
categories.insert("PROCESS_CONTROL_NEW_PROCESS_THREAD");
categories.insert("PROCESS_CONTROL_ADVANCED");
}
else if (my_program == "/bin/mv") {
categories.insert("PROCESS_CONTROL_NEW_PROCESS_THREAD");
categories.insert("FILE_MANAGEMENT_MOVE_DELETE_RENAME_FILE_DIRECTORY");
categories.insert("PROCESS_CONTROL_ADVANCED");
}
else if (my_program == "/usr/bin/time") {
categories.insert("PROCESS_CONTROL_NEW_PROCESS_THREAD");
}
else if (my_program == "/usr/bin/strace") {
categories = restricted_categories;
}
// ---------------------------------------------------------------
// SUBMITTY ANALYSIS TOOLS
else if (my_program == SUBMITTY_INSTALL_DIRECTORY+"/SubmittyAnalysisTools/count") {
//TODO
categories = restricted_categories;
categories.insert("COMMUNICATIONS_AND_NETWORKING_SIGNALS");
categories.insert("FILE_MANAGEMENT_RARE");
categories.insert("PROCESS_CONTROL_NEW_PROCESS_THREAD");
categories.insert("COMMUNICATIONS_AND_NETWORKING_INTERPROCESS_COMMUNICATION");
}
// ---------------------------------------------------------------
// PYTHON
else if (my_program.find("/usr/bin/python") != std::string::npos) {
categories = restricted_categories; //TODO: fix
categories.insert("PROCESS_CONTROL_NEW_PROCESS_THREAD");
categories.insert("COMMUNICATIONS_AND_NETWORKING_SIGNALS");
categories.insert("FILE_MANAGEMENT_RARE");
categories.insert("COMMUNICATIONS_AND_NETWORKING_SOCKETS_MINIMAL");
}
// ---------------------------------------------------------------
// C/C++ COMPILATION
else if (my_program == "/usr/bin/g++" ||
my_program == "/usr/bin/clang++" ||
my_program == "/usr/bin/gcc") {
categories.insert("PROCESS_CONTROL_NEW_PROCESS_THREAD");
categories.insert("FILE_MANAGEMENT_MOVE_DELETE_RENAME_FILE_DIRECTORY");
categories.insert("FILE_MANAGEMENT_PERMISSIONS");
categories.insert("FILE_MANAGEMENT_RARE");
categories.insert("PROCESS_CONTROL_ADVANCED");
categories.insert("PROCESS_CONTROL_NEW_PROCESS_THREAD");
categories.insert("TGKILL");
categories.insert("COMMUNICATIONS_AND_NETWORKING_SIGNALS");
}
// ---------------------------------------------------------------
// CMAKE/MAKE COMPILATION
else if (my_program == "/usr/bin/cmake" ||
my_program == "/usr/bin/make") {
categories = restricted_categories;
}
// ---------------------------------------------------------------
// JAVA COMPILATION
else if (my_program == "/usr/bin/javac") {
categories.insert("PROCESS_CONTROL_NEW_PROCESS_THREAD");
categories.insert("PROCESS_CONTROL_MEMORY_ADVANCED");
categories.insert("PROCESS_CONTROL_SYNCHRONIZATION");
categories.insert("PROCESS_CONTROL_SCHEDULING");
categories.insert("PROCESS_CONTROL_ADVANCED");
categories.insert("FILE_MANAGEMENT_MOVE_DELETE_RENAME_FILE_DIRECTORY");
categories.insert("FILE_MANAGEMENT_PERMISSIONS");
categories.insert("FILE_MANAGEMENT_CAPABILITIES");
categories.insert("FILE_MANAGEMENT_EXTENDED_ATTRIBUTES");
categories.insert("FILE_MANAGEMENT_RARE");
categories.insert("INFORMATION_MAINTENANCE_ADVANCED");
categories.insert("COMMUNICATIONS_AND_NETWORKING_SOCKETS_MINIMAL");
categories.insert("COMMUNICATIONS_AND_NETWORKING_SOCKETS");
categories.insert("COMMUNICATIONS_AND_NETWORKING_SIGNALS");
categories.insert("COMMUNICATIONS_AND_NETWORKING_INTERPROCESS_COMMUNICATION");
categories.insert("TGKILL");
categories.insert("COMMUNICATIONS_AND_NETWORKING_KILL");
categories.insert("UNKNOWN");
categories.insert("UNKNOWN_MODULE");
}
// ---------------------------------------------------------------
// JAVA
else if (my_program == "/usr/bin/java") {
categories.insert("COMMUNICATIONS_AND_NETWORKING_SIGNALS");
categories.insert("COMMUNICATIONS_AND_NETWORKING_SOCKETS_MINIMAL");
categories.insert("COMMUNICATIONS_AND_NETWORKING_SOCKETS");
categories.insert("FILE_MANAGEMENT_MOVE_DELETE_RENAME_FILE_DIRECTORY");
categories.insert("FILE_MANAGEMENT_PERMISSIONS");
categories.insert("FILE_MANAGEMENT_RARE");
categories.insert("PROCESS_CONTROL_ADVANCED");
categories.insert("PROCESS_CONTROL_GET_SET_USER_GROUP_ID");
categories.insert("PROCESS_CONTROL_MEMORY_ADVANCED");
categories.insert("PROCESS_CONTROL_NEW_PROCESS_THREAD");
categories.insert("PROCESS_CONTROL_SCHEDULING");
categories.insert("PROCESS_CONTROL_SYNCHRONIZATION");
categories.insert("FILE_MANAGEMENT_CAPABILITIES");
categories.insert("FILE_MANAGEMENT_EXTENDED_ATTRIBUTES");
categories.insert("INFORMATION_MAINTENANCE_ADVANCED");
categories.insert("COMMUNICATIONS_AND_NETWORKING_INTERPROCESS_COMMUNICATION");
categories.insert("TGKILL");
categories.insert("COMMUNICATIONS_AND_NETWORKING_KILL");
categories.insert("UNKNOWN");
categories.insert("UNKNOWN_MODULE");
}
// ---------------------------------------------------------------
// SWI PROLOG
else if (my_program == "/usr/bin/swipl") {
categories.insert("FILE_MANAGEMENT_PERMISSIONS");
categories.insert("FILE_MANAGEMENT_RARE");
categories.insert("PROCESS_CONTROL_ADVANCED");
categories.insert("PROCESS_CONTROL_NEW_PROCESS_THREAD");
}
// RACKET SCHEME
else if (my_program == "/usr/bin/plt-r5rs") {
categories.insert("COMMUNICATIONS_AND_NETWORKING_INTERPROCESS_COMMUNICATION");
categories.insert("COMMUNICATIONS_AND_NETWORKING_SIGNALS");
categories.insert("FILE_MANAGEMENT_PERMISSIONS");
categories.insert("FILE_MANAGEMENT_RARE");
categories.insert("PROCESS_CONTROL_ADVANCED");
categories.insert("PROCESS_CONTROL_GET_SET_USER_GROUP_ID");
categories.insert("PROCESS_CONTROL_NEW_PROCESS_THREAD");
categories.insert("PROCESS_CONTROL_SYNCHRONIZATION");
}
// ---------------------------------------------------------------
// C++ Memory Debugging
// FIXME: update with the actual dr memory install location?
else if (my_program.find("drmemory") != std::string::npos ||
my_program.find("valgrind") != std::string::npos) {
categories.insert("COMMUNICATIONS_AND_NETWORKING_SIGNALS");
categories.insert("COMMUNICATIONS_AND_NETWORKING_INTERPROCESS_COMMUNICATION");
categories.insert("FILE_MANAGEMENT_EXTENDED_ATTRIBUTES");
categories.insert("FILE_MANAGEMENT_MOVE_DELETE_RENAME_FILE_DIRECTORY");
categories.insert("FILE_MANAGEMENT_PERMISSIONS");
categories.insert("FILE_MANAGEMENT_RARE");
categories.insert("PROCESS_CONTROL_ADVANCED");
categories.insert("PROCESS_CONTROL_GET_SET_USER_GROUP_ID");
categories.insert("PROCESS_CONTROL_NEW_PROCESS_THREAD");
categories.insert("PROCESS_CONTROL_SYNCHRONIZATION");
categories.insert("DEVICE_MANAGEMENT_NEW_DEVICE");
categories.insert("TGKILL");
}
// ---------------------------------------------------------------
// IMAGE COMPARISON
else if (my_program == "/usr/bin/compare") {
categories.insert("FILE_MANAGEMENT_PERMISSIONS");
categories.insert("PROCESS_CONTROL_ADVANCED");
categories.insert("PROCESS_CONTROL_NEW_PROCESS_THREAD");
categories.insert("PROCESS_CONTROL_SCHEDULING");
}
// ---------------------------------------------------------------
else if (my_program == "/usr/bin/sort") {
categories.insert("PROCESS_CONTROL_NEW_PROCESS_THREAD");
categories.insert("PROCESS_CONTROL_SCHEDULING");
categories.insert("FILE_MANAGEMENT_RARE");
categories.insert("PROCESS_CONTROL_ADVANCED");
}
// ---------------------------------------------------------------
//KEYBOARD INPUT
else if(my_program == "/usr/bin/xdotool"){
categories = restricted_categories; //TODO: fix
}
// ---------------------------------------------------------------
//WINDOW FOCUS
else if(my_program == "/usr/bin/wmctrl"){
categories = restricted_categories; //TODO: fix
}
// ---------------------------------------------------------------
//WINDOW INFORMATION
else if(my_program == "/usr/bin/xwininfo"){
categories = restricted_categories; //TODO: fix
}
// ---------------------------------------------------------------
//SCREENSHOT FUNCTIONALITY
else if(my_program == "/usr/bin/scrot"){
categories = restricted_categories; //TODO: fix
}
else {
categories = restricted_categories; //TODO: fix
// UGH, don't want this here
categories.insert("PROCESS_CONTROL_NEW_PROCESS_THREAD");
}
// make sure all categories are valid
for_each(categories.begin(),categories.end(),
[restricted_categories](const std::string &s){
assert (restricted_categories.find(s) != restricted_categories.end()); });
allow_system_calls(sc,categories);
if (seccomp_load(sc) < 0)
return 1; // failure
/* This does not remove the filter */
seccomp_release(sc);
return 0;
}
// ===========================================================================
// ===========================================================================
<commit_msg>[Bugfix] add missing system call when drmemory has errors (#3595)<commit_after>#include <sys/types.h>
#include <sys/stat.h>
#include <cstdio>
#include <cstddef>
#include <cstdlib>
#include <unistd.h>
#include <fcntl.h>
#include <elf.h>
#include <algorithm>
#include <cassert>
// COMPILATION NOTE: Must pass -lseccomp to build
#include <seccomp.h>
#include <set>
#include <string>
#include <seccomp.h>
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#define SUBMITTY_INSTALL_DIRECTORY std::string("__INSTALL__FILLIN__SUBMITTY_INSTALL_DIR__")
#define ALLOW_SYSCALL(name) allow_syscall(sc,SCMP_SYS(name),#name)
inline void allow_syscall(scmp_filter_ctx sc, int syscall, const std::string &syscall_string) {
//std::cout << "allow " << syscall_string << std::endl;
int res = seccomp_rule_add(sc, SCMP_ACT_ALLOW, syscall, 0);
if (res < 0) {
std::cerr << "WARNING: Errno " << res << " installing seccomp rule for " << syscall_string << std::endl;
}
}
// ===========================================================================
// ===========================================================================
//
// This helper file defines one function:
// void allow_system_calls(scmp_filter_ctx sc, const std::set<std::string> &categories) {
//
// It is placed in a separate file, since the helper utility
// system_call_check.cpp parses this function to define the categories.
//
#include "system_call_categories.cpp"
#include "json.hpp"
// ===========================================================================
// ===========================================================================
int install_syscall_filter(bool is_32, const std::string &my_program, std::ofstream &execute_logfile, const nlohmann::json &whole_config) {
int res;
scmp_filter_ctx sc = seccomp_init(SCMP_ACT_KILL);
int target_arch = is_32 ? SCMP_ARCH_X86 : SCMP_ARCH_X86_64;
if (seccomp_arch_native() != target_arch) {
res = seccomp_arch_add(sc, target_arch);
if (res != 0) {
//fprintf(stderr, "seccomp_arch_add failed: %d\n", res);
return 1;
}
}
// libseccomp uses pseudo-syscalls to let us use the 64-bit split
// system call names for SYS_socketcall on 32-bit. The translation
// being on their side means we have no choice in the matter as we
// cannot pass them the number for the target: only for the source.
// We could use raw seccomp-bpf instead.
std::set<std::string> categories;
// grep ' :' grading/system_call_categories.cpp | grep WHITELIST | cut -f 6 -d ' '
// grep ' :' grading/system_call_categories.cpp | grep RESTRICTED | cut -f 6 -d ' '
// grep ' :' grading/system_call_categories.cpp | grep FORBIDDEN | cut -f 6 -d ' '
std::set<std::string> whitelist_categories = {
"PROCESS_CONTROL",
"PROCESS_CONTROL_MEMORY",
"PROCESS_CONTROL_WAITING",
"FILE_MANAGEMENT",
"DEVICE_MANAGEMENT",
"INFORMATION_MAINTENANCE"
};
std::set<std::string> restricted_categories = {
"PROCESS_CONTROL_MEMORY_ADVANCED",
"PROCESS_CONTROL_NEW_PROCESS_THREAD",
"PROCESS_CONTROL_SYNCHRONIZATION",
"PROCESS_CONTROL_SCHEDULING",
"PROCESS_CONTROL_ADVANCED",
"PROCESS_CONTROL_GET_SET_USER_GROUP_ID",
"FILE_MANAGEMENT_MOVE_DELETE_RENAME_FILE_DIRECTORY",
"FILE_MANAGEMENT_PERMISSIONS",
"FILE_MANAGEMENT_CAPABILITIES",
"FILE_MANAGEMENT_EXTENDED_ATTRIBUTES",
"FILE_MANAGEMENT_RARE",
"DEVICE_MANAGEMENT_ADVANCED",
"DEVICE_MANAGEMENT_NEW_DEVICE",
"INFORMATION_MAINTENANCE_ADVANCED",
"COMMUNICATIONS_AND_NETWORKING_SOCKETS_MINIMAL",
"COMMUNICATIONS_AND_NETWORKING_SOCKETS",
"COMMUNICATIONS_AND_NETWORKING_SIGNALS",
"COMMUNICATIONS_AND_NETWORKING_INTERPROCESS_COMMUNICATION",
"TGKILL",
"COMMUNICATIONS_AND_NETWORKING_KILL",
"UNKNOWN",
"UNKNOWN_MODULE",
"UNKNOWN_REMAP_PAGES"
};
std::set<std::string> forbidden_categories = {
"INFORMATION_MAINTENANCE_SET_TIME"
};
// ---------------------------------------------------------------
// READ ALLOWED SYSTEM CALLS FROM CONFIG.JSON
const nlohmann::json &config_whitelist = whole_config.value("allow_system_calls",nlohmann::json());
for (nlohmann::json::const_iterator cwitr = config_whitelist.begin();
cwitr != config_whitelist.end(); cwitr++) {
std::string my_category = *cwitr;
if (my_category.size() > 27 && my_category.substr(0,27) == "ALLOW_SYSTEM_CALL_CATEGORY_") {
my_category = my_category.substr(27,my_category.size()-27);
}
// make sure categories is valid
assert (restricted_categories.find(my_category) != restricted_categories.end());
categories.insert(my_category);
}
// --------------------------------------------------------------
// HELPER UTILTIY PROGRAMS
if (my_program == "/bin/cp") {
categories.insert("PROCESS_CONTROL_NEW_PROCESS_THREAD");
categories.insert("PROCESS_CONTROL_ADVANCED");
}
else if (my_program == "/bin/mv") {
categories.insert("PROCESS_CONTROL_NEW_PROCESS_THREAD");
categories.insert("FILE_MANAGEMENT_MOVE_DELETE_RENAME_FILE_DIRECTORY");
categories.insert("PROCESS_CONTROL_ADVANCED");
}
else if (my_program == "/usr/bin/time") {
categories.insert("PROCESS_CONTROL_NEW_PROCESS_THREAD");
}
else if (my_program == "/usr/bin/strace") {
categories = restricted_categories;
}
// ---------------------------------------------------------------
// SUBMITTY ANALYSIS TOOLS
else if (my_program == SUBMITTY_INSTALL_DIRECTORY+"/SubmittyAnalysisTools/count") {
//TODO
categories = restricted_categories;
categories.insert("COMMUNICATIONS_AND_NETWORKING_SIGNALS");
categories.insert("FILE_MANAGEMENT_RARE");
categories.insert("PROCESS_CONTROL_NEW_PROCESS_THREAD");
categories.insert("COMMUNICATIONS_AND_NETWORKING_INTERPROCESS_COMMUNICATION");
}
// ---------------------------------------------------------------
// PYTHON
else if (my_program.find("/usr/bin/python") != std::string::npos) {
categories = restricted_categories; //TODO: fix
categories.insert("PROCESS_CONTROL_NEW_PROCESS_THREAD");
categories.insert("COMMUNICATIONS_AND_NETWORKING_SIGNALS");
categories.insert("FILE_MANAGEMENT_RARE");
categories.insert("COMMUNICATIONS_AND_NETWORKING_SOCKETS_MINIMAL");
}
// ---------------------------------------------------------------
// C/C++ COMPILATION
else if (my_program == "/usr/bin/g++" ||
my_program == "/usr/bin/clang++" ||
my_program == "/usr/bin/gcc") {
categories.insert("PROCESS_CONTROL_NEW_PROCESS_THREAD");
categories.insert("FILE_MANAGEMENT_MOVE_DELETE_RENAME_FILE_DIRECTORY");
categories.insert("FILE_MANAGEMENT_PERMISSIONS");
categories.insert("FILE_MANAGEMENT_RARE");
categories.insert("PROCESS_CONTROL_ADVANCED");
categories.insert("PROCESS_CONTROL_NEW_PROCESS_THREAD");
categories.insert("TGKILL");
categories.insert("COMMUNICATIONS_AND_NETWORKING_SIGNALS");
}
// ---------------------------------------------------------------
// CMAKE/MAKE COMPILATION
else if (my_program == "/usr/bin/cmake" ||
my_program == "/usr/bin/make") {
categories = restricted_categories;
}
// ---------------------------------------------------------------
// JAVA COMPILATION
else if (my_program == "/usr/bin/javac") {
categories.insert("PROCESS_CONTROL_NEW_PROCESS_THREAD");
categories.insert("PROCESS_CONTROL_MEMORY_ADVANCED");
categories.insert("PROCESS_CONTROL_SYNCHRONIZATION");
categories.insert("PROCESS_CONTROL_SCHEDULING");
categories.insert("PROCESS_CONTROL_ADVANCED");
categories.insert("FILE_MANAGEMENT_MOVE_DELETE_RENAME_FILE_DIRECTORY");
categories.insert("FILE_MANAGEMENT_PERMISSIONS");
categories.insert("FILE_MANAGEMENT_CAPABILITIES");
categories.insert("FILE_MANAGEMENT_EXTENDED_ATTRIBUTES");
categories.insert("FILE_MANAGEMENT_RARE");
categories.insert("INFORMATION_MAINTENANCE_ADVANCED");
categories.insert("COMMUNICATIONS_AND_NETWORKING_SOCKETS_MINIMAL");
categories.insert("COMMUNICATIONS_AND_NETWORKING_SOCKETS");
categories.insert("COMMUNICATIONS_AND_NETWORKING_SIGNALS");
categories.insert("COMMUNICATIONS_AND_NETWORKING_INTERPROCESS_COMMUNICATION");
categories.insert("TGKILL");
categories.insert("COMMUNICATIONS_AND_NETWORKING_KILL");
categories.insert("UNKNOWN");
categories.insert("UNKNOWN_MODULE");
}
// ---------------------------------------------------------------
// JAVA
else if (my_program == "/usr/bin/java") {
categories.insert("COMMUNICATIONS_AND_NETWORKING_SIGNALS");
categories.insert("COMMUNICATIONS_AND_NETWORKING_SOCKETS_MINIMAL");
categories.insert("COMMUNICATIONS_AND_NETWORKING_SOCKETS");
categories.insert("FILE_MANAGEMENT_MOVE_DELETE_RENAME_FILE_DIRECTORY");
categories.insert("FILE_MANAGEMENT_PERMISSIONS");
categories.insert("FILE_MANAGEMENT_RARE");
categories.insert("PROCESS_CONTROL_ADVANCED");
categories.insert("PROCESS_CONTROL_GET_SET_USER_GROUP_ID");
categories.insert("PROCESS_CONTROL_MEMORY_ADVANCED");
categories.insert("PROCESS_CONTROL_NEW_PROCESS_THREAD");
categories.insert("PROCESS_CONTROL_SCHEDULING");
categories.insert("PROCESS_CONTROL_SYNCHRONIZATION");
categories.insert("FILE_MANAGEMENT_CAPABILITIES");
categories.insert("FILE_MANAGEMENT_EXTENDED_ATTRIBUTES");
categories.insert("INFORMATION_MAINTENANCE_ADVANCED");
categories.insert("COMMUNICATIONS_AND_NETWORKING_INTERPROCESS_COMMUNICATION");
categories.insert("TGKILL");
categories.insert("COMMUNICATIONS_AND_NETWORKING_KILL");
categories.insert("UNKNOWN");
categories.insert("UNKNOWN_MODULE");
}
// ---------------------------------------------------------------
// SWI PROLOG
else if (my_program == "/usr/bin/swipl") {
categories.insert("FILE_MANAGEMENT_PERMISSIONS");
categories.insert("FILE_MANAGEMENT_RARE");
categories.insert("PROCESS_CONTROL_ADVANCED");
categories.insert("PROCESS_CONTROL_NEW_PROCESS_THREAD");
}
// RACKET SCHEME
else if (my_program == "/usr/bin/plt-r5rs") {
categories.insert("COMMUNICATIONS_AND_NETWORKING_INTERPROCESS_COMMUNICATION");
categories.insert("COMMUNICATIONS_AND_NETWORKING_SIGNALS");
categories.insert("FILE_MANAGEMENT_PERMISSIONS");
categories.insert("FILE_MANAGEMENT_RARE");
categories.insert("PROCESS_CONTROL_ADVANCED");
categories.insert("PROCESS_CONTROL_GET_SET_USER_GROUP_ID");
categories.insert("PROCESS_CONTROL_NEW_PROCESS_THREAD");
categories.insert("PROCESS_CONTROL_SYNCHRONIZATION");
}
// ---------------------------------------------------------------
// C++ Memory Debugging
// FIXME: update with the actual dr memory install location?
else if (my_program.find("drmemory") != std::string::npos ||
my_program.find("valgrind") != std::string::npos) {
categories.insert("COMMUNICATIONS_AND_NETWORKING_SIGNALS");
categories.insert("COMMUNICATIONS_AND_NETWORKING_INTERPROCESS_COMMUNICATION");
categories.insert("COMMUNICATIONS_AND_NETWORKING_KILL");
categories.insert("FILE_MANAGEMENT_EXTENDED_ATTRIBUTES");
categories.insert("FILE_MANAGEMENT_MOVE_DELETE_RENAME_FILE_DIRECTORY");
categories.insert("FILE_MANAGEMENT_PERMISSIONS");
categories.insert("FILE_MANAGEMENT_RARE");
categories.insert("PROCESS_CONTROL_ADVANCED");
categories.insert("PROCESS_CONTROL_GET_SET_USER_GROUP_ID");
categories.insert("PROCESS_CONTROL_NEW_PROCESS_THREAD");
categories.insert("PROCESS_CONTROL_SYNCHRONIZATION");
categories.insert("DEVICE_MANAGEMENT_NEW_DEVICE");
categories.insert("TGKILL");
}
// ---------------------------------------------------------------
// IMAGE COMPARISON
else if (my_program == "/usr/bin/compare") {
categories.insert("FILE_MANAGEMENT_PERMISSIONS");
categories.insert("PROCESS_CONTROL_ADVANCED");
categories.insert("PROCESS_CONTROL_NEW_PROCESS_THREAD");
categories.insert("PROCESS_CONTROL_SCHEDULING");
}
// ---------------------------------------------------------------
else if (my_program == "/usr/bin/sort") {
categories.insert("PROCESS_CONTROL_NEW_PROCESS_THREAD");
categories.insert("PROCESS_CONTROL_SCHEDULING");
categories.insert("FILE_MANAGEMENT_RARE");
categories.insert("PROCESS_CONTROL_ADVANCED");
}
// ---------------------------------------------------------------
//KEYBOARD INPUT
else if(my_program == "/usr/bin/xdotool"){
categories = restricted_categories; //TODO: fix
}
// ---------------------------------------------------------------
//WINDOW FOCUS
else if(my_program == "/usr/bin/wmctrl"){
categories = restricted_categories; //TODO: fix
}
// ---------------------------------------------------------------
//WINDOW INFORMATION
else if(my_program == "/usr/bin/xwininfo"){
categories = restricted_categories; //TODO: fix
}
// ---------------------------------------------------------------
//SCREENSHOT FUNCTIONALITY
else if(my_program == "/usr/bin/scrot"){
categories = restricted_categories; //TODO: fix
}
else {
categories = restricted_categories; //TODO: fix
// UGH, don't want this here
categories.insert("PROCESS_CONTROL_NEW_PROCESS_THREAD");
}
// make sure all categories are valid
for_each(categories.begin(),categories.end(),
[restricted_categories](const std::string &s){
assert (restricted_categories.find(s) != restricted_categories.end()); });
allow_system_calls(sc,categories);
if (seccomp_load(sc) < 0)
return 1; // failure
/* This does not remove the filter */
seccomp_release(sc);
return 0;
}
// ===========================================================================
// ===========================================================================
<|endoftext|> |
<commit_before>#include "Image.h"
#include "../raster/BgraFrame.h"
namespace Aggplus
{
////////////////////////////////////////////////////////////////////////////////////////
CImage::CImage() : m_dwWidth(0), m_dwHeight(0),
m_nStride(0), m_pImgData(NULL),
m_bExternalBuffer(false), m_Status(WrongState)
{
}
CImage::CImage(const std::wstring& filename) : m_dwWidth(0), m_dwHeight(0),
m_nStride(0), m_pImgData(NULL),
m_bExternalBuffer(false)
{
Create(filename);
}
CImage::~CImage()
{
Destroy();
}
void CImage::Create(const std::wstring& filename)
{
Destroy();
CBgraFrame oFrame;
bool bOpen = oFrame.OpenFile(filename);
if (bOpen)
{
m_pImgData = oFrame.get_Data();
m_dwWidth = (DWORD)oFrame.get_Width();
m_dwHeight = (DWORD)oFrame.get_Height();
m_nStride = oFrame.get_Stride();
m_Status = Ok;
}
oFrame.ClearNoAttack();
}
void CImage::Destroy()
{
if (NULL != m_pImgData)
{
if (!m_bExternalBuffer)
{
delete [] m_pImgData;
}
}
m_Status = WrongState;
m_pImgData = NULL;
m_dwWidth = 0;
m_dwHeight = 0;
m_nStride = 0;
m_bExternalBuffer = false;
}
DWORD CImage::GetWidth() const { return(m_dwWidth); }
DWORD CImage::GetHeight() const { return(m_dwHeight); }
Status CImage::GetLastStatus() const { return(m_Status); }
////////////////////////////////////////////////////////////////////////////////////////
CBitmap::CBitmap(LONG width, LONG height, PixelFormat format) : CImage()
{
if(width <= 0 || height <= 0)
{
m_Status=InvalidParameter;
return;
}
LONG lSize = 4 * width * height;
m_pImgData = new BYTE[lSize];
if (m_pImgData)
{
memset(m_pImgData, 0, lSize);
m_dwWidth = width;
m_dwHeight = height;
m_nStride = 4 * m_dwWidth;
m_Status = Ok;
}
}
CBitmap::CBitmap(LONG width, LONG height, LONG stride, PixelFormat format, BYTE* scan0) : CImage()
{
//Warning! This is not Gdiplus behavior; it returns Ok!
if(width <= 0 || height <= 0 || stride == 0)
{
m_Status = InvalidParameter;
return;
}
m_bExternalBuffer = true;
if (stride > 0)
{
m_pImgData = scan0;
}
else
{
m_pImgData = scan0 + (height - 1) * (-stride);
}
m_dwWidth = width;
m_dwHeight = height;
m_nStride = stride;
m_Status = Ok;
}
CBitmap::CBitmap(const std::wstring& filename) : CImage(filename)
{
}
CBitmap::~CBitmap()
{
}
void CBitmap::LockBits(const RectF* rect, PixelFormat format, CBitmapData* lockedBitmapData)
{
// TODO:
return;
}
}<commit_msg>git-svn-id: svn://fileserver/activex/AVS/Sources/TeamlabOffice/trunk/ServerComponents@55215 954022d7-b5bf-4e40-9824-e11837661b57<commit_after>#include "Image.h"
#include "../raster/BgraFrame.h"
namespace Aggplus
{
////////////////////////////////////////////////////////////////////////////////////////
CImage::CImage() : m_dwWidth(0), m_dwHeight(0),
m_nStride(0), m_pImgData(NULL),
m_bExternalBuffer(false), m_Status(WrongState)
{
}
CImage::CImage(const std::wstring& filename) : m_dwWidth(0), m_dwHeight(0),
m_nStride(0), m_pImgData(NULL),
m_bExternalBuffer(false)
{
Create(filename);
}
CImage::~CImage()
{
Destroy();
}
void CImage::Create(const std::wstring& filename)
{
Destroy();
CBgraFrame oFrame;
bool bOpen = oFrame.OpenFile(filename);
if (bOpen)
{
m_pImgData = oFrame.get_Data();
m_dwWidth = (DWORD)oFrame.get_Width();
m_dwHeight = (DWORD)oFrame.get_Height();
m_nStride = oFrame.get_Stride();
m_Status = Ok;
}
oFrame.ClearNoAttack();
}
void CImage::Destroy()
{
if (NULL != m_pImgData)
{
if (!m_bExternalBuffer)
{
delete [] m_pImgData;
}
}
m_Status = WrongState;
m_pImgData = NULL;
m_dwWidth = 0;
m_dwHeight = 0;
m_nStride = 0;
m_bExternalBuffer = false;
}
DWORD CImage::GetWidth() const { return(m_dwWidth); }
DWORD CImage::GetHeight() const { return(m_dwHeight); }
Status CImage::GetLastStatus() const { return(m_Status); }
////////////////////////////////////////////////////////////////////////////////////////
CBitmap::CBitmap(LONG width, LONG height, PixelFormat format) : CImage()
{
if(width <= 0 || height <= 0)
{
m_Status=InvalidParameter;
return;
}
LONG lSize = 4 * width * height;
m_pImgData = new BYTE[lSize];
if (m_pImgData)
{
memset(m_pImgData, 0, lSize);
m_dwWidth = width;
m_dwHeight = height;
m_nStride = 4 * m_dwWidth;
m_Status = Ok;
}
}
CBitmap::CBitmap(LONG width, LONG height, LONG stride, PixelFormat format, BYTE* scan0) : CImage()
{
//Warning! This is not Gdiplus behavior; it returns Ok!
if(width <= 0 || height <= 0 || stride == 0)
{
m_Status = InvalidParameter;
return;
}
m_bExternalBuffer = true;
if (stride > 0)
{
m_pImgData = scan0;
}
else
{
m_pImgData = scan0 + (height - 1) * (-stride);
}
m_dwWidth = width;
m_dwHeight = height;
m_nStride = stride;
m_Status = Ok;
}
CBitmap::CBitmap(const std::wstring& filename) : CImage(filename)
{
}
CBitmap::~CBitmap()
{
}
void CBitmap::LockBits(const RectF* rect, PixelFormat format, CBitmapData* lockedBitmapData)
{
// TODO:
return;
}
}
<|endoftext|> |
<commit_before>// PacketSensor.cc
#include "lib.h"
#include "PacketSensor.h"
using namespace std;
PacketSensor::PacketSensor() : globalSequence()
{
ackedSize = 0;
ackedSendTime = Time();
}
int PacketSensor::getAckedSize(void) const
{
if (ackedSendTime == Time())
{
logWrite(ERROR, "PacketSensor::getAckedSize() called before localAck()");
}
return ackedSize;
}
Time const & PacketSensor::getAckedSendTime(void) const
{
if (ackedSendTime == Time())
{
logWrite(ERROR, "PacketSensor::getAckedSendTime() called before"
" localAck()");
}
return ackedSendTime;
}
void PacketSensor::localSend(PacketInfo * packet)
{
logWrite(SENSOR,
"PacketSensor::localSend() for sequence number %u",
ntohl(packet->tcp->seq));
unsigned int startSequence = ntohl(packet->tcp->seq);
if (globalSequence.inSequenceBlock(startSequence))
{
logWrite(SENSOR,
"PacketSensor::localSend() within globalSequence");
/*
* This packet should be in our list of sent packets - ie. it's a
* retransmit.
*/
list<SentPacket>::iterator pos = unacked.begin();
list<SentPacket>::iterator limit = unacked.end();
bool done = false;
for (; pos != limit && !done; ++pos)
{
if (pos->inSequenceBlock(startSequence))
{
pos->timestamp = packet->packetTime;
done = true;
}
}
if (!done) {
logWrite(ERROR, "localSend() unable to find packet record to update.");
}
}
else
{
/*
* Not in the current window of unacked packets - create a new
* SentPacket record for it
*/
SentPacket record;
record.seqStart = startSequence;
/*
* Calculate the packet payload size - we have to make sure to take into
* account IP and TCP option headers
*/
unsigned int sequenceLength =
// Total length of the IP part of the packet
(ntohs(packet->ip->ip_len))
// Total length of all IP headers (including options)
- (packet->ip->ip_hl*4)
// Total length of all TCP headers (including options)
- (packet->tcp->doff*4);
record.seqEnd = record.seqStart + sequenceLength;
record.totalLength = packet->packetLength;
record.timestamp = packet->packetTime;
logWrite(SENSOR,
"PacketSensor::localSend() new record: ss=%u,sl=%u,se=%u,tl=%u",
record.seqStart, sequenceLength, record.seqEnd,
record.totalLength);
globalSequence.seqEnd = record.seqEnd;
if (unacked.empty())
{
globalSequence.seqStart = record.seqStart;
globalSequence.seqEnd = record.seqEnd;
}
logWrite(SENSOR,
"PacketSensor::localSend(): global start = %u, global end = %u",
globalSequence.seqStart, globalSequence.seqEnd);
unacked.push_back(record);
}
ackedSize = 0;
ackedSendTime = Time();
}
void PacketSensor::localAck(PacketInfo * packet)
{
list<SentPacket>::iterator pos = unacked.begin();
list<SentPacket>::iterator limit = unacked.end();
bool found = false;
ackedSize = 0;
/*
* When we get an ACK, the sequence number is really the next one the peer
* excects to see: thus, the last sequence number it's ACKing is one less
* than this.
* XXX: Handle wraparound
*/
uint32_t ack_for = ntohl(packet->tcp->ack_seq) - 1;
while (pos != limit && !found)
{
found = pos->inSequenceBlock(ack_for);
/*
* XXX: Assumes that SACK is not in use - assumes that this ACK is for all
* sequence numbers up to the one it's ACKing
*/
ackedSize += pos->totalLength;
if (found)
{
ackedSendTime = pos->timestamp;
}
else
{
++pos;
}
}
if (!found)
{
logWrite(ERROR, "Could not find the ack sequence number in list "
"of unacked packets.");
ackedSize = 0;
ackedSendTime = Time();
return;
}
unacked.erase(unacked.begin(), pos);
if (unacked.empty())
{
globalSequence.seqStart = 0;
globalSequence.seqEnd = 0;
}
else
{
globalSequence.seqStart = unacked.front().seqStart;
}
}
bool PacketSensor::SentPacket::inSequenceBlock(unsigned int sequence)
{
logWrite(SENSOR,
"PacketSensor::inSequenceBlock(): Is %u between %u and %u?",
sequence, seqStart, seqEnd);
bool result = false;
if (seqStart < seqEnd)
{
result = sequence >= seqStart && sequence < seqEnd;
}
else if (seqStart > seqEnd)
{
/*
* This handles the sequence number wrapping around
*/
result = sequence >= seqStart || sequence < seqEnd;
}
if (result)
{
logWrite(SENSOR, "Yes!");
}
else
{
logWrite(SENSOR, "No!");
}
return result;
}
PacketSensor::SentPacket::SentPacket()
: seqStart(0), seqEnd(0), totalLength(), timestamp() {
}
<commit_msg>Bug fixes: Fix range check - this was necessary because of my change to the ackFor calculation.<commit_after>// PacketSensor.cc
#include "lib.h"
#include "PacketSensor.h"
using namespace std;
PacketSensor::PacketSensor() : globalSequence()
{
ackedSize = 0;
ackedSendTime = Time();
}
int PacketSensor::getAckedSize(void) const
{
if (ackedSendTime == Time())
{
logWrite(ERROR, "PacketSensor::getAckedSize() called before localAck()");
}
return ackedSize;
}
Time const & PacketSensor::getAckedSendTime(void) const
{
if (ackedSendTime == Time())
{
logWrite(ERROR, "PacketSensor::getAckedSendTime() called before"
" localAck()");
}
return ackedSendTime;
}
void PacketSensor::localSend(PacketInfo * packet)
{
logWrite(SENSOR,
"PacketSensor::localSend() for sequence number %u",
ntohl(packet->tcp->seq));
unsigned int startSequence = ntohl(packet->tcp->seq);
if (globalSequence.inSequenceBlock(startSequence))
{
logWrite(SENSOR,
"PacketSensor::localSend() within globalSequence");
/*
* This packet should be in our list of sent packets - ie. it's a
* retransmit.
*/
list<SentPacket>::iterator pos = unacked.begin();
list<SentPacket>::iterator limit = unacked.end();
bool done = false;
for (; pos != limit && !done; ++pos)
{
if (pos->inSequenceBlock(startSequence))
{
pos->timestamp = packet->packetTime;
done = true;
}
}
if (!done) {
logWrite(ERROR, "localSend() unable to find packet record to update.");
}
}
else
{
/*
* Not in the current window of unacked packets - create a new
* SentPacket record for it
*/
SentPacket record;
record.seqStart = startSequence;
/*
* Calculate the packet payload size - we have to make sure to take into
* account IP and TCP option headers
*/
unsigned int sequenceLength =
// Total length of the IP part of the packet
(ntohs(packet->ip->ip_len))
// Total length of all IP headers (including options)
- (packet->ip->ip_hl*4)
// Total length of all TCP headers (including options)
- (packet->tcp->doff*4);
// We want to get the sequence number of the last data byte, not the
// sequence number of the first byte of the next segment
record.seqEnd = record.seqStart + sequenceLength - 1;
record.totalLength = packet->packetLength;
record.timestamp = packet->packetTime;
logWrite(SENSOR,
"PacketSensor::localSend() new record: ss=%u,sl=%u,se=%u,tl=%u",
record.seqStart, sequenceLength, record.seqEnd,
record.totalLength);
globalSequence.seqEnd = record.seqEnd;
if (unacked.empty())
{
globalSequence.seqStart = record.seqStart;
globalSequence.seqEnd = record.seqEnd;
}
logWrite(SENSOR,
"PacketSensor::localSend(): global start = %u, global end = %u",
globalSequence.seqStart, globalSequence.seqEnd);
unacked.push_back(record);
}
ackedSize = 0;
ackedSendTime = Time();
}
void PacketSensor::localAck(PacketInfo * packet)
{
list<SentPacket>::iterator pos = unacked.begin();
list<SentPacket>::iterator limit = unacked.end();
bool found = false;
ackedSize = 0;
/*
* When we get an ACK, the sequence number is really the next one the peer
* excects to see: thus, the last sequence number it's ACKing is one less
* than this.
* Note: This should handle wraparound properly
*/
uint32_t ack_for = ntohl(packet->tcp->ack_seq) - 1;
logWrite(SENSOR, "PacketSensor::localAck() for sequence number %u",
ack_for);
/*
* Make sure this packet doesn't have a SACK option, in which case our
* calculation is wrong.
*/
list<Option>::iterator opt;
for (opt = packet->tcpOptions->begin();
opt != packet->tcpOptions->end();
++opt) {
if (opt->type == TCPOPT_SACK) {
logWrite(ERROR,"Packet has a SACK option!");
}
}
while (pos != limit && !found)
{
found = pos->inSequenceBlock(ack_for);
/*
* XXX: Assumes that SACK is not in use - assumes that this ACK is for all
* sequence numbers up to the one it's ACKing
*/
ackedSize += pos->totalLength;
if (found)
{
ackedSendTime = pos->timestamp;
}
++pos;
}
if (!found)
{
logWrite(ERROR, "Could not find the ack sequence number in list "
"of unacked packets.");
ackedSize = 0;
ackedSendTime = Time();
return;
}
unacked.erase(unacked.begin(), pos);
if (unacked.empty())
{
globalSequence.seqStart = 0;
globalSequence.seqEnd = 0;
}
else
{
globalSequence.seqStart = unacked.front().seqStart;
}
logWrite(SENSOR, "PacketSensor::localAck() decided on size %u",
ackedSize);
}
bool PacketSensor::SentPacket::inSequenceBlock(unsigned int sequence)
{
logWrite(SENSOR,
"PacketSensor::inSequenceBlock(): Is %u between %u and %u?",
sequence, seqStart, seqEnd);
bool result = false;
if (seqStart < seqEnd)
{
result = sequence >= seqStart && sequence <= seqEnd;
}
else if (seqStart > seqEnd)
{
/*
* This handles the sequence number wrapping around
*/
result = sequence >= seqStart || sequence <= seqEnd;
}
if (result)
{
logWrite(SENSOR, "Yes!");
}
else
{
logWrite(SENSOR, "No!");
}
return result;
}
PacketSensor::SentPacket::SentPacket()
: seqStart(0), seqEnd(0), totalLength(), timestamp() {
}
<|endoftext|> |
<commit_before>/**
* @copyright Copyright 2017 The J-PET Framework 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 find a copy of the License in the LICENCE file.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @file EventCategorizerTools.cpp
*/
#include "EventCategorizerTools.h"
#include <TMath.h>
#include <vector>
using namespace std;
/**
* Method for determining type of event - back to back 2 gamma
*/
bool EventCategorizerTools::checkFor2Gamma(const JPetEvent& event, JPetStatistics& stats, bool saveHistos)
{
if (event.getHits().size() < 2) return false;
for(uint i = 0; i < event.getHits().size(); i++){
for(uint j = i+1; j < event.getHits().size(); j++){
JPetHit firstHit, secondHit;
if(event.getHits().at(i).getTime() < event.getHits().at(j).getTime()){
firstHit = event.getHits().at(i);
secondHit = event.getHits().at(j);
}else{
firstHit = event.getHits().at(j);
secondHit = event.getHits().at(i);
}
// Checking for back to back
double thetaDiff = fabs(firstHit.getBarrelSlot().getTheta() - secondHit.getBarrelSlot().getTheta());
if(thetaDiff > 177.0 && thetaDiff < 183.0){
if(saveHistos){
double distance = (secondHit.getPos()-firstHit.getPos()).Mag();
TVector3 annhilationPoint = calculateAnnihilationPoint(firstHit, secondHit);
stats.getHisto1D("2Gamma_Zpos")->Fill(firstHit.getPosZ());
stats.getHisto1D("2Gamma_Zpos")->Fill(secondHit.getPosZ());
stats.getHisto1D("2Gamma_TimeDiff")->Fill(secondHit.getTime()-firstHit.getTime());
stats.getHisto1D("2Gamma_Dist")->Fill(distance);
stats.getHisto1D("Annih_TOF")->Fill(calculateTOF(firstHit, secondHit));
stats.getHisto2D("AnnihPoint_XY")->Fill(annhilationPoint.X(), annhilationPoint.Y());
stats.getHisto2D("AnnihPoint_XZ")->Fill(annhilationPoint.X(), annhilationPoint.Z());
stats.getHisto2D("AnnihPoint_YZ")->Fill(annhilationPoint.Y(), annhilationPoint.Z());
}
return true;
}
}
}
return false;
}
/**
* Method for determining type of event - 3Gamma
*/
bool EventCategorizerTools::checkFor3Gamma(const JPetEvent& event, JPetStatistics& stats, bool saveHistos)
{
if (event.getHits().size() < 3) return false;
for(uint i = 0; i < event.getHits().size(); i++){
for(uint j = i+1; j < event.getHits().size(); j++){
for(uint k = j+1; k < event.getHits().size(); k++){
JPetHit& firstHit = event.getHits().at(i);
JPetHit& secondHit = event.getHits().at(j);
JPetHit& thirdHit = event.getHits().at(k);
vector<double> thetaAngles;
thetaAngles.push_back(firstHit.getBarrelSlot().getTheta());
thetaAngles.push_back(secondHit.getBarrelSlot().getTheta());
thetaAngles.push_back(thirdHit.getBarrelSlot().getTheta());
sort(thetaAngles.begin(), thetaAngles.end());
vector<double> relativeAngles;
relativeAngles.push_back(thetaAngles.at(1)-thetaAngles.at(0));
relativeAngles.push_back(thetaAngles.at(2)-thetaAngles.at(1));
relativeAngles.push_back(360.0-thetaAngles.at(2)+thetaAngles.at(0));
sort(relativeAngles.begin(), relativeAngles.end());
double transformedX = relativeAngles.at(1)+relativeAngles.at(0);
double transformedY = relativeAngles.at(1)-relativeAngles.at(0);
if(saveHistos)
stats.getHisto2D("3Gamma_Angles")->Fill(transformedX, transformedY);
}
}
}
return true;
}
/**
* Method for determining type of event - prompt
*/
bool EventCategorizerTools::checkForPrompt(
const JPetEvent& event, JPetStatistics& stats, bool saveHistos,
double deexTOTCutMin, double deexTOTCutMax)
{
for(uint i = 0; i < event.getHits().size(); i++){
JPetHit& hit = event.getHits().at(i);
double tot = calculateTOT(hit);
if(tot > deexTOTCutMin && tot < deexTOTCutMax){
if(saveHistos) stats.getHisto1D("Deex_TOT_cut")->Fill(tot);
return true;
}
}
return false;
}
/**
* Method for determining type of event - scatter
*/
bool EventCategorizerTools::checkForScatter(
const JPetEvent& event,
JPetStatistics& stats,
bool saveHistos,
double scatterTOFTimeDiff)
{
if (event.getHits().size() < 2) return false;
for(uint i = 0; i < event.getHits().size(); i++){
for(uint j = i+1; j < event.getHits().size(); j++){
JPetHit primaryHit, scatterHit;
if(event.getHits().at(i).getTime() < event.getHits().at(j).getTime()){
primaryHit = event.getHits().at(i);
scatterHit = event.getHits().at(j);
}else{
primaryHit = event.getHits().at(j);
scatterHit = event.getHits().at(i);
}
double scattAngle = calculateScatteringAngle(primaryHit, scatterHit);
double scattTOF = calculateScatteringTime(primaryHit, scatterHit)/1000.0;
double timeDiff = scatterHit.getTime() - primaryHit.getTime();
if(saveHistos)
stats.getHisto1D("ScatterTOF_TimeDiff")->Fill(fabs(scattTOF-timeDiff));
if(fabs(scattTOF-timeDiff) < scatterTOFTimeDiff){
if(saveHistos) {
stats.getHisto2D("ScatterAngle_PrimaryTOT")->Fill(scattAngle, calculateTOT(primaryHit));
stats.getHisto2D("ScatterAngle_ScatterTOT")->Fill(scattAngle, calculateTOT(scatterHit));
}
return true;
}
}
}
return false;
}
/**
* Calculation of the total TOT of the hit - Time over Threshold:
* the sum of the TOTs on all of the thresholds (1-4) and on the both sides (A,B)
*/
double EventCategorizerTools::calculateTOT(const JPetHit& hit)
{
double tot = 0.0;
std::vector<JPetSigCh> sigALead;
std::vector<JPetSigCh> sigBLead;
std::vector<JPetSigCh> sigATrail;
std::vector<JPetSigCh> sigBTrail;
sigALead = hit.getSignalA().getRecoSignal()
.getRawSignal().getPoints(JPetSigCh::Leading, JPetRawSignal::ByThrNum);
sigBLead = hit.getSignalB().getRecoSignal()
.getRawSignal().getPoints(JPetSigCh::Leading, JPetRawSignal::ByThrNum);
sigATrail = hit.getSignalA().getRecoSignal()
.getRawSignal().getPoints(JPetSigCh::Trailing, JPetRawSignal::ByThrNum);
sigBTrail = hit.getSignalB().getRecoSignal()
.getRawSignal().getPoints(JPetSigCh::Trailing, JPetRawSignal::ByThrNum);
for(uint i = 0; i < sigALead.size() && i < sigATrail.size(); i++)
tot += (sigATrail.at(i).getValue() - sigALead.at(i).getValue());
for( unsigned i = 0; i < sigBLead.size() && i < sigBTrail.size(); i++)
tot += (sigBTrail.at(i).getValue() - sigBLead.at(i).getValue());
return tot;
}
/**
* Calculation of distance between two hits
*/
double EventCategorizerTools::calculateDistance(const JPetHit& hit1, const JPetHit& hit2)
{
return (hit1.getPos() - hit2.getPos()).Mag();
}
/**
* Calculation of time that light needs to travel the distance between primary gamma
* and scattered gamma. Return value in nanoseconds.
*/
double EventCategorizerTools::calculateScatteringTime(const JPetHit& hit1, const JPetHit& hit2)
{
return calculateDistance(hit1, hit2)/kLightVelocity_cm_ns;
}
/**
* Calculation of scatter angle between primary hit and scattered hit.
* This function assumes that source of first gamma was in (0,0,0).
* Angle is calculated from scalar product, return value in degrees.
*/
double EventCategorizerTools::calculateScatteringAngle(const JPetHit& hit1, const JPetHit& hit2)
{
return TMath::RadToDeg()*hit1.getPos().Angle(hit2.getPos() - hit1.getPos());
}
/**
* Calculation point in 3D, where annihilation occured
*/
TVector3 EventCategorizerTools::calculateAnnihilationPoint(const JPetHit& firstHit, const JPetHit& latterHit)
{
double LORlength = calculateDistance(firstHit, latterHit);
TVector3 middleOfLOR;
middleOfLOR.SetX((firstHit.getPosX()+latterHit.getPosX())/2.0);
middleOfLOR.SetY((firstHit.getPosY()+latterHit.getPosY())/2.0);
middleOfLOR.SetZ((firstHit.getPosZ()+latterHit.getPosZ())/2.0);
TVector3 versorOnLOR;
versorOnLOR.SetX(fabs((latterHit.getPosX()-firstHit.getPosX())/LORlength));
versorOnLOR.SetY(fabs((latterHit.getPosY()-firstHit.getPosY())/LORlength));
versorOnLOR.SetZ(fabs((latterHit.getPosZ()-firstHit.getPosZ())/LORlength));
TVector3 annihilationPoint;
annihilationPoint.SetX(middleOfLOR.X()-versorOnLOR.X()*calculateTOF(firstHit, latterHit)*kLightVelocity_cm_ns/1000.0);
annihilationPoint.SetY(middleOfLOR.Y()-versorOnLOR.Y()*calculateTOF(firstHit, latterHit)*kLightVelocity_cm_ns/1000.0);
annihilationPoint.SetZ(middleOfLOR.Z()-versorOnLOR.Z()*calculateTOF(firstHit, latterHit)*kLightVelocity_cm_ns/1000.0);
return annihilationPoint;
}
/**
* Calculation Time of flight
*/
double EventCategorizerTools::calculateTOF(const JPetHit& firstHit, const JPetHit& latterHit)
{
double TOF = kUndefinedValue;
if(firstHit.getTime() > latterHit.getTime()) {
ERROR("First hit time should be earlier than later hit");
return TOF;
}
TOF = firstHit.getTime()-latterHit.getTime();
if(firstHit.getBarrelSlot().getTheta() < latterHit.getBarrelSlot().getTheta())
return TOF;
else return -1.0*TOF;
}
<commit_msg>corr ev cat tools for bad alloc<commit_after>/**
* @copyright Copyright 2017 The J-PET Framework 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 find a copy of the License in the LICENCE file.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @file EventCategorizerTools.cpp
*/
#include "EventCategorizerTools.h"
#include <TMath.h>
#include <vector>
using namespace std;
/**
* Method for determining type of event - back to back 2 gamma
*/
bool EventCategorizerTools::checkFor2Gamma(const JPetEvent& event, JPetStatistics& stats, bool saveHistos)
{
if (event.getHits().size() < 2) return false;
for(uint i = 0; i < event.getHits().size(); i++){
for(uint j = i+1; j < event.getHits().size(); j++){
JPetHit firstHit, secondHit;
if(event.getHits().at(i).getTime() < event.getHits().at(j).getTime()){
firstHit = event.getHits().at(i);
secondHit = event.getHits().at(j);
}else{
firstHit = event.getHits().at(j);
secondHit = event.getHits().at(i);
}
// Checking for back to back
double thetaDiff = fabs(firstHit.getBarrelSlot().getTheta() - secondHit.getBarrelSlot().getTheta());
if(thetaDiff > 177.0 && thetaDiff < 183.0){
if(saveHistos){
double distance = (secondHit.getPos()-firstHit.getPos()).Mag();
TVector3 annhilationPoint = calculateAnnihilationPoint(firstHit, secondHit);
stats.getHisto1D("2Gamma_Zpos")->Fill(firstHit.getPosZ());
stats.getHisto1D("2Gamma_Zpos")->Fill(secondHit.getPosZ());
stats.getHisto1D("2Gamma_TimeDiff")->Fill(secondHit.getTime()-firstHit.getTime());
stats.getHisto1D("2Gamma_Dist")->Fill(distance);
stats.getHisto1D("Annih_TOF")->Fill(calculateTOF(firstHit, secondHit));
stats.getHisto2D("AnnihPoint_XY")->Fill(annhilationPoint.X(), annhilationPoint.Y());
stats.getHisto2D("AnnihPoint_XZ")->Fill(annhilationPoint.X(), annhilationPoint.Z());
stats.getHisto2D("AnnihPoint_YZ")->Fill(annhilationPoint.Y(), annhilationPoint.Z());
}
return true;
}
}
}
return false;
}
/**
* Method for determining type of event - 3Gamma
*/
bool EventCategorizerTools::checkFor3Gamma(const JPetEvent& event, JPetStatistics& stats, bool saveHistos)
{
if (event.getHits().size() < 3) return false;
for(uint i = 0; i < event.getHits().size(); i++){
for(uint j = i+1; j < event.getHits().size(); j++){
for(uint k = j+1; k < event.getHits().size(); k++){
JPetHit& firstHit = event.getHits().at(i);
JPetHit& secondHit = event.getHits().at(j);
JPetHit& thirdHit = event.getHits().at(k);
vector<double> thetaAngles;
thetaAngles.push_back(firstHit.getBarrelSlot().getTheta());
thetaAngles.push_back(secondHit.getBarrelSlot().getTheta());
thetaAngles.push_back(thirdHit.getBarrelSlot().getTheta());
sort(thetaAngles.begin(), thetaAngles.end());
vector<double> relativeAngles;
relativeAngles.push_back(thetaAngles.at(1)-thetaAngles.at(0));
relativeAngles.push_back(thetaAngles.at(2)-thetaAngles.at(1));
relativeAngles.push_back(360.0-thetaAngles.at(2)+thetaAngles.at(0));
sort(relativeAngles.begin(), relativeAngles.end());
double transformedX = relativeAngles.at(1)+relativeAngles.at(0);
double transformedY = relativeAngles.at(1)-relativeAngles.at(0);
if(saveHistos)
stats.getHisto2D("3Gamma_Angles")->Fill(transformedX, transformedY);
}
}
}
return true;
}
/**
* Method for determining type of event - prompt
*/
bool EventCategorizerTools::checkForPrompt(
const JPetEvent& event, JPetStatistics& stats, bool saveHistos,
double deexTOTCutMin, double deexTOTCutMax)
{
for(uint i = 0; i < event.getHits().size(); i++){
JPetHit& hit = event.getHits().at(i);
double tot = calculateTOT(hit);
if(tot > deexTOTCutMin && tot < deexTOTCutMax){
if(saveHistos) stats.getHisto1D("Deex_TOT_cut")->Fill(tot);
return true;
}
}
return false;
}
/**
* Method for determining type of event - scatter
*/
bool EventCategorizerTools::checkForScatter(
const JPetEvent& event,
JPetStatistics& stats,
bool saveHistos,
double scatterTOFTimeDiff)
{
if (event.getHits().size() < 2) return false;
for(uint i = 0; i < event.getHits().size(); i++){
for(uint j = i+1; j < event.getHits().size(); j++){
JPetHit primaryHit, scatterHit;
if(event.getHits().at(i).getTime() < event.getHits().at(j).getTime()){
primaryHit = event.getHits().at(i);
scatterHit = event.getHits().at(j);
}else{
primaryHit = event.getHits().at(j);
scatterHit = event.getHits().at(i);
}
double scattAngle = calculateScatteringAngle(primaryHit, scatterHit);
double scattTOF = calculateScatteringTime(primaryHit, scatterHit)/1000.0;
double timeDiff = scatterHit.getTime() - primaryHit.getTime();
if(saveHistos)
stats.getHisto1D("ScatterTOF_TimeDiff")->Fill(fabs(scattTOF-timeDiff));
if(fabs(scattTOF-timeDiff) < scatterTOFTimeDiff){
if(saveHistos) {
stats.getHisto2D("ScatterAngle_PrimaryTOT")->Fill(scattAngle, calculateTOT(primaryHit));
stats.getHisto2D("ScatterAngle_ScatterTOT")->Fill(scattAngle, calculateTOT(scatterHit));
}
return true;
}
}
}
return false;
}
/**
* Calculation of the total TOT of the hit - Time over Threshold:
* the sum of the TOTs on all of the thresholds (1-4) and on the both sides (A,B)
*/
double EventCategorizerTools::calculateTOT(const JPetHit& hit)
{
double tot = 0.0;
std::vector<JPetSigCh> sigALead = hit.getSignalA().getRecoSignal()
.getRawSignal().getPoints(JPetSigCh::Leading, JPetRawSignal::ByThrNum);
std::vector<JPetSigCh> sigBLead = hit.getSignalB().getRecoSignal()
.getRawSignal().getPoints(JPetSigCh::Leading, JPetRawSignal::ByThrNum);
std::vector<JPetSigCh> sigATrail = hit.getSignalA().getRecoSignal()
.getRawSignal().getPoints(JPetSigCh::Trailing, JPetRawSignal::ByThrNum);
std::vector<JPetSigCh> sigBTrail = hit.getSignalB().getRecoSignal()
.getRawSignal().getPoints(JPetSigCh::Trailing, JPetRawSignal::ByThrNum);
for(uint i = 0; i < sigALead.size() && i < sigATrail.size(); i++)
tot += (sigATrail.at(i).getValue() - sigALead.at(i).getValue());
for( unsigned i = 0; i < sigBLead.size() && i < sigBTrail.size(); i++)
tot += (sigBTrail.at(i).getValue() - sigBLead.at(i).getValue());
return tot;
}
/**
* Calculation of distance between two hits
*/
double EventCategorizerTools::calculateDistance(const JPetHit& hit1, const JPetHit& hit2)
{
return (hit1.getPos() - hit2.getPos()).Mag();
}
/**
* Calculation of time that light needs to travel the distance between primary gamma
* and scattered gamma. Return value in nanoseconds.
*/
double EventCategorizerTools::calculateScatteringTime(const JPetHit& hit1, const JPetHit& hit2)
{
return calculateDistance(hit1, hit2)/kLightVelocity_cm_ns;
}
/**
* Calculation of scatter angle between primary hit and scattered hit.
* This function assumes that source of first gamma was in (0,0,0).
* Angle is calculated from scalar product, return value in degrees.
*/
double EventCategorizerTools::calculateScatteringAngle(const JPetHit& hit1, const JPetHit& hit2)
{
return TMath::RadToDeg()*hit1.getPos().Angle(hit2.getPos() - hit1.getPos());
}
/**
* Calculation point in 3D, where annihilation occured
*/
TVector3 EventCategorizerTools::calculateAnnihilationPoint(const JPetHit& firstHit, const JPetHit& latterHit)
{
double LORlength = calculateDistance(firstHit, latterHit);
TVector3 middleOfLOR;
middleOfLOR.SetX((firstHit.getPosX()+latterHit.getPosX())/2.0);
middleOfLOR.SetY((firstHit.getPosY()+latterHit.getPosY())/2.0);
middleOfLOR.SetZ((firstHit.getPosZ()+latterHit.getPosZ())/2.0);
TVector3 versorOnLOR;
versorOnLOR.SetX(fabs((latterHit.getPosX()-firstHit.getPosX())/LORlength));
versorOnLOR.SetY(fabs((latterHit.getPosY()-firstHit.getPosY())/LORlength));
versorOnLOR.SetZ(fabs((latterHit.getPosZ()-firstHit.getPosZ())/LORlength));
TVector3 annihilationPoint;
annihilationPoint.SetX(middleOfLOR.X()-versorOnLOR.X()*calculateTOF(firstHit, latterHit)*kLightVelocity_cm_ns/1000.0);
annihilationPoint.SetY(middleOfLOR.Y()-versorOnLOR.Y()*calculateTOF(firstHit, latterHit)*kLightVelocity_cm_ns/1000.0);
annihilationPoint.SetZ(middleOfLOR.Z()-versorOnLOR.Z()*calculateTOF(firstHit, latterHit)*kLightVelocity_cm_ns/1000.0);
return annihilationPoint;
}
/**
* Calculation Time of flight
*/
double EventCategorizerTools::calculateTOF(const JPetHit& firstHit, const JPetHit& latterHit)
{
double TOF = kUndefinedValue;
if(firstHit.getTime() > latterHit.getTime()) {
ERROR("First hit time should be earlier than later hit");
return TOF;
}
TOF = firstHit.getTime()-latterHit.getTime();
if(firstHit.getBarrelSlot().getTheta() < latterHit.getBarrelSlot().getTheta())
return TOF;
else return -1.0*TOF;
}
<|endoftext|> |
<commit_before>//
// Copyright 2016 Giovanni Mels
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef N3_MODEL_HH
#define N3_MODEL_HH
#include <cstddef>
#include <string>
#include <ostream>
#include <vector>
#include <utility>
namespace turtle {
class URIResource;
class BlankNode;
class RDFList;
class Literal;
class BooleanLiteral;
class IntegerLiteral;
class DoubleLiteral;
class DecimalLiteral;
class StringLiteral;
template<typename T>
struct Cloneable {
Cloneable() = default;
Cloneable(const Cloneable &c) = default;
Cloneable(Cloneable &&c) = default;
Cloneable &operator=(const Cloneable &c) = default;
Cloneable &operator=(Cloneable &&c) = default;
virtual T *clone() const = 0;
virtual ~Cloneable() = default;
};
struct N3NodeVisitor {
virtual void visit(const URIResource &resource) = 0;
virtual void visit(const BlankNode &blankNode) = 0;
virtual void visit(const Literal &literal) = 0;
virtual void visit(const RDFList &list) = 0;
virtual void visit(const BooleanLiteral &literal) = 0;
virtual void visit(const IntegerLiteral &literal) = 0;
virtual void visit(const DoubleLiteral &literal) = 0;
virtual void visit(const DecimalLiteral &literal) = 0;
virtual void visit(const StringLiteral &literal) = 0;
virtual ~N3NodeVisitor() {}
};
struct N3Node : public Cloneable<N3Node> {
/*N3Node() = default;
N3Node(const N3Node &c) = default;
N3Node(N3Node &&c) = default;
N3Node &operator=(const N3Node &c) = default;
N3Node &operator=(N3Node &&c) = default;*/
virtual std::ostream &print(std::ostream &out) const = 0;
virtual void visit(N3NodeVisitor &visitor) const = 0;
//virtual ~N3Node() = default;
};
std::ostream &operator<<(std::ostream &out, const N3Node &n);
struct Resource : public N3Node {
virtual Resource *clone() const = 0;
};
class URIResource : public Resource {
std::string m_uri;
public:
explicit URIResource(const std::string &uri) : Resource(), m_uri(uri) {}
explicit URIResource(std::string &&uri) : Resource(), m_uri(std::move(uri)) {}
const std::string &uri() const { return m_uri; }
std::ostream &print(std::ostream &out) const
{
out << '<' << m_uri << '>';
return out;
}
URIResource *clone() const
{
return new URIResource(m_uri);
}
void visit(N3NodeVisitor &visitor) const
{
visitor.visit(*this);
}
};
class BlankNode : public Resource {
std::string m_id;
public:
explicit BlankNode(const std::string &id) : Resource(), m_id(id) {}
explicit BlankNode(std::string &&id) : Resource(), m_id(std::move(id)) {}
const std::string &id() const { return m_id; }
std::ostream &print(std::ostream &out) const
{
out << "_:b" << m_id;
return out;
}
BlankNode *clone() const
{
return new BlankNode(m_id);
}
void visit(N3NodeVisitor &visitor) const
{
visitor.visit(*this);
}
};
class RDFList : public Resource {
std::vector<N3Node *> m_elements;
typedef std::vector<N3Node *>::iterator iterator;
typedef std::vector<N3Node *>::const_iterator const_iterator;
public:
RDFList() : m_elements() {}
RDFList(const RDFList &list) : RDFList()
{
m_elements.reserve(list.m_elements.size());
for (N3Node *n : list.m_elements) {
m_elements.push_back(n->clone());
}
}
RDFList(RDFList &&list) : RDFList()
{
std::swap(list.m_elements, m_elements);
}
RDFList& operator=(RDFList list)
{
std::swap(list.m_elements, m_elements);
return *this;
}
RDFList& operator=(RDFList &&list) // TODO correct?
{
std::swap(list.m_elements, m_elements);
return *this;
}
~RDFList()
{
for (N3Node *n : m_elements)
delete n;
}
void add(N3Node *element)
{
m_elements.push_back(element);
}
N3Node *&operator[](std::size_t index)
{
return m_elements[index];
}
N3Node * const &operator[](std::size_t index) const
{
return m_elements[index];
}
std::size_t size() const
{
return m_elements.size();
}
iterator begin()
{
return m_elements.begin();
}
iterator end()
{
return m_elements.end();
}
const_iterator begin() const
{
return m_elements.begin();
}
const_iterator end() const
{
return m_elements.end();
}
bool empty() const
{
return m_elements.empty();
}
std::ostream &print(std::ostream &out) const
{
out << '(';
for (N3Node *n : m_elements)
out << ' ' << *n;
out << ')';
return out;
}
RDFList *clone() const
{
return new RDFList(*this);
}
void visit(N3NodeVisitor &visitor) const
{
visitor.visit(*this);
}
};
class Literal : public N3Node {
protected:
std::string m_lexical;
const std::string *m_datatype;
Literal(const std::string &lexical, const std::string *datatype) : N3Node(), m_lexical(lexical), m_datatype(datatype) {}
Literal(std::string &&lexical, const std::string *datatype) : N3Node(), m_lexical(std::move(lexical)), m_datatype(datatype) {}
public:
const std::string &lexical() const { return m_lexical; }
const std::string &datatype() const { return *m_datatype; }
void visit(N3NodeVisitor &visitor) const
{
visitor.visit(*this);
}
};
class BooleanLiteral : public Literal {
public:
explicit BooleanLiteral(const std::string &value) : Literal(value, &TYPE) {}
static const std::string TYPE;
static const BooleanLiteral VALUE_TRUE;
static const BooleanLiteral VALUE_FALSE;
static const BooleanLiteral VALUE_1;
static const BooleanLiteral VALUE_0;
std::ostream &print(std::ostream &out) const
{
out << lexical();
return out;
}
bool value() const { return m_lexical == VALUE_TRUE.m_lexical || m_lexical == "1"; }
BooleanLiteral *clone() const
{
return new BooleanLiteral(m_lexical);
}
void visit(N3NodeVisitor &visitor) const
{
visitor.visit(*this);
}
};
class IntegerLiteral : public Literal {
public:
static const std::string TYPE;
explicit IntegerLiteral(const std::string &value) : Literal(value, &TYPE) {}
std::ostream &print(std::ostream &out) const
{
out << lexical();
return out;
}
IntegerLiteral *clone() const
{
return new IntegerLiteral(m_lexical);
}
void visit(N3NodeVisitor &visitor) const
{
visitor.visit(*this);
}
};
class DoubleLiteral : public Literal {
public:
static const std::string TYPE;
explicit DoubleLiteral(const std::string &value) : Literal(value, &TYPE) {}
std::ostream &print(std::ostream &out) const
{
out << lexical();
return out;
}
DoubleLiteral *clone() const
{
return new DoubleLiteral(m_lexical);
}
void visit(N3NodeVisitor &visitor) const
{
visitor.visit(*this);
}
};
class DecimalLiteral : public Literal {
public:
static const std::string TYPE;
explicit DecimalLiteral(const std::string &value) : Literal(value, &TYPE) {}
std::ostream &print(std::ostream &out) const
{
out << lexical();
return out;
}
DecimalLiteral *clone() const
{
return new DecimalLiteral(m_lexical);
}
void visit(N3NodeVisitor &visitor) const
{
visitor.visit(*this);
}
};
class StringLiteral : public Literal {
std::string m_language;
public:
static const std::string TYPE;
explicit StringLiteral(const std::string &value, const std::string &language = std::string()) : Literal(value, &TYPE), m_language(language) {}
explicit StringLiteral(std::string &&value, std::string &&language = std::string()) : Literal(std::move(value), &TYPE), m_language(std::move(language)) {}
const std::string &language() const { return m_language; }
std::ostream &print(std::ostream &out) const
{
out << '"' << lexical() << '"';
if (!language().empty())
out << '@' << language();
return out;
}
StringLiteral *clone() const
{
return new StringLiteral(m_lexical, m_language);
}
void visit(N3NodeVisitor &visitor) const
{
visitor.visit(*this);
}
};
class OtherLiteral : public Literal { /* keeps a copy of the type uri */
std::string m_datatype_copy;
public:
explicit OtherLiteral(const std::string &value, const std::string &datatype) : Literal(value, nullptr), m_datatype_copy(datatype)
{
m_datatype = &m_datatype_copy;
}
explicit OtherLiteral(std::string &&value, std::string &&datatype) : Literal(std::move(value), nullptr), m_datatype_copy(std::move(datatype))
{
m_datatype = &m_datatype_copy;
}
OtherLiteral(const OtherLiteral &other) : Literal(other.m_lexical, nullptr), m_datatype_copy(other.m_datatype_copy)
{
m_datatype = &m_datatype_copy;
}
OtherLiteral(OtherLiteral &&other) : Literal(other.m_lexical, nullptr), m_datatype_copy(other.m_datatype_copy)
{
m_datatype = &m_datatype_copy;
}
OtherLiteral& operator=(OtherLiteral other)
{
std::swap(m_lexical, other.m_lexical);
std::swap(m_datatype, other.m_datatype);
m_datatype = &m_datatype_copy;
return *this;
}
OtherLiteral& operator=(OtherLiteral &&other)
{
std::swap(m_lexical, other.m_lexical);
std::swap(m_datatype, other.m_datatype);
m_datatype = &m_datatype_copy;
return *this;
}
std::ostream &print(std::ostream &out) const
{
out << '"' << lexical() << '"' << '@' << '<' << datatype() << '>';
return out;
}
OtherLiteral *clone() const
{
return new OtherLiteral(m_lexical, m_datatype_copy);
}
};
struct RDF {
static const std::string NS;
static const URIResource type;
static const URIResource first;
static const URIResource rest;
static const URIResource nil;
};
struct XSD {
static const std::string NS;
};
}
#endif /* N3_MODEL_HH */
<commit_msg>Clean up.<commit_after>//
// Copyright 2016 Giovanni Mels
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef N3_MODEL_HH
#define N3_MODEL_HH
#include <cstddef>
#include <string>
#include <ostream>
#include <vector>
#include <utility>
namespace turtle {
class URIResource;
class BlankNode;
class RDFList;
class Literal;
class BooleanLiteral;
class IntegerLiteral;
class DoubleLiteral;
class DecimalLiteral;
class StringLiteral;
template<typename T>
struct Cloneable {
virtual T *clone() const = 0;
virtual ~Cloneable() {};
};
struct N3NodeVisitor {
virtual void visit(const URIResource &resource) = 0;
virtual void visit(const BlankNode &blankNode) = 0;
virtual void visit(const Literal &literal) = 0;
virtual void visit(const RDFList &list) = 0;
virtual void visit(const BooleanLiteral &literal) = 0;
virtual void visit(const IntegerLiteral &literal) = 0;
virtual void visit(const DoubleLiteral &literal) = 0;
virtual void visit(const DecimalLiteral &literal) = 0;
virtual void visit(const StringLiteral &literal) = 0;
virtual ~N3NodeVisitor() {}
};
struct N3Node : public Cloneable<N3Node> {
virtual std::ostream &print(std::ostream &out) const = 0;
virtual void visit(N3NodeVisitor &visitor) const = 0;
};
std::ostream &operator<<(std::ostream &out, const N3Node &n);
struct Resource : public N3Node {
virtual Resource *clone() const = 0;
};
class URIResource : public Resource {
std::string m_uri;
public:
explicit URIResource(const std::string &uri) : Resource(), m_uri(uri) {}
explicit URIResource(std::string &&uri) : Resource(), m_uri(std::move(uri)) {}
const std::string &uri() const { return m_uri; }
std::ostream &print(std::ostream &out) const
{
out << '<' << m_uri << '>';
return out;
}
URIResource *clone() const
{
return new URIResource(m_uri);
}
void visit(N3NodeVisitor &visitor) const
{
visitor.visit(*this);
}
};
class BlankNode : public Resource {
std::string m_id;
public:
explicit BlankNode(const std::string &id) : Resource(), m_id(id) {}
explicit BlankNode(std::string &&id) : Resource(), m_id(std::move(id)) {}
const std::string &id() const { return m_id; }
std::ostream &print(std::ostream &out) const
{
out << "_:b" << m_id;
return out;
}
BlankNode *clone() const
{
return new BlankNode(m_id);
}
void visit(N3NodeVisitor &visitor) const
{
visitor.visit(*this);
}
};
class RDFList : public Resource {
std::vector<N3Node *> m_elements;
typedef std::vector<N3Node *>::iterator iterator;
typedef std::vector<N3Node *>::const_iterator const_iterator;
public:
RDFList() : m_elements() {}
RDFList(const RDFList &list) : RDFList()
{
m_elements.reserve(list.m_elements.size());
for (N3Node *n : list.m_elements) {
m_elements.push_back(n->clone());
}
}
RDFList(RDFList &&list) : RDFList()
{
std::swap(list.m_elements, m_elements);
}
RDFList& operator=(RDFList list)
{
std::swap(list.m_elements, m_elements);
return *this;
}
RDFList& operator=(RDFList &&list)
{
std::swap(list.m_elements, m_elements);
return *this;
}
~RDFList()
{
for (N3Node *n : m_elements)
delete n;
}
void add(N3Node *element)
{
m_elements.push_back(element);
}
N3Node *&operator[](std::size_t index)
{
return m_elements[index];
}
N3Node * const &operator[](std::size_t index) const
{
return m_elements[index];
}
std::size_t size() const
{
return m_elements.size();
}
iterator begin()
{
return m_elements.begin();
}
iterator end()
{
return m_elements.end();
}
const_iterator begin() const
{
return m_elements.begin();
}
const_iterator end() const
{
return m_elements.end();
}
bool empty() const
{
return m_elements.empty();
}
std::ostream &print(std::ostream &out) const
{
out << '(';
for (N3Node *n : m_elements)
out << ' ' << *n;
out << ')';
return out;
}
RDFList *clone() const
{
return new RDFList(*this);
}
void visit(N3NodeVisitor &visitor) const
{
visitor.visit(*this);
}
};
class Literal : public N3Node {
protected:
std::string m_lexical;
const std::string *m_datatype;
Literal(const std::string &lexical, const std::string *datatype) : N3Node(), m_lexical(lexical), m_datatype(datatype) {}
Literal(std::string &&lexical, const std::string *datatype) : N3Node(), m_lexical(std::move(lexical)), m_datatype(datatype) {}
public:
const std::string &lexical() const { return m_lexical; }
const std::string &datatype() const { return *m_datatype; }
void visit(N3NodeVisitor &visitor) const
{
visitor.visit(*this);
}
};
class BooleanLiteral : public Literal {
public:
explicit BooleanLiteral(const std::string &value) : Literal(value, &TYPE) {}
static const std::string TYPE;
static const BooleanLiteral VALUE_TRUE;
static const BooleanLiteral VALUE_FALSE;
static const BooleanLiteral VALUE_1;
static const BooleanLiteral VALUE_0;
std::ostream &print(std::ostream &out) const
{
out << lexical();
return out;
}
bool value() const { return m_lexical == VALUE_TRUE.m_lexical || m_lexical == "1"; }
BooleanLiteral *clone() const
{
return new BooleanLiteral(m_lexical);
}
void visit(N3NodeVisitor &visitor) const
{
visitor.visit(*this);
}
};
class IntegerLiteral : public Literal {
public:
static const std::string TYPE;
explicit IntegerLiteral(const std::string &value) : Literal(value, &TYPE) {}
std::ostream &print(std::ostream &out) const
{
out << lexical();
return out;
}
IntegerLiteral *clone() const
{
return new IntegerLiteral(m_lexical);
}
void visit(N3NodeVisitor &visitor) const
{
visitor.visit(*this);
}
};
class DoubleLiteral : public Literal {
public:
static const std::string TYPE;
explicit DoubleLiteral(const std::string &value) : Literal(value, &TYPE) {}
std::ostream &print(std::ostream &out) const
{
out << lexical();
return out;
}
DoubleLiteral *clone() const
{
return new DoubleLiteral(m_lexical);
}
void visit(N3NodeVisitor &visitor) const
{
visitor.visit(*this);
}
};
class DecimalLiteral : public Literal {
public:
static const std::string TYPE;
explicit DecimalLiteral(const std::string &value) : Literal(value, &TYPE) {}
std::ostream &print(std::ostream &out) const
{
out << lexical();
return out;
}
DecimalLiteral *clone() const
{
return new DecimalLiteral(m_lexical);
}
void visit(N3NodeVisitor &visitor) const
{
visitor.visit(*this);
}
};
class StringLiteral : public Literal {
std::string m_language;
public:
static const std::string TYPE;
explicit StringLiteral(const std::string &value, const std::string &language = std::string()) : Literal(value, &TYPE), m_language(language) {}
explicit StringLiteral(std::string &&value, std::string &&language = std::string()) : Literal(std::move(value), &TYPE), m_language(std::move(language)) {}
const std::string &language() const { return m_language; }
std::ostream &print(std::ostream &out) const
{
out << '"' << lexical() << '"';
if (!language().empty())
out << '@' << language();
return out;
}
StringLiteral *clone() const
{
return new StringLiteral(m_lexical, m_language);
}
void visit(N3NodeVisitor &visitor) const
{
visitor.visit(*this);
}
};
class OtherLiteral : public Literal { /* keeps a copy of the type uri */
std::string m_datatype_copy;
public:
explicit OtherLiteral(const std::string &value, const std::string &datatype) : Literal(value, nullptr), m_datatype_copy(datatype)
{
m_datatype = &m_datatype_copy;
}
explicit OtherLiteral(std::string &&value, std::string &&datatype) : Literal(std::move(value), nullptr), m_datatype_copy(std::move(datatype))
{
m_datatype = &m_datatype_copy;
}
OtherLiteral(const OtherLiteral &other) : Literal(other.m_lexical, nullptr), m_datatype_copy(other.m_datatype_copy)
{
m_datatype = &m_datatype_copy;
}
OtherLiteral(OtherLiteral &&other) : Literal(std::move(other.m_lexical), nullptr), m_datatype_copy(std::move(other.m_datatype_copy))
{
m_datatype = &m_datatype_copy;
}
OtherLiteral& operator=(OtherLiteral other)
{
std::swap(m_lexical, other.m_lexical);
std::swap(m_datatype_copy, other.m_datatype_copy);
m_datatype = &m_datatype_copy;
return *this;
}
OtherLiteral& operator=(OtherLiteral &&other)
{
std::swap(m_lexical, other.m_lexical);
std::swap(m_datatype_copy, other.m_datatype_copy);
m_datatype = &m_datatype_copy;
return *this;
}
std::ostream &print(std::ostream &out) const
{
out << '"' << lexical() << '"' << '@' << '<' << datatype() << '>';
return out;
}
OtherLiteral *clone() const
{
return new OtherLiteral(m_lexical, m_datatype_copy);
}
};
struct RDF {
static const std::string NS;
static const URIResource type;
static const URIResource first;
static const URIResource rest;
static const URIResource nil;
};
struct XSD {
static const std::string NS;
};
}
#endif /* N3_MODEL_HH */
<|endoftext|> |
<commit_before>
/**
* NNTexture.cpp
* ۼ: ̼
* ۼ: 2013. 10. 30
* : ̼
* : 2013. 12. 04
*/
#include "NNTexture.h"
#include "NNApplication.h"
#include "NND2DRenderer.h"
#include "NND3DRenderer.h"
//////////////////////////////////////////////////////////////////////////
/* NND2DTexture */
//////////////////////////////////////////////////////////////////////////
NNTexture* NNTexture::Create( std::wstring path )
{
static RendererStatus rendererStatus = NNApplication::GetInstance()->GetRendererStatus();
NNTexture* pInstance = nullptr;
switch( rendererStatus )
{
case D2D:
pInstance = new NND2DTexture( path );
break;
default:
break;
}
return pInstance;
}
NNTexture* NNTexture::CreateStream( char *buf, int size )
{
static RendererStatus rendererStatus = NNApplication::GetInstance()->GetRendererStatus();
NNTexture* pInstance = nullptr;
switch( rendererStatus )
{
case D2D:
pInstance = new NND2DTexture( buf, size );
break;
default:
break;
}
return pInstance;
}
//////////////////////////////////////////////////////////////////////////
/* NND2DTexture */
//////////////////////////////////////////////////////////////////////////
IWICImagingFactory* NND2DTexture::g_pWICFactory = nullptr;
NND2DTexture::NND2DTexture()
: m_D2DBitmap(nullptr), m_FmtConverter(nullptr)
{
}
NND2DTexture::NND2DTexture( std::wstring path )
{
if ( g_pWICFactory == nullptr)
{
HRESULT ret = CoCreateInstance( CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&g_pWICFactory) );
if( ret == REGDB_E_CLASSNOTREG )
{
CoCreateInstance( CLSID_WICImagingFactory1, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&g_pWICFactory) );
}
}
m_Path = path;
IWICBitmapDecoder* bitmapDecoder = nullptr;
g_pWICFactory->CreateDecoderFromFilename( path.c_str(), nullptr, GENERIC_READ,
WICDecodeMetadataCacheOnDemand, &bitmapDecoder );
IWICBitmapFrameDecode* bitmapFrameDecode = nullptr;
bitmapDecoder->GetFrame( 0, &bitmapFrameDecode );
g_pWICFactory->CreateFormatConverter( &m_FmtConverter );
m_FmtConverter->Initialize( bitmapFrameDecode,
GUID_WICPixelFormat32bppPBGRA,
WICBitmapDitherTypeNone,
nullptr,
0.0f,
WICBitmapPaletteTypeCustom );
NND2DRenderer* pD2DRenderer = static_cast<NND2DRenderer*>(NNApplication::GetInstance()->GetRenderer());
pD2DRenderer->GetHwndRenderTarget()->CreateBitmapFromWicBitmap( m_FmtConverter, nullptr, &m_D2DBitmap );
SafeRelease( bitmapDecoder );
SafeRelease( bitmapFrameDecode );
}
NND2DTexture::NND2DTexture( char *buf, int size )
{
if ( g_pWICFactory == nullptr)
{
HRESULT ret = CoCreateInstance( CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&g_pWICFactory) );
if( ret == REGDB_E_CLASSNOTREG )
{
CoCreateInstance( CLSID_WICImagingFactory1, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&g_pWICFactory) );
}
}
IWICBitmapDecoder* bitmapDecoder = nullptr;
IWICStream* iWICStream;
g_pWICFactory->CreateStream( &iWICStream );
iWICStream->InitializeFromMemory( (WICInProcPointer)buf, size );
g_pWICFactory->CreateDecoderFromStream( iWICStream, nullptr, WICDecodeMetadataCacheOnDemand, &bitmapDecoder );
IWICBitmapFrameDecode* bitmapFrameDecode = nullptr;
bitmapDecoder->GetFrame( 0, &bitmapFrameDecode );
g_pWICFactory->CreateFormatConverter( &m_FmtConverter );
m_FmtConverter->Initialize( bitmapFrameDecode,
GUID_WICPixelFormat32bppPBGRA,
WICBitmapDitherTypeNone,
nullptr,
0.0f,
WICBitmapPaletteTypeCustom );
NND2DRenderer* pD2DRenderer = static_cast<NND2DRenderer*>(NNApplication::GetInstance()->GetRenderer());
pD2DRenderer->GetHwndRenderTarget()->CreateBitmapFromWicBitmap( m_FmtConverter, nullptr, &m_D2DBitmap );
SafeRelease( bitmapDecoder );
SafeRelease( bitmapFrameDecode );
}
NND2DTexture::~NND2DTexture()
{
Destroy();
SafeRelease( g_pWICFactory );
}
void NND2DTexture::Destroy()
{
SafeRelease( m_D2DBitmap );
SafeRelease( m_FmtConverter );
}
//////////////////////////////////////////////////////////////////////////
/* NND3DTexture */
//////////////////////////////////////////////////////////////////////////
NND3DTexture::NND3DTexture()
: mTexture(nullptr)
{
}
NND3DTexture::NND3DTexture( std::wstring path )
{
NND3DRenderer* pD2DRenderer = static_cast<NND3DRenderer*>(NNApplication::GetInstance()->GetRenderer());
D3DXCreateTextureFromFileEx( pD2DRenderer->GetDevice(), path.c_str(), D3DX_DEFAULT_NONPOW2, D3DX_DEFAULT_NONPOW2,
1, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, NULL, NULL, NULL, &mTexture );
}
NND3DTexture::~NND3DTexture()
{
Destroy();
}
void NND3DTexture::Destroy()
{
SafeRelease( mTexture );
}
<commit_msg>Added D3DTexture<commit_after>
/**
* NNTexture.cpp
* ۼ: ̼
* ۼ: 2013. 10. 30
* : ̼
* : 2013. 12. 05
*/
#include "NNTexture.h"
#include "NNApplication.h"
#include "NND2DRenderer.h"
#include "NND3DRenderer.h"
//////////////////////////////////////////////////////////////////////////
/* NND2DTexture */
//////////////////////////////////////////////////////////////////////////
NNTexture* NNTexture::Create( std::wstring path )
{
static RendererStatus rendererStatus = NNApplication::GetInstance()->GetRendererStatus();
NNTexture* pInstance = nullptr;
switch( rendererStatus )
{
case D2D:
pInstance = new NND2DTexture( path );
break;
case D3D:
pInstance = new NND3DTexture( path );
break;
default:
break;
}
return pInstance;
}
NNTexture* NNTexture::CreateStream( char *buf, int size )
{
static RendererStatus rendererStatus = NNApplication::GetInstance()->GetRendererStatus();
NNTexture* pInstance = nullptr;
switch( rendererStatus )
{
case D2D:
pInstance = new NND2DTexture( buf, size );
break;
default:
break;
}
return pInstance;
}
//////////////////////////////////////////////////////////////////////////
/* NND2DTexture */
//////////////////////////////////////////////////////////////////////////
IWICImagingFactory* NND2DTexture::g_pWICFactory = nullptr;
NND2DTexture::NND2DTexture()
: m_D2DBitmap(nullptr), m_FmtConverter(nullptr)
{
}
NND2DTexture::NND2DTexture( std::wstring path )
{
if ( g_pWICFactory == nullptr)
{
HRESULT ret = CoCreateInstance( CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&g_pWICFactory) );
if( ret == REGDB_E_CLASSNOTREG )
{
CoCreateInstance( CLSID_WICImagingFactory1, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&g_pWICFactory) );
}
}
m_Path = path;
IWICBitmapDecoder* bitmapDecoder = nullptr;
g_pWICFactory->CreateDecoderFromFilename( path.c_str(), nullptr, GENERIC_READ,
WICDecodeMetadataCacheOnDemand, &bitmapDecoder );
IWICBitmapFrameDecode* bitmapFrameDecode = nullptr;
bitmapDecoder->GetFrame( 0, &bitmapFrameDecode );
g_pWICFactory->CreateFormatConverter( &m_FmtConverter );
m_FmtConverter->Initialize( bitmapFrameDecode,
GUID_WICPixelFormat32bppPBGRA,
WICBitmapDitherTypeNone,
nullptr,
0.0f,
WICBitmapPaletteTypeCustom );
NND2DRenderer* pD2DRenderer = static_cast<NND2DRenderer*>(NNApplication::GetInstance()->GetRenderer());
pD2DRenderer->GetHwndRenderTarget()->CreateBitmapFromWicBitmap( m_FmtConverter, nullptr, &m_D2DBitmap );
SafeRelease( bitmapDecoder );
SafeRelease( bitmapFrameDecode );
}
NND2DTexture::NND2DTexture( char *buf, int size )
{
if ( g_pWICFactory == nullptr)
{
HRESULT ret = CoCreateInstance( CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&g_pWICFactory) );
if( ret == REGDB_E_CLASSNOTREG )
{
CoCreateInstance( CLSID_WICImagingFactory1, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&g_pWICFactory) );
}
}
IWICBitmapDecoder* bitmapDecoder = nullptr;
IWICStream* iWICStream;
g_pWICFactory->CreateStream( &iWICStream );
iWICStream->InitializeFromMemory( (WICInProcPointer)buf, size );
g_pWICFactory->CreateDecoderFromStream( iWICStream, nullptr, WICDecodeMetadataCacheOnDemand, &bitmapDecoder );
IWICBitmapFrameDecode* bitmapFrameDecode = nullptr;
bitmapDecoder->GetFrame( 0, &bitmapFrameDecode );
g_pWICFactory->CreateFormatConverter( &m_FmtConverter );
m_FmtConverter->Initialize( bitmapFrameDecode,
GUID_WICPixelFormat32bppPBGRA,
WICBitmapDitherTypeNone,
nullptr,
0.0f,
WICBitmapPaletteTypeCustom );
NND2DRenderer* pD2DRenderer = static_cast<NND2DRenderer*>(NNApplication::GetInstance()->GetRenderer());
pD2DRenderer->GetHwndRenderTarget()->CreateBitmapFromWicBitmap( m_FmtConverter, nullptr, &m_D2DBitmap );
SafeRelease( bitmapDecoder );
SafeRelease( bitmapFrameDecode );
}
NND2DTexture::~NND2DTexture()
{
Destroy();
SafeRelease( g_pWICFactory );
}
void NND2DTexture::Destroy()
{
SafeRelease( m_D2DBitmap );
SafeRelease( m_FmtConverter );
}
//////////////////////////////////////////////////////////////////////////
/* NND3DTexture */
//////////////////////////////////////////////////////////////////////////
NND3DTexture::NND3DTexture()
: mTexture(nullptr)
{
}
NND3DTexture::NND3DTexture( std::wstring path )
: mTexture(nullptr)
{
NND3DRenderer* pD3DRenderer = static_cast<NND3DRenderer*>(NNApplication::GetInstance()->GetRenderer());
m_Path = path;
LPDIRECT3DDEVICE9 temp = pD3DRenderer->GetDevice();
HRESULT hr = D3DXCreateTextureFromFileEx( pD3DRenderer->GetDevice(), path.c_str(), D3DX_DEFAULT_NONPOW2, D3DX_DEFAULT_NONPOW2,
1, 0, D3DFMT_FROM_FILE, D3DPOOL_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, NULL, NULL, NULL, &mTexture );
}
NND3DTexture::~NND3DTexture()
{
Destroy();
}
void NND3DTexture::Destroy()
{
SafeRelease( mTexture );
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: BIndex.cxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: hr $ $Date: 2006-06-20 01:08:58 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _CONNECTIVITY_ADABAS_INDEX_HXX_
#include "adabas/BIndex.hxx"
#endif
#ifndef _CONNECTIVITY_ADABAS_INDEXCOLUMNS_HXX_
#include "adabas/BIndexColumns.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _CONNECTIVITY_ADABAS_TABLE_HXX_
#include "adabas/BTable.hxx"
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
using namespace connectivity::adabas;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
// using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
// -------------------------------------------------------------------------
OAdabasIndex::OAdabasIndex( OAdabasTable* _pTable,
const ::rtl::OUString& _Name,
const ::rtl::OUString& _Catalog,
sal_Bool _isUnique,
sal_Bool _isPrimaryKeyIndex,
sal_Bool _isClustered
) : connectivity::sdbcx::OIndex(_Name,
_Catalog,
_isUnique,
_isPrimaryKeyIndex,
_isClustered,sal_True)
,m_pTable(_pTable)
{
construct();
refreshColumns();
}
// -------------------------------------------------------------------------
OAdabasIndex::OAdabasIndex(OAdabasTable* _pTable)
: connectivity::sdbcx::OIndex(sal_True)
,m_pTable(_pTable)
{
construct();
}
// -----------------------------------------------------------------------------
void OAdabasIndex::refreshColumns()
{
if(!m_pTable)
return;
TStringVector aVector;
if(!isNew())
{
Reference< XResultSet > xResult = m_pTable->getMetaData()->getIndexInfo(Any(),
m_pTable->getSchema(),m_pTable->getTableName(),sal_False,sal_False);
if(xResult.is())
{
Reference< XRow > xRow(xResult,UNO_QUERY);
::rtl::OUString aColName;
while(xResult->next())
{
if(xRow->getString(6) == m_Name)
{
aColName = xRow->getString(9);
if(!xRow->wasNull())
aVector.push_back(aColName);
}
}
::comphelper::disposeComponent(xResult);
}
}
if(m_pColumns)
m_pColumns->reFill(aVector);
else
m_pColumns = new OIndexColumns(this,m_aMutex,aVector);
}
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS pchfix02 (1.13.60); FILE MERGED 2006/09/01 17:21:51 kaib 1.13.60.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: BIndex.cxx,v $
*
* $Revision: 1.14 $
*
* last change: $Author: obo $ $Date: 2006-09-17 02:07:01 $
*
* 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_connectivity.hxx"
#ifndef _CONNECTIVITY_ADABAS_INDEX_HXX_
#include "adabas/BIndex.hxx"
#endif
#ifndef _CONNECTIVITY_ADABAS_INDEXCOLUMNS_HXX_
#include "adabas/BIndexColumns.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _CONNECTIVITY_ADABAS_TABLE_HXX_
#include "adabas/BTable.hxx"
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
using namespace connectivity::adabas;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
// using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
// -------------------------------------------------------------------------
OAdabasIndex::OAdabasIndex( OAdabasTable* _pTable,
const ::rtl::OUString& _Name,
const ::rtl::OUString& _Catalog,
sal_Bool _isUnique,
sal_Bool _isPrimaryKeyIndex,
sal_Bool _isClustered
) : connectivity::sdbcx::OIndex(_Name,
_Catalog,
_isUnique,
_isPrimaryKeyIndex,
_isClustered,sal_True)
,m_pTable(_pTable)
{
construct();
refreshColumns();
}
// -------------------------------------------------------------------------
OAdabasIndex::OAdabasIndex(OAdabasTable* _pTable)
: connectivity::sdbcx::OIndex(sal_True)
,m_pTable(_pTable)
{
construct();
}
// -----------------------------------------------------------------------------
void OAdabasIndex::refreshColumns()
{
if(!m_pTable)
return;
TStringVector aVector;
if(!isNew())
{
Reference< XResultSet > xResult = m_pTable->getMetaData()->getIndexInfo(Any(),
m_pTable->getSchema(),m_pTable->getTableName(),sal_False,sal_False);
if(xResult.is())
{
Reference< XRow > xRow(xResult,UNO_QUERY);
::rtl::OUString aColName;
while(xResult->next())
{
if(xRow->getString(6) == m_Name)
{
aColName = xRow->getString(9);
if(!xRow->wasNull())
aVector.push_back(aColName);
}
}
::comphelper::disposeComponent(xResult);
}
}
if(m_pColumns)
m_pColumns->reFill(aVector);
else
m_pColumns = new OIndexColumns(this,m_aMutex,aVector);
}
// -----------------------------------------------------------------------------
<|endoftext|> |
<commit_before>/*
* Polygon.cpp
*
* Created on: Nov 7, 2014
* Author: Péter Fankhauser
* Institute: ETH Zurich, Autonomous Systems Lab
*/
#include <grid_map_core/Polygon.hpp>
// Eigen
#include <Eigen/Dense>
#include <Eigen/Geometry>
namespace grid_map {
Polygon::Polygon() {}
Polygon::Polygon(std::vector<Position> vertices)
{
vertices_ = vertices;
}
Polygon::~Polygon() {}
bool Polygon::isInside(const Position& point)
{
int cross = 0;
for (int i = 0, j = vertices_.size() - 1; i < vertices_.size(); j = i++) {
if ( ((vertices_[i].y() > point.y()) != (vertices_[j].y() > point.y()))
&& (point.x() < (vertices_[j].x() - vertices_[i].x()) * (point.y() - vertices_[i].y()) /
(vertices_[j].y() - vertices_[i].y()) + vertices_[i].x()) )
{
cross++;
}
}
return bool(cross % 2);
}
void Polygon::addVertex(const Position& vertex)
{
vertices_.push_back(vertex);
}
const Position& Polygon::getVertex(const size_t index) const
{
return vertices_.at(index);
}
void Polygon::removeVertices()
{
vertices_.clear();
}
const Position& Polygon::operator [](const size_t index) const
{
return getVertex(index);
}
const std::vector<Position>& Polygon::getVertices() const
{
return vertices_;
}
const size_t Polygon::nVertices() const
{
return vertices_.size();
}
const std::string& Polygon::getFrameId() const
{
return frameId_;
}
void Polygon::setFrameId(const std::string& frameId)
{
frameId_ = frameId;
}
uint64_t Polygon::getTimestamp() const
{
return timestamp_;
}
void Polygon::setTimestamp(const uint64_t timestamp)
{
timestamp_ = timestamp;
}
void Polygon::resetTimestamp()
{
timestamp_ = 0.0;
}
Polygon Polygon::convexHullCircles(const Position center1,
const Position center2, const double radius,
const int nVertices)
{
Eigen::Vector2d centerToVertex, centerToVertexTemp;
centerToVertex = center2 - center1;
centerToVertex.normalize();
centerToVertex *= radius;
grid_map::Polygon polygon;
for (int j = 0; j < ceil(nVertices / 2.0); j++) {
double theta = M_PI_2 + j * M_PI / (ceil(nVertices / 2.0) - 1);
Eigen::Rotation2D<double> rot2d(theta);
centerToVertexTemp = rot2d.toRotationMatrix() * centerToVertex;
polygon.addVertex(center1 + centerToVertexTemp);
}
for (int j = 0; j < ceil(nVertices / 2.0); j++) {
double theta = 3 * M_PI_2 + j * M_PI / (ceil(nVertices / 2.0) - 1);
Eigen::Rotation2D<double> rot2d(theta);
centerToVertexTemp = rot2d.toRotationMatrix() * centerToVertex;
polygon.addVertex(center2 + centerToVertexTemp);
}
return polygon;
}
Polygon Polygon::convexHullCircle(const Position center, const double radius,
const int nVertices)
{
Eigen::Vector2d centerToVertex(radius, 0.0), centerToVertexTemp;
grid_map::Polygon polygon;
for (int j = 0; j < nVertices; j++) {
double theta = j * 2 * M_PI / (nVertices - 1);
Eigen::Rotation2D<double> rot2d(theta);
centerToVertexTemp = rot2d.toRotationMatrix() * centerToVertex;
polygon.addVertex(center + centerToVertexTemp);
}
return polygon;
}
Polygon Polygon::convexHull(Polygon& polygon1, Polygon& polygon2)
{
std::vector<Position> vertices;
vertices.reserve(polygon1.nVertices() + polygon2.nVertices());
vertices.insert(vertices.end(), polygon1.getVertices().begin(), polygon1.getVertices().end());
vertices.insert(vertices.end(), polygon2.getVertices().begin(), polygon2.getVertices().end());
std::vector<Position> hull(vertices.size());
// Sort points lexicographically
std::sort(vertices.begin(), vertices.end(), sortVertices);
int k = 0;
// Build lower hull
for (int i = 0; i < vertices.size(); ++i) {
while (k >= 2
&& computeCrossProduct2D(hull.at(k - 1) - hull.at(k - 2),
vertices.at(i) - hull.at(k - 2)) <= 0)
k--;
hull.at(k++) = vertices.at(i);
}
// Build upper hull
for (int i = vertices.size() - 2, t = k + 1; i >= 0; i--) {
while (k >= t
&& computeCrossProduct2D(hull.at(k - 1) - hull.at(k - 2),
vertices.at(i) - hull.at(k - 2)) <= 0)
k--;
hull.at(k++) = vertices.at(i);
}
hull.resize(k - 1);
return Polygon(hull);
}
bool Polygon::sortVertices(const Eigen::Vector2d& vector1,
const Eigen::Vector2d& vector2)
{
return (vector1.x() < vector2.x()
|| (vector1.x() == vector2.x() && vector1.y() < vector2.y()));
}
double Polygon::computeCrossProduct2D(const Eigen::Vector2d& vector1,
const Eigen::Vector2d& vector2)
{
return (vector1.x() * vector2.y() - vector1.y() * vector2.x());
}
} /* namespace grid_map */
<commit_msg>Fix: changed vector size at convex hull construction<commit_after>/*
* Polygon.cpp
*
* Created on: Nov 7, 2014
* Author: Péter Fankhauser
* Institute: ETH Zurich, Autonomous Systems Lab
*/
#include <grid_map_core/Polygon.hpp>
// Eigen
#include <Eigen/Dense>
#include <Eigen/Geometry>
#include <iostream>
namespace grid_map {
Polygon::Polygon() {}
Polygon::Polygon(std::vector<Position> vertices)
{
vertices_ = vertices;
}
Polygon::~Polygon() {}
bool Polygon::isInside(const Position& point)
{
int cross = 0;
for (int i = 0, j = vertices_.size() - 1; i < vertices_.size(); j = i++) {
if ( ((vertices_[i].y() > point.y()) != (vertices_[j].y() > point.y()))
&& (point.x() < (vertices_[j].x() - vertices_[i].x()) * (point.y() - vertices_[i].y()) /
(vertices_[j].y() - vertices_[i].y()) + vertices_[i].x()) )
{
cross++;
}
}
return bool(cross % 2);
}
void Polygon::addVertex(const Position& vertex)
{
vertices_.push_back(vertex);
}
const Position& Polygon::getVertex(const size_t index) const
{
return vertices_.at(index);
}
void Polygon::removeVertices()
{
vertices_.clear();
}
const Position& Polygon::operator [](const size_t index) const
{
return getVertex(index);
}
const std::vector<Position>& Polygon::getVertices() const
{
return vertices_;
}
const size_t Polygon::nVertices() const
{
return vertices_.size();
}
const std::string& Polygon::getFrameId() const
{
return frameId_;
}
void Polygon::setFrameId(const std::string& frameId)
{
frameId_ = frameId;
}
uint64_t Polygon::getTimestamp() const
{
return timestamp_;
}
void Polygon::setTimestamp(const uint64_t timestamp)
{
timestamp_ = timestamp;
}
void Polygon::resetTimestamp()
{
timestamp_ = 0.0;
}
Polygon Polygon::convexHullCircles(const Position center1,
const Position center2, const double radius,
const int nVertices)
{
Eigen::Vector2d centerToVertex, centerToVertexTemp;
centerToVertex = center2 - center1;
centerToVertex.normalize();
centerToVertex *= radius;
grid_map::Polygon polygon;
for (int j = 0; j < ceil(nVertices / 2.0); j++) {
double theta = M_PI_2 + j * M_PI / (ceil(nVertices / 2.0) - 1);
Eigen::Rotation2D<double> rot2d(theta);
centerToVertexTemp = rot2d.toRotationMatrix() * centerToVertex;
polygon.addVertex(center1 + centerToVertexTemp);
}
for (int j = 0; j < ceil(nVertices / 2.0); j++) {
double theta = 3 * M_PI_2 + j * M_PI / (ceil(nVertices / 2.0) - 1);
Eigen::Rotation2D<double> rot2d(theta);
centerToVertexTemp = rot2d.toRotationMatrix() * centerToVertex;
polygon.addVertex(center2 + centerToVertexTemp);
}
return polygon;
}
Polygon Polygon::convexHullCircle(const Position center, const double radius,
const int nVertices)
{
Eigen::Vector2d centerToVertex(radius, 0.0), centerToVertexTemp;
grid_map::Polygon polygon;
for (int j = 0; j < nVertices; j++) {
double theta = j * 2 * M_PI / (nVertices - 1);
Eigen::Rotation2D<double> rot2d(theta);
centerToVertexTemp = rot2d.toRotationMatrix() * centerToVertex;
polygon.addVertex(center + centerToVertexTemp);
}
return polygon;
}
Polygon Polygon::convexHull(Polygon& polygon1, Polygon& polygon2)
{
std::vector<Position> vertices;
vertices.reserve(polygon1.nVertices() + polygon2.nVertices());
vertices.insert(vertices.end(), polygon1.getVertices().begin(), polygon1.getVertices().end());
vertices.insert(vertices.end(), polygon2.getVertices().begin(), polygon2.getVertices().end());
std::vector<Position> hull(vertices.size()+1);
// Sort points lexicographically
std::sort(vertices.begin(), vertices.end(), sortVertices);
int k = 0;
// Build lower hull
for (int i = 0; i < vertices.size(); ++i) {
while (k >= 2
&& computeCrossProduct2D(hull.at(k - 1) - hull.at(k - 2),
vertices.at(i) - hull.at(k - 2)) <= 0)
k--;
hull.at(k++) = vertices.at(i);
}
// Build upper hull
for (int i = vertices.size() - 2, t = k + 1; i >= 0; i--) {
while (k >= t
&& computeCrossProduct2D(hull.at(k - 1) - hull.at(k - 2),
vertices.at(i) - hull.at(k - 2)) <= 0)
k--;
hull.at(k++) = vertices.at(i);
}
hull.resize(k - 1);
return Polygon(hull);
}
bool Polygon::sortVertices(const Eigen::Vector2d& vector1,
const Eigen::Vector2d& vector2)
{
return (vector1.x() < vector2.x()
|| (vector1.x() == vector2.x() && vector1.y() < vector2.y()));
}
double Polygon::computeCrossProduct2D(const Eigen::Vector2d& vector1,
const Eigen::Vector2d& vector2)
{
return (vector1.x() * vector2.y() - vector1.y() * vector2.x());
}
} /* namespace grid_map */
<|endoftext|> |
<commit_before><commit_msg>`yli::load::load_shaders`: add `const` modifiers to variables.<commit_after><|endoftext|> |
<commit_before>#include "symbiosis.hpp"
#include "shader.hpp"
#include "symbiont_material.hpp"
#include "symbiont_species.hpp"
#include "holobiont.hpp"
#include "material_struct.hpp"
#include "render_templates.hpp"
#include "code/ylikuutio/hierarchy/hierarchy_templates.hpp"
#include <ofbx.h>
// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h> // GLfloat, GLuint etc.
#endif
// Include GLFW
#ifndef __GLFW3_H_INCLUDED
#define __GLFW3_H_INCLUDED
#include <GLFW/glfw3.h>
#endif
// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif
// Include standard headers
#include <iostream> // std::cout, std::cin, std::cerr
#include <stdint.h> // uint32_t etc.
#include <string> // std::string
#include <vector> // std::vector
namespace ontology
{
class Holobiont;
void Symbiosis::bind_symbiont_material(ontology::SymbiontMaterial* const symbiont_material)
{
// get `childID` from `Symbiosis` and set pointer to `symbiont_material`.
hierarchy::bind_child_to_parent<ontology::SymbiontMaterial*>(
symbiont_material,
this->symbiont_material_pointer_vector,
this->free_symbiont_materialID_queue,
&this->number_of_symbiont_materials);
}
void Symbiosis::bind_holobiont(ontology::Holobiont* const holobiont)
{
// get `childID` from `Symbiosis` and set pointer to `holobiont`.
hierarchy::bind_child_to_parent<ontology::Holobiont*>(
holobiont,
this->holobiont_pointer_vector,
this->free_holobiontID_queue,
&this->number_of_holobionts);
}
void Symbiosis::unbind_holobiont(const int32_t childID)
{
ontology::Holobiont* dummy_child_pointer = nullptr;
hierarchy::set_child_pointer(
childID,
dummy_child_pointer,
this->holobiont_pointer_vector,
this->free_holobiontID_queue,
&this->number_of_holobionts);
}
void Symbiosis::bind_to_parent()
{
// get `childID` from `Shader` and set pointer to this `Symbiosis`.
this->parent->bind_symbiosis(this);
}
void Symbiosis::bind_to_new_parent(ontology::Shader* const new_shader_pointer)
{
// unbind from the old parent `Shader`.
this->parent->unbind_symbiosis(this->childID);
// get `childID` from `Shader` and set pointer to this `Symbiosis`.
this->parent = new_shader_pointer;
this->parent->bind_symbiosis(this);
}
Symbiosis::~Symbiosis()
{
// destructor.
std::cout << "Symbiosis with childID " << std::dec << this->childID << " will be destroyed.\n";
// destroy all `Holobiont`s of this `Symbiosis`.
std::cout << "All holobionts of this symbiosis will be destroyed.\n";
hierarchy::delete_children<ontology::Holobiont*>(this->holobiont_pointer_vector, &this->number_of_holobionts);
// destroy all `SymbiontMaterial`s of this `Symbiosis`.
std::cout << "All symbiont materials of this symbiosis will be destroyed.\n";
hierarchy::delete_children<ontology::SymbiontMaterial*>(this->symbiont_material_pointer_vector, &this->number_of_symbiont_materials);
// set pointer to this `Symbiosis` to `nullptr`.
this->parent->set_symbiosis_pointer(this->childID, nullptr);
}
void Symbiosis::render()
{
this->prerender();
// render this `Symbiosis` by calling `render()` function of each `Holobiont`.
ontology::render_children<ontology::Holobiont*>(this->holobiont_pointer_vector);
this->postrender();
}
ontology::Entity* Symbiosis::get_parent() const
{
return this->parent;
}
int32_t Symbiosis::get_number_of_children() const
{
return this->number_of_symbiont_materials + this->number_of_holobionts;
}
int32_t Symbiosis::get_number_of_descendants() const
{
return -1;
}
const std::string& Symbiosis::get_model_file_format()
{
return this->model_file_format;
}
void Symbiosis::set_symbiont_material_pointer(const int32_t childID, ontology::SymbiontMaterial* const child_pointer)
{
hierarchy::set_child_pointer(
childID,
child_pointer,
this->symbiont_material_pointer_vector,
this->free_symbiont_materialID_queue,
&this->number_of_symbiont_materials);
}
void Symbiosis::set_holobiont_pointer(const int32_t childID, ontology::Holobiont* const child_pointer)
{
hierarchy::set_child_pointer(
childID,
child_pointer,
this->holobiont_pointer_vector,
this->free_holobiontID_queue,
&this->number_of_holobionts);
}
void Symbiosis::create_symbionts()
{
SymbiosisLoaderStruct symbiosis_loader_struct;
symbiosis_loader_struct.model_filename = this->model_filename;
symbiosis_loader_struct.model_file_format = this->model_file_format;
symbiosis_loader_struct.triangulation_type = this->triangulation_type;
const bool is_debug_mode = true;
if (loaders::load_symbiosis(
symbiosis_loader_struct,
this->vertices,
this->uvs,
this->normals,
this->indices,
this->indexed_vertices,
this->indexed_uvs,
this->indexed_normals,
this->ofbx_diffuse_texture_mesh_map,
this->ofbx_meshes,
this->ofbx_diffuse_texture_vector,
this->ofbx_normal_texture_vector,
this->ofbx_count_texture_vector,
this->ofbx_mesh_count,
is_debug_mode))
{
std::cout << "number of meshes: " << this->ofbx_mesh_count << "\n";
std::vector<const ofbx::Texture*> ofbx_diffuse_texture_pointer_vector;
ofbx_diffuse_texture_pointer_vector.reserve(this->ofbx_diffuse_texture_mesh_map.size());
this->biontID_symbiont_material_vector.resize(this->ofbx_mesh_count);
this->biontID_symbiont_species_vector.resize(this->ofbx_mesh_count);
for (auto key_and_value : ofbx_diffuse_texture_mesh_map)
{
ofbx_diffuse_texture_pointer_vector.push_back(key_and_value.first); // key.
}
// Create `SymbiontMaterial`s.
for (const ofbx::Texture* ofbx_texture : ofbx_diffuse_texture_pointer_vector)
{
std::cout << "Creating ontology::SymbiontMaterial* based on ofbx::Texture* at 0x" << std::hex << (uint64_t) ofbx_texture << std::dec << " ...\n";
MaterialStruct material_struct;
material_struct.shader = this->parent;
material_struct.symbiosis = this;
material_struct.is_symbiont_material = true;
material_struct.ofbx_texture = ofbx_texture;
ontology::SymbiontMaterial* symbiont_material = new ontology::SymbiontMaterial(this->universe, material_struct);
symbiont_material->load_texture();
std::cout << "ontology::SymbiontMaterial* successfully created.\n";
// Create `SymbiontSpecies`s.
// Care only about `ofbx::Texture*`s which are DIFFUSE textures.
for (int32_t mesh_i : this->ofbx_diffuse_texture_mesh_map.at(ofbx_texture))
{
int32_t vertex_count = this->vertices.at(mesh_i).size();
std::vector<glm::vec3> vertices = this->vertices.at(mesh_i);
SpeciesStruct species_struct;
species_struct.is_symbiont_species = true;
species_struct.scene = static_cast<ontology::Scene*>(this->parent->get_parent());
species_struct.shader = this->parent;
species_struct.symbiont_material = symbiont_material;
species_struct.vertex_count = vertex_count;
species_struct.vertices = this->vertices.at(mesh_i);
species_struct.uvs = this->uvs.at(mesh_i);
species_struct.normals = this->normals.at(mesh_i);
species_struct.light_position = this->light_position;
std::cout << "Creating ontology::SymbiontSpecies*, mesh index " << mesh_i << "...\n";
ontology::SymbiontSpecies* symbiont_species = new ontology::SymbiontSpecies(this->universe, species_struct);
std::cout << "ontology::SymbiontSpecies*, mesh index " << mesh_i << " successfully created.\n";
std::cout << "storing ontology::SymbiontMaterial* symbiont_material into vector with mesh_i " << mesh_i << " ...\n";
this->biontID_symbiont_material_vector.at(mesh_i) = symbiont_material;
std::cout << "storing ontology::SymbiontSpecies* symbiont_species into vector with mesh_i " << mesh_i << " ...\n";
this->biontID_symbiont_species_vector.at(mesh_i) = symbiont_species;
std::cout << "Success.\n";
// TODO: Compute the graph of each type to enable object vertex modification!
}
}
std::cout << "All symbionts successfully created.\n";
}
}
ontology::SymbiontSpecies* Symbiosis::get_symbiont_species(const int32_t biontID) const
{
return this->biontID_symbiont_species_vector.at(biontID);
}
GLuint Symbiosis::get_vertex_position_modelspaceID(const int32_t biontID) const
{
return this->biontID_symbiont_species_vector.at(biontID)->get_vertex_position_modelspaceID();
}
GLuint Symbiosis::get_vertexUVID(const int32_t biontID) const
{
return this->biontID_symbiont_species_vector.at(biontID)->get_vertexUVID();
}
GLuint Symbiosis::get_vertex_normal_modelspaceID(const int32_t biontID) const
{
return this->biontID_symbiont_species_vector.at(biontID)->get_vertex_normal_modelspaceID();
}
GLuint Symbiosis::get_vertexbuffer(const int32_t biontID) const
{
return this->biontID_symbiont_species_vector.at(biontID)->get_vertexbuffer();
}
GLuint Symbiosis::get_uvbuffer(const int32_t biontID) const
{
return this->biontID_symbiont_species_vector.at(biontID)->get_uvbuffer();
}
GLuint Symbiosis::get_normalbuffer(const int32_t biontID) const
{
return this->biontID_symbiont_species_vector.at(biontID)->get_normalbuffer();
}
GLuint Symbiosis::get_elementbuffer(const int32_t biontID) const
{
return this->biontID_symbiont_species_vector.at(biontID)->get_elementbuffer();
}
std::vector<uint32_t> Symbiosis::get_indices(const int32_t biontID) const
{
return this->biontID_symbiont_species_vector.at(biontID)->get_indices();
// return this->indices.at(biontID);
}
GLuint Symbiosis::get_indices_size(const int32_t biontID) const
{
return this->biontID_symbiont_species_vector.at(biontID)->get_indices_size();
// return this->indices.at(biontID).size();
}
int32_t Symbiosis::get_number_of_symbionts() const
{
return this->ofbx_mesh_count;
}
bool Symbiosis::has_texture(const int32_t biontID) const
{
if (biontID >= this->biontID_symbiont_material_vector.size())
{
return false;
}
if (this->biontID_symbiont_material_vector.at(biontID) == nullptr)
{
return false;
}
return true;
}
GLuint Symbiosis::get_texture(const int32_t biontID) const
{
return this->biontID_symbiont_material_vector.at(biontID)->get_texture();
}
GLuint Symbiosis::get_openGL_textureID(const int32_t biontID) const
{
return this->biontID_symbiont_material_vector.at(biontID)->get_openGL_textureID();
}
GLuint Symbiosis::get_lightID(const int32_t biontID) const
{
return this->biontID_symbiont_species_vector.at(biontID)->get_lightID();
}
glm::vec3 Symbiosis::get_light_position(const int32_t biontID) const
{
return this->light_position;
}
}
<commit_msg>`Symbiosis::create_symbionts`: check `ofbx_texture` for `nullptr`.<commit_after>#include "symbiosis.hpp"
#include "shader.hpp"
#include "symbiont_material.hpp"
#include "symbiont_species.hpp"
#include "holobiont.hpp"
#include "material_struct.hpp"
#include "render_templates.hpp"
#include "code/ylikuutio/hierarchy/hierarchy_templates.hpp"
#include <ofbx.h>
// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h> // GLfloat, GLuint etc.
#endif
// Include GLFW
#ifndef __GLFW3_H_INCLUDED
#define __GLFW3_H_INCLUDED
#include <GLFW/glfw3.h>
#endif
// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif
// Include standard headers
#include <iostream> // std::cout, std::cin, std::cerr
#include <stdint.h> // uint32_t etc.
#include <string> // std::string
#include <vector> // std::vector
namespace ontology
{
class Holobiont;
void Symbiosis::bind_symbiont_material(ontology::SymbiontMaterial* const symbiont_material)
{
// get `childID` from `Symbiosis` and set pointer to `symbiont_material`.
hierarchy::bind_child_to_parent<ontology::SymbiontMaterial*>(
symbiont_material,
this->symbiont_material_pointer_vector,
this->free_symbiont_materialID_queue,
&this->number_of_symbiont_materials);
}
void Symbiosis::bind_holobiont(ontology::Holobiont* const holobiont)
{
// get `childID` from `Symbiosis` and set pointer to `holobiont`.
hierarchy::bind_child_to_parent<ontology::Holobiont*>(
holobiont,
this->holobiont_pointer_vector,
this->free_holobiontID_queue,
&this->number_of_holobionts);
}
void Symbiosis::unbind_holobiont(const int32_t childID)
{
ontology::Holobiont* dummy_child_pointer = nullptr;
hierarchy::set_child_pointer(
childID,
dummy_child_pointer,
this->holobiont_pointer_vector,
this->free_holobiontID_queue,
&this->number_of_holobionts);
}
void Symbiosis::bind_to_parent()
{
// get `childID` from `Shader` and set pointer to this `Symbiosis`.
this->parent->bind_symbiosis(this);
}
void Symbiosis::bind_to_new_parent(ontology::Shader* const new_shader_pointer)
{
// unbind from the old parent `Shader`.
this->parent->unbind_symbiosis(this->childID);
// get `childID` from `Shader` and set pointer to this `Symbiosis`.
this->parent = new_shader_pointer;
this->parent->bind_symbiosis(this);
}
Symbiosis::~Symbiosis()
{
// destructor.
std::cout << "Symbiosis with childID " << std::dec << this->childID << " will be destroyed.\n";
// destroy all `Holobiont`s of this `Symbiosis`.
std::cout << "All holobionts of this symbiosis will be destroyed.\n";
hierarchy::delete_children<ontology::Holobiont*>(this->holobiont_pointer_vector, &this->number_of_holobionts);
// destroy all `SymbiontMaterial`s of this `Symbiosis`.
std::cout << "All symbiont materials of this symbiosis will be destroyed.\n";
hierarchy::delete_children<ontology::SymbiontMaterial*>(this->symbiont_material_pointer_vector, &this->number_of_symbiont_materials);
// set pointer to this `Symbiosis` to `nullptr`.
this->parent->set_symbiosis_pointer(this->childID, nullptr);
}
void Symbiosis::render()
{
this->prerender();
// render this `Symbiosis` by calling `render()` function of each `Holobiont`.
ontology::render_children<ontology::Holobiont*>(this->holobiont_pointer_vector);
this->postrender();
}
ontology::Entity* Symbiosis::get_parent() const
{
return this->parent;
}
int32_t Symbiosis::get_number_of_children() const
{
return this->number_of_symbiont_materials + this->number_of_holobionts;
}
int32_t Symbiosis::get_number_of_descendants() const
{
return -1;
}
const std::string& Symbiosis::get_model_file_format()
{
return this->model_file_format;
}
void Symbiosis::set_symbiont_material_pointer(const int32_t childID, ontology::SymbiontMaterial* const child_pointer)
{
hierarchy::set_child_pointer(
childID,
child_pointer,
this->symbiont_material_pointer_vector,
this->free_symbiont_materialID_queue,
&this->number_of_symbiont_materials);
}
void Symbiosis::set_holobiont_pointer(const int32_t childID, ontology::Holobiont* const child_pointer)
{
hierarchy::set_child_pointer(
childID,
child_pointer,
this->holobiont_pointer_vector,
this->free_holobiontID_queue,
&this->number_of_holobionts);
}
void Symbiosis::create_symbionts()
{
SymbiosisLoaderStruct symbiosis_loader_struct;
symbiosis_loader_struct.model_filename = this->model_filename;
symbiosis_loader_struct.model_file_format = this->model_file_format;
symbiosis_loader_struct.triangulation_type = this->triangulation_type;
const bool is_debug_mode = true;
if (loaders::load_symbiosis(
symbiosis_loader_struct,
this->vertices,
this->uvs,
this->normals,
this->indices,
this->indexed_vertices,
this->indexed_uvs,
this->indexed_normals,
this->ofbx_diffuse_texture_mesh_map,
this->ofbx_meshes,
this->ofbx_diffuse_texture_vector,
this->ofbx_normal_texture_vector,
this->ofbx_count_texture_vector,
this->ofbx_mesh_count,
is_debug_mode))
{
std::cout << "number of meshes: " << this->ofbx_mesh_count << "\n";
std::vector<const ofbx::Texture*> ofbx_diffuse_texture_pointer_vector;
ofbx_diffuse_texture_pointer_vector.reserve(this->ofbx_diffuse_texture_mesh_map.size());
this->biontID_symbiont_material_vector.resize(this->ofbx_mesh_count);
this->biontID_symbiont_species_vector.resize(this->ofbx_mesh_count);
for (auto key_and_value : ofbx_diffuse_texture_mesh_map)
{
ofbx_diffuse_texture_pointer_vector.push_back(key_and_value.first); // key.
}
// Create `SymbiontMaterial`s.
for (const ofbx::Texture* ofbx_texture : ofbx_diffuse_texture_pointer_vector)
{
if (ofbx_texture == nullptr)
{
continue;
}
std::cout << "Creating ontology::SymbiontMaterial* based on ofbx::Texture* at 0x" << std::hex << (uint64_t) ofbx_texture << std::dec << " ...\n";
MaterialStruct material_struct;
material_struct.shader = this->parent;
material_struct.symbiosis = this;
material_struct.is_symbiont_material = true;
material_struct.ofbx_texture = ofbx_texture;
ontology::SymbiontMaterial* symbiont_material = new ontology::SymbiontMaterial(this->universe, material_struct);
symbiont_material->load_texture();
std::cout << "ontology::SymbiontMaterial* successfully created.\n";
// Create `SymbiontSpecies`s.
// Care only about `ofbx::Texture*`s which are DIFFUSE textures.
for (int32_t mesh_i : this->ofbx_diffuse_texture_mesh_map.at(ofbx_texture))
{
int32_t vertex_count = this->vertices.at(mesh_i).size();
std::vector<glm::vec3> vertices = this->vertices.at(mesh_i);
SpeciesStruct species_struct;
species_struct.is_symbiont_species = true;
species_struct.scene = static_cast<ontology::Scene*>(this->parent->get_parent());
species_struct.shader = this->parent;
species_struct.symbiont_material = symbiont_material;
species_struct.vertex_count = vertex_count;
species_struct.vertices = this->vertices.at(mesh_i);
species_struct.uvs = this->uvs.at(mesh_i);
species_struct.normals = this->normals.at(mesh_i);
species_struct.light_position = this->light_position;
std::cout << "Creating ontology::SymbiontSpecies*, mesh index " << mesh_i << "...\n";
ontology::SymbiontSpecies* symbiont_species = new ontology::SymbiontSpecies(this->universe, species_struct);
std::cout << "ontology::SymbiontSpecies*, mesh index " << mesh_i << " successfully created.\n";
std::cout << "storing ontology::SymbiontMaterial* symbiont_material into vector with mesh_i " << mesh_i << " ...\n";
this->biontID_symbiont_material_vector.at(mesh_i) = symbiont_material;
std::cout << "storing ontology::SymbiontSpecies* symbiont_species into vector with mesh_i " << mesh_i << " ...\n";
this->biontID_symbiont_species_vector.at(mesh_i) = symbiont_species;
std::cout << "Success.\n";
// TODO: Compute the graph of each type to enable object vertex modification!
}
}
std::cout << "All symbionts successfully created.\n";
}
}
ontology::SymbiontSpecies* Symbiosis::get_symbiont_species(const int32_t biontID) const
{
return this->biontID_symbiont_species_vector.at(biontID);
}
GLuint Symbiosis::get_vertex_position_modelspaceID(const int32_t biontID) const
{
return this->biontID_symbiont_species_vector.at(biontID)->get_vertex_position_modelspaceID();
}
GLuint Symbiosis::get_vertexUVID(const int32_t biontID) const
{
return this->biontID_symbiont_species_vector.at(biontID)->get_vertexUVID();
}
GLuint Symbiosis::get_vertex_normal_modelspaceID(const int32_t biontID) const
{
return this->biontID_symbiont_species_vector.at(biontID)->get_vertex_normal_modelspaceID();
}
GLuint Symbiosis::get_vertexbuffer(const int32_t biontID) const
{
return this->biontID_symbiont_species_vector.at(biontID)->get_vertexbuffer();
}
GLuint Symbiosis::get_uvbuffer(const int32_t biontID) const
{
return this->biontID_symbiont_species_vector.at(biontID)->get_uvbuffer();
}
GLuint Symbiosis::get_normalbuffer(const int32_t biontID) const
{
return this->biontID_symbiont_species_vector.at(biontID)->get_normalbuffer();
}
GLuint Symbiosis::get_elementbuffer(const int32_t biontID) const
{
return this->biontID_symbiont_species_vector.at(biontID)->get_elementbuffer();
}
std::vector<uint32_t> Symbiosis::get_indices(const int32_t biontID) const
{
return this->biontID_symbiont_species_vector.at(biontID)->get_indices();
// return this->indices.at(biontID);
}
GLuint Symbiosis::get_indices_size(const int32_t biontID) const
{
return this->biontID_symbiont_species_vector.at(biontID)->get_indices_size();
// return this->indices.at(biontID).size();
}
int32_t Symbiosis::get_number_of_symbionts() const
{
return this->ofbx_mesh_count;
}
bool Symbiosis::has_texture(const int32_t biontID) const
{
if (biontID >= this->biontID_symbiont_material_vector.size())
{
return false;
}
if (this->biontID_symbiont_material_vector.at(biontID) == nullptr)
{
return false;
}
return true;
}
GLuint Symbiosis::get_texture(const int32_t biontID) const
{
return this->biontID_symbiont_material_vector.at(biontID)->get_texture();
}
GLuint Symbiosis::get_openGL_textureID(const int32_t biontID) const
{
return this->biontID_symbiont_material_vector.at(biontID)->get_openGL_textureID();
}
GLuint Symbiosis::get_lightID(const int32_t biontID) const
{
return this->biontID_symbiont_species_vector.at(biontID)->get_lightID();
}
glm::vec3 Symbiosis::get_light_position(const int32_t biontID) const
{
return this->light_position;
}
}
<|endoftext|> |
<commit_before>#include "flutter_webrtc_base.h"
#include "flutter_data_channel.h"
#include "flutter_peerconnection.h"
namespace flutter_webrtc_plugin {
FlutterWebRTCBase::FlutterWebRTCBase(BinaryMessenger *messenger,
TextureRegistrar *textures)
: messenger_(messenger), textures_(textures) {
LibWebRTC::Initialize();
factory_ = LibWebRTC::CreateRTCPeerConnectionFactory();
audio_device_ = factory_->GetAudioDevice();
video_device_ = factory_->GetVideoDevice();
desktop_device_ = factory_->GetDesktopDevice();
}
FlutterWebRTCBase::~FlutterWebRTCBase() {
LibWebRTC::Terminate();
}
std::string FlutterWebRTCBase::GenerateUUID() {
return uuidxx::uuid::Generate().ToString(false);
}
RTCPeerConnection *FlutterWebRTCBase::PeerConnectionForId(
const std::string &id) {
auto it = peerconnections_.find(id);
if (it != peerconnections_.end()) return (*it).second.get();
return nullptr;
}
void FlutterWebRTCBase::RemovePeerConnectionForId(const std::string &id) {
auto it = peerconnections_.find(id);
if (it != peerconnections_.end()) peerconnections_.erase(it);
}
RTCMediaTrack* FlutterWebRTCBase ::MediaTrackForId(const std::string& id) {
auto it = local_tracks_.find(id);
if (it != local_tracks_.end())
return (*it).second.get();
for (auto kv : peerconnection_observers_) {
auto pco = kv.second.get();
auto track = pco->MediaTrackForId(id);
if (track != nullptr) return track;
}
return nullptr;
}
void FlutterWebRTCBase::RemoveMediaTrackForId(const std::string& id) {
auto it = local_tracks_.find(id);
if (it != local_tracks_.end())
local_tracks_.erase(it);
}
FlutterPeerConnectionObserver* FlutterWebRTCBase::PeerConnectionObserversForId(
const std::string& id) {
auto it = peerconnection_observers_.find(id);
if (it != peerconnection_observers_.end())
return (*it).second.get();
return nullptr;
}
void FlutterWebRTCBase::RemovePeerConnectionObserversForId(
const std::string& id) {
auto it = peerconnection_observers_.find(id);
if (it != peerconnection_observers_.end())
peerconnection_observers_.erase(it);
}
scoped_refptr<RTCMediaStream> FlutterWebRTCBase::MediaStreamForId(
const std::string& id) {
auto it = local_streams_.find(id);
if (it != local_streams_.end()) {
return (*it).second;
}
for (auto kv : peerconnection_observers_) {
auto pco = kv.second.get();
auto stream = pco->MediaStreamForId(id);
if (stream != nullptr) return stream;
}
return nullptr;
}
void FlutterWebRTCBase::RemoveStreamForId(const std::string &id) {
auto it = local_streams_.find(id);
if (it != local_streams_.end()) local_streams_.erase(it);
}
bool FlutterWebRTCBase::ParseConstraints(const EncodableMap &constraints,
RTCConfiguration *configuration) {
memset(&configuration->ice_servers, 0, sizeof(configuration->ice_servers));
return false;
}
void FlutterWebRTCBase::ParseConstraints(
const EncodableMap &src,
scoped_refptr<RTCMediaConstraints> mediaConstraints,
ParseConstraintType type /*= kMandatory*/) {
for (auto kv : src) {
EncodableValue k = kv.first;
EncodableValue v = kv.second;
std::string key = GetValue<std::string>(k);
std::string value;
if (TypeIs<EncodableList>(v) || TypeIs<EncodableMap>(v)) {
} else if (TypeIs<std::string>(v)) {
value = GetValue<std::string>(v);
} else if (TypeIs<double>(v)) {
value = std::to_string(GetValue<double>(v));
} else if (TypeIs<int>(v)) {
value = std::to_string(GetValue<int>(v));
} else if (TypeIs<bool>(v)) {
value = GetValue<bool>(v) ? RTCMediaConstraints::kValueTrue
: RTCMediaConstraints::kValueFalse;
} else {
value = std::to_string(GetValue<int>(v));
}
if (type == kMandatory) {
mediaConstraints->AddMandatoryConstraint(key.c_str(), value.c_str());
} else {
mediaConstraints->AddOptionalConstraint(key.c_str(), value.c_str());
if (key == "DtlsSrtpKeyAgreement") {
configuration_.srtp_type = GetValue<bool>(v)
? MediaSecurityType::kDTLS_SRTP
: MediaSecurityType::kSDES_SRTP;
}
}
}
}
scoped_refptr<RTCMediaConstraints> FlutterWebRTCBase::ParseMediaConstraints(
const EncodableMap &constraints) {
scoped_refptr<RTCMediaConstraints> media_constraints =
RTCMediaConstraints::Create();
if (constraints.find(EncodableValue("mandatory")) != constraints.end()) {
auto it = constraints.find(EncodableValue("mandatory"));
const EncodableMap mandatory = GetValue<EncodableMap>(it->second);
ParseConstraints(mandatory, media_constraints, kMandatory);
} else {
// Log.d(TAG, "mandatory constraints are not a map");
}
auto it = constraints.find(EncodableValue("optional"));
if (it != constraints.end()) {
const EncodableValue optional = it->second;
if (TypeIs<EncodableMap>(optional)) {
ParseConstraints(GetValue<EncodableMap>(optional), media_constraints,
kOptional);
} else if (TypeIs<EncodableList>(optional)) {
const EncodableList list = GetValue<EncodableList>(optional);
for (size_t i = 0; i < list.size(); i++) {
ParseConstraints(GetValue<EncodableMap>(list[i]), media_constraints, kOptional);
}
}
} else {
// Log.d(TAG, "optional constraints are not an array");
}
return media_constraints;
}
bool FlutterWebRTCBase::CreateIceServers(const EncodableList &iceServersArray,
IceServer *ice_servers) {
size_t size = iceServersArray.size();
for (size_t i = 0; i < size; i++) {
IceServer &ice_server = ice_servers[i];
EncodableMap iceServerMap = GetValue<EncodableMap>(iceServersArray[i]);
bool hasUsernameAndCredential =
iceServerMap.find(EncodableValue("username")) != iceServerMap.end() &&
iceServerMap.find(EncodableValue("credential")) != iceServerMap.end();
auto it = iceServerMap.find(EncodableValue("url"));
if (it != iceServerMap.end() && TypeIs<std::string>(it->second)) {
if (hasUsernameAndCredential) {
std::string username =
GetValue<std::string>(iceServerMap.find(EncodableValue("username"))->second);
std::string credential =
GetValue<std::string>(iceServerMap.find(EncodableValue("credential"))
->second);
std::string uri = GetValue<std::string>(it->second);
ice_server.username = username;
ice_server.password = credential;
ice_server.uri = uri;
} else {
std::string uri = GetValue<std::string>(it->second);
ice_server.uri = uri;
}
}
it = iceServerMap.find(EncodableValue("urls"));
if (it != iceServerMap.end()) {
if (TypeIs<std::string>(it->second)) {
if (hasUsernameAndCredential) {
std::string username = GetValue<std::string>(iceServerMap.find(EncodableValue("username"))
->second);
std::string credential =
GetValue<std::string>(iceServerMap.find(EncodableValue("credential"))
->second);
std::string uri = GetValue<std::string>(it->second);
ice_server.username = username;
ice_server.password = credential;
ice_server.uri = uri;
} else {
std::string uri = GetValue<std::string>(it->second);
ice_server.uri = uri;
}
}
if (TypeIs<EncodableList>(it->second)) {
const EncodableList urls = GetValue<EncodableList>(it->second);
for (auto url : urls) {
if (TypeIs<EncodableMap>(url)) {
const EncodableMap map = GetValue<EncodableMap>(url);
std::string value;
auto it2 = map.find(EncodableValue("url"));
if (it2 != map.end()) {
value = GetValue<std::string>(it2->second);
if (hasUsernameAndCredential) {
std::string username =
GetValue<std::string>(iceServerMap.find(EncodableValue("username"))
->second);
std::string credential =
GetValue<std::string>(iceServerMap.find(EncodableValue("credential"))
->second);
ice_server.username = username;
ice_server.password = credential;
ice_server.uri = value;
} else {
ice_server.uri = value;
}
}
}
else if (TypeIs<std::string>(url)) {
std::string urlString = GetValue<std::string>(url);
ice_server.uri = urlString;
}
}
}
}
}
return size > 0;
}
bool FlutterWebRTCBase::ParseRTCConfiguration(const EncodableMap &map,
RTCConfiguration &conf) {
auto it = map.find(EncodableValue("iceServers"));
if (it != map.end()) {
const EncodableList iceServersArray = GetValue<EncodableList>(it->second);
CreateIceServers(iceServersArray, conf.ice_servers);
}
// iceTransportPolicy (public API)
it = map.find(EncodableValue("iceTransportPolicy"));
if (it != map.end() && TypeIs<std::string>(it->second)) {
std::string v = GetValue<std::string>(it->second);
if (v == "all") // public
conf.type = IceTransportsType::kAll;
else if (v == "relay")
conf.type = IceTransportsType::kRelay;
else if (v == "nohost")
conf.type = IceTransportsType::kNoHost;
else if (v == "none")
conf.type = IceTransportsType::kNone;
}
// bundlePolicy (public api)
it = map.find(EncodableValue("bundlePolicy"));
if (it != map.end() && TypeIs<std::string>(it->second)) {
std::string v = GetValue<std::string>(it->second);
if (v == "balanced") // public
conf.bundle_policy = kBundlePolicyBalanced;
else if (v == "max-compat") // public
conf.bundle_policy = kBundlePolicyMaxCompat;
else if (v == "max-bundle") // public
conf.bundle_policy = kBundlePolicyMaxBundle;
}
// rtcpMuxPolicy (public api)
it = map.find(EncodableValue("rtcpMuxPolicy"));
if (it != map.end() && TypeIs<std::string>(it->second)) {
std::string v = GetValue<std::string>(it->second);
if (v == "negotiate") // public
conf.rtcp_mux_policy = RtcpMuxPolicy::kRtcpMuxPolicyNegotiate;
else if (v == "require") // public
conf.rtcp_mux_policy = RtcpMuxPolicy::kRtcpMuxPolicyRequire;
}
// FIXME: peerIdentity of type DOMString (public API)
// FIXME: certificates of type sequence<RTCCertificate> (public API)
// iceCandidatePoolSize of type unsigned short, defaulting to 0
it = map.find(EncodableValue("iceCandidatePoolSize"));
if (it != map.end()) {
conf.ice_candidate_pool_size = GetValue<int>(it->second);
}
// sdpSemantics (public api)
it = map.find(EncodableValue("sdpSemantics"));
if (it != map.end() && TypeIs<std::string>(it->second)) {
std::string v = GetValue<std::string>(it->second);
if (v == "plan-b") // public
conf.sdp_semantics = SdpSemantics::kPlanB;
else if (v == "unified-plan") // public
conf.sdp_semantics = SdpSemantics::kUnifiedPlan;
}
return true;
}
scoped_refptr<RTCMediaTrack> FlutterWebRTCBase::MediaTracksForId(
const std::string& id) {
auto it = local_tracks_.find(id);
if (it != local_tracks_.end()) {
return (*it).second;
}
return nullptr;
}
void FlutterWebRTCBase::RemoveTracksForId(const std::string& id) {
auto it = local_tracks_.find(id);
if (it != local_tracks_.end())
local_tracks_.erase(it);
}
} // namespace flutter_webrtc_plugin
<commit_msg>fix: fix unable to get username/credential when parsing iceServers containing urls<commit_after>#include "flutter_webrtc_base.h"
#include "flutter_data_channel.h"
#include "flutter_peerconnection.h"
namespace flutter_webrtc_plugin {
FlutterWebRTCBase::FlutterWebRTCBase(BinaryMessenger *messenger,
TextureRegistrar *textures)
: messenger_(messenger), textures_(textures) {
LibWebRTC::Initialize();
factory_ = LibWebRTC::CreateRTCPeerConnectionFactory();
audio_device_ = factory_->GetAudioDevice();
video_device_ = factory_->GetVideoDevice();
desktop_device_ = factory_->GetDesktopDevice();
}
FlutterWebRTCBase::~FlutterWebRTCBase() {
LibWebRTC::Terminate();
}
std::string FlutterWebRTCBase::GenerateUUID() {
return uuidxx::uuid::Generate().ToString(false);
}
RTCPeerConnection *FlutterWebRTCBase::PeerConnectionForId(
const std::string &id) {
auto it = peerconnections_.find(id);
if (it != peerconnections_.end()) return (*it).second.get();
return nullptr;
}
void FlutterWebRTCBase::RemovePeerConnectionForId(const std::string &id) {
auto it = peerconnections_.find(id);
if (it != peerconnections_.end()) peerconnections_.erase(it);
}
RTCMediaTrack* FlutterWebRTCBase ::MediaTrackForId(const std::string& id) {
auto it = local_tracks_.find(id);
if (it != local_tracks_.end())
return (*it).second.get();
for (auto kv : peerconnection_observers_) {
auto pco = kv.second.get();
auto track = pco->MediaTrackForId(id);
if (track != nullptr) return track;
}
return nullptr;
}
void FlutterWebRTCBase::RemoveMediaTrackForId(const std::string& id) {
auto it = local_tracks_.find(id);
if (it != local_tracks_.end())
local_tracks_.erase(it);
}
FlutterPeerConnectionObserver* FlutterWebRTCBase::PeerConnectionObserversForId(
const std::string& id) {
auto it = peerconnection_observers_.find(id);
if (it != peerconnection_observers_.end())
return (*it).second.get();
return nullptr;
}
void FlutterWebRTCBase::RemovePeerConnectionObserversForId(
const std::string& id) {
auto it = peerconnection_observers_.find(id);
if (it != peerconnection_observers_.end())
peerconnection_observers_.erase(it);
}
scoped_refptr<RTCMediaStream> FlutterWebRTCBase::MediaStreamForId(
const std::string& id) {
auto it = local_streams_.find(id);
if (it != local_streams_.end()) {
return (*it).second;
}
for (auto kv : peerconnection_observers_) {
auto pco = kv.second.get();
auto stream = pco->MediaStreamForId(id);
if (stream != nullptr) return stream;
}
return nullptr;
}
void FlutterWebRTCBase::RemoveStreamForId(const std::string &id) {
auto it = local_streams_.find(id);
if (it != local_streams_.end()) local_streams_.erase(it);
}
bool FlutterWebRTCBase::ParseConstraints(const EncodableMap &constraints,
RTCConfiguration *configuration) {
memset(&configuration->ice_servers, 0, sizeof(configuration->ice_servers));
return false;
}
void FlutterWebRTCBase::ParseConstraints(
const EncodableMap &src,
scoped_refptr<RTCMediaConstraints> mediaConstraints,
ParseConstraintType type /*= kMandatory*/) {
for (auto kv : src) {
EncodableValue k = kv.first;
EncodableValue v = kv.second;
std::string key = GetValue<std::string>(k);
std::string value;
if (TypeIs<EncodableList>(v) || TypeIs<EncodableMap>(v)) {
} else if (TypeIs<std::string>(v)) {
value = GetValue<std::string>(v);
} else if (TypeIs<double>(v)) {
value = std::to_string(GetValue<double>(v));
} else if (TypeIs<int>(v)) {
value = std::to_string(GetValue<int>(v));
} else if (TypeIs<bool>(v)) {
value = GetValue<bool>(v) ? RTCMediaConstraints::kValueTrue
: RTCMediaConstraints::kValueFalse;
} else {
value = std::to_string(GetValue<int>(v));
}
if (type == kMandatory) {
mediaConstraints->AddMandatoryConstraint(key.c_str(), value.c_str());
} else {
mediaConstraints->AddOptionalConstraint(key.c_str(), value.c_str());
if (key == "DtlsSrtpKeyAgreement") {
configuration_.srtp_type = GetValue<bool>(v)
? MediaSecurityType::kDTLS_SRTP
: MediaSecurityType::kSDES_SRTP;
}
}
}
}
scoped_refptr<RTCMediaConstraints> FlutterWebRTCBase::ParseMediaConstraints(
const EncodableMap &constraints) {
scoped_refptr<RTCMediaConstraints> media_constraints =
RTCMediaConstraints::Create();
if (constraints.find(EncodableValue("mandatory")) != constraints.end()) {
auto it = constraints.find(EncodableValue("mandatory"));
const EncodableMap mandatory = GetValue<EncodableMap>(it->second);
ParseConstraints(mandatory, media_constraints, kMandatory);
} else {
// Log.d(TAG, "mandatory constraints are not a map");
}
auto it = constraints.find(EncodableValue("optional"));
if (it != constraints.end()) {
const EncodableValue optional = it->second;
if (TypeIs<EncodableMap>(optional)) {
ParseConstraints(GetValue<EncodableMap>(optional), media_constraints,
kOptional);
} else if (TypeIs<EncodableList>(optional)) {
const EncodableList list = GetValue<EncodableList>(optional);
for (size_t i = 0; i < list.size(); i++) {
ParseConstraints(GetValue<EncodableMap>(list[i]), media_constraints, kOptional);
}
}
} else {
// Log.d(TAG, "optional constraints are not an array");
}
return media_constraints;
}
bool FlutterWebRTCBase::CreateIceServers(const EncodableList &iceServersArray,
IceServer *ice_servers) {
size_t size = iceServersArray.size();
for (size_t i = 0; i < size; i++) {
IceServer &ice_server = ice_servers[i];
EncodableMap iceServerMap = GetValue<EncodableMap>(iceServersArray[i]);
if (iceServerMap.find(EncodableValue("username")) != iceServerMap.end()) {;
ice_server.username = GetValue<std::string>(
iceServerMap.find(EncodableValue("username"))->second);
}
if (iceServerMap.find(EncodableValue("credential")) != iceServerMap.end()) {
ice_server.password = GetValue<std::string>(
iceServerMap.find(EncodableValue("credential"))->second);
}
auto it = iceServerMap.find(EncodableValue("url"));
if (it != iceServerMap.end() && TypeIs<std::string>(it->second)) {
ice_server.uri = GetValue<std::string>(it->second);
}
it = iceServerMap.find(EncodableValue("urls"));
if (it != iceServerMap.end()) {
if (TypeIs<std::string>(it->second)) {
ice_server.uri = GetValue<std::string>(it->second);
}
if (TypeIs<EncodableList>(it->second)) {
const EncodableList urls = GetValue<EncodableList>(it->second);
for (auto url : urls) {
if (TypeIs<EncodableMap>(url)) {
const EncodableMap map = GetValue<EncodableMap>(url);
std::string value;
auto it2 = map.find(EncodableValue("url"));
if (it2 != map.end()) {
ice_server.uri = GetValue<std::string>(it2->second);
}
} else if (TypeIs<std::string>(url)) {
ice_server.uri = GetValue<std::string>(url);
}
}
}
}
}
return size > 0;
}
bool FlutterWebRTCBase::ParseRTCConfiguration(const EncodableMap &map,
RTCConfiguration &conf) {
auto it = map.find(EncodableValue("iceServers"));
if (it != map.end()) {
const EncodableList iceServersArray = GetValue<EncodableList>(it->second);
CreateIceServers(iceServersArray, conf.ice_servers);
}
// iceTransportPolicy (public API)
it = map.find(EncodableValue("iceTransportPolicy"));
if (it != map.end() && TypeIs<std::string>(it->second)) {
std::string v = GetValue<std::string>(it->second);
if (v == "all") // public
conf.type = IceTransportsType::kAll;
else if (v == "relay")
conf.type = IceTransportsType::kRelay;
else if (v == "nohost")
conf.type = IceTransportsType::kNoHost;
else if (v == "none")
conf.type = IceTransportsType::kNone;
}
// bundlePolicy (public api)
it = map.find(EncodableValue("bundlePolicy"));
if (it != map.end() && TypeIs<std::string>(it->second)) {
std::string v = GetValue<std::string>(it->second);
if (v == "balanced") // public
conf.bundle_policy = kBundlePolicyBalanced;
else if (v == "max-compat") // public
conf.bundle_policy = kBundlePolicyMaxCompat;
else if (v == "max-bundle") // public
conf.bundle_policy = kBundlePolicyMaxBundle;
}
// rtcpMuxPolicy (public api)
it = map.find(EncodableValue("rtcpMuxPolicy"));
if (it != map.end() && TypeIs<std::string>(it->second)) {
std::string v = GetValue<std::string>(it->second);
if (v == "negotiate") // public
conf.rtcp_mux_policy = RtcpMuxPolicy::kRtcpMuxPolicyNegotiate;
else if (v == "require") // public
conf.rtcp_mux_policy = RtcpMuxPolicy::kRtcpMuxPolicyRequire;
}
// FIXME: peerIdentity of type DOMString (public API)
// FIXME: certificates of type sequence<RTCCertificate> (public API)
// iceCandidatePoolSize of type unsigned short, defaulting to 0
it = map.find(EncodableValue("iceCandidatePoolSize"));
if (it != map.end()) {
conf.ice_candidate_pool_size = GetValue<int>(it->second);
}
// sdpSemantics (public api)
it = map.find(EncodableValue("sdpSemantics"));
if (it != map.end() && TypeIs<std::string>(it->second)) {
std::string v = GetValue<std::string>(it->second);
if (v == "plan-b") // public
conf.sdp_semantics = SdpSemantics::kPlanB;
else if (v == "unified-plan") // public
conf.sdp_semantics = SdpSemantics::kUnifiedPlan;
}
return true;
}
scoped_refptr<RTCMediaTrack> FlutterWebRTCBase::MediaTracksForId(
const std::string& id) {
auto it = local_tracks_.find(id);
if (it != local_tracks_.end()) {
return (*it).second;
}
return nullptr;
}
void FlutterWebRTCBase::RemoveTracksForId(const std::string& id) {
auto it = local_tracks_.find(id);
if (it != local_tracks_.end())
local_tracks_.erase(it);
}
} // namespace flutter_webrtc_plugin
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: Boris Polishchuk (Boris.Polishchuk@cern.ch) *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------//
// Class used to do omega(782) -> pi0 pi+ pi- analysis. //
//------------------------------------------------------------------------//
////////////////////////////////////////////////////////////////////////////
#include "AliAnalysisTaskOmegaPi0PiPi.h"
#include "TList.h"
#include "TH1.h"
#include "TH2.h"
#include "AliESDEvent.h"
#include "TRefArray.h"
#include "TLorentzVector.h"
#include "AliESDCaloCluster.h"
#include "AliESDv0.h"
#include "AliESDtrack.h"
ClassImp(AliAnalysisTaskOmegaPi0PiPi)
AliAnalysisTaskOmegaPi0PiPi::AliAnalysisTaskOmegaPi0PiPi() :
AliAnalysisTaskSE(),fOutputContainer(0x0),fhM2piSel(0x0),fhDxy(0x0),fhMggSel(0x0),
fhImpXY(0x0),fhM3pi0to2(0x0),fhM3pi2to4(0x0),fhM3pi4to6(0x0),fhM3pi6to8(0x0),
fhM3pi8to10(0x0),fhM3pi10to12(0x0),fhM3pi12(0x0),fhM3pi0to8(0x0)
{
//Default constructor.
}
AliAnalysisTaskOmegaPi0PiPi::AliAnalysisTaskOmegaPi0PiPi(const char* name) :
AliAnalysisTaskSE(name),fOutputContainer(0x0),fhM2piSel(0x0),fhDxy(0x0),fhMggSel(0x0),
fhImpXY(0x0),fhM3pi0to2(0x0),fhM3pi2to4(0x0),fhM3pi4to6(0x0),fhM3pi6to8(0x0),
fhM3pi8to10(0x0),fhM3pi10to12(0x0),fhM3pi12(0x0),fhM3pi0to8(0x0)
{
//Constructor used to create a named task.
DefineOutput(1,TList::Class());
}
AliAnalysisTaskOmegaPi0PiPi::~AliAnalysisTaskOmegaPi0PiPi()
{
//Destructor
if(fOutputContainer){
fOutputContainer->Delete() ;
delete fOutputContainer ;
}
}
void AliAnalysisTaskOmegaPi0PiPi::UserCreateOutputObjects()
{
//Allocates histograms and puts it to the output container.
fOutputContainer = new TList();
fhM2piSel = new TH1F("hM2pi_sel","V0 inv. mass, Dxy<2cm",100,0.,1.);
fOutputContainer->Add(fhM2piSel);
fhDxy = new TH1F("hDxy","Distance from V0 to primary vertex in XY-plane", 500, 0.,500.);
fOutputContainer->Add(fhDxy);
fhMggSel = new TH1F("hMgg_sel","Inv. mass of two clusters, pT>1GeV",100,0.,0.3);
fOutputContainer->Add(fhMggSel);
fhImpXY = new TH1F("hImpXY","Impact parameters in XY-plane",1000,0.,1.);
fOutputContainer->Add(fhImpXY);
//M(3pi) vs pT(3pi), ptrack < 2GeV
fhM3pi0to2 = new TH2F("hM3pi_0_2","pTrack: 0-2GeV",100,0.,10., 200,0.4,1.);
fOutputContainer->Add(fhM3pi0to2);
//M(3pi) vs pT(3pi), 2GeV < ptrack < 4GeV
fhM3pi2to4 = new TH2F("hM3pi_2_4","pTrack: 2-4GeV",100,0.,10., 200,0.4,1.);
fOutputContainer->Add(fhM3pi2to4);
//M(3pi) vs pT(3pi), 4GeV < ptrack < 6GeV
fhM3pi4to6 = new TH2F("hM3pi_4_6","pTrack: 4-6GeV",100,0.,10., 200,0.4,1.);
fOutputContainer->Add(fhM3pi4to6);
//M(3pi) vs pT(3pi), 6GeV < ptrack < 8GeV
fhM3pi6to8 = new TH2F("hM3pi_6_8","pTrack: 6-8GeV",100,0.,10., 200,0.4,1.);
fOutputContainer->Add(fhM3pi6to8);
//M(3pi) vs pT(3pi), 8GeV < ptrack < 10GeV
fhM3pi8to10 = new TH2F("hM3pi_8_10","pTrack: 8-10GeV",100,0.,10., 200,0.4,1.);
fOutputContainer->Add(fhM3pi8to10);
//M(3pi) vs pT(3pi), 10GeV < ptrack < 12GeV
fhM3pi10to12 = new TH2F("hM3pi_10_12","pTrack: 10-12GeV",100,0.,10., 200,0.4,1.);
fOutputContainer->Add(fhM3pi10to12);
//M(3pi) vs pT(3pi), ptrack > 12GeV
fhM3pi12 = new TH2F("hM3pi_12","pTrack>12GeV",100,0.,10., 200,0.4,1.);
fOutputContainer->Add(fhM3pi12);
//M(3pi) vs pT(3pi), ptrack < 8GeV
fhM3pi0to8 = new TH2F("hM3pi_0_8","pTrack: 0-8GeV",100,0.,10., 200,0.4,1.);
fOutputContainer->Add(fhM3pi0to8);
}
void AliAnalysisTaskOmegaPi0PiPi::UserExec(Option_t* /* option */)
{
//Main function that does all the job.
printf("We are within AliAnalysisTaskOmegaPi0PiPi::UserExec.");
AliVEvent* event = InputEvent();
AliESDEvent* esd = (AliESDEvent*)event ;
Double_t v[3] ; //vertex ;
esd->GetVertex()->GetXYZ(v) ;
TVector3 vtx(v);
printf("Vertex: (%.3f,%.3f,%.3f)\n",vtx.X(),vtx.Y(),vtx.Z());
TRefArray * caloClustersArr = new TRefArray();
esd->GetPHOSClusters(caloClustersArr);
const Int_t kNumberOfTracks = esd->GetNumberOfTracks();
const Int_t kNumberOfV0s = esd->GetNumberOfV0s();
printf("Tracks: %d. V0s: %d\n",kNumberOfTracks,kNumberOfV0s);
Float_t xyImp,zImp,imp1,imp2;
const Int_t kNumberOfPhosClusters = caloClustersArr->GetEntries() ;
printf("CaloClusters: %d\n", kNumberOfPhosClusters);
if(kNumberOfPhosClusters<2) return;
TLorentzVector pc1; //4-momentum of PHOS cluster 1
TLorentzVector pc2; //4-momentum of PHOS cluster 2
TLorentzVector pc12;
TLorentzVector ppos; //4-momentum of positive track
TLorentzVector pneg; //4-momentum of negative track
TLorentzVector ptr12;
TLorentzVector pomega;
Double_t etrack;
Double_t p1,p2; // 3-momentum of tracks
const Double_t kMpi = 0.1396;
for(Int_t iClu=0; iClu<kNumberOfPhosClusters; iClu++) {
AliESDCaloCluster *c1 = (AliESDCaloCluster *) caloClustersArr->At(iClu);
c1->GetMomentum(pc1,v);
for (Int_t jClu=iClu; jClu<kNumberOfPhosClusters; jClu++) {
AliESDCaloCluster *c2 = (AliESDCaloCluster *) caloClustersArr->At(jClu);
if(c2->IsEqual(c1)) continue;
c2->GetMomentum(pc2,v);
pc12 = pc1+pc2;
printf("pc12.M(): %.3f\n",pc12.M());
if(pc12.M()<0.115 || pc12.M()>0.155) continue; //not a pi0 candidate!
if(pc12.Pt()<1.) continue; //pT(pi0) > 1GeV
fhMggSel->Fill(pc12.M());
for(Int_t iTrack=0; iTrack<kNumberOfTracks; iTrack++) {
AliESDtrack* tr1 = esd->GetTrack(iTrack);
p1 = tr1->P();
tr1->GetImpactParameters(xyImp,zImp);
imp1 = TMath::Abs(xyImp);
fhImpXY->Fill(imp1);
Short_t charge = tr1->Charge();
if(imp1>0.004) continue; // not from the primary vertex!
etrack = TMath::Sqrt(p1*p1 + kMpi*kMpi);
ppos.SetPxPyPzE(tr1->Px(),tr1->Py(),tr1->Pz(),etrack);
for(Int_t jTrack=iTrack; jTrack<kNumberOfTracks; jTrack++) {
AliESDtrack* tr2 = esd->GetTrack(jTrack);
p2 = tr2->P();
if(tr2->Charge()==charge) continue; //same sign track (WRONG!!)
tr2->GetImpactParameters(xyImp,zImp);
imp2=TMath::Abs(xyImp);
if(imp2>0.004) continue; // not from the primary vertex!
etrack = TMath::Sqrt(p2*p2 + kMpi*kMpi);
pneg.SetPxPyPzE(tr2->Px(),tr2->Py(),tr2->Pz(),etrack);
ptr12 = ppos + pneg;
// printf("ptr12.M()=%.3f, xyImp1=%f, xyImp2=%f, ch1=%d, ch2=%d,
// p1=%.3f, p2=%.3f, m1=%.3f, m2=%.3f\n",
// ptr12.M(),imp1,imp2,tr1->Charge(),tr2->Charge(),
// tr1->P(),tr2->P(),tr1->M(),tr2->M());
pomega = pc12 + ptr12;
printf("pomega.M(): %f\n",pomega.M());
if( p1<2. && p2<2. )
fhM3pi0to2->Fill(pomega.Pt(),pomega.M());
if( (p1>=2. && p1<4.) && (p2>=2. && p2<4.) )
fhM3pi2to4->Fill(pomega.Pt(),pomega.M());
if( (p1>=4. && p1<6.) && (p2>=4. && p2<6.) )
fhM3pi4to6->Fill(pomega.Pt(),pomega.M());
if( (p1>=6. && p1<8.) && (p2>=6. && p2<8.) )
fhM3pi6to8->Fill(pomega.Pt(),pomega.M());
if( (p1>=8. && p1<10.) && (p2>=8. && p2<10.) )
fhM3pi8to10->Fill(pomega.Pt(),pomega.M());
if( (p1>=10. && p1<12.) && (p2>=10. && p2<12.) )
fhM3pi10to12->Fill(pomega.Pt(),pomega.M());
if( (p1>=12.) && (p2>=12.) )
fhM3pi12->Fill(pomega.Pt(),pomega.M());
if( p1<8. && p2<8. )
fhM3pi0to8->Fill(pomega.Pt(),pomega.M());
}
}
for(Int_t iVert=0; iVert<kNumberOfV0s; iVert++) {
AliESDv0* v0 = esd->GetV0(iVert);
AliESDtrack* ptrack = esd->GetTrack(v0->GetPindex()); //positive track
AliESDtrack* ntrack = esd->GetTrack(v0->GetNindex()); //negative track
etrack = TMath::Sqrt(ptrack->P()*ptrack->P() + kMpi*kMpi);
ppos.SetPxPyPzE(ptrack->Px(),ptrack->Py(),ptrack->Pz(),etrack);
etrack = TMath::Sqrt(ntrack->P()*ntrack->P() + kMpi*kMpi);
pneg.SetPxPyPzE(ntrack->Px(),ntrack->Py(),ntrack->Pz(),etrack);
ptr12 = ppos + pneg;
Double_t dx = vtx.X() - v0->Xv();
Double_t dy = vtx.Y() - v0->Yv();
Double_t dxy = TMath::Sqrt(dx*dx + dy*dy);
fhDxy->Fill(dxy);
printf("V0: dxy=%.3f\n",dxy);
if(dxy<2.) fhM2piSel->Fill(ptr12.M());
}
}
}
delete caloClustersArr;
PostData(1,fOutputContainer);
}
<commit_msg>Printouts hidden under AliDebugs<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: Boris Polishchuk (Boris.Polishchuk@cern.ch) *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------//
// Class used to do omega(782) -> pi0 pi+ pi- analysis. //
//------------------------------------------------------------------------//
////////////////////////////////////////////////////////////////////////////
#include "AliAnalysisTaskOmegaPi0PiPi.h"
#include "TList.h"
#include "TH1.h"
#include "TH2.h"
#include "AliESDEvent.h"
#include "TRefArray.h"
#include "TLorentzVector.h"
#include "AliESDCaloCluster.h"
#include "AliESDv0.h"
#include "AliESDtrack.h"
#include "AliLog.h"
ClassImp(AliAnalysisTaskOmegaPi0PiPi)
AliAnalysisTaskOmegaPi0PiPi::AliAnalysisTaskOmegaPi0PiPi() :
AliAnalysisTaskSE(),fOutputContainer(0x0),fhM2piSel(0x0),fhDxy(0x0),fhMggSel(0x0),
fhImpXY(0x0),fhM3pi0to2(0x0),fhM3pi2to4(0x0),fhM3pi4to6(0x0),fhM3pi6to8(0x0),
fhM3pi8to10(0x0),fhM3pi10to12(0x0),fhM3pi12(0x0),fhM3pi0to8(0x0)
{
//Default constructor.
}
AliAnalysisTaskOmegaPi0PiPi::AliAnalysisTaskOmegaPi0PiPi(const char* name) :
AliAnalysisTaskSE(name),fOutputContainer(0x0),fhM2piSel(0x0),fhDxy(0x0),fhMggSel(0x0),
fhImpXY(0x0),fhM3pi0to2(0x0),fhM3pi2to4(0x0),fhM3pi4to6(0x0),fhM3pi6to8(0x0),
fhM3pi8to10(0x0),fhM3pi10to12(0x0),fhM3pi12(0x0),fhM3pi0to8(0x0)
{
//Constructor used to create a named task.
DefineOutput(1,TList::Class());
}
AliAnalysisTaskOmegaPi0PiPi::~AliAnalysisTaskOmegaPi0PiPi()
{
//Destructor
if(fOutputContainer){
fOutputContainer->Delete() ;
delete fOutputContainer ;
}
}
void AliAnalysisTaskOmegaPi0PiPi::UserCreateOutputObjects()
{
//Allocates histograms and puts it to the output container.
fOutputContainer = new TList();
fhM2piSel = new TH1F("hM2pi_sel","V0 inv. mass, Dxy<2cm",100,0.,1.);
fOutputContainer->Add(fhM2piSel);
fhDxy = new TH1F("hDxy","Distance from V0 to primary vertex in XY-plane", 500, 0.,500.);
fOutputContainer->Add(fhDxy);
fhMggSel = new TH1F("hMgg_sel","Inv. mass of two clusters, pT>1GeV",100,0.,0.3);
fOutputContainer->Add(fhMggSel);
fhImpXY = new TH1F("hImpXY","Impact parameters in XY-plane",1000,0.,1.);
fOutputContainer->Add(fhImpXY);
//M(3pi) vs pT(3pi), ptrack < 2GeV
fhM3pi0to2 = new TH2F("hM3pi_0_2","pTrack: 0-2GeV",100,0.,10., 200,0.4,1.);
fOutputContainer->Add(fhM3pi0to2);
//M(3pi) vs pT(3pi), 2GeV < ptrack < 4GeV
fhM3pi2to4 = new TH2F("hM3pi_2_4","pTrack: 2-4GeV",100,0.,10., 200,0.4,1.);
fOutputContainer->Add(fhM3pi2to4);
//M(3pi) vs pT(3pi), 4GeV < ptrack < 6GeV
fhM3pi4to6 = new TH2F("hM3pi_4_6","pTrack: 4-6GeV",100,0.,10., 200,0.4,1.);
fOutputContainer->Add(fhM3pi4to6);
//M(3pi) vs pT(3pi), 6GeV < ptrack < 8GeV
fhM3pi6to8 = new TH2F("hM3pi_6_8","pTrack: 6-8GeV",100,0.,10., 200,0.4,1.);
fOutputContainer->Add(fhM3pi6to8);
//M(3pi) vs pT(3pi), 8GeV < ptrack < 10GeV
fhM3pi8to10 = new TH2F("hM3pi_8_10","pTrack: 8-10GeV",100,0.,10., 200,0.4,1.);
fOutputContainer->Add(fhM3pi8to10);
//M(3pi) vs pT(3pi), 10GeV < ptrack < 12GeV
fhM3pi10to12 = new TH2F("hM3pi_10_12","pTrack: 10-12GeV",100,0.,10., 200,0.4,1.);
fOutputContainer->Add(fhM3pi10to12);
//M(3pi) vs pT(3pi), ptrack > 12GeV
fhM3pi12 = new TH2F("hM3pi_12","pTrack>12GeV",100,0.,10., 200,0.4,1.);
fOutputContainer->Add(fhM3pi12);
//M(3pi) vs pT(3pi), ptrack < 8GeV
fhM3pi0to8 = new TH2F("hM3pi_0_8","pTrack: 0-8GeV",100,0.,10., 200,0.4,1.);
fOutputContainer->Add(fhM3pi0to8);
}
void AliAnalysisTaskOmegaPi0PiPi::UserExec(Option_t* /* option */)
{
//Main function that does all the job.
AliVEvent* event = InputEvent();
AliESDEvent* esd = (AliESDEvent*)event ;
Double_t v[3] ; //vertex ;
esd->GetVertex()->GetXYZ(v) ;
TVector3 vtx(v);
AliDebug(2,Form("Vertex: (%.3f,%.3f,%.3f)\n",vtx.X(),vtx.Y(),vtx.Z()));
TRefArray * caloClustersArr = new TRefArray();
esd->GetPHOSClusters(caloClustersArr);
const Int_t kNumberOfTracks = esd->GetNumberOfTracks();
const Int_t kNumberOfV0s = esd->GetNumberOfV0s();
AliDebug(2,Form("Tracks: %d. V0s: %d\n",kNumberOfTracks,kNumberOfV0s));
Float_t xyImp,zImp,imp1,imp2;
const Int_t kNumberOfPhosClusters = caloClustersArr->GetEntries() ;
AliDebug(2,Form("CaloClusters: %d\n", kNumberOfPhosClusters));
if(kNumberOfPhosClusters<2) return;
TLorentzVector pc1; //4-momentum of PHOS cluster 1
TLorentzVector pc2; //4-momentum of PHOS cluster 2
TLorentzVector pc12;
TLorentzVector ppos; //4-momentum of positive track
TLorentzVector pneg; //4-momentum of negative track
TLorentzVector ptr12;
TLorentzVector pomega;
Double_t etrack;
Double_t p1,p2; // 3-momentum of tracks
const Double_t kMpi = 0.1396;
for(Int_t iClu=0; iClu<kNumberOfPhosClusters; iClu++) {
AliESDCaloCluster *c1 = (AliESDCaloCluster *) caloClustersArr->At(iClu);
c1->GetMomentum(pc1,v);
for (Int_t jClu=iClu; jClu<kNumberOfPhosClusters; jClu++) {
AliESDCaloCluster *c2 = (AliESDCaloCluster *) caloClustersArr->At(jClu);
if(c2->IsEqual(c1)) continue;
c2->GetMomentum(pc2,v);
pc12 = pc1+pc2;
AliDebug(2,Form("pc12.M(): %.3f\n",pc12.M()));
if(pc12.M()<0.115 || pc12.M()>0.155) continue; //not a pi0 candidate!
if(pc12.Pt()<1.) continue; //pT(pi0) > 1GeV
fhMggSel->Fill(pc12.M());
for(Int_t iTrack=0; iTrack<kNumberOfTracks; iTrack++) {
AliESDtrack* tr1 = esd->GetTrack(iTrack);
p1 = tr1->P();
tr1->GetImpactParameters(xyImp,zImp);
imp1 = TMath::Abs(xyImp);
fhImpXY->Fill(imp1);
Short_t charge = tr1->Charge();
if(imp1>0.004) continue; // not from the primary vertex!
etrack = TMath::Sqrt(p1*p1 + kMpi*kMpi);
ppos.SetPxPyPzE(tr1->Px(),tr1->Py(),tr1->Pz(),etrack);
for(Int_t jTrack=iTrack; jTrack<kNumberOfTracks; jTrack++) {
AliESDtrack* tr2 = esd->GetTrack(jTrack);
p2 = tr2->P();
if(tr2->Charge()==charge) continue; //same sign track (WRONG!!)
tr2->GetImpactParameters(xyImp,zImp);
imp2=TMath::Abs(xyImp);
if(imp2>0.004) continue; // not from the primary vertex!
etrack = TMath::Sqrt(p2*p2 + kMpi*kMpi);
pneg.SetPxPyPzE(tr2->Px(),tr2->Py(),tr2->Pz(),etrack);
ptr12 = ppos + pneg;
// printf("ptr12.M()=%.3f, xyImp1=%f, xyImp2=%f, ch1=%d, ch2=%d,
// p1=%.3f, p2=%.3f, m1=%.3f, m2=%.3f\n",
// ptr12.M(),imp1,imp2,tr1->Charge(),tr2->Charge(),
// tr1->P(),tr2->P(),tr1->M(),tr2->M());
pomega = pc12 + ptr12;
AliDebug(2,Form("pomega.M(): %f\n",pomega.M()));
if( p1<2. && p2<2. )
fhM3pi0to2->Fill(pomega.Pt(),pomega.M());
if( (p1>=2. && p1<4.) && (p2>=2. && p2<4.) )
fhM3pi2to4->Fill(pomega.Pt(),pomega.M());
if( (p1>=4. && p1<6.) && (p2>=4. && p2<6.) )
fhM3pi4to6->Fill(pomega.Pt(),pomega.M());
if( (p1>=6. && p1<8.) && (p2>=6. && p2<8.) )
fhM3pi6to8->Fill(pomega.Pt(),pomega.M());
if( (p1>=8. && p1<10.) && (p2>=8. && p2<10.) )
fhM3pi8to10->Fill(pomega.Pt(),pomega.M());
if( (p1>=10. && p1<12.) && (p2>=10. && p2<12.) )
fhM3pi10to12->Fill(pomega.Pt(),pomega.M());
if( (p1>=12.) && (p2>=12.) )
fhM3pi12->Fill(pomega.Pt(),pomega.M());
if( p1<8. && p2<8. )
fhM3pi0to8->Fill(pomega.Pt(),pomega.M());
}
}
for(Int_t iVert=0; iVert<kNumberOfV0s; iVert++) {
AliESDv0* v0 = esd->GetV0(iVert);
AliESDtrack* ptrack = esd->GetTrack(v0->GetPindex()); //positive track
AliESDtrack* ntrack = esd->GetTrack(v0->GetNindex()); //negative track
etrack = TMath::Sqrt(ptrack->P()*ptrack->P() + kMpi*kMpi);
ppos.SetPxPyPzE(ptrack->Px(),ptrack->Py(),ptrack->Pz(),etrack);
etrack = TMath::Sqrt(ntrack->P()*ntrack->P() + kMpi*kMpi);
pneg.SetPxPyPzE(ntrack->Px(),ntrack->Py(),ntrack->Pz(),etrack);
ptr12 = ppos + pneg;
Double_t dx = vtx.X() - v0->Xv();
Double_t dy = vtx.Y() - v0->Yv();
Double_t dxy = TMath::Sqrt(dx*dx + dy*dy);
fhDxy->Fill(dxy);
AliDebug(2,Form("V0: dxy=%.3f\n",dxy));
if(dxy<2.) fhM2piSel->Fill(ptr12.M());
}
}
}
delete caloClustersArr;
PostData(1,fOutputContainer);
}
<|endoftext|> |
<commit_before><commit_msg>PWGGA/GammaConv: removing nonlin from tree (will be applied on tree level)<commit_after><|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////
//
// DAGON - An Adventure Game Engine
// Copyright (c) 2011-2014 Senscape s.r.l.
// All rights reserved.
//
// 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/.
//
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <cassert>
#include "Audio.h"
#include "Node.h"
#include "Spot.h"
#include "Texture.h"
namespace dagon {
////////////////////////////////////////////////////////////
// Implementation - Constructor
////////////////////////////////////////////////////////////
Node::Node() {
_previousNode = this;
_hasFootstep = false;
_hasEnterEvent = false;
_hasLeaveEvent = false;
_hasPersistEvent = false;
_hasUnpersistEvent = false;
_isSlide = false;
_parentRoom = 0;
_slideReturn = 0;
this->setType(kObjectNode);
}
////////////////////////////////////////////////////////////
// Implementation - Destructor
////////////////////////////////////////////////////////////
Node::~Node() {
// Note that we only delete spots automatically created by this class,
// not ones by the user
bool done = false;
while (!done) {
_it = _arrayOfSpots.begin();
done = true;
while ((_it != _arrayOfSpots.end())) {
Spot* spot = (*_it);
if (spot->hasFlag(kSpotClass)) {
// FIXME: Class spots should be in a different vector
//delete spot;
_arrayOfSpots.erase(_it);
done = false;
break;
} else ++_it;
}
}
}
////////////////////////////////////////////////////////////
// Implementation - Checks
////////////////////////////////////////////////////////////
bool Node::hasBundleName() {
return !_bundleName.empty();
}
bool Node::hasFootstep() {
return _hasFootstep;
}
bool Node::hasEnterEvent() {
return _hasEnterEvent;
}
bool Node::hasLeaveEvent() {
return _hasLeaveEvent;
}
bool Node::hasSpots() {
return !_arrayOfSpots.empty();
}
bool Node::isSlide() {
return _isSlide;
}
int Node::slideReturn() {
return _slideReturn;
}
bool Node::hasPersistEvent() {
return _hasPersistEvent;
}
bool Node::hasUnpersistEvent() {
return _hasUnpersistEvent;
}
////////////////////////////////////////////////////////////
// Implementation - Gets
////////////////////////////////////////////////////////////
std::string Node::bundleName() {
return _bundleName;
}
Spot* Node::currentSpot() {
assert(_it != _arrayOfSpots.end());
return *_it;
}
std::string Node::description() {
return _description;
}
int Node::enterEvent() {
assert(_hasEnterEvent = true);
return _luaEnterReference;
}
Audio* Node::footstep() {
return _footstep;
}
int Node::leaveEvent() {
assert(_hasLeaveEvent = true);
return _luaLeaveReference;
}
Room* Node::parentRoom() {
return _parentRoom;
}
Node* Node::previousNode() {
return _previousNode;
}
size_t Node::numSpots() {
return _arrayOfSpots.size();
}
int Node::persistEvent() {
assert(_hasPersistEvent == true);
return _luaPersistRef;
}
int Node::unpersistEvent() {
assert(_hasUnpersistEvent == true);
return _luaUnpersistRef;
}
////////////////////////////////////////////////////////////
// Implementation - Sets
////////////////////////////////////////////////////////////
void Node::setBundleName(std::string theName) {
_bundleName = theName;
}
void Node::setDescription(std::string theDescription) {
_description = theDescription;
}
void Node::setEnterEvent(int theLuaReference) {
_hasEnterEvent = true;
_luaEnterReference = theLuaReference;
}
void Node::setFootstep(Audio* theFootstep) {
_footstep = theFootstep;
_hasFootstep = true;
}
void Node::setLeaveEvent(int theLuaReference) {
_hasLeaveEvent = true;
_luaLeaveReference = theLuaReference;
}
void Node::setParentRoom(Room* room) {
_parentRoom = room;
}
void Node::setPreviousNode(Node* node) {
_previousNode = node;
}
void Node::setSlide(bool enabled) {
_isSlide = enabled;
}
void Node::setSlideReturn(int luaHandler) {
_slideReturn = luaHandler;
}
void Node::setPersistEvent(const int luaRef) {
_hasPersistEvent = true;
_luaPersistRef = luaRef;
}
void Node::setUnpersistEvent(const int luaRef) {
_hasUnpersistEvent = true;
_luaUnpersistRef = luaRef;
}
////////////////////////////////////////////////////////////
// Implementation - State changes
////////////////////////////////////////////////////////////
void Node::addCustomLink(unsigned withDirection, int luaHandler) {
Action action;
action.type = kActionFunction;
action.cursor = kCursorForward;
action.luaHandler = luaHandler;
_link(withDirection, &action);
}
void Node::addLink(unsigned int withDirection, Object* theTarget) {
Action action;
action.type = kActionSwitch;
action.cursor = kCursorForward;
action.target = theTarget;
_link(withDirection, &action);
}
Spot* Node::addSpot(Spot* aSpot) {
_arrayOfSpots.push_back(aSpot);
return aSpot;
}
void Node::beginIteratingSpots() {
_it = _arrayOfSpots.begin();
}
bool Node::iterateSpots() {
++_it;
if (_it == _arrayOfSpots.end()) {
return false;
} else {
return true;
}
}
////////////////////////////////////////////////////////////
// Implementation - Private methods
////////////////////////////////////////////////////////////
void Node::_link(unsigned int direction, Action* action) {
// We ensure the texture is properly stretched, so we take the default
// cube size.
// TODO: This setting should be obtained directly from the Config class
int minorBound = kDefTexSize / 3;
int majorBound = static_cast<int>(kDefTexSize / 1.5f);
int offset = kDefTexSize / 3;
// We always have four corners here, hence eight elements since they are
// squared spots.
std::vector<int> arrayOfCoordinates;
int coordsNormal[] = {minorBound, minorBound, majorBound, minorBound,
majorBound, majorBound, minorBound, majorBound};
int coordsShiftRight[] = {minorBound + offset, minorBound,
majorBound + offset, minorBound, majorBound + offset, majorBound,
minorBound + offset, majorBound};
int coordsShiftLeft[] = {minorBound - offset, minorBound, majorBound - offset,
minorBound, majorBound - offset, majorBound, minorBound - offset,
majorBound};
Spot *newSpot = NULL, *auxSpot = NULL;
switch (direction) {
case kNorth:
case kEast:
case kSouth:
case kWest: {
arrayOfCoordinates.assign(coordsNormal, coordsNormal + 8);
newSpot = new Spot(arrayOfCoordinates, direction, kSpotClass);
break;
}
case kNorthEast: {
arrayOfCoordinates.assign(coordsShiftRight, coordsShiftRight + 8);
newSpot = new Spot(arrayOfCoordinates, kNorth, kSpotClass);
arrayOfCoordinates.assign(coordsShiftLeft, coordsShiftLeft + 8);
auxSpot = new Spot(arrayOfCoordinates, kEast, kSpotClass);
break;
}
case kSouthEast: {
arrayOfCoordinates.assign(coordsShiftRight, coordsShiftRight + 8);
newSpot = new Spot(arrayOfCoordinates, kEast, kSpotClass);
arrayOfCoordinates.assign(coordsShiftLeft, coordsShiftLeft + 8);
auxSpot = new Spot(arrayOfCoordinates, kSouth, kSpotClass);
break;
}
case kSouthWest: {
arrayOfCoordinates.assign(coordsShiftRight, coordsShiftRight + 8);
newSpot = new Spot(arrayOfCoordinates, kSouth, kSpotClass);
arrayOfCoordinates.assign(coordsShiftLeft, coordsShiftLeft + 8);
auxSpot = new Spot(arrayOfCoordinates, kWest, kSpotClass);
break;
}
case kNorthWest: {
arrayOfCoordinates.assign(coordsShiftRight, coordsShiftRight + 8);
newSpot = new Spot(arrayOfCoordinates, kWest, kSpotClass);
arrayOfCoordinates.assign(coordsShiftLeft, coordsShiftLeft + 8);
auxSpot = new Spot(arrayOfCoordinates, kNorth, kSpotClass);
break;
}
default: {
assert(false);
}
}
newSpot->setAction(action);
newSpot->setColor(0); // Color is set automatically
_arrayOfSpots.push_back(newSpot);
if (auxSpot) {
auxSpot->setAction(action);
auxSpot->setColor(0);
_arrayOfSpots.push_back(auxSpot);
}
}
}
<commit_msg>Erase "class Spots" in a safer manner<commit_after>////////////////////////////////////////////////////////////
//
// DAGON - An Adventure Game Engine
// Copyright (c) 2011-2014 Senscape s.r.l.
// All rights reserved.
//
// 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/.
//
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <algorithm>
#include <cassert>
#include "Audio.h"
#include "Node.h"
#include "Spot.h"
#include "Texture.h"
namespace dagon {
////////////////////////////////////////////////////////////
// Implementation - Constructor
////////////////////////////////////////////////////////////
Node::Node() {
_previousNode = this;
_hasFootstep = false;
_hasEnterEvent = false;
_hasLeaveEvent = false;
_hasPersistEvent = false;
_hasUnpersistEvent = false;
_isSlide = false;
_parentRoom = 0;
_slideReturn = 0;
this->setType(kObjectNode);
}
////////////////////////////////////////////////////////////
// Implementation - Destructor
////////////////////////////////////////////////////////////
Node::~Node() {
// Note that we only delete spots automatically created by this class,
// not ones by the user
// FIXME: Class spots should be in a different vector
_arrayOfSpots.erase(std::remove_if(_arrayOfSpots.begin(),
_arrayOfSpots.end(),
[](Spot *spot) { return spot->hasFlag(kSpotClass); }),
_arrayOfSpots.end());
}
////////////////////////////////////////////////////////////
// Implementation - Checks
////////////////////////////////////////////////////////////
bool Node::hasBundleName() {
return !_bundleName.empty();
}
bool Node::hasFootstep() {
return _hasFootstep;
}
bool Node::hasEnterEvent() {
return _hasEnterEvent;
}
bool Node::hasLeaveEvent() {
return _hasLeaveEvent;
}
bool Node::hasSpots() {
return !_arrayOfSpots.empty();
}
bool Node::isSlide() {
return _isSlide;
}
int Node::slideReturn() {
return _slideReturn;
}
bool Node::hasPersistEvent() {
return _hasPersistEvent;
}
bool Node::hasUnpersistEvent() {
return _hasUnpersistEvent;
}
////////////////////////////////////////////////////////////
// Implementation - Gets
////////////////////////////////////////////////////////////
std::string Node::bundleName() {
return _bundleName;
}
Spot* Node::currentSpot() {
assert(_it != _arrayOfSpots.end());
return *_it;
}
std::string Node::description() {
return _description;
}
int Node::enterEvent() {
assert(_hasEnterEvent = true);
return _luaEnterReference;
}
Audio* Node::footstep() {
return _footstep;
}
int Node::leaveEvent() {
assert(_hasLeaveEvent = true);
return _luaLeaveReference;
}
Room* Node::parentRoom() {
return _parentRoom;
}
Node* Node::previousNode() {
return _previousNode;
}
size_t Node::numSpots() {
return _arrayOfSpots.size();
}
int Node::persistEvent() {
assert(_hasPersistEvent == true);
return _luaPersistRef;
}
int Node::unpersistEvent() {
assert(_hasUnpersistEvent == true);
return _luaUnpersistRef;
}
////////////////////////////////////////////////////////////
// Implementation - Sets
////////////////////////////////////////////////////////////
void Node::setBundleName(std::string theName) {
_bundleName = theName;
}
void Node::setDescription(std::string theDescription) {
_description = theDescription;
}
void Node::setEnterEvent(int theLuaReference) {
_hasEnterEvent = true;
_luaEnterReference = theLuaReference;
}
void Node::setFootstep(Audio* theFootstep) {
_footstep = theFootstep;
_hasFootstep = true;
}
void Node::setLeaveEvent(int theLuaReference) {
_hasLeaveEvent = true;
_luaLeaveReference = theLuaReference;
}
void Node::setParentRoom(Room* room) {
_parentRoom = room;
}
void Node::setPreviousNode(Node* node) {
_previousNode = node;
}
void Node::setSlide(bool enabled) {
_isSlide = enabled;
}
void Node::setSlideReturn(int luaHandler) {
_slideReturn = luaHandler;
}
void Node::setPersistEvent(const int luaRef) {
_hasPersistEvent = true;
_luaPersistRef = luaRef;
}
void Node::setUnpersistEvent(const int luaRef) {
_hasUnpersistEvent = true;
_luaUnpersistRef = luaRef;
}
////////////////////////////////////////////////////////////
// Implementation - State changes
////////////////////////////////////////////////////////////
void Node::addCustomLink(unsigned withDirection, int luaHandler) {
Action action;
action.type = kActionFunction;
action.cursor = kCursorForward;
action.luaHandler = luaHandler;
_link(withDirection, &action);
}
void Node::addLink(unsigned int withDirection, Object* theTarget) {
Action action;
action.type = kActionSwitch;
action.cursor = kCursorForward;
action.target = theTarget;
_link(withDirection, &action);
}
Spot* Node::addSpot(Spot* aSpot) {
_arrayOfSpots.push_back(aSpot);
return aSpot;
}
void Node::beginIteratingSpots() {
_it = _arrayOfSpots.begin();
}
bool Node::iterateSpots() {
++_it;
if (_it == _arrayOfSpots.end()) {
return false;
} else {
return true;
}
}
////////////////////////////////////////////////////////////
// Implementation - Private methods
////////////////////////////////////////////////////////////
void Node::_link(unsigned int direction, Action* action) {
// We ensure the texture is properly stretched, so we take the default
// cube size.
// TODO: This setting should be obtained directly from the Config class
int minorBound = kDefTexSize / 3;
int majorBound = static_cast<int>(kDefTexSize / 1.5f);
int offset = kDefTexSize / 3;
// We always have four corners here, hence eight elements since they are
// squared spots.
std::vector<int> arrayOfCoordinates;
int coordsNormal[] = {minorBound, minorBound, majorBound, minorBound,
majorBound, majorBound, minorBound, majorBound};
int coordsShiftRight[] = {minorBound + offset, minorBound,
majorBound + offset, minorBound, majorBound + offset, majorBound,
minorBound + offset, majorBound};
int coordsShiftLeft[] = {minorBound - offset, minorBound, majorBound - offset,
minorBound, majorBound - offset, majorBound, minorBound - offset,
majorBound};
Spot *newSpot = NULL, *auxSpot = NULL;
switch (direction) {
case kNorth:
case kEast:
case kSouth:
case kWest: {
arrayOfCoordinates.assign(coordsNormal, coordsNormal + 8);
newSpot = new Spot(arrayOfCoordinates, direction, kSpotClass);
break;
}
case kNorthEast: {
arrayOfCoordinates.assign(coordsShiftRight, coordsShiftRight + 8);
newSpot = new Spot(arrayOfCoordinates, kNorth, kSpotClass);
arrayOfCoordinates.assign(coordsShiftLeft, coordsShiftLeft + 8);
auxSpot = new Spot(arrayOfCoordinates, kEast, kSpotClass);
break;
}
case kSouthEast: {
arrayOfCoordinates.assign(coordsShiftRight, coordsShiftRight + 8);
newSpot = new Spot(arrayOfCoordinates, kEast, kSpotClass);
arrayOfCoordinates.assign(coordsShiftLeft, coordsShiftLeft + 8);
auxSpot = new Spot(arrayOfCoordinates, kSouth, kSpotClass);
break;
}
case kSouthWest: {
arrayOfCoordinates.assign(coordsShiftRight, coordsShiftRight + 8);
newSpot = new Spot(arrayOfCoordinates, kSouth, kSpotClass);
arrayOfCoordinates.assign(coordsShiftLeft, coordsShiftLeft + 8);
auxSpot = new Spot(arrayOfCoordinates, kWest, kSpotClass);
break;
}
case kNorthWest: {
arrayOfCoordinates.assign(coordsShiftRight, coordsShiftRight + 8);
newSpot = new Spot(arrayOfCoordinates, kWest, kSpotClass);
arrayOfCoordinates.assign(coordsShiftLeft, coordsShiftLeft + 8);
auxSpot = new Spot(arrayOfCoordinates, kNorth, kSpotClass);
break;
}
default: {
assert(false);
}
}
newSpot->setAction(action);
newSpot->setColor(0); // Color is set automatically
_arrayOfSpots.push_back(newSpot);
if (auxSpot) {
auxSpot->setAction(action);
auxSpot->setColor(0);
_arrayOfSpots.push_back(auxSpot);
}
}
}
<|endoftext|> |
<commit_before>/*
* GridMap.hpp
*
* Created on: Jul 14, 2014
* Author: Péter Fankhauser
* Institute: ETH Zurich, Autonomous Systems Lab
*/
#pragma once
#include "grid_map_core/TypeDefs.hpp"
// STL
#include <vector>
#include <unordered_map>
// Eigen
#include <Eigen/Core>
namespace grid_map {
/*!
* Grid map managing multiple overlaying maps holding float values.
* Data structure implemented as two-dimensional circular buffer so map
* can be moved efficiently.
*
* Data is defined with string keys. Examples are:
* - "elevation"
* - "variance"
* - "color"
* - "quality"
* - "surface_normal_x", "surface_normal_y", "surface_normal_z"
* etc.
*/
class GridMap
{
public:
/*!
* Constructor.
* @param layers a vector of strings containing the definition/description of the data layer.
*/
GridMap(const std::vector<std::string>& layers);
/*!
* Emtpy constructor.
*/
GridMap();
/*!
* Destructor.
*/
virtual ~GridMap();
/*!
* Set the geometry of the grid map. Clears all the data.
* @param length the side lengths in x, and y-direction of the grid map [m].
* @param resolution the cell size in [m/cell].
* @param position the 2d position of the grid map in the grid map frame [m].
*/
void setGeometry(const grid_map::Length& length, const double resolution,
const grid_map::Position& position = grid_map::Position::Zero());
/*!
* Add a new empty data layer.
* @param layer the name of the layer.
* @value value the value to initialize the cells with.
*/
void add(const std::string& layer, const double value = NAN);
/*!
* Add a new data layer (if the layer already exists, overwrite its data, otherwise add layer and data).
* @param layer the name of the layer.
* @param data the data to be added.
*/
void add(const std::string& layer, const grid_map::Matrix& data);
/*!
* Checks if data layer exists.
* @param layer the name of the layer.
* @return true if layer exists, false otherwise.
*/
bool exists(const std::string& layer) const;
/*!
* Returns the grid map data for a layer as matrix.
* @param layer the name of the layer to be returned.
* @return grid map data as matrix.
* @throw std::out_of_range if no map layer with name `layer` is present.
*/
const grid_map::Matrix& get(const std::string& layer) const;
/*!
* Returns the grid map data for a layer as non-const. Use this method
* with care!
* @param layer the name of the layer to be returned.
* @return grid map data.
* @throw std::out_of_range if no map layer with name `layer` is present.
*/
grid_map::Matrix& get(const std::string& layer);
/*!
* Returns the grid map data for a layer as matrix.
* @param layer the name of the layer to be returned.
* @return grid map data as matrix.
* @throw std::out_of_range if no map layer with name `layer` is present.
*/
const grid_map::Matrix& operator [](const std::string& layer) const;
/*!
* Returns the grid map data for a layer as non-const. Use this method
* with care!
* @param layer the name of the layer to be returned.
* @return grid map data.
* @throw std::out_of_range if no map layer with name `layer` is present.
*/
grid_map::Matrix& operator [](const std::string& layer);
/*!
* Removes a layer from the grid map.
* @param layer the name of the layer to be removed.
* @return true if successful.
*/
bool erase(const std::string& layer);
/*!
* Gets the names of the layers.
* @return the names of the layers.
*/
const std::vector<std::string>& getLayers() const;
/*!
* Set the basic layers that need to be valid for a cell to be considered as valid.
* Also, the basic layers are set to NAN when clearing the cells with `clear()`.
* By default the list of basic layers is empty.
* @param basicLayers the list of layer that are the basic types of the map.
*/
void setBasicLayers(const std::vector<std::string>& basicLayers);
/*!
* Gets the names of the basic layers.
* @return the names of the basic layers.
*/
const std::vector<std::string>& getBasicLayers() const;
/*!
* Get cell data at requested position.
* @param layer the name of the layer to be accessed.
* @param position the requested position.
* @return the data of the cell.
* @throw std::out_of_range if no map layer with name `layer` is present.
*/
float& atPosition(const std::string& layer, const grid_map::Position& position);
/*!
* Get cell data at requested position. Const version form above.
* @param layer the name of the layer to be accessed.
* @param position the requested position.
* @return the data of the cell.
* @throw std::out_of_range if no map layer with name `layer` is present.
*/
float atPosition(const std::string& layer, const grid_map::Position& position) const;
/*!
* Get cell data for requested index.
* @param layer the name of the layer to be accessed.
* @param index the requested index.
* @return the data of the cell.
* @throw std::out_of_range if no map layer with name `layer` is present.
*/
float& at(const std::string& layer, const grid_map::Index& index);
/*!
* Get cell data for requested index. Const version form above.
* @param layer the name of the layer to be accessed.
* @param index the requested index.
* @return the data of the cell.
* @throw std::out_of_range if no map layer with name `layer` is present.
*/
float at(const std::string& layer, const grid_map::Index& index) const;
/*!
* Gets the corresponding cell index for a position.
* @param[in] position the requested position.
* @param[out] index the corresponding index.
* @return true if successful, false if position outside of map.
*/
bool getIndex(const grid_map::Position& position, grid_map::Index& index) const;
/*!
* Gets the 2d position of cell specified by the index (x, y of cell position) in
* the grid map frame.
* @param[in] index the index of the requested cell.
* @param[out] position the position of the data point in the parent frame.
* @return true if successful, false if index not within range of buffer.
*/
bool getPosition(const grid_map::Index& index, grid_map::Position& position) const;
/*!
* Check if position is within the map boundaries.
* @param position the position to be checked.
* @return true if position is within map, false otherwise.
*/
bool isInside(const grid_map::Position& position);
/*!
* Checks if the index of all layers defined as basic types are valid,
* i.e. if all basic types are finite. Returns `false` if no basic types are defined.
* @param index the index to check.
* @return true if cell is valid, false otherwise.
*/
bool isValid(const grid_map::Index& index) const;
/*!
* Checks if cell at index is a valid (finite) for a certain layer.
* @param index the index to check.
* @param layer the name of the layer to be checked for validity.
* @return true if cell is valid, false otherwise.
*/
bool isValid(const grid_map::Index& index, const std::string& layer) const;
/*!
* Checks if cell at index is a valid (finite) for certain layers.
* @param index the index to check.
* @param layers the layers to be checked for validity.
* @return true if cell is valid, false otherwise.
*/
bool isValid(const grid_map::Index& index, const std::vector<std::string>& layers) const;
/*!
* Gets the 3d position of a data point (x, y of cell position & cell value as z) in
* the grid map frame. This is useful for data layers such as elevation.
* @param layer the name of the layer to be accessed.
* @param index the index of the requested cell.
* @param position the position of the data point in the parent frame.
* @return true if successful, false if no valid data available.
*/
bool getPosition3(const std::string& layer, const grid_map::Index& index,
grid_map::Position3& position) const;
/*!
* Gets the 3d vector of three layers with suffixes 'x', 'y', and 'z'.
* @param layerPrefix the prefix for the layer to bet get as vector.
* @param index the index of the requested cell.
* @param vector the vector with the values of the data type.
* @return true if successful, false if no valid data available.
*/
bool getVector(const std::string& layerPrefix, const grid_map::Index& index,
Eigen::Vector3d& vector) const;
/*!
* Gets a submap from the map. The requested submap is specified with the requested
* location and length.
* @param[in] position the requested position of the submap (usually the center).
* @param[in] length the requested length of the submap.
* @param[out] isSuccess true if successful, false otherwise.
* @return submap (is empty if success is false).
*/
GridMap getSubmap(const grid_map::Position& position, const grid_map::Length& length,
bool& isSuccess);
/*!
* Gets a submap from the map. The requested submap is specified with the requested
* location and length.
* @param[in] position the requested position of the submap (usually the center).
* @param[in] length the requested length of the submap.
* @param[out] indexInSubmap the index of the requested position in the submap.
* @param[out] isSuccess true if successful, false otherwise.
* @return submap (is empty if success is false).
*/
GridMap getSubmap(const grid_map::Position& position, const grid_map::Length& length,
grid_map::Index& indexInSubmap, bool& isSuccess);
/*!
* Move the grid map w.r.t. to the grid map frame. Use this to move the grid map
* boundaries without moving the grid map data. Takes care of all the data handling,
* such that the grid map data is stationary in the grid map frame.
* @param position the new location of the grid map in the map frame.
*/
void move(const grid_map::Position& position);
/*!
* Clears all cells (set to NAN) for a layer.
* @param layer the layer to be cleared.
*/
void clear(const std::string& layer);
/*!
* Clears all cells (set to NAN) for all basic layers.
* Header information (geometry etc.) remains valid.
*/
void clearBasic();
/*!
* Clears all cells of all layers.
* If basic layers are used, clearBasic() is preferred as it is more efficient.
* Header information (geometry etc.) remains valid.
*/
void clearAll();
/*!
* Set the timestamp of the grid map.
* @param timestamp the timestamp to set (in nanoseconds).
*/
void setTimestamp(const uint64_t timestamp);
/*!
* Get the timestamp of the grid map.
* @return timestamp in nanoseconds.
*/
uint64_t getTimestamp() const;
/*!
* Resets the timestamp of the grid map (to zero).
*/
void resetTimestamp();
/*!
* Set the frame id of the grid map.
* @param frameId the frame id to set.
*/
void setFrameId(const std::string& frameId);
/*!
* Get the frameId of the grid map.
* @return frameId.
*/
const std::string& getFrameId() const;
/*!
* Get the side length of the grid map.
* @return side length of the grid map.
*/
const grid_map::Length& getLength() const;
/*!
* Get the 2d position of the grid map in the grid map frame.
* @return position of the grid map in the grid map frame.
*/
const grid_map::Position& getPosition() const;
/*!
* Get the resolution of the grid map.
* @return resolution of the grid map in the xy plane [m/cell].
*/
double getResolution() const;
/*!
* Get the grid map size (rows and cols of the data structure).
* @return grid map size.
*/
const grid_map::Size& getSize() const;
/*!
* Set the start index of the circular buffer.
* Use this method with caution!
* @return buffer start index.
*/
void setStartIndex(const grid_map::Index& startIndex);
/*!
* Get the start index of the circular buffer.
* @return buffer start index.
*/
const grid_map::Index& getStartIndex() const;
private:
/*!
* Clear a number of columns of the grid map.
* @param index the left index for the columns to be reset.
* @param nCols the number of columns to reset.
*/
void clearCols(unsigned int index, unsigned int nCols);
/*!
* Clear a number of rows of the grid map.
* @param index the upper index for the rows to be reset.
* @param nRows the number of rows to reset.
*/
void clearRows(unsigned int index, unsigned int nRows);
/*!
* Resize the buffer.
* @param bufferSize the requested buffer size.
*/
void resize(const Eigen::Array2i& bufferSize);
//! Frame id of the grid map.
std::string frameId_;
//! Timestamp of the grid map (nanoseconds).
uint64_t timestamp_;
//! Grid map data stored as layers of matrices.
std::unordered_map<std::string, Eigen::MatrixXf> data_;
//! Names of the data layers.
std::vector<std::string> layers_;
//! List of layers from `data_` that are the basic grid map layers.
//! This means that for a cell to be valid, all basic layers need to be valid.
//! Also, the basic layers are set to NAN when clearing the map with `clear()`.
std::vector<std::string> basicLayers_;
//! Side length of the map in x- and y-direction [m].
grid_map::Length length_;
//! Map resolution in xy plane [m/cell].
double resolution_;
//! Map position in the grid map frame [m].
grid_map::Position position_;
//! Size of the buffer (rows and cols of the data structure).
grid_map::Size size_;
//! Circular buffer start indeces.
grid_map::Index startIndex_;
};
} /* namespace */
<commit_msg>Update GridMap.hpp<commit_after>/*
* GridMap.hpp
*
* Created on: Jul 14, 2014
* Author: Péter Fankhauser
* Institute: ETH Zurich, Autonomous Systems Lab
*/
#pragma once
#include "grid_map_core/TypeDefs.hpp"
// STL
#include <vector>
#include <unordered_map>
// Eigen
#include <Eigen/Core>
namespace grid_map {
/*!
* Grid map managing multiple overlaying maps holding float values.
* Data structure implemented as two-dimensional circular buffer so map
* can be moved efficiently.
*
* Data is defined with string keys. Examples are:
* - "elevation"
* - "variance"
* - "color"
* - "quality"
* - "surface_normal_x", "surface_normal_y", "surface_normal_z"
* etc.
*/
class GridMap
{
public:
/*!
* Constructor.
* @param layers a vector of strings containing the definition/description of the data layer.
*/
GridMap(const std::vector<std::string>& layers);
/*!
* Emtpy constructor.
*/
GridMap();
/*!
* Destructor.
*/
virtual ~GridMap();
/*!
* Set the geometry of the grid map. Clears all the data.
* @param length the side lengths in x, and y-direction of the grid map [m].
* @param resolution the cell size in [m/cell].
* @param position the 2d position of the grid map in the grid map frame [m].
*/
void setGeometry(const grid_map::Length& length, const double resolution,
const grid_map::Position& position = grid_map::Position::Zero());
/*!
* Add a new empty data layer.
* @param layer the name of the layer.
* @value value the value to initialize the cells with.
*/
void add(const std::string& layer, const double value = NAN);
/*!
* Add a new data layer (if the layer already exists, overwrite its data, otherwise add layer and data).
* @param layer the name of the layer.
* @param data the data to be added.
*/
void add(const std::string& layer, const grid_map::Matrix& data);
/*!
* Checks if data layer exists.
* @param layer the name of the layer.
* @return true if layer exists, false otherwise.
*/
bool exists(const std::string& layer) const;
/*!
* Returns the grid map data for a layer as matrix.
* @param layer the name of the layer to be returned.
* @return grid map data as matrix.
* @throw std::out_of_range if no map layer with name `layer` is present.
*/
const grid_map::Matrix& get(const std::string& layer) const;
/*!
* Returns the grid map data for a layer as non-const. Use this method
* with care!
* @param layer the name of the layer to be returned.
* @return grid map data.
* @throw std::out_of_range if no map layer with name `layer` is present.
*/
grid_map::Matrix& get(const std::string& layer);
/*!
* Returns the grid map data for a layer as matrix.
* @param layer the name of the layer to be returned.
* @return grid map data as matrix.
* @throw std::out_of_range if no map layer with name `layer` is present.
*/
const grid_map::Matrix& operator [](const std::string& layer) const;
/*!
* Returns the grid map data for a layer as non-const. Use this method
* with care!
* @param layer the name of the layer to be returned.
* @return grid map data.
* @throw std::out_of_range if no map layer with name `layer` is present.
*/
grid_map::Matrix& operator [](const std::string& layer);
/*!
* Removes a layer from the grid map.
* @param layer the name of the layer to be removed.
* @return true if successful.
*/
bool erase(const std::string& layer);
/*!
* Gets the names of the layers.
* @return the names of the layers.
*/
const std::vector<std::string>& getLayers() const;
/*!
* Set the basic layers that need to be valid for a cell to be considered as valid.
* Also, the basic layers are set to NAN when clearing the cells with `clearBasic()`.
* By default the list of basic layers is empty.
* @param basicLayers the list of layers that are the basic layers of the map.
*/
void setBasicLayers(const std::vector<std::string>& basicLayers);
/*!
* Gets the names of the basic layers.
* @return the names of the basic layers.
*/
const std::vector<std::string>& getBasicLayers() const;
/*!
* Get cell data at requested position.
* @param layer the name of the layer to be accessed.
* @param position the requested position.
* @return the data of the cell.
* @throw std::out_of_range if no map layer with name `layer` is present.
*/
float& atPosition(const std::string& layer, const grid_map::Position& position);
/*!
* Get cell data at requested position. Const version form above.
* @param layer the name of the layer to be accessed.
* @param position the requested position.
* @return the data of the cell.
* @throw std::out_of_range if no map layer with name `layer` is present.
*/
float atPosition(const std::string& layer, const grid_map::Position& position) const;
/*!
* Get cell data for requested index.
* @param layer the name of the layer to be accessed.
* @param index the requested index.
* @return the data of the cell.
* @throw std::out_of_range if no map layer with name `layer` is present.
*/
float& at(const std::string& layer, const grid_map::Index& index);
/*!
* Get cell data for requested index. Const version form above.
* @param layer the name of the layer to be accessed.
* @param index the requested index.
* @return the data of the cell.
* @throw std::out_of_range if no map layer with name `layer` is present.
*/
float at(const std::string& layer, const grid_map::Index& index) const;
/*!
* Gets the corresponding cell index for a position.
* @param[in] position the requested position.
* @param[out] index the corresponding index.
* @return true if successful, false if position outside of map.
*/
bool getIndex(const grid_map::Position& position, grid_map::Index& index) const;
/*!
* Gets the 2d position of cell specified by the index (x, y of cell position) in
* the grid map frame.
* @param[in] index the index of the requested cell.
* @param[out] position the position of the data point in the parent frame.
* @return true if successful, false if index not within range of buffer.
*/
bool getPosition(const grid_map::Index& index, grid_map::Position& position) const;
/*!
* Check if position is within the map boundaries.
* @param position the position to be checked.
* @return true if position is within map, false otherwise.
*/
bool isInside(const grid_map::Position& position);
/*!
* Checks if the index of all layers defined as basic types are valid,
* i.e. if all basic types are finite. Returns `false` if no basic types are defined.
* @param index the index to check.
* @return true if cell is valid, false otherwise.
*/
bool isValid(const grid_map::Index& index) const;
/*!
* Checks if cell at index is a valid (finite) for a certain layer.
* @param index the index to check.
* @param layer the name of the layer to be checked for validity.
* @return true if cell is valid, false otherwise.
*/
bool isValid(const grid_map::Index& index, const std::string& layer) const;
/*!
* Checks if cell at index is a valid (finite) for certain layers.
* @param index the index to check.
* @param layers the layers to be checked for validity.
* @return true if cell is valid, false otherwise.
*/
bool isValid(const grid_map::Index& index, const std::vector<std::string>& layers) const;
/*!
* Gets the 3d position of a data point (x, y of cell position & cell value as z) in
* the grid map frame. This is useful for data layers such as elevation.
* @param layer the name of the layer to be accessed.
* @param index the index of the requested cell.
* @param position the position of the data point in the parent frame.
* @return true if successful, false if no valid data available.
*/
bool getPosition3(const std::string& layer, const grid_map::Index& index,
grid_map::Position3& position) const;
/*!
* Gets the 3d vector of three layers with suffixes 'x', 'y', and 'z'.
* @param layerPrefix the prefix for the layer to bet get as vector.
* @param index the index of the requested cell.
* @param vector the vector with the values of the data type.
* @return true if successful, false if no valid data available.
*/
bool getVector(const std::string& layerPrefix, const grid_map::Index& index,
Eigen::Vector3d& vector) const;
/*!
* Gets a submap from the map. The requested submap is specified with the requested
* location and length.
* @param[in] position the requested position of the submap (usually the center).
* @param[in] length the requested length of the submap.
* @param[out] isSuccess true if successful, false otherwise.
* @return submap (is empty if success is false).
*/
GridMap getSubmap(const grid_map::Position& position, const grid_map::Length& length,
bool& isSuccess);
/*!
* Gets a submap from the map. The requested submap is specified with the requested
* location and length.
* @param[in] position the requested position of the submap (usually the center).
* @param[in] length the requested length of the submap.
* @param[out] indexInSubmap the index of the requested position in the submap.
* @param[out] isSuccess true if successful, false otherwise.
* @return submap (is empty if success is false).
*/
GridMap getSubmap(const grid_map::Position& position, const grid_map::Length& length,
grid_map::Index& indexInSubmap, bool& isSuccess);
/*!
* Move the grid map w.r.t. to the grid map frame. Use this to move the grid map
* boundaries without moving the grid map data. Takes care of all the data handling,
* such that the grid map data is stationary in the grid map frame.
* @param position the new location of the grid map in the map frame.
*/
void move(const grid_map::Position& position);
/*!
* Clears all cells (set to NAN) for a layer.
* @param layer the layer to be cleared.
*/
void clear(const std::string& layer);
/*!
* Clears all cells (set to NAN) for all basic layers.
* Header information (geometry etc.) remains valid.
*/
void clearBasic();
/*!
* Clears all cells of all layers.
* If basic layers are used, clearBasic() is preferred as it is more efficient.
* Header information (geometry etc.) remains valid.
*/
void clearAll();
/*!
* Set the timestamp of the grid map.
* @param timestamp the timestamp to set (in nanoseconds).
*/
void setTimestamp(const uint64_t timestamp);
/*!
* Get the timestamp of the grid map.
* @return timestamp in nanoseconds.
*/
uint64_t getTimestamp() const;
/*!
* Resets the timestamp of the grid map (to zero).
*/
void resetTimestamp();
/*!
* Set the frame id of the grid map.
* @param frameId the frame id to set.
*/
void setFrameId(const std::string& frameId);
/*!
* Get the frameId of the grid map.
* @return frameId.
*/
const std::string& getFrameId() const;
/*!
* Get the side length of the grid map.
* @return side length of the grid map.
*/
const grid_map::Length& getLength() const;
/*!
* Get the 2d position of the grid map in the grid map frame.
* @return position of the grid map in the grid map frame.
*/
const grid_map::Position& getPosition() const;
/*!
* Get the resolution of the grid map.
* @return resolution of the grid map in the xy plane [m/cell].
*/
double getResolution() const;
/*!
* Get the grid map size (rows and cols of the data structure).
* @return grid map size.
*/
const grid_map::Size& getSize() const;
/*!
* Set the start index of the circular buffer.
* Use this method with caution!
* @return buffer start index.
*/
void setStartIndex(const grid_map::Index& startIndex);
/*!
* Get the start index of the circular buffer.
* @return buffer start index.
*/
const grid_map::Index& getStartIndex() const;
private:
/*!
* Clear a number of columns of the grid map.
* @param index the left index for the columns to be reset.
* @param nCols the number of columns to reset.
*/
void clearCols(unsigned int index, unsigned int nCols);
/*!
* Clear a number of rows of the grid map.
* @param index the upper index for the rows to be reset.
* @param nRows the number of rows to reset.
*/
void clearRows(unsigned int index, unsigned int nRows);
/*!
* Resize the buffer.
* @param bufferSize the requested buffer size.
*/
void resize(const Eigen::Array2i& bufferSize);
//! Frame id of the grid map.
std::string frameId_;
//! Timestamp of the grid map (nanoseconds).
uint64_t timestamp_;
//! Grid map data stored as layers of matrices.
std::unordered_map<std::string, Eigen::MatrixXf> data_;
//! Names of the data layers.
std::vector<std::string> layers_;
//! List of layers from `data_` that are the basic grid map layers.
//! This means that for a cell to be valid, all basic layers need to be valid.
//! Also, the basic layers are set to NAN when clearing the map with `clear()`.
std::vector<std::string> basicLayers_;
//! Side length of the map in x- and y-direction [m].
grid_map::Length length_;
//! Map resolution in xy plane [m/cell].
double resolution_;
//! Map position in the grid map frame [m].
grid_map::Position position_;
//! Size of the buffer (rows and cols of the data structure).
grid_map::Size size_;
//! Circular buffer start indeces.
grid_map::Index startIndex_;
};
} /* namespace */
<|endoftext|> |
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "EC_WaterPlane.h"
#include "EC_Placeable.h"
#include "IAttribute.h"
#include "Renderer.h"
#include "SceneManager.h"
#include "SceneEvents.h"
#include "EventManager.h"
#include <OgreMaterialUtils.h>
#include "LoggingFunctions.h"
DEFINE_POCO_LOGGING_FUNCTIONS("EC_WaterPlane")
#include <Ogre.h>
#include <OgreQuaternion.h>
#include <OgreColourValue.h>
#include <OgreMath.h>
#include "MemoryLeakCheck.h"
namespace Environment
{
EC_WaterPlane::EC_WaterPlane(IModule *module)
: IComponent(module->GetFramework()),
xSizeAttr(this, "x-size", 5000),
ySizeAttr(this, "y-size", 5000),
depthAttr(this, "Depth", 20),
positionAttr(this, "Position", Vector3df()),
rotationAttr(this, "Rotation", Quaternion()),
scaleUfactorAttr(this, "U factor", 0.0002f),
scaleVfactorAttr(this, "V factor", 0.0002f),
xSegmentsAttr(this, "Segments in x", 10),
ySegmentsAttr(this, "Segments in y", 10),
materialNameAttr(this, "Material", QString("Ocean")),
//textureNameAttr(this, "Texture", QString("DefaultOceanSkyCube.dds")),
fogColorAttr(this, "Fog color", Color(0.2f,0.4f,0.35f,1.0f)),
fogStartAttr(this, "Fog start dist.", 100.f),
fogEndAttr(this, "Fog end dist.", 2000.f),
fogModeAttr(this, "Fog mode", 3),
entity_(0),
node_(0),
attached_(false)
{
static AttributeMetadata metadata;
static bool metadataInitialized = false;
if(!metadataInitialized)
{
metadata.enums[Ogre::FOG_NONE] = "NoFog";
metadata.enums[Ogre::FOG_EXP] = "Exponential";
metadata.enums[Ogre::FOG_EXP2] = "ExponentiallySquare";
metadata.enums[Ogre::FOG_LINEAR] = "Linear";
metadataInitialized = true;
}
fogModeAttr.SetMetadata(&metadata);
renderer_ = framework_->GetServiceManager()->GetService<OgreRenderer::Renderer>();
if(!renderer_.expired())
{
Ogre::SceneManager* scene_mgr = renderer_.lock()->GetSceneManager();
node_ = scene_mgr->createSceneNode();
}
QObject::connect(this, SIGNAL(OnAttributeChanged(IAttribute*, AttributeChange::Type)),
SLOT(AttributeUpdated(IAttribute*, AttributeChange::Type)));
lastXsize_ = xSizeAttr.Get();
lastYsize_ = ySizeAttr.Get();
CreateWaterPlane();
QObject::connect(this, SIGNAL(ParentEntitySet()), this, SLOT(AttachEntity()));
// If there exist placeable copy its position for default position and rotation.
EC_Placeable* placeable = dynamic_cast<EC_Placeable*>(FindPlaceable().get());
if ( placeable != 0)
{
Vector3df vec = placeable->GetPosition();
positionAttr.Set(vec,AttributeChange::Default);
Quaternion rot =placeable->GetOrientation();
rotationAttr.Set(rot, AttributeChange::Default);
ComponentChanged(AttributeChange::Default);
}
}
EC_WaterPlane::~EC_WaterPlane()
{
if (renderer_.expired())
return;
OgreRenderer::RendererPtr renderer = renderer_.lock();
RemoveWaterPlane();
if (node_ != 0)
{
Ogre::SceneManager* scene_mgr = renderer->GetSceneManager();
scene_mgr->destroySceneNode(node_);
node_ = 0;
}
}
bool EC_WaterPlane::IsUnderWater()
{
// Check that is camera inside of defined waterplane.
///todo this cannot be done this way, mesh orientation etc. must take care. Now we just assume that plane does not have orientation.
if ( entity_ == 0)
return false;
Ogre::Camera *camera = renderer_.lock()->GetCurrentCamera();
Ogre::Vector3 posCamera = camera->getDerivedPosition();
Ogre::Vector3 pos;
if (node_ != 0)
pos = node_->_getDerivedPosition();
else
return false;
int xSize = xSizeAttr.Get(), ySize = ySizeAttr.Get(), depth = depthAttr.Get();
int x = posCamera.x, y = posCamera.y, z = posCamera.z;
// HACK this is strange, i thought that it should be 0.5 but some reason, visually it looks like that you can travel really "outside" from water.
int tmpMax = pos.x + 0.25*xSize;
int tmpMin = pos.x - 0.25*xSize;
if ( x >= tmpMin && x <= tmpMax )
{
tmpMax = pos.y + 0.25*ySize;
tmpMin = pos.y - 0.25*ySize;
if ( y >= tmpMin && y <= tmpMax)
{
tmpMax = pos.z;
tmpMin = pos.z - depth;
if ( z >= tmpMin && z <= tmpMax)
{
return true;
}
else
return false;
}
else
return false;
}
return false;
}
void EC_WaterPlane::CreateWaterPlane()
{
// Create waterplane
if (renderer_.lock() != 0)
{
Ogre::SceneManager *sceneMgr = renderer_.lock()->GetSceneManager();
assert(sceneMgr);
if (node_ != 0)
{
int xSize = xSizeAttr.Get();
int ySize = ySizeAttr.Get();
float uTile = scaleUfactorAttr.Get() * xSize; /// Default x-size 5000 --> uTile 1.0
float vTile = scaleVfactorAttr.Get() * ySize;
Ogre::MeshPtr mesh = Ogre::MeshManager::getSingleton().createPlane(name_.toStdString().c_str(), Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
Ogre::Plane(Ogre::Vector3::UNIT_Z, 0),xSize, ySize, xSegmentsAttr.Get(), ySegmentsAttr.Get(), true, 1, uTile, vTile, Ogre::Vector3::UNIT_X);
entity_ = sceneMgr->createEntity(renderer_.lock()->GetUniqueObjectName(), name_.toStdString().c_str());
entity_->setMaterialName(materialNameAttr.Get().toStdString().c_str());
entity_->setCastShadows(false);
// Tries to attach entity, if there is not EC_Placeable availible, it will not attach object
AttachEntity();
}
}
}
void EC_WaterPlane::RemoveWaterPlane()
{
// Remove waterplane
if (renderer_.expired() || !entity_)
return;
OgreRenderer::RendererPtr renderer = renderer_.lock();
DetachEntity();
Ogre::SceneManager* scene_mgr = renderer->GetSceneManager();
scene_mgr->destroyEntity(entity_);
entity_ = 0;
Ogre::MeshManager::getSingleton().remove(name_.toStdString().c_str());
}
Ogre::ColourValue EC_WaterPlane::GetFogColorAsOgreValue() const
{
Color col = fogColorAttr.Get();
return Ogre::ColourValue(col.r, col.g, col.b, col.a);
}
void EC_WaterPlane::AttributeUpdated(IAttribute* attribute, AttributeChange::Type change)
{
ChangeWaterPlane(attribute);
}
void EC_WaterPlane::SetPosition()
{
// Is attached?
if ( entity_ != 0 && !entity_->isAttached() && !attached_ )
{
Ogre::SceneManager* scene_mgr = renderer_.lock()->GetSceneManager();
node_->attachObject(entity_);
attached_ = true;
scene_mgr->getRootSceneNode()->addChild(node_);
node_->setVisible(true);
}
Vector3df vec = positionAttr.Get();
//node_->setPosition(vec.x, vec.y, vec.z);
#if OGRE_VERSION_MINOR <= 6 && OGRE_VERSION_MAJOR <= 1
Ogre::Vector3 current_pos = node_->_getDerivedPosition();
Ogre::Vector3 tmp(vec.x,vec.y,vec.z);
tmp = current_pos + tmp;
Vector3df pos(tmp.x, tmp.y, tmp.z);
if ( !IsValidPositionVector(pos) )
return;
node_->setPosition(tmp);
#else
Ogre::Vector3 pos(vec.x, vec.y, vec.z);
if ( pos.isNaN())
return;
node_->_setDerivedPosition(pos);
#endif
}
void EC_WaterPlane::SetOrientation()
{
// Is attached?
if ( entity_ != 0 && !entity_->isAttached() && attached_ )
{
Ogre::SceneManager* scene_mgr = renderer_.lock()->GetSceneManager();
node_->attachObject(entity_);
attached_ = true;
scene_mgr->getRootSceneNode()->addChild(node_);
node_->setVisible(true);
}
// Set orientation
Quaternion rot = rotationAttr.Get();
#if OGRE_VERSION_MINOR <= 6 && OGRE_VERSION_MAJOR <= 1
Ogre::Quaternion current_rot = node_->_getDerivedOrientation();
Ogre::Quaternion tmp(rot.w, rot.x, rot.y, rot.z);
Ogre::Quaternion rota = current_rot + tmp;
node_->setOrientation(rota);
#else
node_->_setDerivedOrientation(Ogre::Quaternion(rot.w, rot.x, rot.y, rot.z));
#endif
}
void EC_WaterPlane::ChangeWaterPlane(IAttribute* attribute)
{
std::string name = attribute->GetNameString();
if ( ( name == xSizeAttr.GetNameString()
|| name == ySizeAttr.GetNameString()
|| name == scaleUfactorAttr.GetNameString()
|| name == scaleVfactorAttr.GetNameString() ) &&
( lastXsize_ != xSizeAttr.Get() || lastYsize_ != ySizeAttr.Get() ) )
{
RemoveWaterPlane();
CreateWaterPlane();
lastXsize_ = xSizeAttr.Get();
lastYsize_ = ySizeAttr.Get();
}
else if ( name == xSegmentsAttr.GetNameString() || name == ySegmentsAttr.GetNameString() )
{
RemoveWaterPlane();
CreateWaterPlane();
}
else if ( name == positionAttr.GetNameString() )
{
// Change position
SetPosition();
}
else if ( name == rotationAttr.GetNameString() )
{
// Change rotation
// Is there placeable component? If not use given rotation
//if ( dynamic_cast<EC_Placeable*>(FindPlaceable().get()) == 0 )
//{
SetOrientation();
//}
}
else if ( name == depthAttr.GetNameString() )
{
// Change depth
// Currently do nothing..
}
else if ( name == materialNameAttr.GetNameString())
{
//Change material
if ( entity_ != 0)
{
entity_->setMaterialName(materialNameAttr.Get().toStdString().c_str());
}
}
/*
// Currently commented out, working feature but not enabled yet.
else if (name == textureNameAttr.GetNameString() )
{
QString currentMaterial = materialNameAttr.Get();
// Check that has texture really changed.
StringVector names;
Ogre::MaterialPtr materialPtr = Ogre::MaterialManager::getSingleton().getByName(currentMaterial.toStdString().c_str());
if ( materialPtr.get() == 0)
return;
OgreRenderer::GetTextureNamesFromMaterial(materialPtr, names);
QString textureName = textureNameAttr.Get();
for (StringVector::iterator iter = names.begin(); iter != names.end(); ++iter)
{
QString currentTextureName(iter->c_str());
if ( currentTextureName == textureName)
return;
}
// So texture has really changed, let's change it.
OgreRenderer::SetTextureUnitOnMaterial(materialPtr, textureName.toStdString(), 0);
}
*/
}
ComponentPtr EC_WaterPlane::FindPlaceable() const
{
assert(framework_);
ComponentPtr comp;
if(!GetParentEntity())
return comp;
comp = GetParentEntity()->GetComponent<EC_Placeable>();
return comp;
}
void EC_WaterPlane::AttachEntity()
{
EC_Placeable* placeable = dynamic_cast<EC_Placeable*>(FindPlaceable().get());
if ((!entity_) || (!placeable) || attached_)
return;
Ogre::SceneNode* node = placeable->GetSceneNode();
node->addChild(node_);
node_->attachObject(entity_);
attached_ = true;
}
void EC_WaterPlane::DetachEntity()
{
EC_Placeable* placeable = dynamic_cast<EC_Placeable*>(FindPlaceable().get());
if ((!attached_) || (!entity_) || (!placeable))
return;
Ogre::SceneNode* node = placeable->GetSceneNode();
node_->detachObject(entity_);
node->removeChild(node_);
attached_ = false;
}
}<commit_msg>Added missing #include for IsValidPositionVector()<commit_after>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "EC_WaterPlane.h"
#include "EC_Placeable.h"
#include "IAttribute.h"
#include "Renderer.h"
#include "SceneManager.h"
#include "SceneEvents.h"
#include "EventManager.h"
#include <OgreMaterialUtils.h>
#include "LoggingFunctions.h"
DEFINE_POCO_LOGGING_FUNCTIONS("EC_WaterPlane")
#include <Ogre.h>
#include <OgreQuaternion.h>
#include <OgreColourValue.h>
#include <OgreMath.h>
// NaN - check
#include <RexNetworkUtils.h>
#include "MemoryLeakCheck.h"
namespace Environment
{
EC_WaterPlane::EC_WaterPlane(IModule *module)
: IComponent(module->GetFramework()),
xSizeAttr(this, "x-size", 5000),
ySizeAttr(this, "y-size", 5000),
depthAttr(this, "Depth", 20),
positionAttr(this, "Position", Vector3df()),
rotationAttr(this, "Rotation", Quaternion()),
scaleUfactorAttr(this, "U factor", 0.0002f),
scaleVfactorAttr(this, "V factor", 0.0002f),
xSegmentsAttr(this, "Segments in x", 10),
ySegmentsAttr(this, "Segments in y", 10),
materialNameAttr(this, "Material", QString("Ocean")),
//textureNameAttr(this, "Texture", QString("DefaultOceanSkyCube.dds")),
fogColorAttr(this, "Fog color", Color(0.2f,0.4f,0.35f,1.0f)),
fogStartAttr(this, "Fog start dist.", 100.f),
fogEndAttr(this, "Fog end dist.", 2000.f),
fogModeAttr(this, "Fog mode", 3),
entity_(0),
node_(0),
attached_(false)
{
static AttributeMetadata metadata;
static bool metadataInitialized = false;
if(!metadataInitialized)
{
metadata.enums[Ogre::FOG_NONE] = "NoFog";
metadata.enums[Ogre::FOG_EXP] = "Exponential";
metadata.enums[Ogre::FOG_EXP2] = "ExponentiallySquare";
metadata.enums[Ogre::FOG_LINEAR] = "Linear";
metadataInitialized = true;
}
fogModeAttr.SetMetadata(&metadata);
renderer_ = framework_->GetServiceManager()->GetService<OgreRenderer::Renderer>();
if(!renderer_.expired())
{
Ogre::SceneManager* scene_mgr = renderer_.lock()->GetSceneManager();
node_ = scene_mgr->createSceneNode();
}
QObject::connect(this, SIGNAL(OnAttributeChanged(IAttribute*, AttributeChange::Type)),
SLOT(AttributeUpdated(IAttribute*, AttributeChange::Type)));
lastXsize_ = xSizeAttr.Get();
lastYsize_ = ySizeAttr.Get();
CreateWaterPlane();
QObject::connect(this, SIGNAL(ParentEntitySet()), this, SLOT(AttachEntity()));
// If there exist placeable copy its position for default position and rotation.
EC_Placeable* placeable = dynamic_cast<EC_Placeable*>(FindPlaceable().get());
if ( placeable != 0)
{
Vector3df vec = placeable->GetPosition();
positionAttr.Set(vec,AttributeChange::Default);
Quaternion rot =placeable->GetOrientation();
rotationAttr.Set(rot, AttributeChange::Default);
ComponentChanged(AttributeChange::Default);
}
}
EC_WaterPlane::~EC_WaterPlane()
{
if (renderer_.expired())
return;
OgreRenderer::RendererPtr renderer = renderer_.lock();
RemoveWaterPlane();
if (node_ != 0)
{
Ogre::SceneManager* scene_mgr = renderer->GetSceneManager();
scene_mgr->destroySceneNode(node_);
node_ = 0;
}
}
bool EC_WaterPlane::IsUnderWater()
{
// Check that is camera inside of defined waterplane.
///todo this cannot be done this way, mesh orientation etc. must take care. Now we just assume that plane does not have orientation.
if ( entity_ == 0)
return false;
Ogre::Camera *camera = renderer_.lock()->GetCurrentCamera();
Ogre::Vector3 posCamera = camera->getDerivedPosition();
Ogre::Vector3 pos;
if (node_ != 0)
pos = node_->_getDerivedPosition();
else
return false;
int xSize = xSizeAttr.Get(), ySize = ySizeAttr.Get(), depth = depthAttr.Get();
int x = posCamera.x, y = posCamera.y, z = posCamera.z;
// HACK this is strange, i thought that it should be 0.5 but some reason, visually it looks like that you can travel really "outside" from water.
int tmpMax = pos.x + 0.25*xSize;
int tmpMin = pos.x - 0.25*xSize;
if ( x >= tmpMin && x <= tmpMax )
{
tmpMax = pos.y + 0.25*ySize;
tmpMin = pos.y - 0.25*ySize;
if ( y >= tmpMin && y <= tmpMax)
{
tmpMax = pos.z;
tmpMin = pos.z - depth;
if ( z >= tmpMin && z <= tmpMax)
{
return true;
}
else
return false;
}
else
return false;
}
return false;
}
void EC_WaterPlane::CreateWaterPlane()
{
// Create waterplane
if (renderer_.lock() != 0)
{
Ogre::SceneManager *sceneMgr = renderer_.lock()->GetSceneManager();
assert(sceneMgr);
if (node_ != 0)
{
int xSize = xSizeAttr.Get();
int ySize = ySizeAttr.Get();
float uTile = scaleUfactorAttr.Get() * xSize; /// Default x-size 5000 --> uTile 1.0
float vTile = scaleVfactorAttr.Get() * ySize;
Ogre::MeshPtr mesh = Ogre::MeshManager::getSingleton().createPlane(name_.toStdString().c_str(), Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
Ogre::Plane(Ogre::Vector3::UNIT_Z, 0),xSize, ySize, xSegmentsAttr.Get(), ySegmentsAttr.Get(), true, 1, uTile, vTile, Ogre::Vector3::UNIT_X);
entity_ = sceneMgr->createEntity(renderer_.lock()->GetUniqueObjectName(), name_.toStdString().c_str());
entity_->setMaterialName(materialNameAttr.Get().toStdString().c_str());
entity_->setCastShadows(false);
// Tries to attach entity, if there is not EC_Placeable availible, it will not attach object
AttachEntity();
}
}
}
void EC_WaterPlane::RemoveWaterPlane()
{
// Remove waterplane
if (renderer_.expired() || !entity_)
return;
OgreRenderer::RendererPtr renderer = renderer_.lock();
DetachEntity();
Ogre::SceneManager* scene_mgr = renderer->GetSceneManager();
scene_mgr->destroyEntity(entity_);
entity_ = 0;
Ogre::MeshManager::getSingleton().remove(name_.toStdString().c_str());
}
Ogre::ColourValue EC_WaterPlane::GetFogColorAsOgreValue() const
{
Color col = fogColorAttr.Get();
return Ogre::ColourValue(col.r, col.g, col.b, col.a);
}
void EC_WaterPlane::AttributeUpdated(IAttribute* attribute, AttributeChange::Type change)
{
ChangeWaterPlane(attribute);
}
void EC_WaterPlane::SetPosition()
{
// Is attached?
if ( entity_ != 0 && !entity_->isAttached() && !attached_ )
{
Ogre::SceneManager* scene_mgr = renderer_.lock()->GetSceneManager();
node_->attachObject(entity_);
attached_ = true;
scene_mgr->getRootSceneNode()->addChild(node_);
node_->setVisible(true);
}
Vector3df vec = positionAttr.Get();
//node_->setPosition(vec.x, vec.y, vec.z);
#if OGRE_VERSION_MINOR <= 6 && OGRE_VERSION_MAJOR <= 1
Ogre::Vector3 current_pos = node_->_getDerivedPosition();
Ogre::Vector3 tmp(vec.x,vec.y,vec.z);
tmp = current_pos + tmp;
Vector3df pos(tmp.x, tmp.y, tmp.z);
if ( !RexTypes::IsValidPositionVector(pos) )
return;
node_->setPosition(tmp);
#else
Ogre::Vector3 pos(vec.x, vec.y, vec.z);
if ( !RexTypes::IsValidPositionVector(vec) )
return;
node_->_setDerivedPosition(pos);
#endif
}
void EC_WaterPlane::SetOrientation()
{
// Is attached?
if ( entity_ != 0 && !entity_->isAttached() && attached_ )
{
Ogre::SceneManager* scene_mgr = renderer_.lock()->GetSceneManager();
node_->attachObject(entity_);
attached_ = true;
scene_mgr->getRootSceneNode()->addChild(node_);
node_->setVisible(true);
}
// Set orientation
Quaternion rot = rotationAttr.Get();
#if OGRE_VERSION_MINOR <= 6 && OGRE_VERSION_MAJOR <= 1
Ogre::Quaternion current_rot = node_->_getDerivedOrientation();
Ogre::Quaternion tmp(rot.w, rot.x, rot.y, rot.z);
Ogre::Quaternion rota = current_rot + tmp;
node_->setOrientation(rota);
#else
node_->_setDerivedOrientation(Ogre::Quaternion(rot.w, rot.x, rot.y, rot.z));
#endif
}
void EC_WaterPlane::ChangeWaterPlane(IAttribute* attribute)
{
std::string name = attribute->GetNameString();
if ( ( name == xSizeAttr.GetNameString()
|| name == ySizeAttr.GetNameString()
|| name == scaleUfactorAttr.GetNameString()
|| name == scaleVfactorAttr.GetNameString() ) &&
( lastXsize_ != xSizeAttr.Get() || lastYsize_ != ySizeAttr.Get() ) )
{
RemoveWaterPlane();
CreateWaterPlane();
lastXsize_ = xSizeAttr.Get();
lastYsize_ = ySizeAttr.Get();
}
else if ( name == xSegmentsAttr.GetNameString() || name == ySegmentsAttr.GetNameString() )
{
RemoveWaterPlane();
CreateWaterPlane();
}
else if ( name == positionAttr.GetNameString() )
{
// Change position
SetPosition();
}
else if ( name == rotationAttr.GetNameString() )
{
// Change rotation
// Is there placeable component? If not use given rotation
//if ( dynamic_cast<EC_Placeable*>(FindPlaceable().get()) == 0 )
//{
SetOrientation();
//}
}
else if ( name == depthAttr.GetNameString() )
{
// Change depth
// Currently do nothing..
}
else if ( name == materialNameAttr.GetNameString())
{
//Change material
if ( entity_ != 0)
{
entity_->setMaterialName(materialNameAttr.Get().toStdString().c_str());
}
}
/*
// Currently commented out, working feature but not enabled yet.
else if (name == textureNameAttr.GetNameString() )
{
QString currentMaterial = materialNameAttr.Get();
// Check that has texture really changed.
StringVector names;
Ogre::MaterialPtr materialPtr = Ogre::MaterialManager::getSingleton().getByName(currentMaterial.toStdString().c_str());
if ( materialPtr.get() == 0)
return;
OgreRenderer::GetTextureNamesFromMaterial(materialPtr, names);
QString textureName = textureNameAttr.Get();
for (StringVector::iterator iter = names.begin(); iter != names.end(); ++iter)
{
QString currentTextureName(iter->c_str());
if ( currentTextureName == textureName)
return;
}
// So texture has really changed, let's change it.
OgreRenderer::SetTextureUnitOnMaterial(materialPtr, textureName.toStdString(), 0);
}
*/
}
ComponentPtr EC_WaterPlane::FindPlaceable() const
{
assert(framework_);
ComponentPtr comp;
if(!GetParentEntity())
return comp;
comp = GetParentEntity()->GetComponent<EC_Placeable>();
return comp;
}
void EC_WaterPlane::AttachEntity()
{
EC_Placeable* placeable = dynamic_cast<EC_Placeable*>(FindPlaceable().get());
if ((!entity_) || (!placeable) || attached_)
return;
Ogre::SceneNode* node = placeable->GetSceneNode();
node->addChild(node_);
node_->attachObject(entity_);
attached_ = true;
}
void EC_WaterPlane::DetachEntity()
{
EC_Placeable* placeable = dynamic_cast<EC_Placeable*>(FindPlaceable().get());
if ((!attached_) || (!entity_) || (!placeable))
return;
Ogre::SceneNode* node = placeable->GetSceneNode();
node_->detachObject(entity_);
node->removeChild(node_);
attached_ = false;
}
}<|endoftext|> |
<commit_before>/*
The Jinx library is distributed under the MIT License (MIT)
https://opensource.org/licenses/MIT
See LICENSE.TXT or Jinx.h for license details.
Copyright (c) 2016 James Boer
*/
#include "UnitTest.h"
using namespace Jinx;
TEST_CASE("Test Collections", "[Collections]")
{
SECTION("Test create empty collection")
{
static const char * scriptText =
u8R"(
-- Create empty collection
a is []
)";
auto script = TestExecuteScript(scriptText);
REQUIRE(script);
REQUIRE(script->GetVariable("a").IsCollection());
}
SECTION("Test collection initialization list")
{
static const char * scriptText =
u8R"(
-- Create collection using an initialization list
a is 3, 2, 1
)";
auto script = TestExecuteScript(scriptText);
REQUIRE(script);
REQUIRE(script->GetVariable("a").IsCollection());
auto collection = script->GetVariable("a").GetCollection();
REQUIRE(collection);
REQUIRE(collection->size() == 3);
REQUIRE(collection->find(1) != collection->end());
REQUIRE(collection->find(1)->second.GetInteger() == 3);
REQUIRE(collection->find(2) != collection->end());
REQUIRE(collection->find(2)->second.GetInteger() == 2);
REQUIRE(collection->find(3) != collection->end());
REQUIRE(collection->find(3)->second.GetInteger() == 1);
}
SECTION("Test collection initialization list of key-value pairs")
{
static const char * scriptText =
u8R"(
-- Create collection using an initialization list of key-value pairs
a is [1, "red"], [2, "green"], [3, "blue"]
)";
auto script = TestExecuteScript(scriptText);
REQUIRE(script);
REQUIRE(script->GetVariable("a").IsCollection());
auto collection = script->GetVariable("a").GetCollection();
REQUIRE(collection);
REQUIRE(collection->size() == 3);
REQUIRE(collection->find(1) != collection->end());
REQUIRE(collection->find(1)->second.GetString() == "red");
REQUIRE(collection->find(2) != collection->end());
REQUIRE(collection->find(2)->second.GetString() == "green");
REQUIRE(collection->find(3) != collection->end());
REQUIRE(collection->find(3)->second.GetString() == "blue");
}
SECTION("Test assignment of collection element by index operator for variable")
{
static const char * scriptText =
u8R"(
-- Create collection using an initialization list of key-value pairs
a is [1, "red"], [2, "green"], [3, "blue"]
-- Change one of the elements by index
a[2] is "magenta"
)";
auto script = TestExecuteScript(scriptText);
REQUIRE(script);
REQUIRE(script->GetVariable("a").IsCollection());
auto collection = script->GetVariable("a").GetCollection();
REQUIRE(collection);
REQUIRE(collection->size() == 3);
REQUIRE(collection->find(2) != collection->end());
REQUIRE(collection->find(2)->second.GetString() == "magenta");
}
SECTION("Test assignment of collection element by index operator for property")
{
static const char * scriptText =
u8R"(
-- Create collection using an initialization list of key-value pairs
private a is [1, "red"], [2, "green"], [3, "blue"]
-- Change one of the elements by index
a[2] is "magenta"
)";
auto script = TestExecuteScript(scriptText);
REQUIRE(script);
auto library = script->GetLibrary();
REQUIRE(library);
REQUIRE(library->GetProperty("a").IsCollection());
auto collection = library->GetProperty("a").GetCollection();
REQUIRE(collection);
REQUIRE(collection->size() == 3);
REQUIRE(collection->find(2) != collection->end());
REQUIRE(collection->find(2)->second.GetString() == "magenta");
}
SECTION("Test assignment of collection variable by key")
{
static const char * scriptText =
u8R"(
-- Create collection using an initialization list of key-value pairs
a is [1, "red"], [2, "green"], [3, "blue"]
-- Set variable to one of the collection values
b is a[2]
)";
auto script = TestExecuteScript(scriptText);
REQUIRE(script);
REQUIRE(script->GetVariable("b").GetString() == "green");
}
SECTION("Test assignment of collection property by key")
{
static const char * scriptText =
u8R"(
-- Create collection using an initialization list of key-value pairs
private a is [1, "red"], [2, "green"], [3, "blue"]
-- Set variable to one of the collection values
b is a[2]
)";
auto script = TestExecuteScript(scriptText);
REQUIRE(script);
REQUIRE(script->GetVariable("b").GetString() == "green");
}
SECTION("Test adding auto-indexed value to existing collection")
{
static const char * scriptText =
u8R"(
import core
-- Create collection using an initialization list of key-value pairs
a is [1, "red"], [2, "green"], [3, "blue"]
-- Add single element to a
add "purple" to a
)";
auto script = TestExecuteScript(scriptText);
REQUIRE(script);
REQUIRE(script->GetVariable("a").IsCollection());
auto collection = script->GetVariable("a").GetCollection();
REQUIRE(collection);
REQUIRE(collection->size() == 4);
REQUIRE(collection->find(4) != collection->end());
REQUIRE(collection->find(4)->second.GetString() == "purple");
}
SECTION("Test adding collection to existing collection")
{
static const char * scriptText =
u8R"(
import core
-- Create collection using an initialization list of key-value pairs
a is [1, "red"], [2, "green"], [3, "blue"]
-- Set variable to one of the collection values
b is [4, "purple"]
-- Add elements in b to a
add b to a
)";
auto script = TestExecuteScript(scriptText);
REQUIRE(script);
REQUIRE(script->GetVariable("a").IsCollection());
auto collection = script->GetVariable("a").GetCollection();
REQUIRE(collection);
REQUIRE(collection->size() == 4);
REQUIRE(collection->find(4) != collection->end());
REQUIRE(collection->find(4)->second.GetString() == "purple");
}
SECTION("Test erasing single element from collection")
{
static const char * scriptText =
u8R"(
import core
-- Create collection using an initialization list of key-value pairs
a is [1, "red"], [2, "green"], [3, "blue"]
-- Remove element by key
remove 2 from a
)";
auto script = TestExecuteScript(scriptText);
REQUIRE(script);
REQUIRE(script->GetVariable("a").IsCollection());
auto collection = script->GetVariable("a").GetCollection();
REQUIRE(collection);
REQUIRE(collection->size() == 2);
REQUIRE(collection->find(2) == collection->end());
}
SECTION("Test erasing multiple elements from collection")
{
static const char * scriptText =
u8R"(
import core
-- Create collection using an initialization list of key-value pairs
a is [1, "red"], [2, "green"], [3, "blue"]
-- Remove elements by key
remove (1, 2) from a
)";
auto script = TestExecuteScript(scriptText);
REQUIRE(script);
REQUIRE(script->GetVariable("a").IsCollection());
auto collection = script->GetVariable("a").GetCollection();
REQUIRE(collection);
REQUIRE(collection->size() == 1);
REQUIRE(collection->find(1) == collection->end());
REQUIRE(collection->find(2) == collection->end());
}
SECTION("Test erasing single element by value from collection")
{
static const char * scriptText =
u8R"(
import core
-- Create collection using an initialization list of key-value pairs
a is [1, "red"], [2, "green"], [3, "blue"]
-- Remove element by value
remove value "red" from a
)";
auto script = TestExecuteScript(scriptText);
REQUIRE(script);
REQUIRE(script->GetVariable("a").IsCollection());
auto collection = script->GetVariable("a").GetCollection();
REQUIRE(collection);
REQUIRE(collection->size() == 2);
REQUIRE(collection->find(1) == collection->end());
}
SECTION("Test erasing multiple elements by value from collection")
{
static const char * scriptText =
u8R"(
import core
-- Create collection using an initialization list of key-value pairs
a is [1, "red"], [2, "green"], [3, "blue"]
-- Remove multiple elements by value
remove values ("red", "green") from a
)";
auto script = TestExecuteScript(scriptText);
REQUIRE(script);
REQUIRE(script->GetVariable("a").IsCollection());
auto collection = script->GetVariable("a").GetCollection();
REQUIRE(collection);
REQUIRE(collection->size() == 1);
REQUIRE(collection->find(1) == collection->end());
REQUIRE(collection->find(2) == collection->end());
}
}<commit_msg>Add collection test case<commit_after>/*
The Jinx library is distributed under the MIT License (MIT)
https://opensource.org/licenses/MIT
See LICENSE.TXT or Jinx.h for license details.
Copyright (c) 2016 James Boer
*/
#include "UnitTest.h"
using namespace Jinx;
TEST_CASE("Test Collections", "[Collections]")
{
SECTION("Test create empty collection")
{
static const char * scriptText =
u8R"(
-- Create empty collection
a is []
)";
auto script = TestExecuteScript(scriptText);
REQUIRE(script);
REQUIRE(script->GetVariable("a").IsCollection());
}
SECTION("Test collection initialization list")
{
static const char * scriptText =
u8R"(
-- Create collection using an initialization list
a is 3, 2, 1
)";
auto script = TestExecuteScript(scriptText);
REQUIRE(script);
REQUIRE(script->GetVariable("a").IsCollection());
auto collection = script->GetVariable("a").GetCollection();
REQUIRE(collection);
REQUIRE(collection->size() == 3);
REQUIRE(collection->find(1) != collection->end());
REQUIRE(collection->find(1)->second.GetInteger() == 3);
REQUIRE(collection->find(2) != collection->end());
REQUIRE(collection->find(2)->second.GetInteger() == 2);
REQUIRE(collection->find(3) != collection->end());
REQUIRE(collection->find(3)->second.GetInteger() == 1);
}
SECTION("Test collection addition of elements using assignment")
{
static const char * scriptText =
u8R"(
-- Create empty collection and add three elements
a is []
a [1] is 3
a [2] is 2
a [3] is 1
)";
auto script = TestExecuteScript(scriptText);
REQUIRE(script);
REQUIRE(script->GetVariable("a").IsCollection());
auto collection = script->GetVariable("a").GetCollection();
REQUIRE(collection);
REQUIRE(collection->size() == 3);
REQUIRE(collection->find(1) != collection->end());
REQUIRE(collection->find(1)->second.GetInteger() == 3);
REQUIRE(collection->find(2) != collection->end());
REQUIRE(collection->find(2)->second.GetInteger() == 2);
REQUIRE(collection->find(3) != collection->end());
REQUIRE(collection->find(3)->second.GetInteger() == 1);
}
SECTION("Test collection initialization list of key-value pairs")
{
static const char * scriptText =
u8R"(
-- Create collection using an initialization list of key-value pairs
a is [1, "red"], [2, "green"], [3, "blue"]
)";
auto script = TestExecuteScript(scriptText);
REQUIRE(script);
REQUIRE(script->GetVariable("a").IsCollection());
auto collection = script->GetVariable("a").GetCollection();
REQUIRE(collection);
REQUIRE(collection->size() == 3);
REQUIRE(collection->find(1) != collection->end());
REQUIRE(collection->find(1)->second.GetString() == "red");
REQUIRE(collection->find(2) != collection->end());
REQUIRE(collection->find(2)->second.GetString() == "green");
REQUIRE(collection->find(3) != collection->end());
REQUIRE(collection->find(3)->second.GetString() == "blue");
}
SECTION("Test assignment of collection element by index operator for variable")
{
static const char * scriptText =
u8R"(
-- Create collection using an initialization list of key-value pairs
a is [1, "red"], [2, "green"], [3, "blue"]
-- Change one of the elements by index
a[2] is "magenta"
)";
auto script = TestExecuteScript(scriptText);
REQUIRE(script);
REQUIRE(script->GetVariable("a").IsCollection());
auto collection = script->GetVariable("a").GetCollection();
REQUIRE(collection);
REQUIRE(collection->size() == 3);
REQUIRE(collection->find(2) != collection->end());
REQUIRE(collection->find(2)->second.GetString() == "magenta");
}
SECTION("Test assignment of collection element by index operator for property")
{
static const char * scriptText =
u8R"(
-- Create collection using an initialization list of key-value pairs
private a is [1, "red"], [2, "green"], [3, "blue"]
-- Change one of the elements by index
a[2] is "magenta"
)";
auto script = TestExecuteScript(scriptText);
REQUIRE(script);
auto library = script->GetLibrary();
REQUIRE(library);
REQUIRE(library->GetProperty("a").IsCollection());
auto collection = library->GetProperty("a").GetCollection();
REQUIRE(collection);
REQUIRE(collection->size() == 3);
REQUIRE(collection->find(2) != collection->end());
REQUIRE(collection->find(2)->second.GetString() == "magenta");
}
SECTION("Test assignment of collection variable by key")
{
static const char * scriptText =
u8R"(
-- Create collection using an initialization list of key-value pairs
a is [1, "red"], [2, "green"], [3, "blue"]
-- Set variable to one of the collection values
b is a[2]
)";
auto script = TestExecuteScript(scriptText);
REQUIRE(script);
REQUIRE(script->GetVariable("b").GetString() == "green");
}
SECTION("Test assignment of collection property by key")
{
static const char * scriptText =
u8R"(
-- Create collection using an initialization list of key-value pairs
private a is [1, "red"], [2, "green"], [3, "blue"]
-- Set variable to one of the collection values
b is a[2]
)";
auto script = TestExecuteScript(scriptText);
REQUIRE(script);
REQUIRE(script->GetVariable("b").GetString() == "green");
}
SECTION("Test adding auto-indexed value to existing collection")
{
static const char * scriptText =
u8R"(
import core
-- Create collection using an initialization list of key-value pairs
a is [1, "red"], [2, "green"], [3, "blue"]
-- Add single element to a
add "purple" to a
)";
auto script = TestExecuteScript(scriptText);
REQUIRE(script);
REQUIRE(script->GetVariable("a").IsCollection());
auto collection = script->GetVariable("a").GetCollection();
REQUIRE(collection);
REQUIRE(collection->size() == 4);
REQUIRE(collection->find(4) != collection->end());
REQUIRE(collection->find(4)->second.GetString() == "purple");
}
SECTION("Test adding collection to existing collection")
{
static const char * scriptText =
u8R"(
import core
-- Create collection using an initialization list of key-value pairs
a is [1, "red"], [2, "green"], [3, "blue"]
-- Set variable to one of the collection values
b is [4, "purple"]
-- Add elements in b to a
add b to a
)";
auto script = TestExecuteScript(scriptText);
REQUIRE(script);
REQUIRE(script->GetVariable("a").IsCollection());
auto collection = script->GetVariable("a").GetCollection();
REQUIRE(collection);
REQUIRE(collection->size() == 4);
REQUIRE(collection->find(4) != collection->end());
REQUIRE(collection->find(4)->second.GetString() == "purple");
}
SECTION("Test erasing single element from collection")
{
static const char * scriptText =
u8R"(
import core
-- Create collection using an initialization list of key-value pairs
a is [1, "red"], [2, "green"], [3, "blue"]
-- Remove element by key
remove 2 from a
)";
auto script = TestExecuteScript(scriptText);
REQUIRE(script);
REQUIRE(script->GetVariable("a").IsCollection());
auto collection = script->GetVariable("a").GetCollection();
REQUIRE(collection);
REQUIRE(collection->size() == 2);
REQUIRE(collection->find(2) == collection->end());
}
SECTION("Test erasing multiple elements from collection")
{
static const char * scriptText =
u8R"(
import core
-- Create collection using an initialization list of key-value pairs
a is [1, "red"], [2, "green"], [3, "blue"]
-- Remove elements by key
remove (1, 2) from a
)";
auto script = TestExecuteScript(scriptText);
REQUIRE(script);
REQUIRE(script->GetVariable("a").IsCollection());
auto collection = script->GetVariable("a").GetCollection();
REQUIRE(collection);
REQUIRE(collection->size() == 1);
REQUIRE(collection->find(1) == collection->end());
REQUIRE(collection->find(2) == collection->end());
}
SECTION("Test erasing single element by value from collection")
{
static const char * scriptText =
u8R"(
import core
-- Create collection using an initialization list of key-value pairs
a is [1, "red"], [2, "green"], [3, "blue"]
-- Remove element by value
remove value "red" from a
)";
auto script = TestExecuteScript(scriptText);
REQUIRE(script);
REQUIRE(script->GetVariable("a").IsCollection());
auto collection = script->GetVariable("a").GetCollection();
REQUIRE(collection);
REQUIRE(collection->size() == 2);
REQUIRE(collection->find(1) == collection->end());
}
SECTION("Test erasing multiple elements by value from collection")
{
static const char * scriptText =
u8R"(
import core
-- Create collection using an initialization list of key-value pairs
a is [1, "red"], [2, "green"], [3, "blue"]
-- Remove multiple elements by value
remove values ("red", "green") from a
)";
auto script = TestExecuteScript(scriptText);
REQUIRE(script);
REQUIRE(script->GetVariable("a").IsCollection());
auto collection = script->GetVariable("a").GetCollection();
REQUIRE(collection);
REQUIRE(collection->size() == 1);
REQUIRE(collection->find(1) == collection->end());
REQUIRE(collection->find(2) == collection->end());
}
}<|endoftext|> |
<commit_before>// Copyright 2010-2012 RethinkDB, all rights reserved.
#ifndef CLUSTERING_ADMINISTRATION_MAIN_SERVE_HPP_
#define CLUSTERING_ADMINISTRATION_MAIN_SERVE_HPP_
#include <set>
#include <string>
#include "clustering/administration/metadata.hpp"
#include "clustering/administration/persist.hpp"
#include "extproc/spawner.hpp"
struct service_ports_t {
service_ports_t(int _port, int _client_port, int _http_port, int _reql_port, int _port_offset)
: port(_port), client_port(_client_port), http_port(_http_port), reql_port(_reql_port), port_offset(_port_offset)
{ }
int port;
int client_port;
int http_port;
int reql_port;
int port_offset;
};
/* This has been factored out from `command_line.hpp` because it takes a very
long time to compile. */
bool serve(extproc::spawner_t::info_t *spawner_info, io_backender_t *io_backender, const std::string &filepath, metadata_persistence::persistent_file_t *persistent_file, const peer_address_set_t &joins, service_ports_t ports, machine_id_t machine_id, const cluster_semilattice_metadata_t &semilattice_metadata, std::string web_assets, signal_t *stop_cond);
bool serve_proxy(extproc::spawner_t::info_t *spawner_info, const peer_address_set_t &joins, service_ports_t ports, machine_id_t machine_id, const cluster_semilattice_metadata_t &semilattice_metadata, std::string web_assets, signal_t *stop_cond);
#endif /* CLUSTERING_ADMINISTRATION_MAIN_SERVE_HPP_ */
<commit_msg>Adds santization for ports.<commit_after>// Copyright 2010-2012 RethinkDB, all rights reserved.
#ifndef CLUSTERING_ADMINISTRATION_MAIN_SERVE_HPP_
#define CLUSTERING_ADMINISTRATION_MAIN_SERVE_HPP_
#include <set>
#include <string>
#include "clustering/administration/metadata.hpp"
#include "clustering/administration/persist.hpp"
#include "extproc/spawner.hpp"
#define MAX_PORT 65536
inline void sanitize_port(int port, const char *name, int port_offset) {
if (port >= MAX_PORT) {
if (port_offset == 0) {
nice_crash("%s has a value (%d) above the maximum allowed port (%d).", name, port, MAX_PORT);
} else {
nice_crash("%s has a value (%d) above the maximum allowed port (%d). Note port_offset is set to %d which may cause this error.", name, port, MAX_PORT, port_offset);
}
}
}
struct service_ports_t {
service_ports_t(int _port, int _client_port, int _http_port, int _reql_port, int _port_offset)
: port(_port), client_port(_client_port), http_port(_http_port), reql_port(_reql_port), port_offset(_port_offset)
{
sanitize_port(port, "port", port_offset);
sanitize_port(client_port, "client_port", port_offset);
sanitize_port(http_port, "http_port", port_offset);
sanitize_port(reql_port, "reql_port", port_offset);
}
int port;
int client_port;
int http_port;
int reql_port;
int port_offset;
};
/* This has been factored out from `command_line.hpp` because it takes a very
long time to compile. */
bool serve(extproc::spawner_t::info_t *spawner_info, io_backender_t *io_backender, const std::string &filepath, metadata_persistence::persistent_file_t *persistent_file, const peer_address_set_t &joins, service_ports_t ports, machine_id_t machine_id, const cluster_semilattice_metadata_t &semilattice_metadata, std::string web_assets, signal_t *stop_cond);
bool serve_proxy(extproc::spawner_t::info_t *spawner_info, const peer_address_set_t &joins, service_ports_t ports, machine_id_t machine_id, const cluster_semilattice_metadata_t &semilattice_metadata, std::string web_assets, signal_t *stop_cond);
#endif /* CLUSTERING_ADMINISTRATION_MAIN_SERVE_HPP_ */
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2014 The Android Open Source Project
*
* 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 <fstream>
#include "base/stringprintf.h"
#include "builder.h"
#include "dex_file.h"
#include "dex_instruction.h"
#include "graph_visualizer.h"
#include "nodes.h"
#include "optimizing_unit_test.h"
#include "pretty_printer.h"
#include "ssa_builder.h"
#include "ssa_liveness_analysis.h"
#include "utils/arena_allocator.h"
#include "gtest/gtest.h"
namespace art {
static void TestCode(const uint16_t* data, const int* expected_order, size_t number_of_blocks) {
ArenaPool pool;
ArenaAllocator allocator(&pool);
HGraphBuilder builder(&allocator);
const DexFile::CodeItem* item = reinterpret_cast<const DexFile::CodeItem*>(data);
HGraph* graph = builder.BuildGraph(*item);
ASSERT_NE(graph, nullptr);
graph->BuildDominatorTree();
graph->FindNaturalLoops();
SsaLivenessAnalysis liveness(*graph);
liveness.Analyze();
ASSERT_EQ(liveness.GetLinearPostOrder().Size(), number_of_blocks);
for (size_t i = 0; i < number_of_blocks; ++i) {
ASSERT_EQ(liveness.GetLinearPostOrder().Get(number_of_blocks - i - 1)->GetBlockId(),
expected_order[i]);
}
}
TEST(LinearizeTest, CFG1) {
// Structure of this graph (* are back edges)
// Block0
// |
// Block1
// |
// Block2 ******
// / \ *
// Block5 Block7 *
// | | *
// Block6 Block3 *
// * / \ *
// Block4 Block8
const uint16_t data[] = ONE_REGISTER_CODE_ITEM(
Instruction::CONST_4 | 0 | 0,
Instruction::IF_EQ, 5,
Instruction::IF_EQ, 0xFFFE,
Instruction::GOTO | 0xFE00,
Instruction::RETURN_VOID);
const int blocks[] = {0, 1, 2, 7, 3, 4, 8, 5, 6};
TestCode(data, blocks, 9);
}
TEST(LinearizeTest, CFG2) {
// Structure of this graph (* are back edges)
// Block0
// |
// Block1
// |
// Block2 ******
// / \ *
// Block3 Block7 *
// | | *
// Block6 Block4 *
// * / \ *
// Block5 Block8
const uint16_t data[] = ONE_REGISTER_CODE_ITEM(
Instruction::CONST_4 | 0 | 0,
Instruction::IF_EQ, 3,
Instruction::RETURN_VOID,
Instruction::IF_EQ, 0xFFFD,
Instruction::GOTO | 0xFE00);
const int blocks[] = {0, 1, 2, 7, 4, 5, 8, 3, 6};
TestCode(data, blocks, 9);
}
TEST(LinearizeTest, CFG3) {
// Structure of this graph (* are back edges)
// Block0
// |
// Block1
// |
// Block2 ******
// / \ *
// Block3 Block8 *
// | | *
// Block7 Block5 *
// / * \ *
// Block6 * Block9
// | *
// Block4 **
const uint16_t data[] = ONE_REGISTER_CODE_ITEM(
Instruction::CONST_4 | 0 | 0,
Instruction::IF_EQ, 4,
Instruction::RETURN_VOID,
Instruction::GOTO | 0x0100,
Instruction::IF_EQ, 0xFFFC,
Instruction::GOTO | 0xFD00);
const int blocks[] = {0, 1, 2, 8, 5, 6, 4, 9, 3, 7};
TestCode(data, blocks, 10);
}
TEST(LinearizeTest, CFG4) {
// Structure of this graph (* are back edges)
// Block0
// |
// Block1
// |
// Block2
// / * \
// Block6 * Block8
// | * |
// Block7 * Block3 *******
// * / \ *
// Block9 Block10 *
// | *
// Block4 *
// */ \ *
// Block5 Block11
const uint16_t data[] = ONE_REGISTER_CODE_ITEM(
Instruction::CONST_4 | 0 | 0,
Instruction::IF_EQ, 7,
Instruction::IF_EQ, 0xFFFE,
Instruction::IF_EQ, 0xFFFE,
Instruction::GOTO | 0xFE00,
Instruction::RETURN_VOID);
const int blocks[] = {0, 1, 2, 8, 3, 10, 4, 5, 11, 9, 6, 7};
TestCode(data, blocks, 12);
}
TEST(LinearizeTest, CFG5) {
// Structure of this graph (* are back edges)
// Block0
// |
// Block1
// |
// Block2
// / * \
// Block3 * Block8
// | * |
// Block7 * Block4 *******
// * / \ *
// Block9 Block10 *
// | *
// Block5 *
// */ \ *
// Block6 Block11
const uint16_t data[] = ONE_REGISTER_CODE_ITEM(
Instruction::CONST_4 | 0 | 0,
Instruction::IF_EQ, 3,
Instruction::RETURN_VOID,
Instruction::IF_EQ, 0xFFFD,
Instruction::IF_EQ, 0xFFFE,
Instruction::GOTO | 0xFE00);
const int blocks[] = {0, 1, 2, 8, 4, 10, 5, 6, 11, 9, 3, 7};
TestCode(data, blocks, 12);
}
} // namespace art
<commit_msg>am c006db38: Merge "Workaround for multi-line comment error when compiled with g++."<commit_after>/*
* Copyright (C) 2014 The Android Open Source Project
*
* 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 <fstream>
#include "base/stringprintf.h"
#include "builder.h"
#include "dex_file.h"
#include "dex_instruction.h"
#include "graph_visualizer.h"
#include "nodes.h"
#include "optimizing_unit_test.h"
#include "pretty_printer.h"
#include "ssa_builder.h"
#include "ssa_liveness_analysis.h"
#include "utils/arena_allocator.h"
#include "gtest/gtest.h"
namespace art {
static void TestCode(const uint16_t* data, const int* expected_order, size_t number_of_blocks) {
ArenaPool pool;
ArenaAllocator allocator(&pool);
HGraphBuilder builder(&allocator);
const DexFile::CodeItem* item = reinterpret_cast<const DexFile::CodeItem*>(data);
HGraph* graph = builder.BuildGraph(*item);
ASSERT_NE(graph, nullptr);
graph->BuildDominatorTree();
graph->FindNaturalLoops();
SsaLivenessAnalysis liveness(*graph);
liveness.Analyze();
ASSERT_EQ(liveness.GetLinearPostOrder().Size(), number_of_blocks);
for (size_t i = 0; i < number_of_blocks; ++i) {
ASSERT_EQ(liveness.GetLinearPostOrder().Get(number_of_blocks - i - 1)->GetBlockId(),
expected_order[i]);
}
}
TEST(LinearizeTest, CFG1) {
// Structure of this graph (+ are back edges)
// Block0
// |
// Block1
// |
// Block2 ++++++
// / \ +
// Block5 Block7 +
// | | +
// Block6 Block3 +
// + / \ +
// Block4 Block8
const uint16_t data[] = ONE_REGISTER_CODE_ITEM(
Instruction::CONST_4 | 0 | 0,
Instruction::IF_EQ, 5,
Instruction::IF_EQ, 0xFFFE,
Instruction::GOTO | 0xFE00,
Instruction::RETURN_VOID);
const int blocks[] = {0, 1, 2, 7, 3, 4, 8, 5, 6};
TestCode(data, blocks, 9);
}
TEST(LinearizeTest, CFG2) {
// Structure of this graph (+ are back edges)
// Block0
// |
// Block1
// |
// Block2 ++++++
// / \ +
// Block3 Block7 +
// | | +
// Block6 Block4 +
// + / \ +
// Block5 Block8
const uint16_t data[] = ONE_REGISTER_CODE_ITEM(
Instruction::CONST_4 | 0 | 0,
Instruction::IF_EQ, 3,
Instruction::RETURN_VOID,
Instruction::IF_EQ, 0xFFFD,
Instruction::GOTO | 0xFE00);
const int blocks[] = {0, 1, 2, 7, 4, 5, 8, 3, 6};
TestCode(data, blocks, 9);
}
TEST(LinearizeTest, CFG3) {
// Structure of this graph (+ are back edges)
// Block0
// |
// Block1
// |
// Block2 ++++++
// / \ +
// Block3 Block8 +
// | | +
// Block7 Block5 +
// / + \ +
// Block6 + Block9
// | +
// Block4 ++
const uint16_t data[] = ONE_REGISTER_CODE_ITEM(
Instruction::CONST_4 | 0 | 0,
Instruction::IF_EQ, 4,
Instruction::RETURN_VOID,
Instruction::GOTO | 0x0100,
Instruction::IF_EQ, 0xFFFC,
Instruction::GOTO | 0xFD00);
const int blocks[] = {0, 1, 2, 8, 5, 6, 4, 9, 3, 7};
TestCode(data, blocks, 10);
}
TEST(LinearizeTest, CFG4) {
/* Structure of this graph (+ are back edges)
// Block0
// |
// Block1
// |
// Block2
// / + \
// Block6 + Block8
// | + |
// Block7 + Block3 +++++++
// + / \ +
// Block9 Block10 +
// | +
// Block4 +
// + / \ +
// Block5 Block11
*/
const uint16_t data[] = ONE_REGISTER_CODE_ITEM(
Instruction::CONST_4 | 0 | 0,
Instruction::IF_EQ, 7,
Instruction::IF_EQ, 0xFFFE,
Instruction::IF_EQ, 0xFFFE,
Instruction::GOTO | 0xFE00,
Instruction::RETURN_VOID);
const int blocks[] = {0, 1, 2, 8, 3, 10, 4, 5, 11, 9, 6, 7};
TestCode(data, blocks, 12);
}
TEST(LinearizeTest, CFG5) {
/* Structure of this graph (+ are back edges)
// Block0
// |
// Block1
// |
// Block2
// / + \
// Block3 + Block8
// | + |
// Block7 + Block4 +++++++
// + / \ +
// Block9 Block10 +
// | +
// Block5 +
// +/ \ +
// Block6 Block11
*/
const uint16_t data[] = ONE_REGISTER_CODE_ITEM(
Instruction::CONST_4 | 0 | 0,
Instruction::IF_EQ, 3,
Instruction::RETURN_VOID,
Instruction::IF_EQ, 0xFFFD,
Instruction::IF_EQ, 0xFFFE,
Instruction::GOTO | 0xFE00);
const int blocks[] = {0, 1, 2, 8, 4, 10, 5, 6, 11, 9, 3, 7};
TestCode(data, blocks, 12);
}
} // namespace art
<|endoftext|> |
<commit_before>// -*- c++ -*-
/*=========================================================================
Program: Visualization Toolkit
Module: LoadOpenGLExtension.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/*
* Copyright 2004 Sandia Corporation.
* Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive
* license for use of this work by or on behalf of the
* U.S. Government. Redistribution and use in source and binary forms, with
* or without modification, are permitted provided that this Notice and any
* statement of authorship are reproduced on all copies.
*/
// This code test to make sure vtkOpenGLExtensionManager can properly get
// extension functions that can be used. To do this, we convolve an image
// with a kernel for a Laplacian filter. This requires the use of functions
// defined in OpenGL 1.2, which should be available pretty much everywhere
// but still has functions that can be loaded as extensions.
#include "vtkConeSource.h"
#include "vtkPolyDataMapper.h"
#include "vtkActor.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkCamera.h"
#include "vtkCallbackCommand.h"
#include "vtkUnsignedCharArray.h"
#include "vtkRegressionTestImage.h"
#include "vtkOpenGLExtensionManager.h"
#include "vtkgl.h"
vtkUnsignedCharArray *image;
GLfloat laplacian[3][3] = {
{ -0.125f, -0.125f, -0.125f },
{ -0.125f, 1.0f, -0.125f },
{ -0.125f, -0.125f, -0.125f }
};
static void ImageCallback(vtkObject *__renwin, unsigned long, void *, void *)
{
cout << "In ImageCallback" << endl;
vtkRenderWindow *renwin = static_cast<vtkRenderWindow *>(__renwin);
int *size = renwin->GetSize();
cout << "Turn on convolution." << endl;
glEnable(vtkgl::CONVOLUTION_2D);
cout << "Read back image." << endl;
renwin->GetRGBACharPixelData(0, 0, size[0]-1, size[1]-1, 0, image);
cout << "Turn off convolution." << endl;
glDisable(vtkgl::CONVOLUTION_2D);
cout << "Write image." << endl;
renwin->SetRGBACharPixelData(0, 0, size[0]-1, size[1]-1, image, 0);
cout << "Swap buffers." << endl;
renwin->SwapBuffersOn();
renwin->Frame();
renwin->SwapBuffersOff();
}
int LoadOpenGLExtension(int argc, char *argv[])
{
vtkRenderWindow *renwin = vtkRenderWindow::New();
renwin->SetSize(250, 250);
vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
renwin->SetInteractor(iren);
vtkOpenGLExtensionManager *extensions = vtkOpenGLExtensionManager::New();
extensions->SetRenderWindow(renwin);
cout << "Query extension." << endl;
if (!extensions->ExtensionSupported("GL_VERSION_1_2"))
{
cout << "Is it possible that your driver does not support OpenGL 1.2?"
<< endl << endl;;
int forceLoad = 0;
for (int i = 0; i < argc; i++)
{
if (strcmp("-ForceLoad", argv[i]) == 0)
{
forceLoad = 1;
break;
}
}
if (forceLoad)
{
cout << "Some drivers report supporting only GL 1.1 even though they\n"
<< "actually support 1.2 (and probably higher). I'm going to\n"
<< "try to load the extension anyway. You will definitely get\n"
<< "a warning from vtkOpenGLExtensionManager about it. If GL 1.2\n"
<< "really is not supported (or something else is wrong), I will\n"
<< "seg fault." << endl << endl;
}
else
{
cout << "Your OpenGL driver reports that it does not support\n"
<< "OpenGL 1.2. If this is true, I cannot perform this test.\n"
<< "There are a few drivers that report only supporting GL 1.1\n"
<< "when they in fact actually support 1.2 (and probably higher).\n"
<< "If you think this might be the case, try rerunning this test\n"
<< "with the -ForceLoad flag. However, if Opengl 1.2 is really\n"
<< "not supported, a seg fault will occur." << endl;
renwin->Delete();
iren->Delete();
extensions->Delete();
return 0;
}
}
cout << "Load extension." << endl;
extensions->LoadExtension("GL_VERSION_1_2");
extensions->Delete();
cout << "Set up pipeline." << endl;
vtkConeSource *cone = vtkConeSource::New();
vtkPolyDataMapper *mapper = vtkPolyDataMapper::New();
mapper->SetInput(cone->GetOutput());
vtkActor *actor = vtkActor::New();
actor->SetMapper(mapper);
vtkRenderer *renderer = vtkRenderer::New();
renderer->AddActor(actor);
renwin->AddRenderer(renderer);
vtkCamera *camera = renderer->GetActiveCamera();
camera->Elevation(-45);
cout << "Do a render without convolution." << endl;
renwin->Render();
// Set up a convolution filter. We are using the Laplacian filter, which
// is basically an edge detector. Once vtkgl::CONVOLUTION_2D is enabled,
// the filter will be applied any time an image is transfered in the
// pipeline.
cout << "Set up convolution filter." << endl;
vtkgl::ConvolutionFilter2D(vtkgl::CONVOLUTION_2D, GL_LUMINANCE, 3, 3,
GL_LUMINANCE, GL_FLOAT, laplacian);
vtkgl::ConvolutionParameteri(vtkgl::CONVOLUTION_2D,
vtkgl::CONVOLUTION_BORDER_MODE,
vtkgl::REPLICATE_BORDER);
image = vtkUnsignedCharArray::New();
vtkCallbackCommand *cbc = vtkCallbackCommand::New();
cbc->SetCallback(ImageCallback);
renwin->AddObserver(vtkCommand::EndEvent, cbc);
cbc->Delete();
// This is a bit of a hack. The EndEvent on the render window will swap
// the buffers.
renwin->SwapBuffersOff();
cout << "Do test render with convolution on." << endl;
renwin->Render();
int retVal = vtkRegressionTestImage(renwin);
if (retVal == vtkRegressionTester::DO_INTERACTOR)
{
iren->Start();
}
cone->Delete();
mapper->Delete();
actor->Delete();
renderer->Delete();
renwin->Delete();
iren->Delete();
image->Delete();
return !retVal;
}
<commit_msg>ENH: Check for recursive end render callbacks.<commit_after>// -*- c++ -*-
/*=========================================================================
Program: Visualization Toolkit
Module: LoadOpenGLExtension.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/*
* Copyright 2004 Sandia Corporation.
* Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive
* license for use of this work by or on behalf of the
* U.S. Government. Redistribution and use in source and binary forms, with
* or without modification, are permitted provided that this Notice and any
* statement of authorship are reproduced on all copies.
*/
// This code test to make sure vtkOpenGLExtensionManager can properly get
// extension functions that can be used. To do this, we convolve an image
// with a kernel for a Laplacian filter. This requires the use of functions
// defined in OpenGL 1.2, which should be available pretty much everywhere
// but still has functions that can be loaded as extensions.
#include "vtkConeSource.h"
#include "vtkPolyDataMapper.h"
#include "vtkActor.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkCamera.h"
#include "vtkCallbackCommand.h"
#include "vtkUnsignedCharArray.h"
#include "vtkRegressionTestImage.h"
#include "vtkOpenGLExtensionManager.h"
#include "vtkgl.h"
vtkUnsignedCharArray *image;
GLfloat laplacian[3][3] = {
{ -0.125f, -0.125f, -0.125f },
{ -0.125f, 1.0f, -0.125f },
{ -0.125f, -0.125f, -0.125f }
};
static void ImageCallback(vtkObject *__renwin, unsigned long, void *, void *)
{
static int inImageCallback = 0;
if (inImageCallback)
{
cout << "*********ImageCallback called recursively?" << endl;
return;
}
inImageCallback = 1;
cout << "In ImageCallback" << endl;
vtkRenderWindow *renwin = static_cast<vtkRenderWindow *>(__renwin);
int *size = renwin->GetSize();
cout << "Turn on convolution." << endl;
glEnable(vtkgl::CONVOLUTION_2D);
cout << "Read back image." << endl;
renwin->GetRGBACharPixelData(0, 0, size[0]-1, size[1]-1, 0, image);
cout << "Turn off convolution." << endl;
glDisable(vtkgl::CONVOLUTION_2D);
cout << "Write image." << endl;
renwin->SetRGBACharPixelData(0, 0, size[0]-1, size[1]-1, image, 0);
cout << "Swap buffers." << endl;
renwin->SwapBuffersOn();
renwin->Frame();
renwin->SwapBuffersOff();
inImageCallback = 0;
}
int LoadOpenGLExtension(int argc, char *argv[])
{
vtkRenderWindow *renwin = vtkRenderWindow::New();
renwin->SetSize(250, 250);
vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
renwin->SetInteractor(iren);
vtkOpenGLExtensionManager *extensions = vtkOpenGLExtensionManager::New();
extensions->SetRenderWindow(renwin);
cout << "Query extension." << endl;
if (!extensions->ExtensionSupported("GL_VERSION_1_2"))
{
cout << "Is it possible that your driver does not support OpenGL 1.2?"
<< endl << endl;;
int forceLoad = 0;
for (int i = 0; i < argc; i++)
{
if (strcmp("-ForceLoad", argv[i]) == 0)
{
forceLoad = 1;
break;
}
}
if (forceLoad)
{
cout << "Some drivers report supporting only GL 1.1 even though they\n"
<< "actually support 1.2 (and probably higher). I'm going to\n"
<< "try to load the extension anyway. You will definitely get\n"
<< "a warning from vtkOpenGLExtensionManager about it. If GL 1.2\n"
<< "really is not supported (or something else is wrong), I will\n"
<< "seg fault." << endl << endl;
}
else
{
cout << "Your OpenGL driver reports that it does not support\n"
<< "OpenGL 1.2. If this is true, I cannot perform this test.\n"
<< "There are a few drivers that report only supporting GL 1.1\n"
<< "when they in fact actually support 1.2 (and probably higher).\n"
<< "If you think this might be the case, try rerunning this test\n"
<< "with the -ForceLoad flag. However, if Opengl 1.2 is really\n"
<< "not supported, a seg fault will occur." << endl;
renwin->Delete();
iren->Delete();
extensions->Delete();
return 0;
}
}
cout << "Load extension." << endl;
extensions->LoadExtension("GL_VERSION_1_2");
extensions->Delete();
cout << "Set up pipeline." << endl;
vtkConeSource *cone = vtkConeSource::New();
vtkPolyDataMapper *mapper = vtkPolyDataMapper::New();
mapper->SetInput(cone->GetOutput());
vtkActor *actor = vtkActor::New();
actor->SetMapper(mapper);
vtkRenderer *renderer = vtkRenderer::New();
renderer->AddActor(actor);
renwin->AddRenderer(renderer);
vtkCamera *camera = renderer->GetActiveCamera();
camera->Elevation(-45);
cout << "Do a render without convolution." << endl;
renwin->Render();
// Set up a convolution filter. We are using the Laplacian filter, which
// is basically an edge detector. Once vtkgl::CONVOLUTION_2D is enabled,
// the filter will be applied any time an image is transfered in the
// pipeline.
cout << "Set up convolution filter." << endl;
vtkgl::ConvolutionFilter2D(vtkgl::CONVOLUTION_2D, GL_LUMINANCE, 3, 3,
GL_LUMINANCE, GL_FLOAT, laplacian);
vtkgl::ConvolutionParameteri(vtkgl::CONVOLUTION_2D,
vtkgl::CONVOLUTION_BORDER_MODE,
vtkgl::REPLICATE_BORDER);
image = vtkUnsignedCharArray::New();
vtkCallbackCommand *cbc = vtkCallbackCommand::New();
cbc->SetCallback(ImageCallback);
renwin->AddObserver(vtkCommand::EndEvent, cbc);
cbc->Delete();
// This is a bit of a hack. The EndEvent on the render window will swap
// the buffers.
renwin->SwapBuffersOff();
cout << "Do test render with convolution on." << endl;
renwin->Render();
int retVal = vtkRegressionTestImage(renwin);
if (retVal == vtkRegressionTester::DO_INTERACTOR)
{
iren->Start();
}
cone->Delete();
mapper->Delete();
actor->Delete();
renderer->Delete();
renwin->Delete();
iren->Delete();
image->Delete();
return !retVal;
}
<|endoftext|> |
<commit_before>/*!
* @file CurvatureFlow.cpp
* @brief Implementation of a curvature flow algorithm
*/
#include "CurvatureFlow.h"
#include <boost/numeric/bindings/traits/ublas_vector.hpp>
#include <boost/numeric/bindings/traits/ublas_sparse.hpp>
#include <boost/numeric/bindings/umfpack/umfpack.hpp>
namespace psalm
{
/*!
* Sets default values
*/
CurvatureFlow::CurvatureFlow()
{
num_steps = 0;
dt = 0.5;
}
/*!
* Applies the curvature flow algorithm to the vertices of a given mesh.
* The size of timesteps needs to be set before. The input mesh is
* irreversibly changed by this operation.
*
* @param input_mesh Mesh on which the algorithm works.
* @return false if an error occurred, else true
*/
bool CurvatureFlow::apply_to(mesh& input_mesh)
{
namespace ublas = boost::numeric::ublas;
namespace umf = boost::numeric::bindings::umfpack;
size_t n = input_mesh.num_vertices();
if(n == 0)
return(true); // silently ignore empty meshes
// Stores x,y,z components of the vertices in the mesh
ublas::vector<double> X(n);
ublas::vector<double> Y(n);
ublas::vector<double> Z(n);
// Fill vector with position data
for(size_t i = 0; i < n; i++)
{
const v3ctor& pos = input_mesh.get_vertex(i)->get_position();
X[i] = pos[0];
Y[i] = pos[1];
Z[i] = pos[2];
}
for(size_t i = 0; i < num_steps; i++)
{
// Prepare for "solving" the linear system (for now, this is something
// akin to the explicit Euler method)
ublas::compressed_matrix< double,
ublas::column_major,
0,
ublas::unbounded_array<int>,
ublas::unbounded_array<double> > M(n, n); // transformed matrix for the solving
// process, i.e. id - dt*K, where K is
// the matrix of the curvature operator
M = ublas::identity_matrix<double>(n, n) - dt*calc_curvature_operator(input_mesh);
// Solve x,y,z components independently. This may be slower,
// but sufficient for small meshes.
umf::symbolic_type<double> Symbolic;
umf::numeric_type<double> Numeric;
umf::symbolic(M, Symbolic);
umf::numeric(M, Symbolic, Numeric);
ublas::vector<double> X_new(input_mesh.num_vertices());
ublas::vector<double> Y_new(input_mesh.num_vertices());
ublas::vector<double> Z_new(input_mesh.num_vertices());
umf::solve(M, X_new, X, Numeric);
umf::solve(M, Y_new, Y, Numeric);
umf::solve(M, Z_new, Z, Numeric);
X = X_new;
Y = Y_new;
Z = Z_new;
for(size_t i = 0; i < n; i++)
input_mesh.get_vertex(i)->set_position(X[i], Y[i], Z[i]);
}
return(true);
}
/*!
* Given an input mesh, calculates the curvature operator matrix for this
* mesh. The matrix will be a _sparse_ matrix, hence the need for handling
* it via boost.
*
* @param input_mesh Mesh to be processed
* @return Sparse matrix describing the curvature operator
*/
boost::numeric::ublas::compressed_matrix<double> CurvatureFlow::calc_curvature_operator(mesh& input_mesh)
{
using namespace boost::numeric::ublas;
compressed_matrix<double> K(input_mesh.num_vertices(), input_mesh.num_vertices()); // K as in "Kurvature"...
// We iterate over all vertices and calculate the contributions of each
// vertex to the corresponding entry of the matrix
for(size_t i = 0; i < input_mesh.num_vertices(); i++)
{
vertex* v = input_mesh.get_vertex(i);
std::vector<const vertex*> neighbours = v->get_neighbours();
// FIXME: Used to update the correct matrix entries
// below. This assumes that the IDs have been allocated
// sequentially.
size_t cur_id = v->get_id();
// Find "opposing angles" for all neighbours; these are
// the $\alpha_{ij}$ and $\beta_{ij}$ values used for
// calculating the discrete curvature
for(size_t j = 0; j < neighbours.size(); j++)
{
std::pair<double, double> angles = v->find_opposite_angles(neighbours[j]);
if(angles.first >= 0.0 && angles.second >= 0.0)
{
// calculate contribution to matrix entries
double contribution = 1.0/tan(angles.first) + 1.0/tan(angles.second);
K(cur_id, cur_id) += contribution;
K(cur_id, neighbours[j]->get_id()) -= contribution;
}
}
}
// Scale the ith row of the matrix by the Voronoi area around the ith
// vertex; this works because the _first_ iterator of all matrix types
// is dense, whereas the second iterator is sparse in this case
size_t i = 0;
for(compressed_matrix<double>::iterator1 it1 = K.begin1(); it1 != K.end1(); it1++)
{
double area = input_mesh.get_vertex(i)->calc_ring_area();
if(area < 2*std::numeric_limits<double>::epsilon())
{
// skip on error or upon encountering a Voronoi area
// that is too small
i++;
continue;
}
for(compressed_matrix<double>::iterator2 it2 = it1.begin(); it2 != it1.end(); it2++)
(*it2) /= 4.0*area;
i++;
}
return(K);
}
/*!
* Sets current value for the delta parameter (used per timestep).
*
* @param delta New value for delta parameter
*/
void CurvatureFlow::set_delta(double delta)
{
this->dt = delta;
}
/*!
* @returns Current value of delta parameter (used per timestep).
*/
double CurvatureFlow::get_delta()
{
return(dt);
}
/*!
* Sets current value for the number of steps the algorithm is supposed to
* perform.
*
* @param num_steps New value for the number of steps
*/
void CurvatureFlow::set_steps(size_t num_steps)
{
this->num_steps = num_steps;
}
/*!
* @returns Current number of steps the algorithm performs when being
* applied to a mesh.
*/
size_t CurvatureFlow::get_steps()
{
return(num_steps);
}
} // end of namespace "psalm"
<commit_msg>Fixed includes for `boost.numeric`<commit_after>/*!
* @file CurvatureFlow.cpp
* @brief Implementation of a curvature flow algorithm
*/
#include "CurvatureFlow.h"
#include <boost/numeric/ublas/matrix_sparse.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/vector_sparse.hpp>
#include <boost/numeric/bindings/traits/ublas_sparse.hpp>
#include <boost/numeric/bindings/traits/ublas_vector.hpp>
#include <boost/numeric/bindings/umfpack/umfpack.hpp>
namespace psalm
{
/*!
* Sets default values
*/
CurvatureFlow::CurvatureFlow()
{
num_steps = 0;
dt = 0.5;
}
/*!
* Applies the curvature flow algorithm to the vertices of a given mesh.
* The size of timesteps needs to be set before. The input mesh is
* irreversibly changed by this operation.
*
* @param input_mesh Mesh on which the algorithm works.
* @return false if an error occurred, else true
*/
bool CurvatureFlow::apply_to(mesh& input_mesh)
{
namespace ublas = boost::numeric::ublas;
namespace umf = boost::numeric::bindings::umfpack;
size_t n = input_mesh.num_vertices();
if(n == 0)
return(true); // silently ignore empty meshes
// Stores x,y,z components of the vertices in the mesh
ublas::vector<double> X(n);
ublas::vector<double> Y(n);
ublas::vector<double> Z(n);
// Fill vector with position data
for(size_t i = 0; i < n; i++)
{
const v3ctor& pos = input_mesh.get_vertex(i)->get_position();
X[i] = pos[0];
Y[i] = pos[1];
Z[i] = pos[2];
}
for(size_t i = 0; i < num_steps; i++)
{
// Prepare for "solving" the linear system (for now, this is something
// akin to the explicit Euler method)
ublas::compressed_matrix< double,
ublas::column_major,
0,
ublas::unbounded_array<int>,
ublas::unbounded_array<double> > M(n, n); // transformed matrix for the solving
// process, i.e. id - dt*K, where K is
// the matrix of the curvature operator
M = ublas::identity_matrix<double>(n, n) - dt*calc_curvature_operator(input_mesh);
// Solve x,y,z components independently. This may be slower,
// but sufficient for small meshes.
umf::symbolic_type<double> Symbolic;
umf::numeric_type<double> Numeric;
umf::symbolic(M, Symbolic);
umf::numeric(M, Symbolic, Numeric);
ublas::vector<double> X_new(input_mesh.num_vertices());
ublas::vector<double> Y_new(input_mesh.num_vertices());
ublas::vector<double> Z_new(input_mesh.num_vertices());
umf::solve(M, X_new, X, Numeric);
umf::solve(M, Y_new, Y, Numeric);
umf::solve(M, Z_new, Z, Numeric);
X = X_new;
Y = Y_new;
Z = Z_new;
for(size_t i = 0; i < n; i++)
input_mesh.get_vertex(i)->set_position(X[i], Y[i], Z[i]);
}
return(true);
}
/*!
* Given an input mesh, calculates the curvature operator matrix for this
* mesh. The matrix will be a _sparse_ matrix, hence the need for handling
* it via boost.
*
* @param input_mesh Mesh to be processed
* @return Sparse matrix describing the curvature operator
*/
boost::numeric::ublas::compressed_matrix<double> CurvatureFlow::calc_curvature_operator(mesh& input_mesh)
{
using namespace boost::numeric::ublas;
compressed_matrix<double> K(input_mesh.num_vertices(), input_mesh.num_vertices()); // K as in "Kurvature"...
// We iterate over all vertices and calculate the contributions of each
// vertex to the corresponding entry of the matrix
for(size_t i = 0; i < input_mesh.num_vertices(); i++)
{
vertex* v = input_mesh.get_vertex(i);
std::vector<const vertex*> neighbours = v->get_neighbours();
// FIXME: Used to update the correct matrix entries
// below. This assumes that the IDs have been allocated
// sequentially.
size_t cur_id = v->get_id();
// Find "opposing angles" for all neighbours; these are
// the $\alpha_{ij}$ and $\beta_{ij}$ values used for
// calculating the discrete curvature
for(size_t j = 0; j < neighbours.size(); j++)
{
std::pair<double, double> angles = v->find_opposite_angles(neighbours[j]);
if(angles.first >= 0.0 && angles.second >= 0.0)
{
// calculate contribution to matrix entries
double contribution = 1.0/tan(angles.first) + 1.0/tan(angles.second);
K(cur_id, cur_id) += contribution;
K(cur_id, neighbours[j]->get_id()) -= contribution;
}
}
}
// Scale the ith row of the matrix by the Voronoi area around the ith
// vertex; this works because the _first_ iterator of all matrix types
// is dense, whereas the second iterator is sparse in this case
size_t i = 0;
for(compressed_matrix<double>::iterator1 it1 = K.begin1(); it1 != K.end1(); it1++)
{
double area = input_mesh.get_vertex(i)->calc_ring_area();
if(area < 2*std::numeric_limits<double>::epsilon())
{
// skip on error or upon encountering a Voronoi area
// that is too small
i++;
continue;
}
for(compressed_matrix<double>::iterator2 it2 = it1.begin(); it2 != it1.end(); it2++)
(*it2) /= 4.0*area;
i++;
}
return(K);
}
/*!
* Sets current value for the delta parameter (used per timestep).
*
* @param delta New value for delta parameter
*/
void CurvatureFlow::set_delta(double delta)
{
this->dt = delta;
}
/*!
* @returns Current value of delta parameter (used per timestep).
*/
double CurvatureFlow::get_delta()
{
return(dt);
}
/*!
* Sets current value for the number of steps the algorithm is supposed to
* perform.
*
* @param num_steps New value for the number of steps
*/
void CurvatureFlow::set_steps(size_t num_steps)
{
this->num_steps = num_steps;
}
/*!
* @returns Current number of steps the algorithm performs when being
* applied to a mesh.
*/
size_t CurvatureFlow::get_steps()
{
return(num_steps);
}
} // end of namespace "psalm"
<|endoftext|> |
<commit_before>/*
* Copyright 2020 McGraw-Hill Education. All rights reserved. No reproduction or distribution without the prior written consent of McGraw-Hill Education.
*/
#include <memory>
#include "common.h"
#include "console_printer.h"
#include "console_inputter.h"
#include "framework.h"
struct CLIArgs
{
uint32_t print_output = false;
uint32_t asm_print_level = 0;
uint32_t asm_print_level_override = false;
uint32_t sim_print_level = 0;
uint32_t sim_print_level_override = false;
bool ignore_privilege = false;
};
void setup(void);
void shutdown(void);
void testBringup(lc3::sim & sim);
void testTeardown(lc3::sim & sim);
std::vector<TestCase> tests;
uint32_t verify_count;
uint32_t verify_valid;
bool endsWith(std::string const & search, std::string const & suffix)
{
if(suffix.size() > search.size()) { return false; }
return std::equal(suffix.rbegin(), suffix.rend(), search.rbegin());
}
void BufferedPrinter::print(std::string const & string)
{
std::copy(string.begin(), string.end(), std::back_inserter(display_buffer));
if(print_output) {
std::cout << string;
}
}
void BufferedPrinter::newline(void)
{
display_buffer.push_back('\n');
if(print_output) {
std::cout << "\n";
}
}
void StringInputter::setStringAfter(std::string const & source, uint32_t inst_count)
{
this->inst_delay = inst_count;
this->source = source;
this->pos = 0;
}
bool StringInputter::getChar(char & c)
{
if(inst_delay > 0) {
inst_delay -= 1;
return false;
}
if(pos == source.size()) {
return false;
}
c = source[pos];
pos += 1;
return true;
}
int main(int argc, char * argv[])
{
CLIArgs args;
std::vector<std::pair<std::string, std::string>> parsed_args = parseCLIArgs(argc, argv);
for(auto const & arg : parsed_args) {
if(std::get<0>(arg) == "print-output") {
args.print_output = true;
} else if(std::get<0>(arg) == "asm-print-level") {
args.asm_print_level = std::stoi(std::get<1>(arg));
args.asm_print_level_override = true;
} else if(std::get<0>(arg) == "sim-print-level") {
args.sim_print_level = std::stoi(std::get<1>(arg));
args.sim_print_level_override = true;
args.print_output = true;
} else if(std::get<0>(arg) == "ignore-privilege") {
args.ignore_privilege = true;
} else if(std::get<0>(arg) == "h" || std::get<0>(arg) == "help") {
std::cout << "usage: " << argv[0] << " [OPTIONS]\n";
std::cout << "\n";
std::cout << " -h,--help Print this message\n";
std::cout << " --print-output Print program output\n";
std::cout << " --asm-print-level=N Assembler output verbosity [0-9]\n";
std::cout << " --sim-print-level=N Simulator output verbosity [0-9]\n";
std::cout << " --ignore-privilege Ignore access violations\n";
return 0;
}
}
lc3::ConsolePrinter asm_printer;
lc3::as assembler(asm_printer, args.asm_print_level_override ? args.asm_print_level : 0, false, true);
lc3::conv converter(asm_printer, args.asm_print_level_override ? args.asm_print_level : 0, false);
std::vector<std::string> obj_filenames;
bool valid_program = true;
for(int i = 1; i < argc; i += 1) {
std::string filename(argv[i]);
if(filename[0] != '-') {
lc3::optional<std::string> result;
if(! endsWith(filename, ".obj")) {
if(endsWith(filename, ".bin")) {
result = converter.convertBin(filename);
} else {
result = assembler.assemble(filename);
}
} else {
result = filename;
}
if(result) {
obj_filenames.push_back(*result);
} else {
valid_program = false;
}
}
}
if(obj_filenames.size() == 0) {
return 1;
}
setup();
uint32_t total_points_earned = 0;
uint32_t total_possible_points = 0;
if(valid_program) {
for(TestCase const & test : tests) {
BufferedPrinter sim_printer(args.print_output);
StringInputter sim_inputter;
lc3::sim simulator(sim_printer, sim_inputter, false,
args.sim_print_level_override ? args.sim_print_level : 1, true);
testBringup(simulator);
verify_count = 0;
verify_valid = 0;
total_possible_points += test.points;
std::cout << "Test: " << test.name;
if(test.randomize) {
simulator.randomize();
std::cout << " (Randomized Machine)";
}
std::cout << std::endl;
for(std::string const & obj_filename : obj_filenames) {
if(! simulator.loadObjFile(obj_filename)) {
std::cout << "could not init simulator\n";
return 2;
}
}
if(args.ignore_privilege) {
simulator.setIgnorePrivilege(true);
}
try {
test.test_func(simulator, sim_inputter);
} catch(lc3::utils::exception const & e) {
std::cout << "Test case ran into exception: " << e.what() << "\n";
continue;
}
testTeardown(simulator);
float percent_points_earned = ((float) verify_valid) / verify_count;
uint32_t points_earned = (uint32_t) ( percent_points_earned * test.points);
std::cout << "Test points earned: " << points_earned << "/" << test.points << " ("
<< (percent_points_earned * 100) << "%)\n";
std::cout << "==========\n";
total_points_earned += points_earned;
}
}
std::cout << "==========\n";
float percent_points_earned;
if(total_possible_points == 0) {
percent_points_earned = 0;
} else {
percent_points_earned = ((float) total_points_earned) / total_possible_points;
}
std::cout << "Total points earned: " << total_points_earned << "/" << total_possible_points << " ("
<< (percent_points_earned * 100) << "%)\n";
shutdown();
return 0;
}
bool outputCompare(lc3::utils::IPrinter const & printer, std::string check, bool substr)
{
BufferedPrinter const & buffered_printer = static_cast<BufferedPrinter const &>(printer);
std::cout << "is '" << check << "' " << (substr ? "substring of" : "==") << " '";
for(uint32_t i = 0; i < buffered_printer.display_buffer.size(); i += 1) {
if(buffered_printer.display_buffer[i] == '\n') {
std::cout << "\\n";
} else {
std::cout << buffered_printer.display_buffer[i];
}
}
std::cout << "'\n";
if(substr) {
uint64_t buffer_pos = 0;
while(buffer_pos + check.size() < buffered_printer.display_buffer.size()) {
uint64_t check_pos;
for(check_pos = 0; check_pos < check.size(); check_pos += 1) {
if(check[check_pos] != buffered_printer.display_buffer[buffer_pos + check_pos]) {
break;
}
}
if(check_pos == check.size()) { return true; }
buffer_pos += 1;
}
return false;
} else {
if(buffered_printer.display_buffer.size() != check.size()) { return false; }
for(uint32_t i = 0; i < check.size(); i += 1) {
if(buffered_printer.display_buffer[i] != check[i]) { return false; }
}
return true;
}
return false;
}
<commit_msg>[grader] Add flag to enable liberal assembly<commit_after>/*
* Copyright 2020 McGraw-Hill Education. All rights reserved. No reproduction or distribution without the prior written consent of McGraw-Hill Education.
*/
#include <memory>
#include "common.h"
#include "console_printer.h"
#include "console_inputter.h"
#include "framework.h"
struct CLIArgs
{
uint32_t print_output = false;
uint32_t asm_print_level = 0;
uint32_t asm_print_level_override = false;
uint32_t sim_print_level = 0;
uint32_t sim_print_level_override = false;
bool ignore_privilege = false;
bool liberal_asm = false;
};
void setup(void);
void shutdown(void);
void testBringup(lc3::sim & sim);
void testTeardown(lc3::sim & sim);
std::vector<TestCase> tests;
uint32_t verify_count;
uint32_t verify_valid;
bool endsWith(std::string const & search, std::string const & suffix)
{
if(suffix.size() > search.size()) { return false; }
return std::equal(suffix.rbegin(), suffix.rend(), search.rbegin());
}
void BufferedPrinter::print(std::string const & string)
{
std::copy(string.begin(), string.end(), std::back_inserter(display_buffer));
if(print_output) {
std::cout << string;
}
}
void BufferedPrinter::newline(void)
{
display_buffer.push_back('\n');
if(print_output) {
std::cout << "\n";
}
}
void StringInputter::setStringAfter(std::string const & source, uint32_t inst_count)
{
this->inst_delay = inst_count;
this->source = source;
this->pos = 0;
}
bool StringInputter::getChar(char & c)
{
if(inst_delay > 0) {
inst_delay -= 1;
return false;
}
if(pos == source.size()) {
return false;
}
c = source[pos];
pos += 1;
return true;
}
int main(int argc, char * argv[])
{
CLIArgs args;
std::vector<std::pair<std::string, std::string>> parsed_args = parseCLIArgs(argc, argv);
for(auto const & arg : parsed_args) {
if(std::get<0>(arg) == "print-output") {
args.print_output = true;
} else if(std::get<0>(arg) == "asm-print-level") {
args.asm_print_level = std::stoi(std::get<1>(arg));
args.asm_print_level_override = true;
} else if(std::get<0>(arg) == "sim-print-level") {
args.sim_print_level = std::stoi(std::get<1>(arg));
args.sim_print_level_override = true;
args.print_output = true;
} else if(std::get<0>(arg) == "ignore-privilege") {
args.ignore_privilege = true;
} else if(std::get<0>(arg) == "liberal-asm") {
args.liberal_asm = true;
} else if(std::get<0>(arg) == "h" || std::get<0>(arg) == "help") {
std::cout << "usage: " << argv[0] << " [OPTIONS]\n";
std::cout << "\n";
std::cout << " -h,--help Print this message\n";
std::cout << " --print-output Print program output\n";
std::cout << " --asm-print-level=N Assembler output verbosity [0-9]\n";
std::cout << " --sim-print-level=N Simulator output verbosity [0-9]\n";
std::cout << " --ignore-privilege Ignore access violations\n";
std::cout << " --liberal-asm Enable liberal assembly syntax\n";
return 0;
}
}
lc3::ConsolePrinter asm_printer;
lc3::as assembler(asm_printer, args.asm_print_level_override ? args.asm_print_level : 0, false, args.liberal_asm);
lc3::conv converter(asm_printer, args.asm_print_level_override ? args.asm_print_level : 0, false);
std::vector<std::string> obj_filenames;
bool valid_program = true;
for(int i = 1; i < argc; i += 1) {
std::string filename(argv[i]);
if(filename[0] != '-') {
lc3::optional<std::string> result;
if(! endsWith(filename, ".obj")) {
if(endsWith(filename, ".bin")) {
result = converter.convertBin(filename);
} else {
result = assembler.assemble(filename);
}
} else {
result = filename;
}
if(result) {
obj_filenames.push_back(*result);
} else {
valid_program = false;
}
}
}
if(obj_filenames.size() == 0) {
return 1;
}
setup();
uint32_t total_points_earned = 0;
uint32_t total_possible_points = 0;
if(valid_program) {
for(TestCase const & test : tests) {
BufferedPrinter sim_printer(args.print_output);
StringInputter sim_inputter;
lc3::sim simulator(sim_printer, sim_inputter, false,
args.sim_print_level_override ? args.sim_print_level : 1, true);
testBringup(simulator);
verify_count = 0;
verify_valid = 0;
total_possible_points += test.points;
std::cout << "Test: " << test.name;
if(test.randomize) {
simulator.randomize();
std::cout << " (Randomized Machine)";
}
std::cout << std::endl;
for(std::string const & obj_filename : obj_filenames) {
if(! simulator.loadObjFile(obj_filename)) {
std::cout << "could not init simulator\n";
return 2;
}
}
if(args.ignore_privilege) {
simulator.setIgnorePrivilege(true);
}
try {
test.test_func(simulator, sim_inputter);
} catch(lc3::utils::exception const & e) {
std::cout << "Test case ran into exception: " << e.what() << "\n";
continue;
}
testTeardown(simulator);
float percent_points_earned = ((float) verify_valid) / verify_count;
uint32_t points_earned = (uint32_t) ( percent_points_earned * test.points);
std::cout << "Test points earned: " << points_earned << "/" << test.points << " ("
<< (percent_points_earned * 100) << "%)\n";
std::cout << "==========\n";
total_points_earned += points_earned;
}
}
std::cout << "==========\n";
float percent_points_earned;
if(total_possible_points == 0) {
percent_points_earned = 0;
} else {
percent_points_earned = ((float) total_points_earned) / total_possible_points;
}
std::cout << "Total points earned: " << total_points_earned << "/" << total_possible_points << " ("
<< (percent_points_earned * 100) << "%)\n";
shutdown();
return 0;
}
bool outputCompare(lc3::utils::IPrinter const & printer, std::string check, bool substr)
{
BufferedPrinter const & buffered_printer = static_cast<BufferedPrinter const &>(printer);
std::cout << "is '" << check << "' " << (substr ? "substring of" : "==") << " '";
for(uint32_t i = 0; i < buffered_printer.display_buffer.size(); i += 1) {
if(buffered_printer.display_buffer[i] == '\n') {
std::cout << "\\n";
} else {
std::cout << buffered_printer.display_buffer[i];
}
}
std::cout << "'\n";
if(substr) {
uint64_t buffer_pos = 0;
while(buffer_pos + check.size() < buffered_printer.display_buffer.size()) {
uint64_t check_pos;
for(check_pos = 0; check_pos < check.size(); check_pos += 1) {
if(check[check_pos] != buffered_printer.display_buffer[buffer_pos + check_pos]) {
break;
}
}
if(check_pos == check.size()) { return true; }
buffer_pos += 1;
}
return false;
} else {
if(buffered_printer.display_buffer.size() != check.size()) { return false; }
for(uint32_t i = 0; i < check.size(); i += 1) {
if(buffered_printer.display_buffer[i] != check[i]) { return false; }
}
return true;
}
return false;
}
<|endoftext|> |
<commit_before>/* This file is part of the KDE project.
Copyright (C) 2011 Trever Fischer <tdfischer@fedoraproject.org>
This library is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 2.1 or 3 of the License.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#include "plugininstaller.h"
#include <gst/gst.h>
#include <QtCore/QCoreApplication>
#include <QtGui/QApplication>
#include <QtGui/QWidget>
#include <QtCore/QLibrary>
#include <QtCore/QPointer>
#include <QtCore/QMetaType>
#ifdef PLUGIN_INSTALL_API
#include <gst/pbutils/pbutils.h>
#endif
namespace Phonon
{
namespace Gstreamer
{
bool PluginInstaller::s_ready = false;
bool PluginInstaller::init()
{
if (!s_ready) {
#ifdef PLUGIN_INSTALL_API
gst_pb_utils_init();
s_ready = true;
#endif
}
return s_ready;
}
QString PluginInstaller::description(const GstCaps *caps, PluginType type)
{
#ifdef PLUGIN_INSTALL_API
if (init()) {
QString pluginStr;
gchar *pluginDesc = 0;
switch(type) {
case Decoder:
pluginDesc = gst_pb_utils_get_decoder_description(caps);
break;
case Encoder:
pluginDesc = gst_pb_utils_get_encoder_description(caps);
break;
case Codec:
pluginDesc = gst_pb_utils_get_codec_description(caps);
break;
default:
return 0;
}
pluginStr = QString::fromUtf8(pluginDesc);
g_free(pluginDesc);
return pluginStr;
}
#else
Q_UNUSED(type)
Q_UNUSED(caps)
#endif
return getCapType(caps);
}
QString PluginInstaller::description(const gchar *name, PluginType type)
{
#ifdef PLUGIN_INSTALL_API
if (init()) {
QString pluginStr;
gchar *pluginDesc = 0;
switch(type) {
case Source:
pluginDesc = gst_pb_utils_get_source_description(name);
break;
case Sink:
pluginDesc = gst_pb_utils_get_sink_description(name);
break;
case Element:
pluginDesc = gst_pb_utils_get_element_description(name);
break;
default:
return 0;
}
pluginStr = QString::fromUtf8(pluginDesc);
g_free(pluginDesc);
return pluginStr;
}
#endif
return name;
}
QString PluginInstaller::buildInstallationString(const GstCaps *caps, PluginType type)
{
QString descType;
switch(type) {
case Codec:
case Decoder:
descType = "decoder";
break;
case Encoder:
descType = "encoder";
break;
default:
return QString();
}
return QString("gstreamer|0.10|%0|%1|%2-%3")
.arg(qApp->applicationName())
.arg(description(caps, type))
.arg(descType)
.arg(getCapType(caps));
}
QString PluginInstaller::buildInstallationString(const gchar *name, PluginType type)
{
QString descType;
switch(type) {
case Element:
descType = "element";
break;
default:
return QString();
}
return QString("gstreamer|0.10|%0|%1|%2-%3")
.arg(qApp->applicationName())
.arg(description(name, type))
.arg(descType)
.arg(name);
}
PluginInstaller::PluginInstaller(QObject *parent)
: QObject(parent)
, m_state(Idle)
{
}
void PluginInstaller::addPlugin(const QString &name, PluginType type)
{
m_pluginList.insert(name, type);
}
void PluginInstaller::addPlugin(GstMessage *gstMessage)
{
gchar *details = gst_missing_plugin_message_get_installer_detail(gstMessage);
m_descList << details;
g_free(details);
}
#ifdef PLUGIN_INSTALL_API
void PluginInstaller::run()
{
GstInstallPluginsContext *ctx = gst_install_plugins_context_new();
QWidget *activeWindow = QApplication::activeWindow();
if (activeWindow) {
gst_install_plugins_context_set_xid(ctx, static_cast<int>(activeWindow->winId()));
}
gchar *details[m_pluginList.size()+m_descList.size()+1];
int i = 0;
foreach (const QString &plugin, m_pluginList.keys()) {
details[i] = strdup(buildInstallationString(plugin.toLocal8Bit().data(), m_pluginList[plugin]).toLocal8Bit().data());
i++;
}
foreach (const QString &desc, m_descList) {
details[i] = strdup(desc.toLocal8Bit().data());
i++;
}
details[i] = 0;
GstInstallPluginsReturn status;
status = gst_install_plugins_async(details, ctx, pluginInstallationDone, new QPointer<PluginInstaller>(this));
gst_install_plugins_context_free(ctx);
if (status != GST_INSTALL_PLUGINS_STARTED_OK) {
if (status == GST_INSTALL_PLUGINS_HELPER_MISSING)
emit failure(tr("Missing codec helper script assistant."));
else
emit failure(tr("Plugin codec installation failed."));
} else {
emit started();
}
while (i) {
free(details[i--]);
}
reset();
}
void PluginInstaller::pluginInstallationDone(GstInstallPluginsReturn result, gpointer data)
{
QPointer<PluginInstaller> *that = static_cast<QPointer<PluginInstaller>*>(data);
if (*that) {
qRegisterMetaType<GstInstallPluginsReturn>("GstInstallPluginsReturn");
(*that)->pluginInstallationResult(result);
}
}
void PluginInstaller::pluginInstallationResult(GstInstallPluginsReturn result)
{
switch(result) {
case GST_INSTALL_PLUGINS_INVALID:
emit failure(tr("Phonon attempted to install an invalid codec name."));
break;
case GST_INSTALL_PLUGINS_CRASHED:
emit failure(tr("The codec installer crashed."));
break;
case GST_INSTALL_PLUGINS_NOT_FOUND:
emit failure(tr("The required codec could not be found for installation."));
break;
case GST_INSTALL_PLUGINS_ERROR:
emit failure(tr("An unspecified error occurred during codec installation."));
break;
case GST_INSTALL_PLUGINS_PARTIAL_SUCCESS:
emit failure(tr("Not all codecs could be installed."));
break;
case GST_INSTALL_PLUGINS_USER_ABORT:
emit failure(tr("User aborted codec installation"));
break;
//These four should never ever be passed in.
//If they have, gstreamer has probably imploded in on itself.
case GST_INSTALL_PLUGINS_STARTED_OK:
case GST_INSTALL_PLUGINS_INTERNAL_FAILURE:
case GST_INSTALL_PLUGINS_HELPER_MISSING:
case GST_INSTALL_PLUGINS_INSTALL_IN_PROGRESS:
//But this one is OK.
case GST_INSTALL_PLUGINS_SUCCESS:
if (!gst_update_registry()) {
emit failure(tr("Could not update plugin registry after update."));
} else {
emit success();
}
break;
}
m_state = Idle;
}
#endif
PluginInstaller::InstallStatus PluginInstaller::checkInstalledPlugins()
{
if (m_state != Idle)
return m_state;
bool allFound = true;
foreach (const QString &plugin, m_pluginList.keys()) {
if (!gst_default_registry_check_feature_version(plugin.toLocal8Bit().data(), 0, 10, 0)) {
allFound = false;
break;
}
}
if (!allFound || m_descList.size() > 0) {
#ifdef PLUGIN_INSTALL_API
run();
m_state = Installing;
return Installing;
#else
return Missing;
#endif
} else {
return Installed;
}
}
QString PluginInstaller::getCapType(const GstCaps *caps)
{
GstStructure *str = gst_caps_get_structure(caps, 0);
gchar *strstr = gst_structure_to_string(str);
QString capType = QString::fromUtf8(strstr);
g_free(strstr);
return capType;
}
void PluginInstaller::reset()
{
m_descList.clear();
m_pluginList.clear();
}
} // ns Gstreamer
} // ns Phonon
#include "moc_plugininstaller.cpp"
<commit_msg>Port plugininstaller.cpp to GStreamer 1.0<commit_after>/* This file is part of the KDE project.
Copyright (C) 2011 Trever Fischer <tdfischer@fedoraproject.org>
This library is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 2.1 or 3 of the License.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#include "plugininstaller.h"
#include <gst/gst.h>
#include <QtCore/QCoreApplication>
#include <QtGui/QApplication>
#include <QtGui/QWidget>
#include <QtCore/QLibrary>
#include <QtCore/QPointer>
#include <QtCore/QMetaType>
#ifdef PLUGIN_INSTALL_API
#include <gst/pbutils/pbutils.h>
#endif
namespace Phonon
{
namespace Gstreamer
{
bool PluginInstaller::s_ready = false;
bool PluginInstaller::init()
{
if (!s_ready) {
#ifdef PLUGIN_INSTALL_API
gst_pb_utils_init();
s_ready = true;
#endif
}
return s_ready;
}
QString PluginInstaller::description(const GstCaps *caps, PluginType type)
{
#ifdef PLUGIN_INSTALL_API
if (init()) {
QString pluginStr;
gchar *pluginDesc = 0;
switch(type) {
case Decoder:
pluginDesc = gst_pb_utils_get_decoder_description(caps);
break;
case Encoder:
pluginDesc = gst_pb_utils_get_encoder_description(caps);
break;
case Codec:
pluginDesc = gst_pb_utils_get_codec_description(caps);
break;
default:
return 0;
}
pluginStr = QString::fromUtf8(pluginDesc);
g_free(pluginDesc);
return pluginStr;
}
#else
Q_UNUSED(type)
Q_UNUSED(caps)
#endif
return getCapType(caps);
}
QString PluginInstaller::description(const gchar *name, PluginType type)
{
#ifdef PLUGIN_INSTALL_API
if (init()) {
QString pluginStr;
gchar *pluginDesc = 0;
switch(type) {
case Source:
pluginDesc = gst_pb_utils_get_source_description(name);
break;
case Sink:
pluginDesc = gst_pb_utils_get_sink_description(name);
break;
case Element:
pluginDesc = gst_pb_utils_get_element_description(name);
break;
default:
return 0;
}
pluginStr = QString::fromUtf8(pluginDesc);
g_free(pluginDesc);
return pluginStr;
}
#endif
return name;
}
QString PluginInstaller::buildInstallationString(const GstCaps *caps, PluginType type)
{
QString descType;
switch(type) {
case Codec:
case Decoder:
descType = "decoder";
break;
case Encoder:
descType = "encoder";
break;
default:
return QString();
}
return QString("gstreamer|0.10|%0|%1|%2-%3")
.arg(qApp->applicationName())
.arg(description(caps, type))
.arg(descType)
.arg(getCapType(caps));
}
QString PluginInstaller::buildInstallationString(const gchar *name, PluginType type)
{
QString descType;
switch(type) {
case Element:
descType = "element";
break;
default:
return QString();
}
return QString("gstreamer|0.10|%0|%1|%2-%3")
.arg(qApp->applicationName())
.arg(description(name, type))
.arg(descType)
.arg(name);
}
PluginInstaller::PluginInstaller(QObject *parent)
: QObject(parent)
, m_state(Idle)
{
}
void PluginInstaller::addPlugin(const QString &name, PluginType type)
{
m_pluginList.insert(name, type);
}
void PluginInstaller::addPlugin(GstMessage *gstMessage)
{
gchar *details = gst_missing_plugin_message_get_installer_detail(gstMessage);
m_descList << details;
g_free(details);
}
#ifdef PLUGIN_INSTALL_API
void PluginInstaller::run()
{
GstInstallPluginsContext *ctx = gst_install_plugins_context_new();
QWidget *activeWindow = QApplication::activeWindow();
if (activeWindow) {
gst_install_plugins_context_set_xid(ctx, static_cast<int>(activeWindow->winId()));
}
gchar *details[m_pluginList.size()+m_descList.size()+1];
int i = 0;
foreach (const QString &plugin, m_pluginList.keys()) {
details[i] = strdup(buildInstallationString(plugin.toLocal8Bit().data(), m_pluginList[plugin]).toLocal8Bit().data());
i++;
}
foreach (const QString &desc, m_descList) {
details[i] = strdup(desc.toLocal8Bit().data());
i++;
}
details[i] = 0;
GstInstallPluginsReturn status;
status = gst_install_plugins_async(details, ctx, pluginInstallationDone, new QPointer<PluginInstaller>(this));
gst_install_plugins_context_free(ctx);
if (status != GST_INSTALL_PLUGINS_STARTED_OK) {
if (status == GST_INSTALL_PLUGINS_HELPER_MISSING)
emit failure(tr("Missing codec helper script assistant."));
else
emit failure(tr("Plugin codec installation failed."));
} else {
emit started();
}
while (i) {
free(details[i--]);
}
reset();
}
void PluginInstaller::pluginInstallationDone(GstInstallPluginsReturn result, gpointer data)
{
QPointer<PluginInstaller> *that = static_cast<QPointer<PluginInstaller>*>(data);
if (*that) {
qRegisterMetaType<GstInstallPluginsReturn>("GstInstallPluginsReturn");
(*that)->pluginInstallationResult(result);
}
}
void PluginInstaller::pluginInstallationResult(GstInstallPluginsReturn result)
{
switch(result) {
case GST_INSTALL_PLUGINS_INVALID:
emit failure(tr("Phonon attempted to install an invalid codec name."));
break;
case GST_INSTALL_PLUGINS_CRASHED:
emit failure(tr("The codec installer crashed."));
break;
case GST_INSTALL_PLUGINS_NOT_FOUND:
emit failure(tr("The required codec could not be found for installation."));
break;
case GST_INSTALL_PLUGINS_ERROR:
emit failure(tr("An unspecified error occurred during codec installation."));
break;
case GST_INSTALL_PLUGINS_PARTIAL_SUCCESS:
emit failure(tr("Not all codecs could be installed."));
break;
case GST_INSTALL_PLUGINS_USER_ABORT:
emit failure(tr("User aborted codec installation"));
break;
//These four should never ever be passed in.
//If they have, gstreamer has probably imploded in on itself.
case GST_INSTALL_PLUGINS_STARTED_OK:
case GST_INSTALL_PLUGINS_INTERNAL_FAILURE:
case GST_INSTALL_PLUGINS_HELPER_MISSING:
case GST_INSTALL_PLUGINS_INSTALL_IN_PROGRESS:
//But this one is OK.
case GST_INSTALL_PLUGINS_SUCCESS:
if (!gst_update_registry()) {
emit failure(tr("Could not update plugin registry after update."));
} else {
emit success();
}
break;
}
m_state = Idle;
}
#endif
PluginInstaller::InstallStatus PluginInstaller::checkInstalledPlugins()
{
if (m_state != Idle)
return m_state;
bool allFound = true;
foreach (const QString &plugin, m_pluginList.keys()) {
if (
#if GST_VERSION < GST_VERSION_CHECK (1,0,0,0)
!gst_default_registry_check_feature_version(plugin.toLocal8Bit().data(), 0, 10, 0)
#else
!gst_registry_check_feature_version(gst_registry_get(), plugin.toLocal8Bit().data(), 1, 0, 0)
#endif
) {
allFound = false;
break;
}
}
if (!allFound || m_descList.size() > 0) {
#ifdef PLUGIN_INSTALL_API
run();
m_state = Installing;
return Installing;
#else
return Missing;
#endif
} else {
return Installed;
}
}
QString PluginInstaller::getCapType(const GstCaps *caps)
{
GstStructure *str = gst_caps_get_structure(caps, 0);
gchar *strstr = gst_structure_to_string(str);
QString capType = QString::fromUtf8(strstr);
g_free(strstr);
return capType;
}
void PluginInstaller::reset()
{
m_descList.clear();
m_pluginList.clear();
}
} // ns Gstreamer
} // ns Phonon
#include "moc_plugininstaller.cpp"
<|endoftext|> |
<commit_before><commit_msg>Use regular intrinsic names rather than alternatives<commit_after><|endoftext|> |
<commit_before><commit_msg>Realloc wave gen data when needed<commit_after><|endoftext|> |
<commit_before>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Module: FGKinemat.cpp
Author: Tony Peden, for flight control system authored by Jon S. Berndt
Date started: 12/02/01
------------- Copyright (C) 2000 Anthony K. Peden -------------
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA.
Further information about the GNU General Public License can also be found on
the world wide web at http://www.gnu.org.
FUNCTIONAL DESCRIPTION
--------------------------------------------------------------------------------
HISTORY
--------------------------------------------------------------------------------
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
COMMENTS, REFERENCES, and NOTES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#include "FGKinemat.h"
static const char *IdSrc = "$Id: FGKinemat.cpp,v 1.7 2001/12/23 21:49:01 jberndt Exp $";
static const char *IdHdr = ID_FLAPS;
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS IMPLEMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
FGKinemat::FGKinemat(FGFCS* fcs, FGConfigFile* AC_cfg) : FGFCSComponent(fcs),
AC_cfg(AC_cfg)
{
string token;
double tmpDetent;
double tmpTime;
Detents.clear();
TransitionTimes.clear();
Type = AC_cfg->GetValue("TYPE");
Name = AC_cfg->GetValue("NAME");
AC_cfg->GetNextConfigLine();
while ((token = AC_cfg->GetValue()) != string("/COMPONENT")) {
*AC_cfg >> token;
if (token == "ID") {
*AC_cfg >> ID;
} else if (token == "INPUT") {
token = AC_cfg->GetValue("INPUT");
if (token.find("FG_") != token.npos) {
*AC_cfg >> token;
InputIdx = fcs->GetState()->GetParameterIndex(token);
InputType = itPilotAC;
}
} else if ( token == "DETENTS" ) {
*AC_cfg >> NumDetents;
for(int i=0;i<NumDetents;i++) {
*AC_cfg >> tmpDetent;
*AC_cfg >> tmpTime;
Detents.push_back(tmpDetent);
TransitionTimes.push_back(tmpTime);
}
} else if (token == "OUTPUT") {
IsOutput = true;
*AC_cfg >> sOutputIdx;
OutputIdx = fcs->GetState()->GetParameterIndex(sOutputIdx);
}
}
Debug(0);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FGKinemat::~FGKinemat()
{
Debug(1);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
bool FGKinemat::Run(void ) {
double dt=fcs->GetState()->Getdt();
double output_transit_rate=0;
FGFCSComponent::Run(); // call the base class for initialization of Input
InputCmd = Input*Detents[NumDetents-1];
OutputPos = fcs->GetState()->GetParameter(OutputIdx);
if(InputCmd < Detents[0]) {
fi=0;
InputCmd=Detents[0];
lastInputCmd=InputCmd;
OutputPos=Detents[0];
Output=OutputPos;
} else if(InputCmd > Detents[NumDetents-1]) {
fi=NumDetents-1;
InputCmd=Detents[fi];
lastInputCmd=InputCmd;
OutputPos=Detents[fi];
Output=OutputPos;
} else {
//cout << "FGKinemat::Run Handle: " << InputCmd << " Position: " << OutputPos << endl;
if(dt <= 0)
OutputPos=InputCmd;
else {
if(InputCmd != lastInputCmd) {
InTransit=1;
}
if(InTransit) {
//fprintf(stderr,"InputCmd: %g, OutputPos: %g\n",InputCmd,OutputPos);
fi=0;
while(Detents[fi] < InputCmd) {
fi++;
}
if(OutputPos < InputCmd) {
if(TransitionTimes[fi] > 0)
output_transit_rate=(Detents[fi] - Detents[fi-1])/TransitionTimes[fi];
else
output_transit_rate=(Detents[fi] - Detents[fi-1])/5;
} else {
if(TransitionTimes[fi+1] > 0)
output_transit_rate=(Detents[fi] - Detents[fi+1])/TransitionTimes[fi+1];
else
output_transit_rate=(Detents[fi] - Detents[fi+1])/5;
}
if(fabs(OutputPos - InputCmd) > dt*output_transit_rate)
OutputPos+=output_transit_rate*dt;
else {
InTransit=0;
OutputPos=InputCmd;
}
}
}
lastInputCmd = InputCmd;
Output = OutputPos;
}
if (IsOutput) SetOutput();
return true;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// The bitmasked value choices are as follows:
// unset: In this case (the default) JSBSim would only print
// out the normally expected messages, essentially echoing
// the config files as they are read. If the environment
// variable is not set, debug_lvl is set to 1 internally
// 0: This requests JSBSim not to output any messages
// whatsoever.
// 1: This value explicity requests the normal JSBSim
// startup messages
// 2: This value asks for a message to be printed out when
// a class is instantiated
// 4: When this value is set, a message is displayed when a
// FGModel object executes its Run() method
// 8: When this value is set, various runtime state variables
// are printed out periodically
// 16: When set various parameters are sanity checked and
// a message is printed out when they go out of bounds
void FGKinemat::Debug(int from)
{
if (debug_lvl <= 0) return;
if (debug_lvl & 1) { // Standard console startup message output
if (from == 0) { // Constructor
cout << " ID: " << ID << endl;
cout << " INPUT: " << InputIdx << endl;
cout << " DETENTS: " << NumDetents << endl;
for(int i=0;i<NumDetents;i++) {
cout << " " << Detents[i] << " " << TransitionTimes[i] << endl;
}
if (IsOutput) cout << " OUTPUT: " <<sOutputIdx << endl;
}
}
if (debug_lvl & 2 ) { // Instantiation/Destruction notification
if (from == 0) cout << "Instantiated: FGKinemat" << endl;
if (from == 1) cout << "Destroyed: FGKinemat" << endl;
}
if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects
}
if (debug_lvl & 8 ) { // Runtime state variables
}
if (debug_lvl & 16) { // Sanity checking
}
if (debug_lvl & 64) {
if (from == 0) { // Constructor
cout << IdSrc << endl;
cout << IdHdr << endl;
}
}
}
<commit_msg>Fix contributed by Erik Hofman. Thanks!<commit_after>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Module: FGKinemat.cpp
Author: Tony Peden, for flight control system authored by Jon S. Berndt
Date started: 12/02/01
------------- Copyright (C) 2000 Anthony K. Peden -------------
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA.
Further information about the GNU General Public License can also be found on
the world wide web at http://www.gnu.org.
FUNCTIONAL DESCRIPTION
--------------------------------------------------------------------------------
HISTORY
--------------------------------------------------------------------------------
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
COMMENTS, REFERENCES, and NOTES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#include "FGKinemat.h"
static const char *IdSrc = "$Id: FGKinemat.cpp,v 1.8 2002/02/15 23:14:18 apeden Exp $";
static const char *IdHdr = ID_FLAPS;
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS IMPLEMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
FGKinemat::FGKinemat(FGFCS* fcs, FGConfigFile* AC_cfg) : FGFCSComponent(fcs),
AC_cfg(AC_cfg)
{
string token;
double tmpDetent;
double tmpTime;
Detents.clear();
TransitionTimes.clear();
Type = AC_cfg->GetValue("TYPE");
Name = AC_cfg->GetValue("NAME");
AC_cfg->GetNextConfigLine();
while ((token = AC_cfg->GetValue()) != string("/COMPONENT")) {
*AC_cfg >> token;
if (token == "ID") {
*AC_cfg >> ID;
} else if (token == "INPUT") {
token = AC_cfg->GetValue("INPUT");
if (token.find("FG_") != token.npos) {
*AC_cfg >> token;
InputIdx = fcs->GetState()->GetParameterIndex(token);
InputType = itPilotAC;
}
} else if ( token == "DETENTS" ) {
*AC_cfg >> NumDetents;
for(int i=0;i<NumDetents;i++) {
*AC_cfg >> tmpDetent;
*AC_cfg >> tmpTime;
Detents.push_back(tmpDetent);
TransitionTimes.push_back(tmpTime);
}
} else if (token == "OUTPUT") {
IsOutput = true;
*AC_cfg >> sOutputIdx;
OutputIdx = fcs->GetState()->GetParameterIndex(sOutputIdx);
}
}
Debug(0);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FGKinemat::~FGKinemat()
{
Debug(1);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
bool FGKinemat::Run(void ) {
double dt=fcs->GetState()->Getdt();
double output_transit_rate=0;
FGFCSComponent::Run(); // call the base class for initialization of Input
InputCmd = Input*Detents[NumDetents-1];
OutputPos = fcs->GetState()->GetParameter(OutputIdx);
if(InputCmd < Detents[0]) {
fi=0;
InputCmd=Detents[0];
lastInputCmd=InputCmd;
OutputPos=Detents[0];
Output=OutputPos;
} else if(InputCmd > Detents[NumDetents-1]) {
fi=NumDetents-1;
InputCmd=Detents[fi];
lastInputCmd=InputCmd;
OutputPos=Detents[fi];
Output=OutputPos;
} else {
//cout << "FGKinemat::Run Handle: " << InputCmd << " Position: " << OutputPos << endl;
if(dt <= 0)
OutputPos=InputCmd;
else {
if(InputCmd != lastInputCmd) {
InTransit=1;
}
if(InTransit) {
//fprintf(stderr,"InputCmd: %g, OutputPos: %g\n",InputCmd,OutputPos);
fi=0;
while(Detents[fi] < InputCmd) {
fi++;
}
if(OutputPos < InputCmd) {
if(TransitionTimes[fi] > 0)
output_transit_rate=(Detents[fi] - Detents[fi-1])/TransitionTimes[fi];
else
output_transit_rate=(Detents[fi] - Detents[fi-1])/5;
} else {
if(TransitionTimes[fi+1] > 0)
output_transit_rate=(Detents[fi] - Detents[fi+1])/TransitionTimes[fi+1];
else
output_transit_rate=(Detents[fi] - Detents[fi+1])/5;
}
if(fabs(OutputPos - InputCmd) > fabs(dt*output_transit_rate) )
OutputPos+=output_transit_rate*dt;
else {
InTransit=0;
OutputPos=InputCmd;
}
}
}
lastInputCmd = InputCmd;
Output = OutputPos;
}
if (IsOutput) SetOutput();
return true;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// The bitmasked value choices are as follows:
// unset: In this case (the default) JSBSim would only print
// out the normally expected messages, essentially echoing
// the config files as they are read. If the environment
// variable is not set, debug_lvl is set to 1 internally
// 0: This requests JSBSim not to output any messages
// whatsoever.
// 1: This value explicity requests the normal JSBSim
// startup messages
// 2: This value asks for a message to be printed out when
// a class is instantiated
// 4: When this value is set, a message is displayed when a
// FGModel object executes its Run() method
// 8: When this value is set, various runtime state variables
// are printed out periodically
// 16: When set various parameters are sanity checked and
// a message is printed out when they go out of bounds
void FGKinemat::Debug(int from)
{
if (debug_lvl <= 0) return;
if (debug_lvl & 1) { // Standard console startup message output
if (from == 0) { // Constructor
cout << " ID: " << ID << endl;
cout << " INPUT: " << InputIdx << endl;
cout << " DETENTS: " << NumDetents << endl;
for(int i=0;i<NumDetents;i++) {
cout << " " << Detents[i] << " " << TransitionTimes[i] << endl;
}
if (IsOutput) cout << " OUTPUT: " <<sOutputIdx << endl;
}
}
if (debug_lvl & 2 ) { // Instantiation/Destruction notification
if (from == 0) cout << "Instantiated: FGKinemat" << endl;
if (from == 1) cout << "Destroyed: FGKinemat" << endl;
}
if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects
}
if (debug_lvl & 8 ) { // Runtime state variables
}
if (debug_lvl & 16) { // Sanity checking
}
if (debug_lvl & 64) {
if (from == 0) { // Constructor
cout << IdSrc << endl;
cout << IdHdr << endl;
}
}
}
<|endoftext|> |
<commit_before>#include "simulatedbody.h"
SimulatedBody::SimulatedBody()
{}
//mass = radius
SimulatedBody::SimulatedBody(Color color, const Vector3 &position, int radius, const Vector3 &velocity)
{
color_ = color;
center_ = position;
velocity_ = velocity;
radius_ = radius;
mass_ = radius;
}
//Setters
void SimulatedBody::setMass(int mass)
{
mass_ = mass;
}
void SimulatedBody::setAcceleration(const Vector3& acceleration)
{
acceleration_ = acceleration;
}
void SimulatedBody::setForce(const Vector3& force)
{
acceleration_ = force;
}
//Getters
Color::Color SimulatedBody::getColor() const
{
return color_;
}
int SimulatedBody::getMass() const
{
return mass_;
}
Vector3 SimulatedBody::getAcceleration() const
{
return acceleration_;
}
Vector3 SimulatedBody::getForce() const
{
return force_;
}<commit_msg>Overloaded advance function to account for acceleration<commit_after>#include "simulatedbody.h"
SimulatedBody::SimulatedBody()
{}
//mass = radius
SimulatedBody::SimulatedBody(const Vector3 &position, int radius, const Vector3 &velocity)
{
center_ = position;
velocity_ = velocity;
radius_ = radius;
mass_ = radius;
}
//Modifies position and velocity based on current velocity and acceleration
//*TODO* assert( ||v|| < c )
void SimulatedBody::advance(const double time) {
center_ += velocity_ * time;
center_ += acceleration_ * 0.5 * time * time; // 1/2 * a * t^2
velocity_ += acceleration_ * time; // v(t) = v(0) + at
}
//Setters
void SimulatedBody::setMass(int mass)
{
mass_ = mass;
}
void SimulatedBody::setAcceleration(const Vector3& acceleration)
{
acceleration_ = acceleration;
}
void SimulatedBody::setForce(const Vector3& force)
{
acceleration_ = force;
}
//Getters
int SimulatedBody::getMass() const
{
return mass_;
}
Vector3 SimulatedBody::getAcceleration() const
{
return acceleration_;
}
Vector3 SimulatedBody::getForce() const
{
return force_;
}<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#ifdef Q_OS_WIN
# include <windows.h>
#else
# include <sys/stat.h>
# include <sys/types.h>
# include <dirent.h>
# include <unistd.h>
#endif
class Test : public QObject{
Q_OBJECT
public slots:
void initTestCase() {
QDir testdir = QDir::tempPath();
const QString subfolder_name = QLatin1String("test_speed");
QVERIFY(testdir.mkdir(subfolder_name));
QVERIFY(testdir.cd(subfolder_name));
for (uint i=0; i<10000; ++i) {
QFile file(testdir.absolutePath() + "/testfile_" + QString::number(i));
file.open(QIODevice::WriteOnly);
}
}
void cleanupTestCase() {
{
QDir testdir(QDir::tempPath() + QLatin1String("/test_speed"));
testdir.setSorting(QDir::Unsorted);
testdir.setFilter(QDir::AllEntries | QDir::System | QDir::Hidden);
foreach (const QString &filename, testdir.entryList()) {
testdir.remove(filename);
}
}
const QDir temp = QDir(QDir::tempPath());
temp.rmdir(QLatin1String("test_speed"));
}
private slots:
void sizeSpeed() {
QDir testdir(QDir::tempPath() + QLatin1String("/test_speed"));
QBENCHMARK {
QFileInfoList fileInfoList = testdir.entryInfoList(QDir::Files, QDir::Unsorted);
foreach (const QFileInfo &fileInfo, fileInfoList) {
fileInfo.isDir();
fileInfo.size();
}
}
}
void sizeSpeedWithoutFilter() {
QDir testdir(QDir::tempPath() + QLatin1String("/test_speed"));
QBENCHMARK {
QFileInfoList fileInfoList = testdir.entryInfoList(QDir::NoFilter, QDir::Unsorted);
foreach (const QFileInfo &fileInfo, fileInfoList) {
fileInfo.size();
}
}
}
void sizeSpeedWithoutFileInfoList() {
QDir testdir(QDir::tempPath() + QLatin1String("/test_speed"));
testdir.setSorting(QDir::Unsorted);
QBENCHMARK {
QStringList fileList = testdir.entryList(QDir::NoFilter, QDir::Unsorted);
foreach (const QString &filename, fileList) {
QFileInfo fileInfo(filename);
fileInfo.size();
}
}
}
void iDontWantAnyStat() {
QDir testdir(QDir::tempPath() + QLatin1String("/test_speed"));
testdir.setSorting(QDir::Unsorted);
testdir.setFilter(QDir::AllEntries | QDir::System | QDir::Hidden);
QBENCHMARK {
QStringList fileList = testdir.entryList(QDir::NoFilter, QDir::Unsorted);
foreach (const QString &filename, fileList) {
}
}
}
void testLowLevel() {
#ifdef Q_OS_WIN
const wchar_t *dirpath = (wchar_t*)testdir.absolutePath().utf16();
wchar_t appendedPath[MAX_PATH];
wcscpy(appendedPath, dirpath);
wcscat(appendedPath, L"\\*");
WIN32_FIND_DATA fd;
HANDLE hSearch = FindFirstFileW(appendedPath, &fd);
QVERIFY(hSearch == INVALID_HANDLE_VALUE);
QBENCHMARK {
do {
} while (FindNextFile(hSearch, &fd));
}
FindClose(hSearch);
#else
QDir testdir(QDir::tempPath() + QLatin1String("/test_speed"));
DIR *dir = opendir(qPrintable(testdir.absolutePath()));
QVERIFY(dir);
QVERIFY(!chdir(qPrintable(testdir.absolutePath())));
QBENCHMARK {
struct dirent *item = readdir(dir);
while (item) {
char *fileName = item->d_name;
struct stat fileStat;
QVERIFY(!stat(fileName, &fileStat));
item = readdir(dir);
}
}
closedir(dir);
#endif
}
};
QTEST_MAIN(Test)
#include "tst_qdir.moc"
<commit_msg>Benchmark: Duplicate the tests on QDirIterator as well.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#ifdef Q_OS_WIN
# include <windows.h>
#else
# include <sys/stat.h>
# include <sys/types.h>
# include <dirent.h>
# include <unistd.h>
#endif
class Test : public QObject{
Q_OBJECT
public slots:
void initTestCase() {
QDir testdir = QDir::tempPath();
const QString subfolder_name = QLatin1String("test_speed");
QVERIFY(testdir.mkdir(subfolder_name));
QVERIFY(testdir.cd(subfolder_name));
for (uint i=0; i<10000; ++i) {
QFile file(testdir.absolutePath() + "/testfile_" + QString::number(i));
file.open(QIODevice::WriteOnly);
}
}
void cleanupTestCase() {
{
QDir testdir(QDir::tempPath() + QLatin1String("/test_speed"));
testdir.setSorting(QDir::Unsorted);
testdir.setFilter(QDir::AllEntries | QDir::System | QDir::Hidden);
foreach (const QString &filename, testdir.entryList()) {
testdir.remove(filename);
}
}
const QDir temp = QDir(QDir::tempPath());
temp.rmdir(QLatin1String("test_speed"));
}
private slots:
void baseline() {}
void sizeSpeed() {
QDir testdir(QDir::tempPath() + QLatin1String("/test_speed"));
QBENCHMARK {
QFileInfoList fileInfoList = testdir.entryInfoList(QDir::Files, QDir::Unsorted);
foreach (const QFileInfo &fileInfo, fileInfoList) {
fileInfo.isDir();
fileInfo.size();
}
}
}
void sizeSpeedIterator() {
QDir testdir(QDir::tempPath() + QLatin1String("/test_speed"));
QBENCHMARK {
QDirIterator dit(testdir.path(), QDir::Files);
while (dit.hasNext()) {
dit.fileInfo().isDir();
dit.fileInfo().size();
dit.next();
}
}
}
void sizeSpeedWithoutFilter() {
QDir testdir(QDir::tempPath() + QLatin1String("/test_speed"));
QBENCHMARK {
QFileInfoList fileInfoList = testdir.entryInfoList(QDir::NoFilter, QDir::Unsorted);
foreach (const QFileInfo &fileInfo, fileInfoList) {
fileInfo.size();
}
}
}
void sizeSpeedWithoutFilterIterator() {
QDir testdir(QDir::tempPath() + QLatin1String("/test_speed"));
QBENCHMARK {
QDirIterator dit(testdir.path());
while (dit.hasNext()) {
dit.fileInfo().isDir();
dit.fileInfo().size();
dit.next();
}
}
}
void sizeSpeedWithoutFileInfoList() {
QDir testdir(QDir::tempPath() + QLatin1String("/test_speed"));
testdir.setSorting(QDir::Unsorted);
QBENCHMARK {
QStringList fileList = testdir.entryList(QDir::NoFilter, QDir::Unsorted);
foreach (const QString &filename, fileList) {
QFileInfo fileInfo(filename);
fileInfo.size();
}
}
}
void iDontWantAnyStat() {
QDir testdir(QDir::tempPath() + QLatin1String("/test_speed"));
testdir.setSorting(QDir::Unsorted);
testdir.setFilter(QDir::AllEntries | QDir::System | QDir::Hidden);
QBENCHMARK {
QStringList fileList = testdir.entryList(QDir::NoFilter, QDir::Unsorted);
foreach (const QString &filename, fileList) {
}
}
}
void iDontWantAnyStatIterator() {
QBENCHMARK {
QDirIterator dit(QDir::tempPath() + QLatin1String("/test_speed"));
while (dit.hasNext()) {
dit.next();
}
}
}
void sizeSpeedWithoutFilterLowLevel() {
#ifdef Q_OS_WIN
const wchar_t *dirpath = (wchar_t*)testdir.absolutePath().utf16();
wchar_t appendedPath[MAX_PATH];
wcscpy(appendedPath, dirpath);
wcscat(appendedPath, L"\\*");
WIN32_FIND_DATA fd;
HANDLE hSearch = FindFirstFileW(appendedPath, &fd);
QVERIFY(hSearch == INVALID_HANDLE_VALUE);
QBENCHMARK {
do {
} while (FindNextFile(hSearch, &fd));
}
FindClose(hSearch);
#else
QDir testdir(QDir::tempPath() + QLatin1String("/test_speed"));
DIR *dir = opendir(qPrintable(testdir.absolutePath()));
QVERIFY(dir);
QVERIFY(!chdir(qPrintable(testdir.absolutePath())));
QBENCHMARK {
struct dirent *item = readdir(dir);
while (item) {
char *fileName = item->d_name;
struct stat fileStat;
QVERIFY(!stat(fileName, &fileStat));
item = readdir(dir);
}
}
closedir(dir);
#endif
}
};
QTEST_MAIN(Test)
#include "tst_qdir.moc"
<|endoftext|> |
<commit_before>//=====================================================================//
/*! @file
@brief RX65N デジタル・ストレージ・オシロスコープ @n
マイコン内臓12ビットA/D変換を使って、波形を観測するガジェット
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2018 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/renesas.hpp"
#include "common/cmt_io.hpp"
#include "common/fixed_fifo.hpp"
#include "common/sci_io.hpp"
#include "common/sci_i2c_io.hpp"
#include "common/format.hpp"
#include "common/command.hpp"
#include "common/spi_io2.hpp"
#include "common/sdc_man.hpp"
#include "common/tpu_io.hpp"
#include "common/qspi_io.hpp"
#include "graphics/font8x16.hpp"
#include "graphics/graphics.hpp"
#include "graphics/filer.hpp"
#define CASH_KFONT
#include "graphics/kfont.hpp"
#include "chip/FT5206.hpp"
#include "capture.hpp"
#include "render_wave.hpp"
namespace {
typedef device::PORT<device::PORT7, device::bitpos::B0> LED;
typedef device::system_io<12000000> SYSTEM_IO;
device::cmt_io<device::CMT0, utils::null_task> cmt_;
typedef utils::fixed_fifo<char, 512> RECV_BUFF;
typedef utils::fixed_fifo<char, 1024> SEND_BUFF;
typedef device::sci_io<device::SCI9, RECV_BUFF, SEND_BUFF> SCI;
SCI sci_;
// カード電源制御は使わないので、「device::NULL_PORT」を指定する。
// typedef device::PORT<device::PORT6, device::bitpos::B4> SDC_POWER;
typedef device::NULL_PORT SDC_POWER;
#ifdef SDHI_IF
// RX65N Envision Kit の SDHI ポートは、候補3になっている
typedef fatfs::sdhi_io<device::SDHI, SDC_POWER, device::port_map::option::THIRD> SDHI;
SDHI sdh_;
#else
// Soft SDC 用 SPI 定義(SPI)
typedef device::PORT<device::PORT2, device::bitpos::B2> MISO; // DAT0
typedef device::PORT<device::PORT2, device::bitpos::B0> MOSI; // CMD
typedef device::PORT<device::PORT2, device::bitpos::B1> SPCK; // CLK
typedef device::spi_io2<MISO, MOSI, SPCK> SPI; ///< Soft SPI 定義
SPI spi_;
typedef device::PORT<device::PORT1, device::bitpos::B7> SDC_SELECT; // DAT3 カード選択信号
typedef device::PORT<device::PORT2, device::bitpos::B5> SDC_DETECT; // CD カード検出
typedef fatfs::mmc_io<SPI, SDC_SELECT, SDC_POWER, SDC_DETECT> MMC; // ハードウェアー定義
MMC sdh_(spi_, 20000000);
#endif
typedef utils::sdc_man SDC;
SDC sdc_;
typedef device::PORT<device::PORT6, device::bitpos::B3> LCD_DISP;
typedef device::PORT<device::PORT6, device::bitpos::B6> LCD_LIGHT;
typedef device::glcdc_io<device::GLCDC, 480, 272,
device::glcdc_def::PIX_TYPE::RGB565> GLCDC_IO;
/// device::glcdc_def::PIX_TYPE::CLUT8> GLCDC_IO;
GLCDC_IO glcdc_io_;
typedef device::drw2d_mgr<device::DRW2D, 480, 272> DRW2D_MGR;
DRW2D_MGR drw2d_mgr_;
typedef graphics::font8x16 AFONT;
#ifdef CASH_KFONT
typedef graphics::kfont<16, 16, 64> KFONT;
#else
typedef graphics::kfont<16, 16> KFONT;
#endif
KFONT kfont_;
typedef graphics::render<uint16_t, 480, 272, AFONT, KFONT> RENDER;
RENDER render_(reinterpret_cast<uint16_t*>(0x00000000), kfont_);
typedef utils::capture<2048> CAPTURE;
CAPTURE capture_;
// FT5206, SCI6 簡易 I2C 定義
typedef device::PORT<device::PORT0, device::bitpos::B7> FT5206_RESET;
typedef utils::fixed_fifo<uint8_t, 64> RB6;
typedef utils::fixed_fifo<uint8_t, 64> SB6;
typedef device::sci_i2c_io<device::SCI6, RB6, SB6,
device::port_map::option::FIRST_I2C> FT5206_I2C;
FT5206_I2C ft5206_i2c_;
typedef chip::FT5206<FT5206_I2C> FT5206;
FT5206 ft5206_(ft5206_i2c_);
typedef utils::render_wave<RENDER, CAPTURE, FT5206> RENDER_WAVE;
RENDER_WAVE render_wave_(render_, capture_, ft5206_);
utils::command<256> cmd_;
utils::capture_trigger trigger_ = utils::capture_trigger::NONE;
bool check_mount_() {
return sdc_.get_mount();
}
void update_led_()
{
static uint8_t n = 0;
++n;
if(n >= 30) {
n = 0;
}
if(n < 10) {
LED::P = 0;
} else {
LED::P = 1;
}
}
void command_()
{
if(!cmd_.service()) {
return;
}
uint8_t cmdn = cmd_.get_words();
if(cmdn >= 1) {
bool f = false;
if(cmd_.cmp_word(0, "dir")) { // dir [xxx]
if(check_mount_()) {
if(cmdn >= 2) {
char tmp[128];
cmd_.get_word(1, tmp, sizeof(tmp));
sdc_.dir(tmp);
} else {
sdc_.dir("");
}
}
f = true;
} else if(cmd_.cmp_word(0, "cd")) { // cd [xxx]
if(check_mount_()) {
if(cmdn >= 2) {
char tmp[128];
cmd_.get_word(1, tmp, sizeof(tmp));
sdc_.cd(tmp);
} else {
sdc_.cd("/");
}
}
f = true;
} else if(cmd_.cmp_word(0, "pwd")) { // pwd
utils::format("%s\n") % sdc_.get_current();
f = true;
} else if(cmd_.cmp_word(0, "cap")) { // capture
trigger_ = utils::capture_trigger::SINGLE;
capture_.set_trigger(trigger_);
f = true;
} else if(cmd_.cmp_word(0, "help")) {
utils::format(" dir [path]\n");
utils::format(" cd [path]\n");
utils::format(" pwd\n");
utils::format(" cap single trigger\n");
f = true;
}
if(!f) {
char tmp[128];
if(cmd_.get_word(0, tmp, sizeof(tmp))) {
utils::format("Command error: '%s'\n") % tmp;
}
}
}
}
}
extern "C" {
void sci_putch(char ch)
{
sci_.putch(ch);
}
void sci_puts(const char* str)
{
sci_.puts(str);
}
char sci_getch(void)
{
return sci_.getch();
}
uint16_t sci_length()
{
return sci_.recv_length();
}
DSTATUS disk_initialize(BYTE drv) {
return sdh_.disk_initialize(drv);
}
DSTATUS disk_status(BYTE drv) {
return sdh_.disk_status(drv);
}
DRESULT disk_read(BYTE drv, BYTE* buff, DWORD sector, UINT count) {
return sdh_.disk_read(drv, buff, sector, count);
}
DRESULT disk_write(BYTE drv, const BYTE* buff, DWORD sector, UINT count) {
return sdh_.disk_write(drv, buff, sector, count);
}
DRESULT disk_ioctl(BYTE drv, BYTE ctrl, void* buff) {
return sdh_.disk_ioctl(drv, ctrl, buff);
}
DWORD get_fattime(void) {
time_t t = 0;
/// rtc_.get_time(t);
return utils::str::get_fattime(t);
}
// for syscalls API (POSIX API)
void utf8_to_sjis(const char* src, char* dst, uint32_t len) {
utils::str::utf8_to_sjis(src, dst, len);
}
int fatfs_get_mount() {
return check_mount_();
}
int make_full_path(const char* src, char* dst, uint16_t len)
{
return sdc_.make_full_path(src, dst, len);
}
}
int main(int argc, char** argv);
int main(int argc, char** argv)
{
SYSTEM_IO::setup_system_clock();
{ // SCI 設定
static const uint8_t sci_level = 2;
sci_.start(115200, sci_level);
}
{ // SD カード・クラスの初期化
sdh_.start();
sdc_.start();
}
{ // キャプチャー開始
// uint32_t freq = 2000000; // 2 MHz
uint32_t freq = 100000; // 100 KHz
if(!capture_.start(freq)) {
utils::format("Capture not start...\n");
}
}
utils::format("RTK5RX65N Start for Digital Storage Oscilloscope\n");
cmd_.set_prompt("# ");
{ // GLCDC の初期化
LCD_DISP::DIR = 1;
LCD_LIGHT::DIR = 1;
LCD_DISP::P = 0; // DISP Disable
LCD_LIGHT::P = 0; // BackLight Disable (No PWM)
if(glcdc_io_.start()) {
utils::format("Start GLCDC\n");
LCD_DISP::P = 1; // DISP Enable
LCD_LIGHT::P = 1; // BackLight Enable (No PWM)
if(!glcdc_io_.control(GLCDC_IO::CONTROL_CMD::START_DISPLAY)) {
utils::format("GLCDC ctrl fail...\n");
}
} else {
utils::format("GLCDC Fail\n");
}
}
{ // DRW2D 初期化
auto ver = drw2d_mgr_.get_version();
utils::format("DRW2D Version: %04X\n") % ver;
if(drw2d_mgr_.start(0x00000000)) {
utils:: format("Start DRW2D\n");
} else {
utils:: format("DRW2D Fail\n");
}
}
{ // FT5206 touch screen controller
FT5206::reset<FT5206_RESET>();
uint8_t intr_lvl = 1;
if(!ft5206_i2c_.start(FT5206_I2C::SPEED::STANDARD, intr_lvl)) {
utils::format("FT5206 I2C Start Fail...\n");
}
if(!ft5206_.start()) {
utils::format("FT5206 Start Fail...\n");
}
}
LED::DIR = 1;
{ // startup trigger...
trigger_ = utils::capture_trigger::SINGLE;
capture_.set_trigger(trigger_);
}
// タッチパネルの安定待ち
#if 0
{
uint8_t nnn = 0;
while(1) {
glcdc_io_.sync_vpos();
ft5206_.update();
// if(ft5206_.get_touch_num() == 0) {
// ++nnn;
/// if(nnn >= 60) break;
// } else {
// utils::format("%d\n") % static_cast<uint16_t>(ft5206_.get_touch_num());
// nnn = 0;
// }
}
}
#endif
while(1) {
glcdc_io_.sync_vpos();
ft5206_.update();
sdc_.service(sdh_.service());
command_();
// タッチ操作による画面更新が必要か?
bool f = render_wave_.ui_service();
// 波形をキャプチャーしたら描画
if(f || (trigger_ != utils::capture_trigger::NONE
&& capture_.get_trigger() == utils::capture_trigger::NONE)) {
trigger_ = utils::capture_trigger::NONE;
render_wave_.update();
}
update_led_();
}
}
<commit_msg>update: cleanup<commit_after>//=====================================================================//
/*! @file
@brief RX65N デジタル・ストレージ・オシロスコープ @n
マイコン内臓12ビットA/D変換を使って、波形を観測するガジェット
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2018 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/renesas.hpp"
#include "common/cmt_io.hpp"
#include "common/fixed_fifo.hpp"
#include "common/sci_io.hpp"
#include "common/sci_i2c_io.hpp"
#include "common/format.hpp"
#include "common/command.hpp"
#include "common/spi_io2.hpp"
#include "common/sdc_man.hpp"
#include "common/tpu_io.hpp"
#include "common/qspi_io.hpp"
#include "graphics/font8x16.hpp"
#include "graphics/graphics.hpp"
#include "graphics/filer.hpp"
#define CASH_KFONT
#include "graphics/kfont.hpp"
#include "chip/FT5206.hpp"
#include "capture.hpp"
#include "render_wave.hpp"
namespace {
typedef device::PORT<device::PORT7, device::bitpos::B0> LED;
typedef device::system_io<12000000> SYSTEM_IO;
device::cmt_io<device::CMT0, utils::null_task> cmt_;
typedef utils::fixed_fifo<char, 512> RECV_BUFF;
typedef utils::fixed_fifo<char, 1024> SEND_BUFF;
typedef device::sci_io<device::SCI9, RECV_BUFF, SEND_BUFF> SCI;
SCI sci_;
// カード電源制御は使わないので、「device::NULL_PORT」を指定する。
// typedef device::PORT<device::PORT6, device::bitpos::B4> SDC_POWER;
typedef device::NULL_PORT SDC_POWER;
#ifdef SDHI_IF
// RX65N Envision Kit の SDHI ポートは、候補3になっている
typedef fatfs::sdhi_io<device::SDHI, SDC_POWER, device::port_map::option::THIRD> SDHI;
SDHI sdh_;
#else
// Soft SDC 用 SPI 定義(SPI)
typedef device::PORT<device::PORT2, device::bitpos::B2> MISO; // DAT0
typedef device::PORT<device::PORT2, device::bitpos::B0> MOSI; // CMD
typedef device::PORT<device::PORT2, device::bitpos::B1> SPCK; // CLK
typedef device::spi_io2<MISO, MOSI, SPCK> SPI; ///< Soft SPI 定義
SPI spi_;
typedef device::PORT<device::PORT1, device::bitpos::B7> SDC_SELECT; // DAT3 カード選択信号
typedef device::PORT<device::PORT2, device::bitpos::B5> SDC_DETECT; // CD カード検出
typedef fatfs::mmc_io<SPI, SDC_SELECT, SDC_POWER, SDC_DETECT> MMC; // ハードウェアー定義
MMC sdh_(spi_, 20000000);
#endif
typedef utils::sdc_man SDC;
SDC sdc_;
typedef device::PORT<device::PORT6, device::bitpos::B3> LCD_DISP;
typedef device::PORT<device::PORT6, device::bitpos::B6> LCD_LIGHT;
typedef device::glcdc_io<device::GLCDC, 480, 272,
device::glcdc_def::PIX_TYPE::RGB565> GLCDC_IO;
/// device::glcdc_def::PIX_TYPE::CLUT8> GLCDC_IO;
GLCDC_IO glcdc_io_;
typedef device::drw2d_mgr<device::DRW2D, 480, 272> DRW2D_MGR;
DRW2D_MGR drw2d_mgr_;
typedef graphics::font8x16 AFONT;
#ifdef CASH_KFONT
typedef graphics::kfont<16, 16, 64> KFONT;
#else
typedef graphics::kfont<16, 16> KFONT;
#endif
KFONT kfont_;
typedef graphics::render<uint16_t, 480, 272, AFONT, KFONT> RENDER;
RENDER render_(reinterpret_cast<uint16_t*>(0x00000000), kfont_);
typedef utils::capture<2048> CAPTURE;
CAPTURE capture_;
// FT5206, SCI6 簡易 I2C 定義
typedef device::PORT<device::PORT0, device::bitpos::B7> FT5206_RESET;
typedef utils::fixed_fifo<uint8_t, 64> RB6;
typedef utils::fixed_fifo<uint8_t, 64> SB6;
typedef device::sci_i2c_io<device::SCI6, RB6, SB6,
device::port_map::option::FIRST_I2C> FT5206_I2C;
FT5206_I2C ft5206_i2c_;
typedef chip::FT5206<FT5206_I2C> FT5206;
FT5206 ft5206_(ft5206_i2c_);
typedef utils::render_wave<RENDER, CAPTURE, FT5206> RENDER_WAVE;
RENDER_WAVE render_wave_(render_, capture_, ft5206_);
utils::command<256> cmd_;
utils::capture_trigger trigger_ = utils::capture_trigger::NONE;
bool check_mount_() {
return sdc_.get_mount();
}
void update_led_()
{
static uint8_t n = 0;
++n;
if(n >= 30) {
n = 0;
}
if(n < 10) {
LED::P = 0;
} else {
LED::P = 1;
}
}
void command_()
{
if(!cmd_.service()) {
return;
}
uint8_t cmdn = cmd_.get_words();
if(cmdn >= 1) {
bool f = false;
if(cmd_.cmp_word(0, "dir")) { // dir [xxx]
if(check_mount_()) {
if(cmdn >= 2) {
char tmp[128];
cmd_.get_word(1, tmp, sizeof(tmp));
sdc_.dir(tmp);
} else {
sdc_.dir("");
}
}
f = true;
} else if(cmd_.cmp_word(0, "cd")) { // cd [xxx]
if(check_mount_()) {
if(cmdn >= 2) {
char tmp[128];
cmd_.get_word(1, tmp, sizeof(tmp));
sdc_.cd(tmp);
} else {
sdc_.cd("/");
}
}
f = true;
} else if(cmd_.cmp_word(0, "pwd")) { // pwd
utils::format("%s\n") % sdc_.get_current();
f = true;
} else if(cmd_.cmp_word(0, "cap")) { // capture
trigger_ = utils::capture_trigger::SINGLE;
capture_.set_trigger(trigger_);
f = true;
} else if(cmd_.cmp_word(0, "help")) {
utils::format(" dir [path]\n");
utils::format(" cd [path]\n");
utils::format(" pwd\n");
utils::format(" cap single trigger\n");
f = true;
}
if(!f) {
char tmp[128];
if(cmd_.get_word(0, tmp, sizeof(tmp))) {
utils::format("Command error: '%s'\n") % tmp;
}
}
}
}
}
extern "C" {
void sci_putch(char ch)
{
sci_.putch(ch);
}
void sci_puts(const char* str)
{
sci_.puts(str);
}
char sci_getch(void)
{
return sci_.getch();
}
uint16_t sci_length()
{
return sci_.recv_length();
}
DSTATUS disk_initialize(BYTE drv) {
return sdh_.disk_initialize(drv);
}
DSTATUS disk_status(BYTE drv) {
return sdh_.disk_status(drv);
}
DRESULT disk_read(BYTE drv, BYTE* buff, DWORD sector, UINT count) {
return sdh_.disk_read(drv, buff, sector, count);
}
DRESULT disk_write(BYTE drv, const BYTE* buff, DWORD sector, UINT count) {
return sdh_.disk_write(drv, buff, sector, count);
}
DRESULT disk_ioctl(BYTE drv, BYTE ctrl, void* buff) {
return sdh_.disk_ioctl(drv, ctrl, buff);
}
DWORD get_fattime(void) {
time_t t = 0;
/// rtc_.get_time(t);
return utils::str::get_fattime(t);
}
// for syscalls API (POSIX API)
void utf8_to_sjis(const char* src, char* dst, uint32_t len) {
utils::str::utf8_to_sjis(src, dst, len);
}
int fatfs_get_mount() {
return check_mount_();
}
int make_full_path(const char* src, char* dst, uint16_t len)
{
return sdc_.make_full_path(src, dst, len);
}
}
int main(int argc, char** argv);
int main(int argc, char** argv)
{
SYSTEM_IO::setup_system_clock();
{ // SCI 設定
static const uint8_t sci_level = 2;
sci_.start(115200, sci_level);
}
{ // SD カード・クラスの初期化
sdh_.start();
sdc_.start();
}
{ // キャプチャー開始
// uint32_t freq = 2000000; // 2 MHz
uint32_t freq = 100000; // 100 KHz
if(!capture_.start(freq)) {
utils::format("Capture not start...\n");
}
}
utils::format("RTK5RX65N Start for Digital Storage Oscilloscope\n");
cmd_.set_prompt("# ");
{ // GLCDC の初期化
LCD_DISP::DIR = 1;
LCD_LIGHT::DIR = 1;
LCD_DISP::P = 0; // DISP Disable
LCD_LIGHT::P = 0; // BackLight Disable (No PWM)
if(glcdc_io_.start()) {
utils::format("Start GLCDC\n");
LCD_DISP::P = 1; // DISP Enable
LCD_LIGHT::P = 1; // BackLight Enable (No PWM)
if(!glcdc_io_.control(GLCDC_IO::CONTROL_CMD::START_DISPLAY)) {
utils::format("GLCDC ctrl fail...\n");
}
} else {
utils::format("GLCDC Fail\n");
}
}
{ // DRW2D 初期化
auto ver = drw2d_mgr_.get_version();
utils::format("DRW2D Version: %04X\n") % ver;
if(drw2d_mgr_.start(0x00000000)) {
utils:: format("Start DRW2D\n");
} else {
utils:: format("DRW2D Fail\n");
}
}
{ // FT5206 touch screen controller
FT5206::reset<FT5206_RESET>();
uint8_t intr_lvl = 1;
if(!ft5206_i2c_.start(FT5206_I2C::SPEED::STANDARD, intr_lvl)) {
utils::format("FT5206 I2C Start Fail...\n");
}
if(!ft5206_.start()) {
utils::format("FT5206 Start Fail...\n");
}
}
LED::DIR = 1;
{ // startup trigger...
trigger_ = utils::capture_trigger::SINGLE;
capture_.set_trigger(trigger_);
}
// タッチパネルの安定待ち
#if 0
{
uint8_t nnn = 0;
while(1) {
glcdc_io_.sync_vpos();
ft5206_.update();
// if(ft5206_.get_touch_num() == 0) {
// ++nnn;
/// if(nnn >= 60) break;
// } else {
// utils::format("%d\n") % static_cast<uint16_t>(ft5206_.get_touch_num());
// nnn = 0;
// }
}
}
#endif
while(1) {
glcdc_io_.sync_vpos();
ft5206_.update();
sdc_.service(sdh_.service());
command_();
// タッチ操作による画面更新が必要か?
bool f = render_wave_.ui_service();
// 波形をキャプチャーしたら描画
if(f || (trigger_ != utils::capture_trigger::NONE
&& capture_.get_trigger() == utils::capture_trigger::NONE)) {
trigger_ = utils::capture_trigger::NONE;
render_wave_.update();
}
update_led_();
}
}
<|endoftext|> |
<commit_before>//..............................................................................
//
// This file is part of the Jancy toolkit.
//
// Jancy is distributed under the MIT license.
// For details see accompanying license.txt file,
// the public copy of which is also available at:
// http://tibbo.com/downloads/archive/jancy/license.txt
//
//..............................................................................
#include "pch.h"
#include "jnc_ct_DoxyHost.h"
#include "jnc_ct_Module.h"
namespace jnc {
namespace ct {
//..............................................................................
DoxyHost::DoxyHost()
{
m_module = Module::getCurrentConstructedModule();
ASSERT(m_module);
}
dox::Block*
DoxyHost::findItemBlock(handle_t item0)
{
ModuleItem* item = (ModuleItem*) item0;
return item->getDecl()->m_doxyBlock;
}
dox::Block*
DoxyHost::getItemBlock(handle_t item0)
{
ModuleItem* item = (ModuleItem*) item0;
return getItemBlock(item, item->getDecl());
}
void
DoxyHost::setItemBlock(
handle_t item0,
dox::Block* block
)
{
ModuleItem* item = (ModuleItem*) item0;
setItemBlock(item, item->getDecl(), block);
}
dox::Block*
DoxyHost::getItemBlock(
ModuleItem* item,
ModuleItemDecl* itemDecl
)
{
if (!itemDecl->m_doxyBlock)
itemDecl->m_doxyBlock = m_module->m_doxyModule.createBlock(item);
return itemDecl->m_doxyBlock;
}
void
DoxyHost::setItemBlock(
ModuleItem* item,
ModuleItemDecl* itemDecl,
dox::Block* block
)
{
itemDecl->m_doxyBlock = block;
block->m_item = item;
}
sl::String
DoxyHost::createItemRefId(handle_t item)
{
return ((ModuleItem*)item)->createDoxyRefId();
}
sl::StringRef
DoxyHost::getItemCompoundElementName(handle_t item)
{
ModuleItemKind itemKind = ((ModuleItem*) item)->getItemKind();
bool isCompoundFile =
itemKind == ModuleItemKind_Namespace ||
itemKind == ModuleItemKind_Type && ((Type*)item)->getTypeKind() != TypeKind_Enum;
return isCompoundFile ? itemKind == ModuleItemKind_Namespace ? "innernamespace" : "innerclass" : NULL;
}
handle_t
DoxyHost::findItem(
const sl::StringRef& name,
size_t overloadIdx
)
{
ModuleItem* item = m_module->m_namespaceMgr.getGlobalNamespace()->findItemByName(name);
if (!item)
return NULL;
if (overloadIdx && item->getItemKind() == ModuleItemKind_Function)
{
Function* overload = ((Function*)item)->getOverload(overloadIdx);
if (overload)
item = overload;
}
return item;
}
handle_t
DoxyHost::getCurrentNamespace()
{
return m_module->m_namespaceMgr.getCurrentNamespace();
}
bool
DoxyHost::generateGlobalNamespaceDocumentation(
const sl::StringRef& outputDir,
sl::String* itemXml,
sl::String* indexXml
)
{
return m_module->m_namespaceMgr.getGlobalNamespace()->generateDocumentation(outputDir, itemXml, indexXml);
}
//..............................................................................
} // namespace jnc
} // namespace ct
<commit_msg>[jnc_ct] DoxyHost::setItemBlock should check for null-blocks<commit_after>//..............................................................................
//
// This file is part of the Jancy toolkit.
//
// Jancy is distributed under the MIT license.
// For details see accompanying license.txt file,
// the public copy of which is also available at:
// http://tibbo.com/downloads/archive/jancy/license.txt
//
//..............................................................................
#include "pch.h"
#include "jnc_ct_DoxyHost.h"
#include "jnc_ct_Module.h"
namespace jnc {
namespace ct {
//..............................................................................
DoxyHost::DoxyHost()
{
m_module = Module::getCurrentConstructedModule();
ASSERT(m_module);
}
dox::Block*
DoxyHost::findItemBlock(handle_t item0)
{
ModuleItem* item = (ModuleItem*) item0;
return item->getDecl()->m_doxyBlock;
}
dox::Block*
DoxyHost::getItemBlock(handle_t item0)
{
ModuleItem* item = (ModuleItem*) item0;
return getItemBlock(item, item->getDecl());
}
void
DoxyHost::setItemBlock(
handle_t item0,
dox::Block* block
)
{
ModuleItem* item = (ModuleItem*) item0;
setItemBlock(item, item->getDecl(), block);
}
dox::Block*
DoxyHost::getItemBlock(
ModuleItem* item,
ModuleItemDecl* itemDecl
)
{
if (!itemDecl->m_doxyBlock)
itemDecl->m_doxyBlock = m_module->m_doxyModule.createBlock(item);
return itemDecl->m_doxyBlock;
}
void
DoxyHost::setItemBlock(
ModuleItem* item,
ModuleItemDecl* itemDecl,
dox::Block* block
)
{
itemDecl->m_doxyBlock = block;
if (block)
block->m_item = item;
}
sl::String
DoxyHost::createItemRefId(handle_t item)
{
return ((ModuleItem*)item)->createDoxyRefId();
}
sl::StringRef
DoxyHost::getItemCompoundElementName(handle_t item)
{
ModuleItemKind itemKind = ((ModuleItem*) item)->getItemKind();
bool isCompoundFile =
itemKind == ModuleItemKind_Namespace ||
itemKind == ModuleItemKind_Type && ((Type*)item)->getTypeKind() != TypeKind_Enum;
return isCompoundFile ? itemKind == ModuleItemKind_Namespace ? "innernamespace" : "innerclass" : NULL;
}
handle_t
DoxyHost::findItem(
const sl::StringRef& name,
size_t overloadIdx
)
{
ModuleItem* item = m_module->m_namespaceMgr.getGlobalNamespace()->findItemByName(name);
if (!item)
return NULL;
if (overloadIdx && item->getItemKind() == ModuleItemKind_Function)
{
Function* overload = ((Function*)item)->getOverload(overloadIdx);
if (overload)
item = overload;
}
return item;
}
handle_t
DoxyHost::getCurrentNamespace()
{
return m_module->m_namespaceMgr.getCurrentNamespace();
}
bool
DoxyHost::generateGlobalNamespaceDocumentation(
const sl::StringRef& outputDir,
sl::String* itemXml,
sl::String* indexXml
)
{
return m_module->m_namespaceMgr.getGlobalNamespace()->generateDocumentation(outputDir, itemXml, indexXml);
}
//..............................................................................
} // namespace jnc
} // namespace ct
<|endoftext|> |
<commit_before>// @(#)root/hist:$Id$
// Author: Olivier Couet 13/07/09
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "Riostream.h"
#include "TPad.h"
#include "TGraphStruct.h"
#include <stdio.h>
#include <gvc.h>
#include <gvplugin.h>
#ifdef GVIZ_STATIC
extern gvplugin_library_t gvplugin_dot_layout_LTX_library;
///extern gvplugin_library_t gvplugin_neato_layout_LTX_library;
///extern gvplugin_library_t gvplugin_core_LTX_library;
lt_symlist_t lt_preloaded_symbols[] = {
{ "gvplugin_dot_layout_LTX_library", (void*)(&gvplugin_dot_layout_LTX_library) },
/// { "gvplugin_neato_layout_LTX_library", (void*)(&gvplugin_neato_layout_LTX_library) },
/// { "gvplugin_core_LTX_library", (void*)(&gvplugin_core_LTX_library) },
{ 0, 0 }
};
#endif
ClassImp(TGraphStruct)
//______________________________________________________________________________
/* Begin_Html
<center><h2>Graph Structure class</h2></center>
The Graph Structure is an interface to the graphviz package.
<p>
The graphviz package is a graph visualization system. This interface consists in
three classes:
<ol>
<li> TGraphStruct: holds the graph structure. It uses the graphiz library to
layout the graphs and the ROOT graphics to paint them.
<li> TGraphNode: Is a graph node object which can be added in a TGraphStruct.
<li> TGraphEdge: Is an edge object connecting two nodes which can be added in
a TGraphStruct.
</ol>
End_Html
Begin_Macro(source)
../../../tutorials/graphs/graphstruct.C
End_Macro
Begin_Html
A graph structure can be dumped into a "dot" file using DumpAsDotFile.
End_Html */
//______________________________________________________________________________
TGraphStruct::TGraphStruct()
{
// Graph Structure default constructor.
fNodes = 0;
fEdges = 0;
fGVGraph = 0;
fGVC = 0;
SetMargin();
}
//______________________________________________________________________________
TGraphStruct::~TGraphStruct()
{
// Graph Structure default destructor.
gvFreeLayout(fGVC,fGVGraph);
agclose(fGVGraph);
gvFreeContext(fGVC);
if (fNodes) delete fNodes;
if (fEdges) delete fEdges;
}
//______________________________________________________________________________
void TGraphStruct::AddEdge(TGraphEdge *edge)
{
// Add the edge "edge" in this TGraphStruct.
if (!fEdges) fEdges = new TList;
fEdges->Add(edge);
}
//______________________________________________________________________________
TGraphEdge *TGraphStruct::AddEdge(TGraphNode *n1, TGraphNode *n2)
{
// Create an edge between n1 and n2 and put it in this graph.
//
// Two edges can connect the same nodes the same way, so there
// is no need to check if an edge already exists.
if (!fEdges) fEdges = new TList;
TGraphEdge *edge = new TGraphEdge(n1, n2);
fEdges->Add(edge);
return edge;
}
//______________________________________________________________________________
void TGraphStruct::AddNode(TGraphNode *node)
{
// Add the node "node" in this TGraphStruct.
if (!fNodes) fNodes = new TList;
fNodes->Add(node);
}
//______________________________________________________________________________
TGraphNode *TGraphStruct::AddNode(const char *name, const char *title)
{
// Create the node "name" if it does not exist and add it to this TGraphStruct.
if (!fNodes) fNodes = new TList;
TGraphNode *node = (TGraphNode*)fNodes->FindObject(name);
if (!node) {
node = new TGraphNode(name, title);
fNodes->Add(node);
}
return node;
}
//______________________________________________________________________________
void TGraphStruct::DumpAsDotFile(const char *filename)
{
// Dump this graph structure as a "dot" file.
if (!fGVGraph) {
Int_t ierr = Layout();
if (ierr) return;
}
FILE *file;
file=fopen(filename,"wt");
agwrite(fGVGraph, file);
fclose(file);
}
//______________________________________________________________________________
void TGraphStruct::Draw(Option_t *option)
{
// Draw the graph
if (!fGVGraph) {
Int_t ierr = Layout();
if (ierr) return;
}
// Get the bounding box
if (gPad) {
gPad->Range(GD_bb(fGVGraph).LL.x-fMargin, GD_bb(fGVGraph).LL.y-fMargin,
GD_bb(fGVGraph).UR.x+fMargin, GD_bb(fGVGraph).UR.y+fMargin);
}
AppendPad(option);
// Draw the nodes
if (fNodes) {
TGraphNode *node;
node = (TGraphNode*) fNodes->First();
node->Draw();
for(Int_t i = 1; i < fNodes->GetSize(); i++){
node = (TGraphNode*)fNodes->After(node);
if (node) node->Draw();
}
}
// Draw the edges
if (fEdges) {
TGraphEdge *edge;
edge = (TGraphEdge*) fEdges->First();
edge->Draw();
for(Int_t i = 1; i < fEdges->GetSize(); i++){
edge = (TGraphEdge*)fEdges->After(edge);
edge->Draw();
}
}
}
//______________________________________________________________________________
Int_t TGraphStruct::Layout()
{
// Layout the graph into a GraphViz data structure
TGraphNode *node;
TGraphEdge *edge;
// Create the graph context.
if (fGVC) gvFreeContext(fGVC);
#ifdef GVIZ_STATIC
fGVC = gvContextPlugins(lt_preloaded_symbols, 0);
#else
fGVC = gvContext();
#endif
// Create the graph.
if (fGVGraph) {
gvFreeLayout(fGVC,fGVGraph);
agclose(fGVGraph);
}
fGVGraph = agopen((char*)"GVGraph", AGDIGRAPH);
// Put the GV nodes into the GV graph
if (fNodes) {
node = (TGraphNode*) fNodes->First();
node->CreateGVNode(fGVGraph);
for(Int_t i = 1; i < fNodes->GetSize(); i++){
node = (TGraphNode*)fNodes->After(node);
node->CreateGVNode(fGVGraph);
}
}
// Put the edges into the graph
if (fEdges) {
edge = (TGraphEdge*) fEdges->First();
edge->CreateGVEdge(fGVGraph);
for(Int_t i = 1; i < fEdges->GetSize(); i++){
edge = (TGraphEdge*)fEdges->After(edge);
edge->CreateGVEdge(fGVGraph);
}
}
// Layout the graph
int ierr = gvLayout(fGVC, fGVGraph, (char*)"dot");
if (ierr) return ierr;
// Layout the nodes
if (fNodes) {
node = (TGraphNode*) fNodes->First();
node->Layout();
for(Int_t i = 1; i < fNodes->GetSize(); i++){
node = (TGraphNode*)fNodes->After(node);
node->Layout();
}
}
// Layout the edges
if (fEdges) {
edge = (TGraphEdge*) fEdges->First();
edge->Layout();
for(Int_t i = 1; i < fEdges->GetSize(); i++){
edge = (TGraphEdge*)fEdges->After(edge);
edge->Layout();
}
}
return 0;
}
//______________________________________________________________________________
void TGraphStruct::SavePrimitive(ostream &out, Option_t * /*= ""*/)
{
// Save primitive as a C++ statement(s) on output stream out
out<<" TGraphStruct *graphstruct = new TGraphStruct();"<<endl;
// Save the nodes
if (fNodes) {
TGraphNode *node;
node = (TGraphNode*) fNodes->First();
out<<" TGraphNode *"<<node->GetName()<<" = graphstruct->AddNode(\""<<
node->GetName()<<"\",\""<<
node->GetTitle()<<"\");"<<endl;
node->SaveAttributes(out);
for(Int_t i = 1; i < fNodes->GetSize(); i++){
node = (TGraphNode*)fNodes->After(node);
out<<" TGraphNode *"<<node->GetName()<<" = graphstruct->AddNode(\""<<
node->GetName()<<"\",\""<<
node->GetTitle()<<"\");"<<endl;
node->SaveAttributes(out);
}
}
// Save the edges
if (fEdges) {
TGraphEdge *edge;
Int_t en = 1;
edge = (TGraphEdge*) fEdges->First();
out<<" TGraphEdge *"<<"e"<<en<<
" = new TGraphEdge("<<
edge->GetNode1()->GetName()<<","<<
edge->GetNode2()->GetName()<<");"<<endl;
out<<" graphstruct->AddEdge("<<"e"<<en<<");"<<endl;
edge->SaveAttributes(out,Form("e%d",en));
for(Int_t i = 1; i < fEdges->GetSize(); i++){
en++;
edge = (TGraphEdge*)fEdges->After(edge);
out<<" TGraphEdge *"<<"e"<<en<<
" = new TGraphEdge("<<
edge->GetNode1()->GetName()<<","<<
edge->GetNode2()->GetName()<<");"<<endl;
out<<" graphstruct->AddEdge("<<"e"<<en<<");"<<endl;
edge->SaveAttributes(out,Form("e%d",en));
}
}
out<<" graphstruct->Draw();"<<endl;
}
//______________________________________________________________________________
void TGraphStruct::Streamer(TBuffer &/*b*/)
{
}
<commit_msg>Fix coverity reports (NULL_RETURNS)<commit_after>// @(#)root/hist:$Id$
// Author: Olivier Couet 13/07/09
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "Riostream.h"
#include "TPad.h"
#include "TGraphStruct.h"
#include <stdio.h>
#include <gvc.h>
#include <gvplugin.h>
#ifdef GVIZ_STATIC
extern gvplugin_library_t gvplugin_dot_layout_LTX_library;
///extern gvplugin_library_t gvplugin_neato_layout_LTX_library;
///extern gvplugin_library_t gvplugin_core_LTX_library;
lt_symlist_t lt_preloaded_symbols[] = {
{ "gvplugin_dot_layout_LTX_library", (void*)(&gvplugin_dot_layout_LTX_library) },
/// { "gvplugin_neato_layout_LTX_library", (void*)(&gvplugin_neato_layout_LTX_library) },
/// { "gvplugin_core_LTX_library", (void*)(&gvplugin_core_LTX_library) },
{ 0, 0 }
};
#endif
ClassImp(TGraphStruct)
//______________________________________________________________________________
/* Begin_Html
<center><h2>Graph Structure class</h2></center>
The Graph Structure is an interface to the graphviz package.
<p>
The graphviz package is a graph visualization system. This interface consists in
three classes:
<ol>
<li> TGraphStruct: holds the graph structure. It uses the graphiz library to
layout the graphs and the ROOT graphics to paint them.
<li> TGraphNode: Is a graph node object which can be added in a TGraphStruct.
<li> TGraphEdge: Is an edge object connecting two nodes which can be added in
a TGraphStruct.
</ol>
End_Html
Begin_Macro(source)
../../../tutorials/graphs/graphstruct.C
End_Macro
Begin_Html
A graph structure can be dumped into a "dot" file using DumpAsDotFile.
End_Html */
//______________________________________________________________________________
TGraphStruct::TGraphStruct()
{
// Graph Structure default constructor.
fNodes = 0;
fEdges = 0;
fGVGraph = 0;
fGVC = 0;
SetMargin();
}
//______________________________________________________________________________
TGraphStruct::~TGraphStruct()
{
// Graph Structure default destructor.
gvFreeLayout(fGVC,fGVGraph);
agclose(fGVGraph);
gvFreeContext(fGVC);
if (fNodes) delete fNodes;
if (fEdges) delete fEdges;
}
//______________________________________________________________________________
void TGraphStruct::AddEdge(TGraphEdge *edge)
{
// Add the edge "edge" in this TGraphStruct.
if (!fEdges) fEdges = new TList;
fEdges->Add(edge);
}
//______________________________________________________________________________
TGraphEdge *TGraphStruct::AddEdge(TGraphNode *n1, TGraphNode *n2)
{
// Create an edge between n1 and n2 and put it in this graph.
//
// Two edges can connect the same nodes the same way, so there
// is no need to check if an edge already exists.
if (!fEdges) fEdges = new TList;
TGraphEdge *edge = new TGraphEdge(n1, n2);
fEdges->Add(edge);
return edge;
}
//______________________________________________________________________________
void TGraphStruct::AddNode(TGraphNode *node)
{
// Add the node "node" in this TGraphStruct.
if (!fNodes) fNodes = new TList;
fNodes->Add(node);
}
//______________________________________________________________________________
TGraphNode *TGraphStruct::AddNode(const char *name, const char *title)
{
// Create the node "name" if it does not exist and add it to this TGraphStruct.
if (!fNodes) fNodes = new TList;
TGraphNode *node = (TGraphNode*)fNodes->FindObject(name);
if (!node) {
node = new TGraphNode(name, title);
fNodes->Add(node);
}
return node;
}
//______________________________________________________________________________
void TGraphStruct::DumpAsDotFile(const char *filename)
{
// Dump this graph structure as a "dot" file.
if (!fGVGraph) {
Int_t ierr = Layout();
if (ierr) return;
}
FILE *file;
file=fopen(filename,"wt");
if (file) {
agwrite(fGVGraph, file);
fclose(file);
}
}
//______________________________________________________________________________
void TGraphStruct::Draw(Option_t *option)
{
// Draw the graph
if (!fGVGraph) {
Int_t ierr = Layout();
if (ierr) return;
}
// Get the bounding box
if (gPad) {
gPad->Range(GD_bb(fGVGraph).LL.x-fMargin, GD_bb(fGVGraph).LL.y-fMargin,
GD_bb(fGVGraph).UR.x+fMargin, GD_bb(fGVGraph).UR.y+fMargin);
}
AppendPad(option);
// Draw the nodes
if (fNodes) {
TGraphNode *node;
node = (TGraphNode*) fNodes->First();
node->Draw();
for(Int_t i = 1; i < fNodes->GetSize(); i++){
node = (TGraphNode*)fNodes->After(node);
if (node) node->Draw();
}
}
// Draw the edges
if (fEdges) {
TGraphEdge *edge;
edge = (TGraphEdge*) fEdges->First();
edge->Draw();
for(Int_t i = 1; i < fEdges->GetSize(); i++){
edge = (TGraphEdge*)fEdges->After(edge);
if (edge) edge->Draw();
}
}
}
//______________________________________________________________________________
Int_t TGraphStruct::Layout()
{
// Layout the graph into a GraphViz data structure
TGraphNode *node;
TGraphEdge *edge;
// Create the graph context.
if (fGVC) gvFreeContext(fGVC);
#ifdef GVIZ_STATIC
fGVC = gvContextPlugins(lt_preloaded_symbols, 0);
#else
fGVC = gvContext();
#endif
// Create the graph.
if (fGVGraph) {
gvFreeLayout(fGVC,fGVGraph);
agclose(fGVGraph);
}
fGVGraph = agopen((char*)"GVGraph", AGDIGRAPH);
// Put the GV nodes into the GV graph
if (fNodes) {
node = (TGraphNode*) fNodes->First();
node->CreateGVNode(fGVGraph);
for(Int_t i = 1; i < fNodes->GetSize(); i++){
node = (TGraphNode*)fNodes->After(node);
if (node) node->CreateGVNode(fGVGraph);
}
}
// Put the edges into the graph
if (fEdges) {
edge = (TGraphEdge*) fEdges->First();
edge->CreateGVEdge(fGVGraph);
for(Int_t i = 1; i < fEdges->GetSize(); i++){
edge = (TGraphEdge*)fEdges->After(edge);
if (edge) edge->CreateGVEdge(fGVGraph);
}
}
// Layout the graph
int ierr = gvLayout(fGVC, fGVGraph, (char*)"dot");
if (ierr) return ierr;
// Layout the nodes
if (fNodes) {
node = (TGraphNode*) fNodes->First();
node->Layout();
for(Int_t i = 1; i < fNodes->GetSize(); i++){
node = (TGraphNode*)fNodes->After(node);
if (node) node->Layout();
}
}
// Layout the edges
if (fEdges) {
edge = (TGraphEdge*) fEdges->First();
edge->Layout();
for(Int_t i = 1; i < fEdges->GetSize(); i++){
edge = (TGraphEdge*)fEdges->After(edge);
if (edge) edge->Layout();
}
}
return 0;
}
//______________________________________________________________________________
void TGraphStruct::SavePrimitive(ostream &out, Option_t * /*= ""*/)
{
// Save primitive as a C++ statement(s) on output stream out
out<<" TGraphStruct *graphstruct = new TGraphStruct();"<<endl;
// Save the nodes
if (fNodes) {
TGraphNode *node;
node = (TGraphNode*) fNodes->First();
out<<" TGraphNode *"<<node->GetName()<<" = graphstruct->AddNode(\""<<
node->GetName()<<"\",\""<<
node->GetTitle()<<"\");"<<endl;
node->SaveAttributes(out);
for(Int_t i = 1; i < fNodes->GetSize(); i++){
node = (TGraphNode*)fNodes->After(node);
if (node) {
out<<" TGraphNode *"<<node->GetName()<<" = graphstruct->AddNode(\""<<
node->GetName()<<"\",\""<<
node->GetTitle()<<"\");"<<endl;
node->SaveAttributes(out);
}
}
}
// Save the edges
if (fEdges) {
TGraphEdge *edge;
Int_t en = 1;
edge = (TGraphEdge*) fEdges->First();
out<<" TGraphEdge *"<<"e"<<en<<
" = new TGraphEdge("<<
edge->GetNode1()->GetName()<<","<<
edge->GetNode2()->GetName()<<");"<<endl;
out<<" graphstruct->AddEdge("<<"e"<<en<<");"<<endl;
edge->SaveAttributes(out,Form("e%d",en));
for(Int_t i = 1; i < fEdges->GetSize(); i++){
en++;
edge = (TGraphEdge*)fEdges->After(edge);
if (edge) {
out<<" TGraphEdge *"<<"e"<<en<<
" = new TGraphEdge("<<
edge->GetNode1()->GetName()<<","<<
edge->GetNode2()->GetName()<<");"<<endl;
out<<" graphstruct->AddEdge("<<"e"<<en<<");"<<endl;
edge->SaveAttributes(out,Form("e%d",en));
}
}
}
out<<" graphstruct->Draw();"<<endl;
}
//______________________________________________________________________________
void TGraphStruct::Streamer(TBuffer &/*b*/)
{
}
<|endoftext|> |
<commit_before>#include "ShaderControl.h"
ShaderControl::ShaderControl()
{
}
ShaderControl::~ShaderControl()
{
}
bool ShaderControl::Initialize(ID3D11Device * gDevice, ID3D11DeviceContext * gDeviceContext, const DirectX::XMINT2& resolution)
{
this->m_Device = gDevice;
this->m_DeviceContext = gDeviceContext;
m_shaders[DEFERRED] = new DeferredShader();
m_shaders[DEFERRED]->Initialize(gDevice, gDeviceContext, resolution);
m_shaders[FINAL] = new FinalShader();
m_shaders[FINAL]->Initialize(gDevice, gDeviceContext, resolution);
m_shaders[POSTPROCESS] = new PostProcessShader();
m_shaders[POSTPROCESS]->Initialize(gDevice, gDeviceContext, resolution);
return true;
}
void ShaderControl::Release()
{
for (size_t i = 0; i < NUM_SHADERS; i++)
{
m_shaders[i]->Release();
delete m_shaders[i];
m_shaders[i] = nullptr;
}
}
void ShaderControl::SetActive(Shaders type)
{
m_activeShader = type;
switch (m_activeShader)
{
case DEFERRED:
{
m_shaders[DEFERRED]->SetActive();
break;
}
}
}
void ShaderControl::SetVariation(ShaderLib::ShaderVariations ShaderVariations)
{
switch (m_activeShader)
{
case DEFERRED:
{
m_shaders[DEFERRED]->SetVariation(ShaderVariations);
break;
}
}
}
int ShaderControl::SetBackBufferRTV(ID3D11RenderTargetView * backBufferRTV)
{
this->backBufferRTV = backBufferRTV;
((FinalShader*)m_shaders[FINAL])->SetRenderParameters(backBufferRTV,
((DeferredShader*)m_shaders[DEFERRED])->GetShaderResourceViews()
);
return 0;
}
void ShaderControl::PostProcess()
{
ID3D11RenderTargetView* rtv = this->backBufferRTV;
for (size_t i = 0; i < PostProcessShader::NUM_TYPES; i++)
{
PostProcessShader::PostEffects fx = PostProcessShader::PostEffects(i);
//If the effect is activated
if (((PostProcessShader*)m_shaders[POSTPROCESS])->isActive(fx)) {
((PostProcessShader*)m_shaders[POSTPROCESS])->SetActive(PostProcessShader::PostEffects(fx));
rtv = ((PostProcessShader*)m_shaders[POSTPROCESS])->Draw();
}
}
if (rtv != nullptr)
m_DeviceContext->OMSetRenderTargets(1, &rtv, NULL);
}
void ShaderControl::Draw(Resources::Model * model)
{
switch (m_activeShader)
{
case DEFERRED:
((DeferredShader*)m_shaders[DEFERRED])->Draw(model);
break;
}
}
void ShaderControl::DrawFinal()
{
this->m_activeShader = Shaders::FINAL;
((FinalShader*)this->m_shaders[FINAL])->SetActive();
((FinalShader*)this->m_shaders[FINAL])->Draw();
}
int ShaderControl::ClearFrame()
{
((DeferredShader*)this->m_shaders[DEFERRED])->Clear();
return 0;
}
<commit_msg>DELETE: removed a if statment that wasnt needed<commit_after>#include "ShaderControl.h"
ShaderControl::ShaderControl()
{
}
ShaderControl::~ShaderControl()
{
}
bool ShaderControl::Initialize(ID3D11Device * gDevice, ID3D11DeviceContext * gDeviceContext, const DirectX::XMINT2& resolution)
{
this->m_Device = gDevice;
this->m_DeviceContext = gDeviceContext;
m_shaders[DEFERRED] = new DeferredShader();
m_shaders[DEFERRED]->Initialize(gDevice, gDeviceContext, resolution);
m_shaders[FINAL] = new FinalShader();
m_shaders[FINAL]->Initialize(gDevice, gDeviceContext, resolution);
m_shaders[POSTPROCESS] = new PostProcessShader();
m_shaders[POSTPROCESS]->Initialize(gDevice, gDeviceContext, resolution);
return true;
}
void ShaderControl::Release()
{
for (size_t i = 0; i < NUM_SHADERS; i++)
{
m_shaders[i]->Release();
delete m_shaders[i];
m_shaders[i] = nullptr;
}
}
void ShaderControl::SetActive(Shaders type)
{
m_activeShader = type;
switch (m_activeShader)
{
case DEFERRED:
{
m_shaders[DEFERRED]->SetActive();
break;
}
}
}
void ShaderControl::SetVariation(ShaderLib::ShaderVariations ShaderVariations)
{
switch (m_activeShader)
{
case DEFERRED:
{
m_shaders[DEFERRED]->SetVariation(ShaderVariations);
break;
}
}
}
int ShaderControl::SetBackBufferRTV(ID3D11RenderTargetView * backBufferRTV)
{
this->backBufferRTV = backBufferRTV;
((FinalShader*)m_shaders[FINAL])->SetRenderParameters(backBufferRTV,
((DeferredShader*)m_shaders[DEFERRED])->GetShaderResourceViews()
);
return 0;
}
void ShaderControl::PostProcess()
{
ID3D11RenderTargetView* rtv = this->backBufferRTV;
PostProcessShader::PostEffects fx;
for (size_t i = 0; i < PostProcessShader::NUM_TYPES; i++)
{
fx = PostProcessShader::PostEffects(i);
//If the effect is activated
if (((PostProcessShader*)m_shaders[POSTPROCESS])->isActive(fx)) {
((PostProcessShader*)m_shaders[POSTPROCESS])->SetActive(PostProcessShader::PostEffects(fx));
rtv = ((PostProcessShader*)m_shaders[POSTPROCESS])->Draw();
}
}
m_DeviceContext->OMSetRenderTargets(1, &rtv, NULL);
}
void ShaderControl::Draw(Resources::Model * model)
{
switch (m_activeShader)
{
case DEFERRED:
((DeferredShader*)m_shaders[DEFERRED])->Draw(model);
break;
}
}
void ShaderControl::DrawFinal()
{
this->m_activeShader = Shaders::FINAL;
((FinalShader*)this->m_shaders[FINAL])->SetActive();
((FinalShader*)this->m_shaders[FINAL])->Draw();
}
int ShaderControl::ClearFrame()
{
((DeferredShader*)this->m_shaders[DEFERRED])->Clear();
return 0;
}
<|endoftext|> |
<commit_before>
#include <iostream>
#include <cstdint>
extern "C" {
#include <math.h>
#include <libavutil/opt.h>
#include <libavcodec/avcodec.h>
#include <libavutil/channel_layout.h>
#include <libavutil/common.h>
#include <libavutil/imgutils.h>
#include <libavutil/mathematics.h>
#include <libavutil/samplefmt.h>
}
#define INBUF_SIZE 4096
static const uint32_t WIDTH = 352;
static const uint32_t HEIGHT = 288;
static const uint32_t DEPTH = 25;
/*
* Video encoding example
*/
static void video_encode_example(const char *filename, AVCodecID codec_id)
{
AVCodec *codec;
AVCodecContext *c= NULL;
int ret, got_output;
FILE *f;
AVFrame *frame;
AVPacket pkt;
/* uint8_t endcode[] = { 0, 0, 1, 0xb7 }; */
printf("Encode video file %s\n", filename);
/* find the mpeg1 video encoder */
codec = avcodec_find_encoder(codec_id);
if (!codec) {
fprintf(stderr, "Codec not found\n");
exit(1);
}
c = avcodec_alloc_context3(codec);
if (!c) {
fprintf(stderr, "Could not allocate video codec context\n");
exit(1);
}
/* put sample parameters */
c->bit_rate = 400000;
/* resolution must be a multiple of two */
c->width = WIDTH;
c->height = HEIGHT;
/* frames per second */
c->time_base = (AVRational){1,25};
/* emit one intra frame every ten frames
* check frame pict_type before passing frame
* to encoder, if frame->pict_type is AV_PICTURE_TYPE_I
* then gop_size is ignored and the output of encoder
* will always be I frame irrespective to gop_size
*/
c->gop_size = 10;
c->max_b_frames = 1;
c->pix_fmt = AV_PIX_FMT_YUV420P;
if (codec_id == AV_CODEC_ID_H264)
av_opt_set(c->priv_data, "preset", "slow", 0);
/* open it */
if (avcodec_open2(c, codec, NULL) < 0) {
fprintf(stderr, "Could not open codec\n");
exit(1);
}
f = fopen(filename, "wb");
if (!f) {
fprintf(stderr, "Could not open %s\n", filename);
exit(1);
}
frame = av_frame_alloc();
if (!frame) {
fprintf(stderr, "Could not allocate video frame\n");
exit(1);
}
frame->format = c->pix_fmt;
frame->width = c->width;
frame->height = c->height;
/* the image can be allocated by any means and av_image_alloc() is
* just the most convenient way if av_malloc() is to be used */
ret = av_image_alloc(frame->data, frame->linesize, c->width, c->height,
c->pix_fmt, 32);
if (ret < 0) {
fprintf(stderr, "Could not allocate raw picture buffer\n");
exit(1);
}
/* encode 1 second of video */
for (uint32_t i = 0; i < DEPTH; i++) {
av_init_packet(&pkt);
pkt.data = NULL; // packet data will be allocated by the encoder
pkt.size = 0;
fflush(stdout);
/* prepare a dummy image */
/* Y */
float offset = 0.f;
float ymin = 0;
float ymax = 0;
for (uint32_t y = 0; y < (uint32_t)c->height; y++) {
offset = .05*(i/5)*c->height;
ymin = (.1*c->height)+offset;
ymax = (.13*c->height)+offset;
for (uint32_t x = 0; x < (uint32_t)c->width; x++) {
frame->data[0][y * frame->linesize[0] + x] = x + y + i * 3;
if((y>ymin && y<ymax) &&
(x % 4 < 2) && x<=(5*(i+1)))
frame->data[0][(y) * frame->linesize[0] + x] = 16;
}
}
/* Cb and Cr */
for (uint32_t y = 0; y < c->height/2u; y++) {
for (uint32_t x = 0; x < c->width/2u; x++) {
frame->data[1][y * frame->linesize[1] + x] = 128 + y + i * 2;
frame->data[2][y * frame->linesize[2] + x] = 64 + x + i * 5;
/* if((y>(.1/2.*c->height) && y<(.3/2.*c->height)) && */
/* (x % 2 < 1) && x<=(5*(i+1))){ */
/* frame->data[1][y * frame->linesize[1] + x] = 128; */
/* frame->data[2][y * frame->linesize[2] + x] = 128; */
/* } */
}
}
frame->pts = i;
/* encode the image */
ret = avcodec_encode_video2(c, &pkt, frame, &got_output);
if (ret < 0) {
fprintf(stderr, "Error encoding frame\n");
exit(1);
}
if (got_output) {
printf("Write frame %3d (size=%5d)\n", i,pkt.size);
fwrite(pkt.data, 1, pkt.size, f);
av_free_packet(&pkt);
}
}
/* get the delayed frames */
got_output = 1;
for (uint32_t i = DEPTH; got_output; i++) {
fflush(stdout);
ret = avcodec_encode_video2(c, &pkt, NULL, &got_output);
if (ret < 0) {
fprintf(stderr, "Error encoding frame\n");
exit(1);
}
if (got_output) {
printf("Write frame %3d (size=%5d) [delayed]\n", i, pkt.size);
fwrite(pkt.data, 1, pkt.size, f);
av_free_packet(&pkt);
}
}
/* add sequence end code to have a real mpeg file */
//fwrite(endcode, 1, sizeof(endcode), f);
fclose(f);
avcodec_close(c);
av_free(c);
av_freep(&frame->data[0]);
av_frame_free(&frame);
printf("\n");
}
int main(int argc, char **argv)
{
/* register all the codecs */
avcodec_register_all();
if (argc < 2){
std::cout << "usage: ./roundtrip <codec>\n"
<< "app to experiment on how to decode an encoded piece of memory\nrather then writing it to disk"
<< "codec\tpossible values: 'h264' or 'hevc'\n";
return 1;
}
std::string file_type = argv[1];
if(file_type.find("h264") != std::string::npos)
video_encode_example("test.h264", AV_CODEC_ID_H264);
else{
if(file_type.find("hevc") != std::string::npos)
video_encode_example("test.hevc", AV_CODEC_ID_HEVC);
else{
std::cerr << "file_type unknown " << file_type << "\n";
return 1;
}
}
return 0;
}
<commit_msg>buffered encoding works as expected<commit_after>#include <fstream>
#include <iostream>
#include <cstdint>
#include <vector>
#include <iterator>
extern "C" {
#include <math.h>
#include <libavutil/opt.h>
#include <libavcodec/avcodec.h>
#include <libavutil/channel_layout.h>
#include <libavutil/common.h>
#include <libavutil/imgutils.h>
#include <libavutil/mathematics.h>
#include <libavutil/samplefmt.h>
}
#define INBUF_SIZE 4096
static const uint32_t WIDTH = 352;
static const uint32_t HEIGHT = 288;
static const uint32_t DEPTH = 25;
/*
* Video encoding example
*/
static void video_encode_example(const char *filename, AVCodecID codec_id)
{
AVCodec *codec;
AVCodecContext *c= NULL;
int ret, got_output;
FILE *f;
AVFrame *frame;
AVPacket pkt;
/* uint8_t endcode[] = { 0, 0, 1, 0xb7 }; */
printf("Encode video file %s\n", filename);
/* find the mpeg1 video encoder */
codec = avcodec_find_encoder(codec_id);
if (!codec) {
fprintf(stderr, "Codec not found\n");
exit(1);
}
c = avcodec_alloc_context3(codec);
if (!c) {
fprintf(stderr, "Could not allocate video codec context\n");
exit(1);
}
/* put sample parameters */
c->bit_rate = 400000;
/* resolution must be a multiple of two */
c->width = WIDTH;
c->height = HEIGHT;
/* frames per second */
c->time_base = (AVRational){1,25};
/* emit one intra frame every ten frames
* check frame pict_type before passing frame
* to encoder, if frame->pict_type is AV_PICTURE_TYPE_I
* then gop_size is ignored and the output of encoder
* will always be I frame irrespective to gop_size
*/
c->gop_size = 10;
c->max_b_frames = 1;
c->pix_fmt = AV_PIX_FMT_YUV420P;
if (codec_id == AV_CODEC_ID_H264)
av_opt_set(c->priv_data, "preset", "slow", 0);
/* open it */
if (avcodec_open2(c, codec, NULL) < 0) {
fprintf(stderr, "Could not open codec\n");
exit(1);
}
f = fopen(filename, "wb");
if (!f) {
fprintf(stderr, "Could not open %s\n", filename);
exit(1);
}
frame = av_frame_alloc();
if (!frame) {
fprintf(stderr, "Could not allocate video frame\n");
exit(1);
}
frame->format = c->pix_fmt;
frame->width = c->width;
frame->height = c->height;
/* the image can be allocated by any means and av_image_alloc() is
* just the most convenient way if av_malloc() is to be used */
ret = av_image_alloc(frame->data, frame->linesize, c->width, c->height,
c->pix_fmt, 32);
if (ret < 0) {
fprintf(stderr, "Could not allocate raw picture buffer\n");
exit(1);
}
/* encode 1 second of video */
for (uint32_t i = 0; i < DEPTH; i++) {
av_init_packet(&pkt);
pkt.data = NULL; // packet data will be allocated by the encoder
pkt.size = 0;
fflush(stdout);
/* prepare a dummy image */
/* Y */
float offset = 0.f;
float ymin = 0;
float ymax = 0;
for (uint32_t y = 0; y < (uint32_t)c->height; y++) {
offset = .05*(i/5)*c->height;
ymin = (.1*c->height)+offset;
ymax = (.13*c->height)+offset;
for (uint32_t x = 0; x < (uint32_t)c->width; x++) {
frame->data[0][y * frame->linesize[0] + x] = x + y + i * 3;
if((y>ymin && y<ymax) &&
(x % 4 < 2) && x<=(5*(i+1)))
frame->data[0][(y) * frame->linesize[0] + x] = 16;
}
}
/* Cb and Cr */
for (uint32_t y = 0; y < c->height/2u; y++) {
for (uint32_t x = 0; x < c->width/2u; x++) {
frame->data[1][y * frame->linesize[1] + x] = 128 + y + i * 2;
frame->data[2][y * frame->linesize[2] + x] = 64 + x + i * 5;
/* if((y>(.1/2.*c->height) && y<(.3/2.*c->height)) && */
/* (x % 2 < 1) && x<=(5*(i+1))){ */
/* frame->data[1][y * frame->linesize[1] + x] = 128; */
/* frame->data[2][y * frame->linesize[2] + x] = 128; */
/* } */
}
}
frame->pts = i;
/* encode the image */
ret = avcodec_encode_video2(c, &pkt, frame, &got_output);
if (ret < 0) {
fprintf(stderr, "Error encoding frame\n");
exit(1);
}
if (got_output) {
printf("Write frame %3d (size=%5d)\n", i,pkt.size);
fwrite(pkt.data, 1, pkt.size, f);
av_free_packet(&pkt);
}
}
/* get the delayed frames */
got_output = 1;
for (uint32_t i = DEPTH; got_output; i++) {
fflush(stdout);
ret = avcodec_encode_video2(c, &pkt, NULL, &got_output);
if (ret < 0) {
fprintf(stderr, "Error encoding frame\n");
exit(1);
}
if (got_output) {
printf("Write frame %3d (size=%5d) [delayed]\n", i, pkt.size);
fwrite(pkt.data, 1, pkt.size, f);
av_free_packet(&pkt);
}
}
/* add sequence end code to have a real mpeg file */
//fwrite(endcode, 1, sizeof(endcode), f);
fclose(f);
avcodec_close(c);
av_free(c);
av_freep(&frame->data[0]);
av_frame_free(&frame);
printf("\n");
}
/*
* Video encoding example
*/
static void video_encode_to_buffer(std::vector<uint8_t>& _buffer, AVCodecID codec_id)
{
AVCodec *codec;
AVCodecContext *c= NULL;
int ret, got_output;
AVFrame *frame;
AVPacket pkt;
/* find the mpeg1 video encoder */
codec = avcodec_find_encoder(codec_id);
if (!codec) {
fprintf(stderr, "Codec not found\n");
exit(1);
}
c = avcodec_alloc_context3(codec);
if (!c) {
fprintf(stderr, "Could not allocate video codec context\n");
exit(1);
}
/* put sample parameters */
c->bit_rate = 400000;
/* resolution must be a multiple of two */
c->width = WIDTH;
c->height = HEIGHT;
/* frames per second */
c->time_base = (AVRational){1,25};
/* emit one intra frame every ten frames
* check frame pict_type before passing frame
* to encoder, if frame->pict_type is AV_PICTURE_TYPE_I
* then gop_size is ignored and the output of encoder
* will always be I frame irrespective to gop_size
*/
c->gop_size = 10;
c->max_b_frames = 1;
c->pix_fmt = AV_PIX_FMT_YUV420P;
if (codec_id == AV_CODEC_ID_H264)
av_opt_set(c->priv_data, "preset", "slow", 0);
/* open it */
if (avcodec_open2(c, codec, NULL) < 0) {
fprintf(stderr, "Could not open codec\n");
exit(1);
}
frame = av_frame_alloc();
if (!frame) {
fprintf(stderr, "Could not allocate video frame\n");
exit(1);
}
frame->format = c->pix_fmt;
frame->width = c->width;
frame->height = c->height;
/* the image can be allocated by any means and av_image_alloc() is
* just the most convenient way if av_malloc() is to be used */
ret = av_image_alloc(frame->data, frame->linesize, c->width, c->height,
c->pix_fmt, 32);
if (ret < 0) {
fprintf(stderr, "Could not allocate raw picture buffer\n");
exit(1);
}
/* encode 1 second of video */
for (uint32_t i = 0; i < DEPTH; i++) {
av_init_packet(&pkt);
pkt.data = NULL; // packet data will be allocated by the encoder
pkt.size = 0;
fflush(stdout);
/* prepare a dummy image */
/* Y */
float offset = 0.f;
float ymin = 0;
float ymax = 0;
for (uint32_t y = 0; y < (uint32_t)c->height; y++) {
offset = .05*(i/5)*c->height;
ymin = (.1*c->height)+offset;
ymax = (.13*c->height)+offset;
for (uint32_t x = 0; x < (uint32_t)c->width; x++) {
frame->data[0][y * frame->linesize[0] + x] = x + y + i * 3;
if((y>ymin && y<ymax) &&
(x % 4 < 2) && x<=(5*(i+1)))
frame->data[0][(y) * frame->linesize[0] + x] = 16;
}
}
/* Cb and Cr */
for (uint32_t y = 0; y < c->height/2u; y++) {
for (uint32_t x = 0; x < c->width/2u; x++) {
frame->data[1][y * frame->linesize[1] + x] = 128 + y + i * 2;
frame->data[2][y * frame->linesize[2] + x] = 64 + x + i * 5;
/* if((y>(.1/2.*c->height) && y<(.3/2.*c->height)) && */
/* (x % 2 < 1) && x<=(5*(i+1))){ */
/* frame->data[1][y * frame->linesize[1] + x] = 128; */
/* frame->data[2][y * frame->linesize[2] + x] = 128; */
/* } */
}
}
frame->pts = i;
/* encode the image */
ret = avcodec_encode_video2(c, &pkt, frame, &got_output);
if (ret < 0) {
fprintf(stderr, "Error encoding frame\n");
exit(1);
}
if (got_output) {
printf("Write frame %3d (size=%5d)\n", i,pkt.size);
std::copy(pkt.data,pkt.data+pkt.size,std::back_inserter(_buffer));
// fwrite(pkt.data, 1, pkt.size, f);
av_free_packet(&pkt);
}
}
/* get the delayed frames */
got_output = 1;
for (uint32_t i = DEPTH; got_output; i++) {
fflush(stdout);
ret = avcodec_encode_video2(c, &pkt, NULL, &got_output);
if (ret < 0) {
fprintf(stderr, "Error encoding frame\n");
exit(1);
}
if (got_output) {
printf("Write frame %3d (size=%5d) [delayed]\n", i, pkt.size);
std::copy(pkt.data,pkt.data+pkt.size,std::back_inserter(_buffer));
// fwrite(pkt.data, 1, pkt.size, f);
av_free_packet(&pkt);
}
}
/* add sequence end code to have a real mpeg file */
//fwrite(endcode, 1, sizeof(endcode), f);
// fclose(f);
avcodec_close(c);
av_free(c);
av_freep(&frame->data[0]);
av_frame_free(&frame);
printf("\n");
}
int main(int argc, char **argv)
{
/* register all the codecs */
avcodec_register_all();
if (argc < 2){
std::cout << "usage: ./roundtrip <codec>\n"
<< "app to experiment on how to decode an encoded piece of memory\nrather then writing it to disk"
<< "codec\tpossible values: 'h264' or 'hevc'\n";
return 1;
}
std::string oname;
AVCodecID codec_id;
std::string file_type = argv[1];
if(file_type.find("h264") != std::string::npos){
codec_id = AV_CODEC_ID_H264;
oname = "test.h264";
}
else{
if(file_type.find("hevc") != std::string::npos){
codec_id = AV_CODEC_ID_HEVC;
oname = "test.hevc";
}
else{
std::cerr << "file_type unknown " << file_type << "\n";
return 1;
}
}
//video_encode_example(oname.c_str(), codec_id);
std::vector<uint8_t> fbuffer;
std::string buffered = "buffered-";
buffered += oname;
video_encode_to_buffer(fbuffer, codec_id);
std::ofstream ofile(buffered, std::ios::binary | std::ios::out | std::ios::trunc );
ofile.write(reinterpret_cast<const char*>(&fbuffer[0]),fbuffer.size());
ofile.close();
return 0;
}
<|endoftext|> |
<commit_before>#include <mantella_bits/optimisationProblem/roboticsOptimisationProblem/robotModel/parallelKinematicMachine6PUPS.hpp>
// C++ standard library
#include <cassert>
// Mantella
#include <mantella_bits/helper/assert.hpp>
#include <mantella_bits/helper/geometry.hpp>
namespace mant {
namespace robotics {
ParallelKinematicMachine6PUPS::ParallelKinematicMachine6PUPS()
: ParallelKinematicMachine6PUPS(
// endEffectorJointPositions
{-0.025561381023353, 0.086293776138137, 0.12,
0.025561381023353, 0.086293776138137, 0.12,
0.087513292835791, -0.021010082747031, 0.12,
0.061951911812438, -0.065283693391106, 0.12,
-0.061951911812438, -0.065283693391106, 0.12,
-0.087513292835791, -0.021010082747032, 0.12},
// minimalActiveJointsActuation
{0.39, 0.39, 0.39, 0.39, 0.39, 0.39},
// maximalActiveJointsActuation
{0.95, 0.95, 0.95, 0.95, 0.95, 0.95},
// redundantJointStartPositions
{-0.463708870031622, 0.417029254828353, -0.346410161513775,
0.463708870031622, 0.417029254828353, -0.346410161513775,
0.593012363818459, 0.193069033993384, -0.346410161513775,
0.129303493786838, -0.610098288821738, -0.346410161513775,
-0.129303493786837, -0.610098288821738, -0.346410161513775,
-0.593012363818459, 0.193069033993384, -0.346410161513775},
// redundantJointEndPositions
{-0.247202519085512, 0.292029254828353, 0.086602540378444,
0.247202519085512, 0.292029254828353, 0.086602540378444,
0.376506012872349, 0.068069033993384, 0.086602540378444,
0.129303493786838, -0.360098288821738, 0.086602540378444,
-0.129303493786837, -0.360098288821738, 0.086602540378444,
-0.376506012872349, 0.068069033993384, 0.086602540378444}) {
}
ParallelKinematicMachine6PUPS::ParallelKinematicMachine6PUPS(
const arma::Mat<double>::fixed<3, 6>& endEffectorJointPositions,
const arma::Row<double>::fixed<6>& minimalActiveJointsActuation,
const arma::Row<double>::fixed<6>& maximalActiveJointsActuation,
const arma::Mat<double>::fixed<3, 6>& redundantJointStartPositions,
const arma::Mat<double>::fixed<3, 6>& redundantJointEndPositions)
: RobotModel(6, static_cast<arma::Col<double>>(arma::nonzeros(redundantJointEndPositions - redundantJointStartPositions)).n_elem),
endEffectorJointPositions_(endEffectorJointPositions),
minimalActiveJointsActuation_(minimalActiveJointsActuation),
maximalActiveJointsActuation_(maximalActiveJointsActuation),
redundantJointStartPositions_(redundantJointStartPositions),
redundantJointEndPositions_(redundantJointEndPositions),
redundantJointStartToEndPositions_(redundantJointEndPositions_ - redundantJointStartPositions_),
redundantJointIndicies_(arma::find(arma::any(redundantJointStartToEndPositions_))),
redundantJointRotationAngles_(6, redundantJointIndicies_.n_elem) {
for (arma::uword n = 0; n < redundantJointIndicies_.n_elem; ++n) {
const double& redundantJointXAngle = std::atan2(redundantJointStartToEndPositions_(1, n), redundantJointStartToEndPositions_(0, n));
const double& redundantJointYAngle = std::atan2(redundantJointStartToEndPositions_(2, n), redundantJointStartToEndPositions_(1, n));
redundantJointRotationAngles_.col(n) = arma::Col<double>({std::cos(redundantJointXAngle) * std::cos(redundantJointYAngle), std::sin(redundantJointXAngle) * std::cos(redundantJointYAngle), std::sin(redundantJointYAngle)});
}
}
arma::Mat<double>::fixed<3, 6> ParallelKinematicMachine6PUPS::getEndEffectorJointPositions() const {
return endEffectorJointPositions_;
}
arma::Row<double>::fixed<6> ParallelKinematicMachine6PUPS::getMinimalActiveJointsActuation() const {
return minimalActiveJointsActuation_;
}
arma::Row<double>::fixed<6> ParallelKinematicMachine6PUPS::getMaximalActiveJointsActuation() const {
return maximalActiveJointsActuation_;
}
arma::Mat<double>::fixed<3, 6> ParallelKinematicMachine6PUPS::getRedundantJointStartPositions() const{
return redundantJointStartPositions_;
}
arma::Mat<double>::fixed<3, 6> ParallelKinematicMachine6PUPS::getRedundantJointEndPositions() const{
return redundantJointEndPositions_;
}
arma::Cube<double> ParallelKinematicMachine6PUPS::getModelImplementation(
const arma::Col<double>& endEffectorPose,
const arma::Row<double>& redundantJointsActuation) const {
assert(redundantJointsActuation.n_elem == numberOfRedundantJoints_);
assert(!arma::any(redundantJointsActuation < 0) && !arma::any(redundantJointsActuation > 1));
arma::Cube<double> model(3, 6, 2);
const arma::Col<double>& endEffectorPosition = endEffectorPose.subvec(0, 2);
const double& endEffectorRollAngle = endEffectorPose(3);
const double& endEffectorPitchAngle = endEffectorPose(4);
const double& endEffectorYawAngle = endEffectorPose(5);
model.slice(0) = redundantJointStartPositions_;
for (arma::uword n = 0; n < redundantJointIndicies_.n_elem; ++n) {
const arma::uword& redundantJointIndex = redundantJointIndicies_(n);
model.slice(0).col(redundantJointIndex) += redundantJointsActuation(redundantJointIndex) * redundantJointStartToEndPositions_.col(redundantJointIndex);
}
model.slice(1) = get3DRotation(endEffectorRollAngle, endEffectorPitchAngle, endEffectorYawAngle) * endEffectorJointPositions_;
model.slice(1).each_col() += endEffectorPosition;
return model;
}
arma::Row<double> ParallelKinematicMachine6PUPS::getActuationImplementation(
const arma::Col<double>& endEffectorPose,
const arma::Row<double>& redundantJointsActuation) const {
assert(redundantJointsActuation.n_elem == numberOfRedundantJoints_);
assert(!arma::any(redundantJointsActuation < 0) && !arma::any(redundantJointsActuation > 1));
const arma::Cube<double>& model = getModel(endEffectorPose, redundantJointsActuation);
const arma::Mat<double>& baseJoints = model.slice(0);
const arma::Mat<double>& endEffectorJoints = model.slice(1);
return arma::sqrt(arma::sum(arma::square(endEffectorJoints - baseJoints)));
}
double ParallelKinematicMachine6PUPS::getEndEffectorPoseErrorImplementation(
const arma::Col<double>& endEffectorPose,
const arma::Row<double>& redundantJointsActuation) const {
assert(redundantJointsActuation.n_elem == numberOfRedundantJoints_);
assert(!arma::any(redundantJointsActuation < 0) && !arma::any(redundantJointsActuation > 1));
const arma::Cube<double>& model = getModel(endEffectorPose, redundantJointsActuation);
const arma::Mat<double>& baseJoints = model.slice(1);
const arma::Mat<double>& endEffectorJoints = model.slice(1);
arma::Mat<double> endEffectorJointsRotated = endEffectorJoints;
endEffectorJointsRotated.each_col() -= endEffectorPose.subvec(0, 2);
const arma::Mat<double>& baseToEndEffectorJointPositions = endEffectorJoints - baseJoints;
const arma::Row<double>& baseToEndEffectorJointsActuation = arma::sqrt(arma::sum(arma::square(baseToEndEffectorJointPositions)));
if (arma::any(baseToEndEffectorJointsActuation < minimalActiveJointsActuation_) || arma::any(baseToEndEffectorJointsActuation > maximalActiveJointsActuation_)) {
return 0.0;
}
arma::Mat<double> forwardKinematic;
forwardKinematic.head_rows(3) = baseToEndEffectorJointPositions;
for (arma::uword n = 0; n < baseToEndEffectorJointPositions.n_cols; ++n) {
forwardKinematic.submat(3, n, 5, n) = arma::cross(endEffectorJointsRotated.col(n), baseToEndEffectorJointPositions.col(n));
}
arma::Mat<double> inverseKinematic(6, 6 + redundantJointIndicies_.n_elem, arma::fill::zeros);
inverseKinematic.diag() = -arma::sqrt(arma::sum(arma::square(baseToEndEffectorJointPositions)));
for (arma::uword n = 0; n < redundantJointIndicies_.n_elem; ++n) {
const arma::uword& redundantJointIndex = redundantJointIndicies_(n);
inverseKinematic(n, 6 + n) = arma::dot(baseToEndEffectorJointPositions.col(redundantJointIndex), redundantJointRotationAngles_.col(redundantJointIndex));
}
return -1.0 / arma::cond(arma::solve(forwardKinematic.t(), inverseKinematic));
}
std::string ParallelKinematicMachine6PUPS::toString() const {
return "robotics_parallel_kinematic_machine_6pups";
}
}
}
<commit_msg>Fixed CID 136472 Explicit null dereferenced<commit_after>#include <mantella_bits/optimisationProblem/roboticsOptimisationProblem/robotModel/parallelKinematicMachine6PUPS.hpp>
// C++ standard library
#include <cassert>
// Mantella
#include <mantella_bits/helper/assert.hpp>
#include <mantella_bits/helper/geometry.hpp>
namespace mant {
namespace robotics {
ParallelKinematicMachine6PUPS::ParallelKinematicMachine6PUPS()
: ParallelKinematicMachine6PUPS(
// endEffectorJointPositions
{-0.025561381023353, 0.086293776138137, 0.12,
0.025561381023353, 0.086293776138137, 0.12,
0.087513292835791, -0.021010082747031, 0.12,
0.061951911812438, -0.065283693391106, 0.12,
-0.061951911812438, -0.065283693391106, 0.12,
-0.087513292835791, -0.021010082747032, 0.12},
// minimalActiveJointsActuation
{0.39, 0.39, 0.39, 0.39, 0.39, 0.39},
// maximalActiveJointsActuation
{0.95, 0.95, 0.95, 0.95, 0.95, 0.95},
// redundantJointStartPositions
{-0.463708870031622, 0.417029254828353, -0.346410161513775,
0.463708870031622, 0.417029254828353, -0.346410161513775,
0.593012363818459, 0.193069033993384, -0.346410161513775,
0.129303493786838, -0.610098288821738, -0.346410161513775,
-0.129303493786837, -0.610098288821738, -0.346410161513775,
-0.593012363818459, 0.193069033993384, -0.346410161513775},
// redundantJointEndPositions
{-0.247202519085512, 0.292029254828353, 0.086602540378444,
0.247202519085512, 0.292029254828353, 0.086602540378444,
0.376506012872349, 0.068069033993384, 0.086602540378444,
0.129303493786838, -0.360098288821738, 0.086602540378444,
-0.129303493786837, -0.360098288821738, 0.086602540378444,
-0.376506012872349, 0.068069033993384, 0.086602540378444}) {
}
ParallelKinematicMachine6PUPS::ParallelKinematicMachine6PUPS(
const arma::Mat<double>::fixed<3, 6>& endEffectorJointPositions,
const arma::Row<double>::fixed<6>& minimalActiveJointsActuation,
const arma::Row<double>::fixed<6>& maximalActiveJointsActuation,
const arma::Mat<double>::fixed<3, 6>& redundantJointStartPositions,
const arma::Mat<double>::fixed<3, 6>& redundantJointEndPositions)
: RobotModel(6, static_cast<arma::Col<double>>(arma::nonzeros(redundantJointEndPositions - redundantJointStartPositions)).n_elem),
endEffectorJointPositions_(endEffectorJointPositions),
minimalActiveJointsActuation_(minimalActiveJointsActuation),
maximalActiveJointsActuation_(maximalActiveJointsActuation),
redundantJointStartPositions_(redundantJointStartPositions),
redundantJointEndPositions_(redundantJointEndPositions),
redundantJointStartToEndPositions_(redundantJointEndPositions_ - redundantJointStartPositions_),
redundantJointIndicies_(arma::find(arma::any(redundantJointStartToEndPositions_))),
redundantJointRotationAngles_(6, redundantJointIndicies_.n_elem) {
for (arma::uword n = 0; n < redundantJointIndicies_.n_elem; ++n) {
const double& redundantJointXAngle = std::atan2(redundantJointStartToEndPositions_(1, n), redundantJointStartToEndPositions_(0, n));
const double& redundantJointYAngle = std::atan2(redundantJointStartToEndPositions_(2, n), redundantJointStartToEndPositions_(1, n));
redundantJointRotationAngles_.col(n) = arma::Col<double>({std::cos(redundantJointXAngle) * std::cos(redundantJointYAngle), std::sin(redundantJointXAngle) * std::cos(redundantJointYAngle), std::sin(redundantJointYAngle)});
}
}
arma::Mat<double>::fixed<3, 6> ParallelKinematicMachine6PUPS::getEndEffectorJointPositions() const {
return endEffectorJointPositions_;
}
arma::Row<double>::fixed<6> ParallelKinematicMachine6PUPS::getMinimalActiveJointsActuation() const {
return minimalActiveJointsActuation_;
}
arma::Row<double>::fixed<6> ParallelKinematicMachine6PUPS::getMaximalActiveJointsActuation() const {
return maximalActiveJointsActuation_;
}
arma::Mat<double>::fixed<3, 6> ParallelKinematicMachine6PUPS::getRedundantJointStartPositions() const{
return redundantJointStartPositions_;
}
arma::Mat<double>::fixed<3, 6> ParallelKinematicMachine6PUPS::getRedundantJointEndPositions() const{
return redundantJointEndPositions_;
}
arma::Cube<double> ParallelKinematicMachine6PUPS::getModelImplementation(
const arma::Col<double>& endEffectorPose,
const arma::Row<double>& redundantJointsActuation) const {
assert(redundantJointsActuation.n_elem == numberOfRedundantJoints_);
assert(!arma::any(redundantJointsActuation < 0) && !arma::any(redundantJointsActuation > 1));
arma::Cube<double>::fixed<3, 6, 2> model;
const arma::Col<double>& endEffectorPosition = endEffectorPose.subvec(0, 2);
const double& endEffectorRollAngle = endEffectorPose(3);
const double& endEffectorPitchAngle = endEffectorPose(4);
const double& endEffectorYawAngle = endEffectorPose(5);
model.slice(0) = redundantJointStartPositions_;
for (arma::uword n = 0; n < redundantJointIndicies_.n_elem; ++n) {
const arma::uword& redundantJointIndex = redundantJointIndicies_(n);
model.slice(0).col(redundantJointIndex) += redundantJointsActuation(redundantJointIndex) * redundantJointStartToEndPositions_.col(redundantJointIndex);
}
model.slice(1) = get3DRotation(endEffectorRollAngle, endEffectorPitchAngle, endEffectorYawAngle) * endEffectorJointPositions_;
model.slice(1).each_col() += endEffectorPosition;
return model;
}
arma::Row<double> ParallelKinematicMachine6PUPS::getActuationImplementation(
const arma::Col<double>& endEffectorPose,
const arma::Row<double>& redundantJointsActuation) const {
assert(redundantJointsActuation.n_elem == numberOfRedundantJoints_);
assert(!arma::any(redundantJointsActuation < 0) && !arma::any(redundantJointsActuation > 1));
const arma::Cube<double>& model = getModel(endEffectorPose, redundantJointsActuation);
const arma::Mat<double>& baseJoints = model.slice(0);
const arma::Mat<double>& endEffectorJoints = model.slice(1);
return arma::sqrt(arma::sum(arma::square(endEffectorJoints - baseJoints)));
}
double ParallelKinematicMachine6PUPS::getEndEffectorPoseErrorImplementation(
const arma::Col<double>& endEffectorPose,
const arma::Row<double>& redundantJointsActuation) const {
assert(redundantJointsActuation.n_elem == numberOfRedundantJoints_);
assert(!arma::any(redundantJointsActuation < 0) && !arma::any(redundantJointsActuation > 1));
const arma::Cube<double>& model = getModel(endEffectorPose, redundantJointsActuation);
const arma::Mat<double>& baseJoints = model.slice(1);
const arma::Mat<double>& endEffectorJoints = model.slice(1);
arma::Mat<double> endEffectorJointsRotated = endEffectorJoints;
endEffectorJointsRotated.each_col() -= endEffectorPose.subvec(0, 2);
const arma::Mat<double>& baseToEndEffectorJointPositions = endEffectorJoints - baseJoints;
const arma::Row<double>& baseToEndEffectorJointsActuation = arma::sqrt(arma::sum(arma::square(baseToEndEffectorJointPositions)));
if (arma::any(baseToEndEffectorJointsActuation < minimalActiveJointsActuation_) || arma::any(baseToEndEffectorJointsActuation > maximalActiveJointsActuation_)) {
return 0.0;
}
arma::Mat<double> forwardKinematic;
forwardKinematic.head_rows(3) = baseToEndEffectorJointPositions;
for (arma::uword n = 0; n < baseToEndEffectorJointPositions.n_cols; ++n) {
forwardKinematic.submat(3, n, 5, n) = arma::cross(endEffectorJointsRotated.col(n), baseToEndEffectorJointPositions.col(n));
}
arma::Mat<double> inverseKinematic(6, 6 + redundantJointIndicies_.n_elem, arma::fill::zeros);
inverseKinematic.diag() = -arma::sqrt(arma::sum(arma::square(baseToEndEffectorJointPositions)));
for (arma::uword n = 0; n < redundantJointIndicies_.n_elem; ++n) {
const arma::uword& redundantJointIndex = redundantJointIndicies_(n);
inverseKinematic(n, 6 + n) = arma::dot(baseToEndEffectorJointPositions.col(redundantJointIndex), redundantJointRotationAngles_.col(redundantJointIndex));
}
return -1.0 / arma::cond(arma::solve(forwardKinematic.t(), inverseKinematic));
}
std::string ParallelKinematicMachine6PUPS::toString() const {
return "robotics_parallel_kinematic_machine_6pups";
}
}
}
<|endoftext|> |
<commit_before>/**
** \file scheduler/scheduler.cc
** \brief Implementation of scheduler::Scheduler.
*/
//#define ENABLE_DEBUG_TRACES
#include <cassert>
#include <cstdlib>
#include <libport/compiler.hh>
#include <libport/containers.hh>
#include <libport/foreach.hh>
#include "kernel/userver.hh"
#include "object/urbi-exception.hh"
#include "scheduler/scheduler.hh"
#include "scheduler/job.hh"
namespace scheduler
{
// This function is required to start a new job using the libcoroutine.
// Its only purpose is to create the context and start the execution
// of the new job.
static void
run_job (void* job)
{
static_cast<Job*>(job)->run();
}
void
Scheduler::add_job (Job* job)
{
assert (job);
assert (!libport::has (jobs_, job));
assert (!libport::has (jobs_to_start_, job));
jobs_to_start_.push_back (job);
}
libport::utime_t
Scheduler::work ()
{
#ifdef ENABLE_DEBUG_TRACES
static int cycle = 0;
#endif
ECHO ("======================================================== cycle "
<< ++cycle);
// Start new jobs. You may note that to_kill_ is reset at the beginning
// of each loop and one final time at the end. This is to ensure that
// we are not trying to clear the job on which we are iterating (it
// may only be set to a reference onto the latest scheduled job).
to_start_.clear ();
std::swap (to_start_, jobs_to_start_);
foreach (Job* job, to_start_)
{
to_kill_ = 0;
assert (job);
ECHO ("will start job " << *job);
// Job will start for a very short time and do a yield_front() to
// be restarted below in the course of the regular cycle.
assert (!current_job_);
current_job_ = job;
Coro_startCoro_ (self_, job->coro_get(), job, run_job);
// We have to assume that a new job may have had side-effects.
possible_side_effect_ = true;
}
// Start deferred jobs
for (libport::utime_t current_time = ::urbiserver->getTime ();
!deferred_jobs_.empty();
deferred_jobs_.pop ())
{
deferred_job j = deferred_jobs_.top ();
if (current_time < j.get<0>())
break;
jobs_.push_back (j.get<1> ());
}
// If something is going to happen, or if we have just started a
// new job, add the list of jobs waiting for something to happen
// on the pending jobs queue.
if (!if_change_jobs_.empty() && (possible_side_effect_ || !jobs_.empty()))
{
foreach (Job* job, if_change_jobs_)
jobs_.push_back (job);
if_change_jobs_.clear ();
}
// Run all the jobs in the run queue once. If any job declares upon entry or
// return that it is not side-effect free, we remember that for the next
// cycle.
possible_side_effect_ = false;
pending_.clear ();
std::swap (pending_, jobs_);
execute_round (pending_);
check_for_stopped_tags ();
// Do we have some work to do now?
if (!jobs_.empty () || !jobs_to_start_.empty())
{
ECHO ("scheduler: asking to be recalled ASAP, " << jobs_.size() << " jobs ready and " << jobs_to_start_.size()
<< " to start");
return 0;
}
// Do we have deferred jobs?
if (!deferred_jobs_.empty ())
{
ECHO ("scheduler: asking to be recalled later");
return deferred_jobs_.top ().get<0> ();
}
// Ok, let's say, we'll be called again in one hour.
ECHO ("scheduler: asking to be recalled in a long time");
return ::urbiserver->getTime() + 3600000000LL;
}
void
Scheduler::execute_round (const jobs_type& jobs)
{
ECHO (pending_.size() << " jobs in the queue for this round");
foreach (Job* job, jobs)
{
// Kill a job if needed. See explanation in job.hh.
to_kill_ = 0;
assert (job);
assert (!job->terminated ());
ECHO ("will resume job " << *job << (job->side_effect_free_get() ? " (side-effect free)" : ""));
possible_side_effect_ |= !job->side_effect_free_get ();
assert (!current_job_);
Coro_switchTo_ (self_, job->coro_get ());
assert (!current_job_);
possible_side_effect_ |= !job->side_effect_free_get ();
ECHO ("back from job " << *job << (job->side_effect_free_get() ? " (side-effect free)" : ""));
}
// Kill a job if needed. See explanation in job.hh.
to_kill_ = 0;
}
void
Scheduler::check_for_stopped_tags ()
{
// If we have had no stopped tag, return immediately.
if (stopped_tags_.empty ())
return;
// Extract blocked jobs from every queue, and run them once so that they can react to the
// stop. To do that, we build a list of jobs to start, unschedule them then execute them.
jobs_type to_start;
foreach (Job *job, jobs_)
if (job->blocked ())
to_start.push_back (job);
foreach (Job *job, suspended_jobs_)
if (job->blocked ())
to_start.push_back (job);
foreach (Job *job, if_change_jobs_)
if (job->blocked ())
to_start.push_back (job);
deferred_jobs deferred_jobs_copy = deferred_jobs_;
while (!deferred_jobs_copy.empty ())
{
deferred_job j = deferred_jobs_copy.top ();
deferred_jobs_copy.pop ();
Job *job = j.get<1>();
if (job->blocked ())
to_start.push_back (job);
}
foreach (Job* job, to_start)
unschedule_job (job);
execute_round (to_start);
// Reset tags to their real blocked value and reset the list
foreach (tag_state_type t, stopped_tags_)
t.first->set_blocked (t.second);
stopped_tags_.clear ();
}
void
Scheduler::switch_back (Job* job)
{
// Switch back to the scheduler.
assert (current_job_ == job);
current_job_ = 0;
Coro_switchTo_ (job->coro_get (), self_);
// We regained control, we are again in the context of the job.
assert (!current_job_);
current_job_ = job;
ECHO ("job " << *job << " resumed");
// Check that we are not near exhausting the stack space.
job->check_stack_space ();
// Execute a deferred exception if any
job->check_for_pending_exception ();
// If we are in frozen state, let's requeue ourselves waiting
// for something to change. And let's mark us side-effect
// free during this time so that we won't cause other jobs
// to be scheduled. Of course, we have to check for pending
// exceptions each time we are woken up.
if (job->frozen ())
{
bool side_effect_free_save = job->side_effect_free_get ();
do {
job->side_effect_free_set (true);
job->yield_until_things_changed ();
job->side_effect_free_set (side_effect_free_save);
// Execute a deferred exception if any
job->check_for_pending_exception ();
} while (job->frozen ());
}
}
void
Scheduler::resume_scheduler (Job* job)
{
// If the job has not terminated and is side-effect free, then we
// assume it will not take a long time as we are probably evaluating
// a condition. In order to reduce the number of cycles spent to evaluate
// the condition, continue until it asks to be suspended in another
// way or until it is no longer side-effect free.
if (!job->terminated () && job->side_effect_free_get ())
return;
// If the job has not terminated, put it at the back of the run queue
// so that the run queue order is preserved between work cycles.
if (!job->terminated ())
jobs_.push_back (job);
ECHO (*job << " has " << (job->terminated () ? "" : "not ") << "terminated");
switch_back (job);
}
void
Scheduler::resume_scheduler_front (Job* job)
{
// Put the job in front of the queue. If the job asks to be requeued,
// it is not terminated.
assert (!job->terminated ());
jobs_.push_front (job);
switch_back (job);
}
void
Scheduler::resume_scheduler_until (Job* job, libport::utime_t deadline)
{
// Put the job in the deferred queue. If the job asks to be requeued,
// it is not terminated.
assert (!job->terminated ());
deferred_jobs_.push (boost::make_tuple (deadline, job));
switch_back (job);
}
void
Scheduler::resume_scheduler_suspend (Job* job)
{
suspended_jobs_.push_back (job);
switch_back (job);
}
void
Scheduler::resume_scheduler_things_changed (Job* job)
{
if_change_jobs_.push_back (job);
switch_back (job);
}
void
Scheduler::resume_job (Job* job)
{
// Suspended job may have been killed externally, in which case it
// will not appear in the list of suspended jobs.
if (libport::has (suspended_jobs_, job))
{
jobs_.push_back (job);
suspended_jobs_.remove (job);
}
}
void
Scheduler::killall_jobs ()
{
ECHO ("killing all jobs!");
// This implementation is quite inefficient because it will call
// kill_job() for each job. But who cares? We are killing everyone
// anyway.
while (!jobs_to_start_.empty ())
jobs_to_start_.pop_front ();
while (!suspended_jobs_.empty ())
kill_job (suspended_jobs_.front ());
while (!if_change_jobs_.empty ())
kill_job (if_change_jobs_.front ());
while (!jobs_.empty ())
kill_job (jobs_.front ());
while (!deferred_jobs_.empty ())
kill_job (deferred_jobs_.top ().get<1>());
}
void
Scheduler::unschedule_job (Job* job)
{
assert (job);
assert (job != current_job_);
ECHO ("unscheduling job " << *job);
// Remove the job from the queues where it could be stored.
jobs_to_start_.remove (job);
jobs_.remove (job);
suspended_jobs_.remove (job);
if_change_jobs_.remove (job);
// Remove it from live queues as well if the job is destroyed.
to_start_.remove (job);
pending_.remove (job);
// We have no remove() on a priority queue, regenerate a queue without
// this job.
{
deferred_jobs old_deferred;
std::swap (old_deferred, deferred_jobs_);
while (!old_deferred.empty ())
{
deferred_job j = old_deferred.top ();
old_deferred.pop ();
if (j.get<1>() != job)
deferred_jobs_.push (j);
}
}
}
void
Scheduler::kill_job (Job* job)
{
assert (job != current_job_);
ECHO ("deleting job " << *job);
delete job;
}
void Scheduler::signal_stop (Tag* t)
{
bool previous_state = t->own_blocked ();
t->set_blocked (true);
stopped_tags_.push_back (std::make_pair(t, previous_state));
}
bool operator> (const deferred_job& left, const deferred_job& right)
{
return left.get<0>() > right.get<0>();
}
} // namespace scheduler
<commit_msg>Style: wrap at 80 columns<commit_after>/**
** \file scheduler/scheduler.cc
** \brief Implementation of scheduler::Scheduler.
*/
//#define ENABLE_DEBUG_TRACES
#include <cassert>
#include <cstdlib>
#include <libport/compiler.hh>
#include <libport/containers.hh>
#include <libport/foreach.hh>
#include "kernel/userver.hh"
#include "object/urbi-exception.hh"
#include "scheduler/scheduler.hh"
#include "scheduler/job.hh"
namespace scheduler
{
// This function is required to start a new job using the libcoroutine.
// Its only purpose is to create the context and start the execution
// of the new job.
static void
run_job (void* job)
{
static_cast<Job*>(job)->run();
}
void
Scheduler::add_job (Job* job)
{
assert (job);
assert (!libport::has (jobs_, job));
assert (!libport::has (jobs_to_start_, job));
jobs_to_start_.push_back (job);
}
libport::utime_t
Scheduler::work ()
{
#ifdef ENABLE_DEBUG_TRACES
static int cycle = 0;
#endif
ECHO ("======================================================== cycle "
<< ++cycle);
// Start new jobs. You may note that to_kill_ is reset at the beginning
// of each loop and one final time at the end. This is to ensure that
// we are not trying to clear the job on which we are iterating (it
// may only be set to a reference onto the latest scheduled job).
to_start_.clear ();
std::swap (to_start_, jobs_to_start_);
foreach (Job* job, to_start_)
{
to_kill_ = 0;
assert (job);
ECHO ("will start job " << *job);
// Job will start for a very short time and do a yield_front() to
// be restarted below in the course of the regular cycle.
assert (!current_job_);
current_job_ = job;
Coro_startCoro_ (self_, job->coro_get(), job, run_job);
// We have to assume that a new job may have had side-effects.
possible_side_effect_ = true;
}
// Start deferred jobs
for (libport::utime_t current_time = ::urbiserver->getTime ();
!deferred_jobs_.empty();
deferred_jobs_.pop ())
{
deferred_job j = deferred_jobs_.top ();
if (current_time < j.get<0>())
break;
jobs_.push_back (j.get<1> ());
}
// If something is going to happen, or if we have just started a
// new job, add the list of jobs waiting for something to happen
// on the pending jobs queue.
if (!if_change_jobs_.empty() && (possible_side_effect_ || !jobs_.empty()))
{
foreach (Job* job, if_change_jobs_)
jobs_.push_back (job);
if_change_jobs_.clear ();
}
// Run all the jobs in the run queue once. If any job declares upon entry or
// return that it is not side-effect free, we remember that for the next
// cycle.
possible_side_effect_ = false;
pending_.clear ();
std::swap (pending_, jobs_);
execute_round (pending_);
check_for_stopped_tags ();
// Do we have some work to do now?
if (!jobs_.empty () || !jobs_to_start_.empty())
{
ECHO ("scheduler: asking to be recalled ASAP, " << jobs_.size()
<< " jobs ready and " << jobs_to_start_.size()
<< " to start");
return 0;
}
// Do we have deferred jobs?
if (!deferred_jobs_.empty ())
{
ECHO ("scheduler: asking to be recalled later");
return deferred_jobs_.top ().get<0> ();
}
// Ok, let's say, we'll be called again in one hour.
ECHO ("scheduler: asking to be recalled in a long time");
return ::urbiserver->getTime() + 3600000000LL;
}
void
Scheduler::execute_round (const jobs_type& jobs)
{
ECHO (pending_.size() << " jobs in the queue for this round");
foreach (Job* job, jobs)
{
// Kill a job if needed. See explanation in job.hh.
to_kill_ = 0;
assert (job);
assert (!job->terminated ());
ECHO ("will resume job " << *job
<< (job->side_effect_free_get() ? " (side-effect free)" : ""));
possible_side_effect_ |= !job->side_effect_free_get ();
assert (!current_job_);
Coro_switchTo_ (self_, job->coro_get ());
assert (!current_job_);
possible_side_effect_ |= !job->side_effect_free_get ();
ECHO ("back from job " << *job
<< (job->side_effect_free_get() ? " (side-effect free)" : ""));
}
// Kill a job if needed. See explanation in job.hh.
to_kill_ = 0;
}
void
Scheduler::check_for_stopped_tags ()
{
// If we have had no stopped tag, return immediately.
if (stopped_tags_.empty ())
return;
// Extract blocked jobs from every queue, and run them once so
// that they can react to the stop. To do that, we build a list of
// jobs to start, unschedule them then execute them.
jobs_type to_start;
foreach (Job *job, jobs_)
if (job->blocked ())
to_start.push_back (job);
foreach (Job *job, suspended_jobs_)
if (job->blocked ())
to_start.push_back (job);
foreach (Job *job, if_change_jobs_)
if (job->blocked ())
to_start.push_back (job);
deferred_jobs deferred_jobs_copy = deferred_jobs_;
while (!deferred_jobs_copy.empty ())
{
deferred_job j = deferred_jobs_copy.top ();
deferred_jobs_copy.pop ();
Job *job = j.get<1>();
if (job->blocked ())
to_start.push_back (job);
}
foreach (Job* job, to_start)
unschedule_job (job);
execute_round (to_start);
// Reset tags to their real blocked value and reset the list.
foreach (tag_state_type t, stopped_tags_)
t.first->set_blocked (t.second);
stopped_tags_.clear ();
}
void
Scheduler::switch_back (Job* job)
{
// Switch back to the scheduler.
assert (current_job_ == job);
current_job_ = 0;
Coro_switchTo_ (job->coro_get (), self_);
// We regained control, we are again in the context of the job.
assert (!current_job_);
current_job_ = job;
ECHO ("job " << *job << " resumed");
// Check that we are not near exhausting the stack space.
job->check_stack_space ();
// Execute a deferred exception if any
job->check_for_pending_exception ();
// If we are in frozen state, let's requeue ourselves waiting
// for something to change. And let's mark us side-effect
// free during this time so that we won't cause other jobs
// to be scheduled. Of course, we have to check for pending
// exceptions each time we are woken up.
if (job->frozen ())
{
bool side_effect_free_save = job->side_effect_free_get ();
do {
job->side_effect_free_set (true);
job->yield_until_things_changed ();
job->side_effect_free_set (side_effect_free_save);
// Execute a deferred exception if any
job->check_for_pending_exception ();
} while (job->frozen ());
}
}
void
Scheduler::resume_scheduler (Job* job)
{
// If the job has not terminated and is side-effect free, then we
// assume it will not take a long time as we are probably evaluating
// a condition. In order to reduce the number of cycles spent to evaluate
// the condition, continue until it asks to be suspended in another
// way or until it is no longer side-effect free.
if (!job->terminated () && job->side_effect_free_get ())
return;
// If the job has not terminated, put it at the back of the run queue
// so that the run queue order is preserved between work cycles.
if (!job->terminated ())
jobs_.push_back (job);
ECHO (*job << " has " << (job->terminated () ? "" : "not ") << "terminated");
switch_back (job);
}
void
Scheduler::resume_scheduler_front (Job* job)
{
// Put the job in front of the queue. If the job asks to be requeued,
// it is not terminated.
assert (!job->terminated ());
jobs_.push_front (job);
switch_back (job);
}
void
Scheduler::resume_scheduler_until (Job* job, libport::utime_t deadline)
{
// Put the job in the deferred queue. If the job asks to be requeued,
// it is not terminated.
assert (!job->terminated ());
deferred_jobs_.push (boost::make_tuple (deadline, job));
switch_back (job);
}
void
Scheduler::resume_scheduler_suspend (Job* job)
{
suspended_jobs_.push_back (job);
switch_back (job);
}
void
Scheduler::resume_scheduler_things_changed (Job* job)
{
if_change_jobs_.push_back (job);
switch_back (job);
}
void
Scheduler::resume_job (Job* job)
{
// Suspended job may have been killed externally, in which case it
// will not appear in the list of suspended jobs.
if (libport::has (suspended_jobs_, job))
{
jobs_.push_back (job);
suspended_jobs_.remove (job);
}
}
void
Scheduler::killall_jobs ()
{
ECHO ("killing all jobs!");
// This implementation is quite inefficient because it will call
// kill_job() for each job. But who cares? We are killing everyone
// anyway.
while (!jobs_to_start_.empty ())
jobs_to_start_.pop_front ();
while (!suspended_jobs_.empty ())
kill_job (suspended_jobs_.front ());
while (!if_change_jobs_.empty ())
kill_job (if_change_jobs_.front ());
while (!jobs_.empty ())
kill_job (jobs_.front ());
while (!deferred_jobs_.empty ())
kill_job (deferred_jobs_.top ().get<1>());
}
void
Scheduler::unschedule_job (Job* job)
{
assert (job);
assert (job != current_job_);
ECHO ("unscheduling job " << *job);
// Remove the job from the queues where it could be stored.
jobs_to_start_.remove (job);
jobs_.remove (job);
suspended_jobs_.remove (job);
if_change_jobs_.remove (job);
// Remove it from live queues as well if the job is destroyed.
to_start_.remove (job);
pending_.remove (job);
// We have no remove() on a priority queue, regenerate a queue without
// this job.
{
deferred_jobs old_deferred;
std::swap (old_deferred, deferred_jobs_);
while (!old_deferred.empty ())
{
deferred_job j = old_deferred.top ();
old_deferred.pop ();
if (j.get<1>() != job)
deferred_jobs_.push (j);
}
}
}
void
Scheduler::kill_job (Job* job)
{
assert (job != current_job_);
ECHO ("deleting job " << *job);
delete job;
}
void Scheduler::signal_stop (Tag* t)
{
bool previous_state = t->own_blocked ();
t->set_blocked (true);
stopped_tags_.push_back (std::make_pair(t, previous_state));
}
bool operator> (const deferred_job& left, const deferred_job& right)
{
return left.get<0>() > right.get<0>();
}
} // namespace scheduler
<|endoftext|> |
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* LXQt - a lightweight, Qt based, desktop toolset
* https://lxqt.org
*
* Copyright: 2012 Razor team
* Authors:
* Johannes Zellner <webmaster@nebulon.de>
*
* This program or library is free software; you can redistribute it
* and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General
* Public License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*
* END_COMMON_COPYRIGHT_HEADER */
#include "alsaengine.h"
#include "alsadevice.h"
#include <QMetaType>
#include <QSocketNotifier>
#include <QtDebug>
AlsaEngine *AlsaEngine::m_instance = 0;
static int alsa_elem_event_callback(snd_mixer_elem_t *elem, unsigned int mask)
{
AlsaEngine *engine = AlsaEngine::instance();
if (engine)
engine->updateDevice(engine->getDeviceByAlsaElem(elem));
return 0;
}
static int alsa_mixer_event_callback(snd_mixer_t *mixer, unsigned int mask, snd_mixer_elem_t *elem)
{
return 0;
}
AlsaEngine::AlsaEngine(QObject *parent) :
AudioEngine(parent)
{
discoverDevices();
m_instance = this;
}
AlsaEngine *AlsaEngine::instance()
{
return m_instance;
}
int AlsaEngine::volumeMax(AudioDevice *device) const
{
AlsaDevice * alsa_dev = qobject_cast<AlsaDevice *>(device);
Q_ASSERT(alsa_dev);
return alsa_dev->volumeMax();
}
AlsaDevice *AlsaEngine::getDeviceByAlsaElem(snd_mixer_elem_t *elem) const
{
for (AudioDevice *device : qAsConst(m_sinks)) {
AlsaDevice *dev = qobject_cast<AlsaDevice*>(device);
if (!dev || !dev->element())
continue;
if (dev->element() == elem)
return dev;
}
return 0;
}
void AlsaEngine::commitDeviceVolume(AudioDevice *device)
{
AlsaDevice *dev = qobject_cast<AlsaDevice*>(device);
if (!dev || !dev->element())
return;
long value = dev->volumeMin() + qRound(static_cast<double>(dev->volume()) / 100.0 * (dev->volumeMax() - dev->volumeMin()));
snd_mixer_selem_set_playback_volume_all(dev->element(), value);
}
void AlsaEngine::setMute(AudioDevice *device, bool state)
{
AlsaDevice *dev = qobject_cast<AlsaDevice*>(device);
if (!dev || !dev->element())
return;
if (snd_mixer_selem_has_playback_switch(dev->element()))
snd_mixer_selem_set_playback_switch_all(dev->element(), (int)!state);
else if (state)
dev->setVolume(0);
}
void AlsaEngine::updateDevice(AlsaDevice *device)
{
if (!device)
return;
long value;
snd_mixer_selem_get_playback_volume(device->element(), (snd_mixer_selem_channel_id_t)0, &value);
// qDebug() << "updateDevice:" << device->name() << value;
device->setVolumeNoCommit(qRound((static_cast<double>(value - device->volumeMin()) * 100.0) / (device->volumeMax() - device->volumeMin())));
if (snd_mixer_selem_has_playback_switch(device->element())) {
int mute;
snd_mixer_selem_get_playback_switch(device->element(), (snd_mixer_selem_channel_id_t)0, &mute);
device->setMuteNoCommit(!(bool)mute);
}
}
void AlsaEngine::driveAlsaEventHandling(int fd)
{
snd_mixer_handle_events(m_mixerMap.value(fd));
}
void AlsaEngine::discoverDevices()
{
int error;
int cardNum = -1;
const int BUFF_SIZE = 64;
while (1) {
if ((error = snd_card_next(&cardNum)) < 0) {
qWarning("Can't get the next card number: %s\n", snd_strerror(error));
break;
}
if (cardNum < 0)
break;
char str[BUFF_SIZE];
const size_t n = snprintf(str, sizeof(str), "hw:%i", cardNum);
if (BUFF_SIZE <= n) {
qWarning("AlsaEngine::discoverDevices: Buffer too small\n");
continue;
}
snd_ctl_t *cardHandle;
if ((error = snd_ctl_open(&cardHandle, str, 0)) < 0) {
qWarning("Can't open card %i: %s\n", cardNum, snd_strerror(error));
continue;
}
snd_ctl_card_info_t *cardInfo;
snd_ctl_card_info_alloca(&cardInfo);
QString cardName = QString::fromLatin1(snd_ctl_card_info_get_name(cardInfo));
if (cardName.isEmpty())
cardName = QString::fromLatin1(str);
if ((error = snd_ctl_card_info(cardHandle, cardInfo)) < 0) {
qWarning("Can't get info for card %i: %s\n", cardNum, snd_strerror(error));
} else {
// setup mixer and iterate over channels
snd_mixer_t *mixer = nullptr;
snd_mixer_open(&mixer, nullptr);
snd_mixer_attach(mixer, str);
snd_mixer_selem_register(mixer, nullptr, nullptr);
snd_mixer_load(mixer);
// setup event handler for mixer
snd_mixer_set_callback(mixer, alsa_mixer_event_callback);
// setup eventloop handling
struct pollfd pfd;
if (snd_mixer_poll_descriptors(mixer, &pfd, 1)) {
QSocketNotifier *notifier = new QSocketNotifier(pfd.fd, QSocketNotifier::Read, this);
connect(notifier, SIGNAL(activated(int)), this, SLOT(driveAlsaEventHandling(int)));
m_mixerMap.insert(pfd.fd, mixer);
}
snd_mixer_elem_t *mixerElem = 0;
mixerElem = snd_mixer_first_elem(mixer);
while (mixerElem) {
// check if we have a Sink or Source
if (snd_mixer_selem_has_playback_volume(mixerElem)) {
AlsaDevice *dev = new AlsaDevice(Sink, this, this);
dev->setName(QString::fromLatin1(snd_mixer_selem_get_name(mixerElem)));
dev->setIndex(cardNum);
dev->setDescription(cardName + " - " + dev->name());
// set alsa specific members
dev->setCardName(QString::fromLatin1(str));
dev->setMixer(mixer);
dev->setElement(mixerElem);
// get & store the range
long min, max;
snd_mixer_selem_get_playback_volume_range(mixerElem, &min, &max);
dev->setVolumeMinMax(min, max);
updateDevice(dev);
// register event callback
snd_mixer_elem_set_callback(mixerElem, alsa_elem_event_callback);
m_sinks.append(dev);
}
mixerElem = snd_mixer_elem_next(mixerElem);
}
}
snd_ctl_close(cardHandle);
}
snd_config_update_free_global();
}
<commit_msg>Fix FTBFS after 9dfa154413356e4247ff2d99adc2557c58711cbc<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* LXQt - a lightweight, Qt based, desktop toolset
* https://lxqt.org
*
* Copyright: 2012 Razor team
* Authors:
* Johannes Zellner <webmaster@nebulon.de>
*
* This program or library is free software; you can redistribute it
* and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General
* Public License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*
* END_COMMON_COPYRIGHT_HEADER */
#include "alsaengine.h"
#include "alsadevice.h"
#include <QMetaType>
#include <QSocketNotifier>
#include <QtDebug>
AlsaEngine *AlsaEngine::m_instance = 0;
static int alsa_elem_event_callback(snd_mixer_elem_t *elem, unsigned int mask)
{
AlsaEngine *engine = AlsaEngine::instance();
if (engine)
engine->updateDevice(engine->getDeviceByAlsaElem(elem));
return 0;
}
static int alsa_mixer_event_callback(snd_mixer_t *mixer, unsigned int mask, snd_mixer_elem_t *elem)
{
return 0;
}
AlsaEngine::AlsaEngine(QObject *parent) :
AudioEngine(parent)
{
discoverDevices();
m_instance = this;
}
AlsaEngine *AlsaEngine::instance()
{
return m_instance;
}
int AlsaEngine::volumeMax(AudioDevice *device) const
{
AlsaDevice * alsa_dev = qobject_cast<AlsaDevice *>(device);
Q_ASSERT(alsa_dev);
return alsa_dev->volumeMax();
}
AlsaDevice *AlsaEngine::getDeviceByAlsaElem(snd_mixer_elem_t *elem) const
{
for (AudioDevice *device : qAsConst(m_sinks)) {
AlsaDevice *dev = qobject_cast<AlsaDevice*>(device);
if (!dev || !dev->element())
continue;
if (dev->element() == elem)
return dev;
}
return 0;
}
void AlsaEngine::commitDeviceVolume(AudioDevice *device)
{
AlsaDevice *dev = qobject_cast<AlsaDevice*>(device);
if (!dev || !dev->element())
return;
long value = dev->volumeMin() + qRound(static_cast<double>(dev->volume()) / 100.0 * (dev->volumeMax() - dev->volumeMin()));
snd_mixer_selem_set_playback_volume_all(dev->element(), value);
}
void AlsaEngine::setMute(AudioDevice *device, bool state)
{
AlsaDevice *dev = qobject_cast<AlsaDevice*>(device);
if (!dev || !dev->element())
return;
if (snd_mixer_selem_has_playback_switch(dev->element()))
snd_mixer_selem_set_playback_switch_all(dev->element(), (int)!state);
else if (state)
dev->setVolume(0);
}
void AlsaEngine::updateDevice(AlsaDevice *device)
{
if (!device)
return;
long value;
snd_mixer_selem_get_playback_volume(device->element(), (snd_mixer_selem_channel_id_t)0, &value);
// qDebug() << "updateDevice:" << device->name() << value;
device->setVolumeNoCommit(qRound((static_cast<double>(value - device->volumeMin()) * 100.0) / (device->volumeMax() - device->volumeMin())));
if (snd_mixer_selem_has_playback_switch(device->element())) {
int mute;
snd_mixer_selem_get_playback_switch(device->element(), (snd_mixer_selem_channel_id_t)0, &mute);
device->setMuteNoCommit(!(bool)mute);
}
}
void AlsaEngine::driveAlsaEventHandling(int fd)
{
snd_mixer_handle_events(m_mixerMap.value(fd));
}
void AlsaEngine::discoverDevices()
{
int error;
int cardNum = -1;
const int BUFF_SIZE = 64;
while (1) {
if ((error = snd_card_next(&cardNum)) < 0) {
qWarning("Can't get the next card number: %s\n", snd_strerror(error));
break;
}
if (cardNum < 0)
break;
char str[BUFF_SIZE];
const size_t n = snprintf(str, sizeof(str), "hw:%i", cardNum);
if (BUFF_SIZE <= n) {
qWarning("AlsaEngine::discoverDevices: Buffer too small\n");
continue;
}
snd_ctl_t *cardHandle;
if ((error = snd_ctl_open(&cardHandle, str, 0)) < 0) {
qWarning("Can't open card %i: %s\n", cardNum, snd_strerror(error));
continue;
}
snd_ctl_card_info_t *cardInfo;
snd_ctl_card_info_alloca(&cardInfo);
QString cardName = QString::fromLatin1(snd_ctl_card_info_get_name(cardInfo));
if (cardName.isEmpty())
cardName = QString::fromLatin1(str);
if ((error = snd_ctl_card_info(cardHandle, cardInfo)) < 0) {
qWarning("Can't get info for card %i: %s\n", cardNum, snd_strerror(error));
} else {
// setup mixer and iterate over channels
snd_mixer_t *mixer = nullptr;
snd_mixer_open(&mixer, 0);
snd_mixer_attach(mixer, str);
snd_mixer_selem_register(mixer, nullptr, nullptr);
snd_mixer_load(mixer);
// setup event handler for mixer
snd_mixer_set_callback(mixer, alsa_mixer_event_callback);
// setup eventloop handling
struct pollfd pfd;
if (snd_mixer_poll_descriptors(mixer, &pfd, 1)) {
QSocketNotifier *notifier = new QSocketNotifier(pfd.fd, QSocketNotifier::Read, this);
connect(notifier, SIGNAL(activated(int)), this, SLOT(driveAlsaEventHandling(int)));
m_mixerMap.insert(pfd.fd, mixer);
}
snd_mixer_elem_t *mixerElem = 0;
mixerElem = snd_mixer_first_elem(mixer);
while (mixerElem) {
// check if we have a Sink or Source
if (snd_mixer_selem_has_playback_volume(mixerElem)) {
AlsaDevice *dev = new AlsaDevice(Sink, this, this);
dev->setName(QString::fromLatin1(snd_mixer_selem_get_name(mixerElem)));
dev->setIndex(cardNum);
dev->setDescription(cardName + " - " + dev->name());
// set alsa specific members
dev->setCardName(QString::fromLatin1(str));
dev->setMixer(mixer);
dev->setElement(mixerElem);
// get & store the range
long min, max;
snd_mixer_selem_get_playback_volume_range(mixerElem, &min, &max);
dev->setVolumeMinMax(min, max);
updateDevice(dev);
// register event callback
snd_mixer_elem_set_callback(mixerElem, alsa_elem_event_callback);
m_sinks.append(dev);
}
mixerElem = snd_mixer_elem_next(mixerElem);
}
}
snd_ctl_close(cardHandle);
}
snd_config_update_free_global();
}
<|endoftext|> |
<commit_before>// @(#)root/ged:$Id$
// Author: Ilka Antcheva 11/05/04
/*************************************************************************
* Copyright (C) 1995-2002, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TAttMarkerEditor //
// //
// Implements GUI for editing marker attributes. //
// color, style and size //
// //
//////////////////////////////////////////////////////////////////////////
//Begin_Html
/*
<img src="gif/TAttMarkerEditor.gif">
*/
//End_Html
#include "TAttMarkerEditor.h"
#include "TGedMarkerSelect.h"
#include "TGColorSelect.h"
#include "TGNumberEntry.h"
#include "TColor.h"
#include "TGLabel.h"
#include "TGNumberEntry.h"
#include "TPad.h"
#include "TCanvas.h"
#include "TROOT.h"
ClassImp(TAttMarkerEditor)
enum EMarkerWid {
kCOLOR,
kMARKER,
kMARKER_SIZE,
kALPHA,
kALPHAFIELD
};
//______________________________________________________________________________
TAttMarkerEditor::TAttMarkerEditor(const TGWindow *p, Int_t width,
Int_t height,UInt_t options, Pixel_t back)
: TGedFrame(p, width, height, options | kVerticalFrame, back)
{
// Constructor of marker attributes GUI.
fAttMarker = 0;
fSizeForText = kFALSE;
MakeTitle("Marker");
TGCompositeFrame *f2 = new TGCompositeFrame(this, 80, 20, kHorizontalFrame);
fColorSelect = new TGColorSelect(f2, 0, kCOLOR);
f2->AddFrame(fColorSelect, new TGLayoutHints(kLHintsLeft, 1, 1, 1, 1));
fColorSelect->Associate(this);
fMarkerType = new TGedMarkerSelect(f2, 1, kMARKER);
f2->AddFrame(fMarkerType, new TGLayoutHints(kLHintsLeft, 1, 1, 1, 1));
fMarkerType->Associate(this);
fMarkerSize = new TGNumberEntry(f2, 0., 4, kMARKER_SIZE,
TGNumberFormat::kNESRealOne,
TGNumberFormat::kNEANonNegative,
TGNumberFormat::kNELLimitMinMax, 0.2, 5.0);
fMarkerSize->GetNumberEntry()->SetToolTipText("Set marker size");
f2->AddFrame(fMarkerSize, new TGLayoutHints(kLHintsLeft, 1, 1, 1, 1));
fMarkerSize->Associate(this);
AddFrame(f2, new TGLayoutHints(kLHintsTop, 1, 1, 0, 0));
TGLabel *AlphaLabel = new TGLabel(this,"Opacity");
AddFrame(AlphaLabel,
new TGLayoutHints(kLHintsLeft | kLHintsCenterY));
TGHorizontalFrame *f2a = new TGHorizontalFrame(this);
fAlpha = new TGHSlider(f2a,100,kSlider2|kScaleNo,kALPHA);
fAlpha->SetRange(0,1000);
f2a->AddFrame(fAlpha,new TGLayoutHints(kLHintsLeft | kLHintsCenterY));
fAlphaField = new TGNumberEntryField(f2a, kALPHAFIELD, 0,
TGNumberFormat::kNESReal,
TGNumberFormat::kNEANonNegative);
fAlphaField->Resize(40,20);
if (!TCanvas::SupportAlpha()) {
fAlpha->SetEnabled(kFALSE);
AlphaLabel->Disable(kTRUE);
fAlphaField->SetEnabled(kFALSE);
}
f2a->AddFrame(fAlphaField,new TGLayoutHints(kLHintsLeft | kLHintsCenterY));
AddFrame(f2a, new TGLayoutHints(kLHintsLeft | kLHintsCenterY));
}
//______________________________________________________________________________
TAttMarkerEditor::~TAttMarkerEditor()
{
// Destructor of marker editor.
}
//______________________________________________________________________________
void TAttMarkerEditor::ConnectSignals2Slots()
{
// Connect signals to slots.
fColorSelect->Connect("ColorSelected(Pixel_t)", "TAttMarkerEditor", this, "DoMarkerColor(Pixel_t)");
fColorSelect->Connect("AlphaColorSelected(ULong_t)", "TAttMarkerEditor", this, "DoMarkerAlphaColor(ULong_t)");
fMarkerType->Connect("MarkerSelected(Style_t)", "TAttMarkerEditor", this, "DoMarkerStyle(Style_t)");
fMarkerSize->Connect("ValueSet(Long_t)", "TAttMarkerEditor", this, "DoMarkerSize()");
(fMarkerSize->GetNumberEntry())->Connect("ReturnPressed()", "TAttMarkerEditor", this, "DoMarkerSize()");
fAlpha->Connect("Released()","TAttMarkerEditor", this, "DoAlpha()");
fAlpha->Connect("PositionChanged(Int_t)","TAttMarkerEditor", this, "DoLiveAlpha(Int_t)");
fAlphaField->Connect("ReturnPressed()","TAttMarkerEditor", this, "DoAlphaField()");
fAlpha->Connect("Pressed()","TAttMarkerEditor", this, "GetCurAlpha()");
fInit = kFALSE;
}
//______________________________________________________________________________
void TAttMarkerEditor::SetModel(TObject* obj)
{
// Pick up the values of used marker attributes.
fAvoidSignal = kTRUE;
fAttMarker = dynamic_cast<TAttMarker *>(obj);
if (!fAttMarker) return;
TString str = GetDrawOption();
str.ToUpper();
if (obj->InheritsFrom("TH2") && str.Contains("TEXT")) {
fSizeForText = kTRUE;
} else {
fSizeForText = kFALSE;
}
Style_t marker = fAttMarker->GetMarkerStyle();
if ((marker==1 || marker==6 || marker==7) && !fSizeForText) {
fMarkerSize->SetNumber(1.);
fMarkerSize->SetState(kFALSE);
} else {
Float_t s = fAttMarker->GetMarkerSize();
fMarkerSize->SetState(kFALSE);
fMarkerSize->SetNumber(s);
}
fMarkerType->SetMarkerStyle(marker);
Color_t c = fAttMarker->GetMarkerColor();
Pixel_t p = TColor::Number2Pixel(c);
fColorSelect->SetColor(p);
if (fInit) ConnectSignals2Slots();
fAvoidSignal = kFALSE;
if (TColor *color = gROOT->GetColor(fAttMarker->GetMarkerColor())) {
fAlpha->SetPosition((Int_t)(color->GetAlpha()*1000));
fAlphaField->SetNumber(color->GetAlpha());
}
}
//______________________________________________________________________________
void TAttMarkerEditor::DoMarkerColor(Pixel_t color)
{
// Slot connected to the marker color.
if (fAvoidSignal) return;
fAttMarker->SetMarkerColor(TColor::GetColor(color));
if (TColor *tcolor = gROOT->GetColor(TColor::GetColor(color))) {
fAlpha->SetPosition((Int_t)(tcolor->GetAlpha()*1000));
fAlphaField->SetNumber(tcolor->GetAlpha());
}
Update();
}
//______________________________________________________________________________
void TAttMarkerEditor::DoMarkerAlphaColor(ULong_t p)
{
// Slot connected to the color with alpha.
TColor *color = (TColor *)p;
if (fAvoidSignal) return;
fAttMarker->SetMarkerColor(color->GetNumber());
fAlpha->SetPosition((Int_t)(color->GetAlpha()*1000));
fAlphaField->SetNumber(color->GetAlpha());
Update();
}
//______________________________________________________________________________
void TAttMarkerEditor::DoMarkerStyle(Style_t marker)
{
// Slot connected to the marker type.
if (fAvoidSignal) return;
if ((marker==1 || marker==6 || marker==7) && !fSizeForText) {
fMarkerSize->SetNumber(1.);
fMarkerSize->SetState(kFALSE);
} else
fMarkerSize->SetState(kFALSE);
fAttMarker->SetMarkerStyle(marker);
Update();
}
//______________________________________________________________________________
void TAttMarkerEditor::DoMarkerSize()
{
// Slot connected to the marker size.
if (fAvoidSignal) return;
Style_t marker = fAttMarker->GetMarkerStyle();
if ((marker==1 || marker==6 || marker==7) && !fSizeForText) {
fMarkerSize->SetNumber(1.);
fMarkerSize->SetState(kFALSE);
} else
fMarkerSize->SetState(kFALSE);
Float_t size = fMarkerSize->GetNumber();
fAttMarker->SetMarkerSize(size);
Update();
}
//______________________________________________________________________________
void TAttMarkerEditor::DoAlphaField()
{
// Slot to set the alpha value from the entry field.
if (fAvoidSignal) return;
if (TColor *color = gROOT->GetColor(fAttMarker->GetMarkerColor())) {
color->SetAlpha((Float_t)fAlphaField->GetNumber());
fAlpha->SetPosition((Int_t)fAlphaField->GetNumber()*1000);
}
Update();
}
//______________________________________________________________________________
void TAttMarkerEditor::DoAlpha()
{
// Slot to set the alpha value
if (fAvoidSignal) return;
if (TColor *color = gROOT->GetColor(fAttMarker->GetMarkerColor())) {
color->SetAlpha((Float_t)fAlpha->GetPosition()/1000);
fAlphaField->SetNumber((Float_t)fAlpha->GetPosition()/1000);
}
Update();
}
//______________________________________________________________________________
void TAttMarkerEditor::DoLiveAlpha(Int_t a)
{
// Slot to set alpha value online.
if (fAvoidSignal) return;
fAlphaField->SetNumber((Float_t)a/1000);
if (TColor *color = gROOT->GetColor(fAttMarker->GetMarkerColor())) color->SetAlpha((Float_t)a/1000);
Update();
}
//_______________________________________________________________________________
void TAttMarkerEditor::GetCurAlpha()
{
// Slot to update alpha value on click on Slider
if (fAvoidSignal) return;
if (TColor *color = gROOT->GetColor(fAttMarker->GetMarkerColor())) {
fAlpha->SetPosition((Int_t)(color->GetAlpha()*1000));
fAlphaField->SetNumber(color->GetAlpha());
}
Update();
}
<commit_msg>Ooops, rollback mods in ged.<commit_after>// @(#)root/ged:$Id$
// Author: Ilka Antcheva 11/05/04
/*************************************************************************
* Copyright (C) 1995-2002, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TAttMarkerEditor //
// //
// Implements GUI for editing marker attributes. //
// color, style and size //
// //
//////////////////////////////////////////////////////////////////////////
//Begin_Html
/*
<img src="gif/TAttMarkerEditor.gif">
*/
//End_Html
#include "TAttMarkerEditor.h"
#include "TGedMarkerSelect.h"
#include "TGColorSelect.h"
#include "TGNumberEntry.h"
#include "TColor.h"
#include "TGLabel.h"
#include "TGNumberEntry.h"
#include "TPad.h"
#include "TCanvas.h"
#include "TROOT.h"
ClassImp(TAttMarkerEditor)
enum EMarkerWid {
kCOLOR,
kMARKER,
kMARKER_SIZE,
kALPHA,
kALPHAFIELD
};
//______________________________________________________________________________
TAttMarkerEditor::TAttMarkerEditor(const TGWindow *p, Int_t width,
Int_t height,UInt_t options, Pixel_t back)
: TGedFrame(p, width, height, options | kVerticalFrame, back)
{
// Constructor of marker attributes GUI.
fAttMarker = 0;
fSizeForText = kFALSE;
MakeTitle("Marker");
TGCompositeFrame *f2 = new TGCompositeFrame(this, 80, 20, kHorizontalFrame);
fColorSelect = new TGColorSelect(f2, 0, kCOLOR);
f2->AddFrame(fColorSelect, new TGLayoutHints(kLHintsLeft, 1, 1, 1, 1));
fColorSelect->Associate(this);
fMarkerType = new TGedMarkerSelect(f2, 1, kMARKER);
f2->AddFrame(fMarkerType, new TGLayoutHints(kLHintsLeft, 1, 1, 1, 1));
fMarkerType->Associate(this);
fMarkerSize = new TGNumberEntry(f2, 0., 4, kMARKER_SIZE,
TGNumberFormat::kNESRealOne,
TGNumberFormat::kNEANonNegative,
TGNumberFormat::kNELLimitMinMax, 0.2, 5.0);
fMarkerSize->GetNumberEntry()->SetToolTipText("Set marker size");
f2->AddFrame(fMarkerSize, new TGLayoutHints(kLHintsLeft, 1, 1, 1, 1));
fMarkerSize->Associate(this);
AddFrame(f2, new TGLayoutHints(kLHintsTop, 1, 1, 0, 0));
TGLabel *AlphaLabel = new TGLabel(this,"Opacity");
AddFrame(AlphaLabel,
new TGLayoutHints(kLHintsLeft | kLHintsCenterY));
TGHorizontalFrame *f2a = new TGHorizontalFrame(this);
fAlpha = new TGHSlider(f2a,100,kSlider2|kScaleNo,kALPHA);
fAlpha->SetRange(0,1000);
f2a->AddFrame(fAlpha,new TGLayoutHints(kLHintsLeft | kLHintsCenterY));
fAlphaField = new TGNumberEntryField(f2a, kALPHAFIELD, 0,
TGNumberFormat::kNESReal,
TGNumberFormat::kNEANonNegative);
fAlphaField->Resize(40,20);
if (!TCanvas::SupportAlpha()) {
fAlpha->SetEnabled(kFALSE);
AlphaLabel->Disable(kTRUE);
fAlphaField->SetEnabled(kFALSE);
}
f2a->AddFrame(fAlphaField,new TGLayoutHints(kLHintsLeft | kLHintsCenterY));
AddFrame(f2a, new TGLayoutHints(kLHintsLeft | kLHintsCenterY));
}
//______________________________________________________________________________
TAttMarkerEditor::~TAttMarkerEditor()
{
// Destructor of marker editor.
}
//______________________________________________________________________________
void TAttMarkerEditor::ConnectSignals2Slots()
{
// Connect signals to slots.
fColorSelect->Connect("ColorSelected(Pixel_t)", "TAttMarkerEditor", this, "DoMarkerColor(Pixel_t)");
fColorSelect->Connect("AlphaColorSelected(ULong_t)", "TAttMarkerEditor", this, "DoMarkerAlphaColor(ULong_t)");
fMarkerType->Connect("MarkerSelected(Style_t)", "TAttMarkerEditor", this, "DoMarkerStyle(Style_t)");
fMarkerSize->Connect("ValueSet(Long_t)", "TAttMarkerEditor", this, "DoMarkerSize()");
(fMarkerSize->GetNumberEntry())->Connect("ReturnPressed()", "TAttMarkerEditor", this, "DoMarkerSize()");
fAlpha->Connect("Released()","TAttMarkerEditor", this, "DoAlpha()");
fAlpha->Connect("PositionChanged(Int_t)","TAttMarkerEditor", this, "DoLiveAlpha(Int_t)");
fAlphaField->Connect("ReturnPressed()","TAttMarkerEditor", this, "DoAlphaField()");
fAlpha->Connect("Pressed()","TAttMarkerEditor", this, "GetCurAlpha()");
fInit = kFALSE;
}
//______________________________________________________________________________
void TAttMarkerEditor::SetModel(TObject* obj)
{
// Pick up the values of used marker attributes.
fAvoidSignal = kTRUE;
fAttMarker = dynamic_cast<TAttMarker *>(obj);
if (!fAttMarker) return;
TString str = GetDrawOption();
str.ToUpper();
if (obj->InheritsFrom("TH2") && str.Contains("TEXT")) {
fSizeForText = kTRUE;
} else {
fSizeForText = kFALSE;
}
Style_t marker = fAttMarker->GetMarkerStyle();
if ((marker==1 || marker==6 || marker==7) && !fSizeForText) {
fMarkerSize->SetNumber(1.);
fMarkerSize->SetState(kFALSE);
} else {
Float_t s = fAttMarker->GetMarkerSize();
fMarkerSize->SetState(kTRUE);
fMarkerSize->SetNumber(s);
}
fMarkerType->SetMarkerStyle(marker);
Color_t c = fAttMarker->GetMarkerColor();
Pixel_t p = TColor::Number2Pixel(c);
fColorSelect->SetColor(p);
if (fInit) ConnectSignals2Slots();
fAvoidSignal = kFALSE;
if (TColor *color = gROOT->GetColor(fAttMarker->GetMarkerColor())) {
fAlpha->SetPosition((Int_t)(color->GetAlpha()*1000));
fAlphaField->SetNumber(color->GetAlpha());
}
}
//______________________________________________________________________________
void TAttMarkerEditor::DoMarkerColor(Pixel_t color)
{
// Slot connected to the marker color.
if (fAvoidSignal) return;
fAttMarker->SetMarkerColor(TColor::GetColor(color));
if (TColor *tcolor = gROOT->GetColor(TColor::GetColor(color))) {
fAlpha->SetPosition((Int_t)(tcolor->GetAlpha()*1000));
fAlphaField->SetNumber(tcolor->GetAlpha());
}
Update();
}
//______________________________________________________________________________
void TAttMarkerEditor::DoMarkerAlphaColor(ULong_t p)
{
// Slot connected to the color with alpha.
TColor *color = (TColor *)p;
if (fAvoidSignal) return;
fAttMarker->SetMarkerColor(color->GetNumber());
fAlpha->SetPosition((Int_t)(color->GetAlpha()*1000));
fAlphaField->SetNumber(color->GetAlpha());
Update();
}
//______________________________________________________________________________
void TAttMarkerEditor::DoMarkerStyle(Style_t marker)
{
// Slot connected to the marker type.
if (fAvoidSignal) return;
if ((marker==1 || marker==6 || marker==7) && !fSizeForText) {
fMarkerSize->SetNumber(1.);
fMarkerSize->SetState(kFALSE);
} else
fMarkerSize->SetState(kTRUE);
fAttMarker->SetMarkerStyle(marker);
Update();
}
//______________________________________________________________________________
void TAttMarkerEditor::DoMarkerSize()
{
// Slot connected to the marker size.
if (fAvoidSignal) return;
Style_t marker = fAttMarker->GetMarkerStyle();
if ((marker==1 || marker==6 || marker==7) && !fSizeForText) {
fMarkerSize->SetNumber(1.);
fMarkerSize->SetState(kFALSE);
} else
fMarkerSize->SetState(kTRUE);
Float_t size = fMarkerSize->GetNumber();
fAttMarker->SetMarkerSize(size);
Update();
}
//______________________________________________________________________________
void TAttMarkerEditor::DoAlphaField()
{
// Slot to set the alpha value from the entry field.
if (fAvoidSignal) return;
if (TColor *color = gROOT->GetColor(fAttMarker->GetMarkerColor())) {
color->SetAlpha((Float_t)fAlphaField->GetNumber());
fAlpha->SetPosition((Int_t)fAlphaField->GetNumber()*1000);
}
Update();
}
//______________________________________________________________________________
void TAttMarkerEditor::DoAlpha()
{
// Slot to set the alpha value
if (fAvoidSignal) return;
if (TColor *color = gROOT->GetColor(fAttMarker->GetMarkerColor())) {
color->SetAlpha((Float_t)fAlpha->GetPosition()/1000);
fAlphaField->SetNumber((Float_t)fAlpha->GetPosition()/1000);
}
Update();
}
//______________________________________________________________________________
void TAttMarkerEditor::DoLiveAlpha(Int_t a)
{
// Slot to set alpha value online.
if (fAvoidSignal) return;
fAlphaField->SetNumber((Float_t)a/1000);
if (TColor *color = gROOT->GetColor(fAttMarker->GetMarkerColor())) color->SetAlpha((Float_t)a/1000);
Update();
}
//_______________________________________________________________________________
void TAttMarkerEditor::GetCurAlpha()
{
// Slot to update alpha value on click on Slider
if (fAvoidSignal) return;
if (TColor *color = gROOT->GetColor(fAttMarker->GetMarkerColor())) {
fAlpha->SetPosition((Int_t)(color->GetAlpha()*1000));
fAlphaField->SetNumber(color->GetAlpha());
}
Update();
}
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright (c) 2014-2015, The Pennsylvania State University
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission of the
* respective copyright holder or contributor.
*
* 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, FITNESS FOR A PARTICULAR PURPOSE,
* AND NONINFRINGEMENT OF INTELLECTUAL PROPERTY ARE EXPRESSLY DISCLAIMED. IN
* NO EVENT SHALL THE COPYRIGHT HOLDERS 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 "metrics.h"
#include "logging.h"
#include "dayill.h"
#include <fstream>
#include "functions.h"
namespace stadic {
Metrics::Metrics(BuildingControl *model) :
m_Model(model)
{
}
bool Metrics::processMetrics()
{
std::vector<std::shared_ptr<Control>> spaces=m_Model->spaces();
for (int i=0;i<spaces.size();i++){
DaylightIlluminanceData daylightIll;
daylightIll.parseTimeBased(spaces[i].get()->spaceDirectory()+spaces[i].get()->resultsDirectory()+spaces[i].get()->spaceName()+".ill");
//Test whether Daylight Autonomy needs to be calculated
if (spaces[i].get()->runDA()){
if(calculateDA(spaces[i].get(), &daylightIll)){
spaces[i].get()->setCalcDA(false); //Set calculate to false for DA in control file if returned true
}
}
if (spaces[i].get()->runcDA()){
if (calculatecDA(spaces[i].get(), &daylightIll)){
spaces[i].get()->setCalccDA(false);
}
}
if (spaces[i].get()->runDF()){
if (calculateDF(spaces[i].get(), &daylightIll)){
spaces[i].get()->setDF(false);
}
}
if (spaces[i].get()->runUDI()){
if (calculateUDI(spaces[i].get(), &daylightIll)){
spaces[i].get()->setCalcUDI(false);
}
}
if (spaces[i].get()->runsDA()){
if (calculatesDA(spaces[i].get(), &daylightIll)){
spaces[i].get()->setCalcsDA(false);
}
}
if (spaces[i].get()->runOccsDA()){
if (calculateOccsDA(spaces[i].get(), &daylightIll)){
spaces[i].get()->setCalcOccsDA(false);
}
}
}
return true;
}
bool Metrics::calculateDA(Control *model, DaylightIlluminanceData *dayIll)
{
for (int i=0;i<dayIll->illuminance().size();i++){
}
return true;
}
bool Metrics::calculatecDA(Control *model, DaylightIlluminanceData *dayIll)
{
return true;
}
bool Metrics::calculateDF(Control *model, DaylightIlluminanceData *dayIll)
{
return true;
}
bool Metrics::calculateUDI(Control *model, DaylightIlluminanceData *dayIll)
{
return true;
}
bool Metrics::calculatesDA(Control *model, DaylightIlluminanceData *dayIll)
{
return true;
}
bool Metrics::calculateOccsDA(Control *model, DaylightIlluminanceData *dayIll)
{
return true;
}
bool Metrics::parseOccupancy(std::string file, double threshold){
std::ifstream occFile;
occFile.open(file);
if (!occFile.is_open()){
STADIC_LOG(Severity::Error, "The opening of the occupancy file "+file+" has failed.");
return false;
}
std::string line;
while (std::getline(occFile, line)){
std::vector<std::string> vals;
vals=split(line, ' ');
if (toDouble(vals[3])<threshold){
m_Occupancy.push_back(false);
}else{
m_Occupancy.push_back(true);
}
}
occFile.close();
return true;
}
}
<commit_msg>Updated metrics object.<commit_after>/******************************************************************************
* Copyright (c) 2014-2015, The Pennsylvania State University
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission of the
* respective copyright holder or contributor.
*
* 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, FITNESS FOR A PARTICULAR PURPOSE,
* AND NONINFRINGEMENT OF INTELLECTUAL PROPERTY ARE EXPRESSLY DISCLAIMED. IN
* NO EVENT SHALL THE COPYRIGHT HOLDERS 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 "metrics.h"
#include "logging.h"
#include "dayill.h"
#include <fstream>
#include "functions.h"
namespace stadic {
Metrics::Metrics(BuildingControl *model) :
m_Model(model)
{
}
bool Metrics::processMetrics()
{
std::vector<std::shared_ptr<Control>> spaces=m_Model->spaces();
for (int i=0;i<spaces.size();i++){
DaylightIlluminanceData daylightIll;
daylightIll.parseTimeBased(spaces[i].get()->spaceDirectory()+spaces[i].get()->resultsDirectory()+spaces[i].get()->spaceName()+".ill");
//Test whether Daylight Autonomy needs to be calculated
if (spaces[i].get()->runDA()){
if(calculateDA(spaces[i].get(), &daylightIll)){
spaces[i].get()->setCalcDA(false); //Set calculate to false for DA in control file if returned true
}
}
if (spaces[i].get()->runcDA()){
if (calculatecDA(spaces[i].get(), &daylightIll)){
spaces[i].get()->setCalccDA(false);
}
}
if (spaces[i].get()->runDF()){
if (calculateDF(spaces[i].get(), &daylightIll)){
spaces[i].get()->setDF(false);
}
}
if (spaces[i].get()->runUDI()){
if (calculateUDI(spaces[i].get(), &daylightIll)){
spaces[i].get()->setCalcUDI(false);
}
}
if (spaces[i].get()->runsDA()){
if (calculatesDA(spaces[i].get(), &daylightIll)){
spaces[i].get()->setCalcsDA(false);
}
}
if (spaces[i].get()->runOccsDA()){
if (calculateOccsDA(spaces[i].get(), &daylightIll)){
spaces[i].get()->setCalcOccsDA(false);
}
}
}
return true;
}
bool Metrics::calculateDA(Control *model, DaylightIlluminanceData *dayIll)
{
std::vector<int> pointCount;
for (int i=0;i<dayIll->illuminance()[0].lux().size();i++){
pointCount.push_back(0);
}
int hourCount=0;
for (int i=0;i<dayIll->illuminance().size();i++){
if(m_Occupancy[i]){
hourCount++;
if (model->illumUnits()=="lux"){
for (int j=0;j<dayIll->illuminance()[i].lux().size();j++){
if (dayIll->illuminance()[i].lux()[j]>model->DAIllum()){
pointCount[j]++;
}
}
}else{
for (int j=0;j<dayIll->illuminance()[i].fc().size();j++){
if (dayIll->illuminance()[i].fc()[j]>model->DAIllum()){
pointCount[j]++;
}
}
}
}
}
std::ofstream outDA;
std::string tmpFileName;
tmpFileName=model->spaceDirectory()+model->resultsDirectory()+model->spaceName()+"_DA.res";
outDA.open(tmpFileName);
if (!outDA.is_open()){
STADIC_LOG(Severity::Error, "The opening of the Daylight Autonomy results file "+tmpFileName +" has failed.");
return false;
}
for (int i=0;i<dayIll->illuminance()[0].lux().size();i++){
outDA<<double(pointCount[i])/hourCount<<std::endl;
}
outDA.close();
return true;
}
bool Metrics::calculatecDA(Control *model, DaylightIlluminanceData *dayIll)
{
std::vector<double> pointCount;
for (int i=0;i<dayIll->illuminance()[0].lux().size();i++){
pointCount.push_back(0);
}
int hourCount=0;
for (int i=0;i<dayIll->illuminance().size();i++){
if(m_Occupancy[i]){
hourCount++;
if (model->illumUnits()=="lux"){
for (int j=0;j<dayIll->illuminance()[i].lux().size();j++){
pointCount[j]=pointCount[j]+dayIll->illuminance()[i].lux()[j]/model->cDAIllum();
}
}else{
for (int j=0;j<dayIll->illuminance()[i].fc().size();j++){
pointCount[j]=pointCount[j]+dayIll->illuminance()[i].fc()[j]/model->cDAIllum();
}
}
}
}
std::ofstream outcDA;
std::string tmpFileName;
tmpFileName=model->spaceDirectory()+model->resultsDirectory()+model->spaceName()+"_cDA.res";
outcDA.open(tmpFileName);
if (!outcDA.is_open()){
STADIC_LOG(Severity::Error, "The opening of the Continuous Daylight Autonomy results file "+tmpFileName +" has failed.");
return false;
}
for (int i=0;i<dayIll->illuminance()[0].lux().size();i++){
outcDA<<double(pointCount[i])/hourCount<<std::endl;
}
outcDA.close();
return true;
}
bool Metrics::calculateDF(Control *model, DaylightIlluminanceData *dayIll)
{
return true;
}
bool Metrics::calculateUDI(Control *model, DaylightIlluminanceData *dayIll)
{
std::vector<double> countWithin;
std::vector<double> countBelow;
std::vector<double> countAbove;
for (int i=0;i<dayIll->illuminance()[0].lux().size();i++){
countWithin.push_back(0);
countBelow.push_back(0);
countAbove.push_back(0);
}
int hourCount=0;
for (int i=0;i<dayIll->illuminance().size();i++){
if(m_Occupancy[i]){
hourCount++;
if (model->illumUnits()=="lux"){
for (int j=0;j<dayIll->illuminance()[i].lux().size();j++){
if (dayIll->illuminance()[i].lux()[j]<model->UDIMin()){
countBelow[j]++;
}else if(dayIll->illuminance()[i].lux()[j]<=model->UDIMax()){
countWithin[j]++;
}else{
countAbove[j]++;
}
}
}else{
for (int j=0;j<dayIll->illuminance()[i].fc().size();j++){
if (dayIll->illuminance()[i].fc()[j]<model->UDIMin()){
countBelow[j]++;
}else if(dayIll->illuminance()[i].fc()[j]<=model->UDIMax()){
countWithin[j]++;
}else{
countAbove[j]++;
}
}
}
}
}
std::ofstream outUDIbelow;
std::string tmpFileName;
tmpFileName=model->spaceDirectory()+model->resultsDirectory()+model->spaceName()+"_below_UDI.res";
outUDIbelow.open(tmpFileName);
if (!outUDIbelow.is_open()){
STADIC_LOG(Severity::Error, "The opening of the below UDI results file "+tmpFileName +" has failed.");
return false;
}
for (int i=0;i<dayIll->illuminance()[0].lux().size();i++){
outUDIbelow<<double(countBelow[i])/hourCount<<std::endl;
}
outUDIbelow.close();
std::ofstream outUDI;
tmpFileName=model->spaceDirectory()+model->resultsDirectory()+model->spaceName()+"_UDI.res";
outUDI.open(tmpFileName);
if (!outUDI.is_open()){
STADIC_LOG(Severity::Error, "The opening of the UDI results file "+tmpFileName +" has failed.");
return false;
}
for (int i=0;i<dayIll->illuminance()[0].lux().size();i++){
outUDI<<double(countWithin[i])/hourCount<<std::endl;
}
outUDI.close();
std::ofstream outUDIabove;
tmpFileName=model->spaceDirectory()+model->resultsDirectory()+model->spaceName()+"_above_UDI.res";
outUDIabove.open(tmpFileName);
if (!outUDIabove.is_open()){
STADIC_LOG(Severity::Error, "The opening of the above UDI results file "+tmpFileName +" has failed.");
return false;
}
for (int i=0;i<dayIll->illuminance()[0].lux().size();i++){
outUDIabove<<double(countAbove[i])/hourCount<<std::endl;
}
outUDIabove.close();
return true;
}
bool Metrics::calculatesDA(Control *model, DaylightIlluminanceData *dayIll)
{
return true;
}
bool Metrics::calculateOccsDA(Control *model, DaylightIlluminanceData *dayIll)
{
return true;
}
bool Metrics::parseOccupancy(std::string file, double threshold){
std::ifstream occFile;
occFile.open(file);
if (!occFile.is_open()){
STADIC_LOG(Severity::Error, "The opening of the occupancy file "+file+" has failed.");
return false;
}
std::string line;
while (std::getline(occFile, line)){
std::vector<std::string> vals;
vals=split(line, ' ');
if (toDouble(vals[3])<threshold){
m_Occupancy.push_back(false);
}else{
m_Occupancy.push_back(true);
}
}
occFile.close();
return true;
}
}
<|endoftext|> |
<commit_before>#pragma once
#include <forward_list>
#include <unordered_map>
#include <limits>
#include <GLFW/glfw3.h>
#include "subsystem_base.hxx"
namespace
{
using window_owner_dictionary_t = std::unordered_map
< GLFWwindow*
, std::weak_ptr<wonder_rabbit_project::wonderland::subsystem::subsystem_base_t>
>;
window_owner_dictionary_t window_owner_dictionary;
}
namespace wonder_rabbit_project
{
namespace wonderland
{
namespace subsystem
{
struct glfw3_runtime_error_t
: subsystem_runtime_error_t
{
glfw3_runtime_error_t(const std::string& what)
: subsystem_runtime_error_t(what)
{ }
};
class GLFW3_t
: public subsystem_base_t
{
using dtor_hook_t = std::function<void()>;
using dtor_hooks_t = std::forward_list<dtor_hook_t>;
dtor_hooks_t _dtor_hooks;
GLFWwindow* _window;
public:
pointing_states_t::wheel_t temporary_wheel;
private:
auto initialize_glfw() -> void
{
const auto r = glfwInit();
if ( not r )
throw glfw3_runtime_error_t( std::string("glfwInit failed. return value: ") + std::to_string(r) );
_dtor_hooks.emplace_front( []{ glfwTerminate(); } );
}
auto initialize_set_error_callback() const -> void
{
glfwSetErrorCallback
( [](int error, const char* description)
{ throw glfw3_runtime_error_t
( std::string("glfw error: error = ") + std::to_string(error)
+ std::string(" , description = ") + std::string(description)
);
}
);
}
auto initialize_window_hints(initialize_params_t& ps) -> void
{
initialize_params_t dps;
default_initialize_params_window_hints(dps);
const auto get = [&ps, &dps](const char* name)
{ return ps.get(name, dps.get<int>(name)); };
const auto get_bool_as_int = [&ps, &dps](const char* name)
{ return int(ps.get(name, dps.get<bool>(name))); };
glfwWindowHint( GLFW_RESIZABLE , get_bool_as_int("resizable") );
glfwWindowHint( GLFW_VISIBLE , get_bool_as_int("visible" ) );
glfwWindowHint( GLFW_DECORATED , get_bool_as_int("decorated" ) );
glfwWindowHint( GLFW_RED_BITS , get("red_bits" ) );
glfwWindowHint( GLFW_GREEN_BITS , get("green_bits" ) );
glfwWindowHint( GLFW_BLUE_BITS , get("blue_bits" ) );
glfwWindowHint( GLFW_ALPHA_BITS , get("alpha_bits" ) );
glfwWindowHint( GLFW_DEPTH_BITS , get("depth_bits" ) );
glfwWindowHint( GLFW_STENCIL_BITS , get("stencil_bits" ) );
glfwWindowHint( GLFW_ACCUM_RED_BITS , get("accum_red_bits" ) );
glfwWindowHint( GLFW_ACCUM_GREEN_BITS , get("accum_green_bits" ) );
glfwWindowHint( GLFW_ACCUM_BLUE_BITS , get("accum_blue_bits" ) );
glfwWindowHint( GLFW_ACCUM_ALPHA_BITS , get("accum_alpha_bits" ) );
glfwWindowHint( GLFW_AUX_BUFFERS , get("aux_buffers" ) );
glfwWindowHint( GLFW_SAMPLES , get("samples" ) );
glfwWindowHint( GLFW_REFRESH_RATE , get("refresh_rate" ) );
glfwWindowHint( GLFW_STEREO , get_bool_as_int("stereo" ) );
glfwWindowHint( GLFW_SRGB_CAPABLE , get_bool_as_int("srgb_capable" ) );
glfwWindowHint( GLFW_CLIENT_API , get("client_api" ) );
glfwWindowHint( GLFW_CONTEXT_VERSION_MAJOR , get("context_version_major" ) );
glfwWindowHint( GLFW_CONTEXT_VERSION_MINOR , get("context_version_minor" ) );
glfwWindowHint( GLFW_CONTEXT_ROBUSTNESS , get("context_robustness" ) );
glfwWindowHint( GLFW_OPENGL_FORWARD_COMPAT , get_bool_as_int("opengl_forward_compat" ) );
glfwWindowHint( GLFW_OPENGL_DEBUG_CONTEXT , get_bool_as_int("opengl_debug_context" ) );
glfwWindowHint( GLFW_OPENGL_PROFILE , get("opengl_profile" ) );
}
auto initialize_create_window(initialize_params_t& ps) -> void
{
initialize_params_t dps;
default_initialize_params_create_window(dps);
const auto window = _window
= glfwCreateWindow
( ps.get("width" , dps.get<int>("width") )
, ps.get("height", dps.get<int>("height") )
, ps.get("title" , dps.get<std::string>("title") ).data()
, static_cast<GLFWmonitor*>(ps.get("GLFW.monitor", dps.get<void*>("GLFW.monitor")) )
, static_cast<GLFWwindow* >(ps.get("GLFW.window" , dps.get<void*>("GLFW.window")) )
);
if ( not window )
throw glfw3_runtime_error_t
( "glfwCreateWindow failed. window is nullptr." );
::window_owner_dictionary.emplace( window, shared_from_this() );
_dtor_hooks.emplace_front( [ window ]
{
::window_owner_dictionary.erase( window );
glfwDestroyWindow( window );
});
}
auto initialize_make_contex_current() const ->void
{ glfwMakeContextCurrent( _window ); }
auto initialize_set_scroll_callback() const -> void
{
glfwSetScrollCallback( _window, [](GLFWwindow* window, double xoffset, double yoffset)
{
std::dynamic_pointer_cast<wonder_rabbit_project::wonderland::subsystem::GLFW3_t>
( ::window_owner_dictionary
.at(window)
.lock()
)
-> temporary_wheel = { std::move(xoffset), std::move(yoffset) };
} );
}
auto initialize_set_frame_buffer_size_callback() const -> void
{
glfwSetFramebufferSizeCallback
( _window
, [](GLFWwindow* window, int width, int height)
{ glViewport(0, 0, width, height); }
);
}
auto window_position(initialize_params_t ps) const -> void
{
initialize_params_t dps;
default_initialize_params_window_position(dps);
// TODO: support SDL convertible flags
// 0x1FFF0000: UNDEFINED
// 0x2FFF0000: CENTERED
glfwSetWindowPos
( _window
, ps.get("x" , dps.get<int>("x") ) & 0x0000FFFF
, ps.get("y" , dps.get<int>("y") ) & 0x0000FFFF
);
}
auto process_input_states() -> void
{
process_input_states_keyboard();
process_input_states_pointing();
}
auto process_input_states_keyboard() -> void
{
for ( int glfw3_key = GLFW_KEY_SPACE; glfw3_key < GLFW_KEY_LAST; ++glfw3_key )
{
const auto action = glfwGetKey( _window, glfw3_key );
const auto fixed_key = key_code_from_glfw3(glfw3_key);
keyboard_state( fixed_key, bool( action == GLFW_PRESS ) );
}
}
auto process_input_states_pointing() -> void
{
pointing_states_button<0>( glfwGetMouseButton( _window, 0) );
pointing_states_button<1>( glfwGetMouseButton( _window, 1) );
pointing_states_button<2>( glfwGetMouseButton( _window, 2) );
pointing_states_button<3>( glfwGetMouseButton( _window, 3) );
pointing_states_button<4>( glfwGetMouseButton( _window, 4) );
pointing_states_button<5>( glfwGetMouseButton( _window, 5) );
pointing_states_button<6>( glfwGetMouseButton( _window, 6) );
pointing_states_button<7>( glfwGetMouseButton( _window, 7) );
double x, y;
glfwGetCursorPos( _window, &x, &y );
pointing_states_position( { std::move(x), std::move(y) } );
pointing_states_wheel( std::move( temporary_wheel ) );
temporary_wheel = { 0, 0 };
}
public:
~GLFW3_t() override
{
while( not _dtor_hooks.empty() )
{
_dtor_hooks.front()();
_dtor_hooks.pop_front();
}
}
auto default_initialize_params_create_window(initialize_params_t& ps) const
-> void
{
// http://www.glfw.org/docs/latest/group__window.html#ga5c336fddf2cbb5b92f65f10fb6043344
ps.put( "width" , 320 );
ps.put( "height" , 240 );
ps.put( "title" , "some other wonderland with GLFW3" );
ps.put<GLFWmonitor*>( "GLFW.monitor", nullptr );
ps.put<GLFWwindow* >( "GLFW.window" , nullptr );
}
auto default_initialize_params_window_hints(initialize_params_t& ps) const
-> void
{
// http://www.glfw.org/docs/latest/window.html#window_hints_values
ps.put( "resizable" , true );
ps.put( "visible" , true );
ps.put( "decorated" , true );
ps.put( "red_bits" , 8 );
ps.put( "green_bits" , 8 );
ps.put( "blue_bits" , 8 );
ps.put( "alpha_bits" , 8 );
ps.put( "depth_bits" , 24 );
ps.put( "stencil_bits" , 8 );
ps.put( "accum_red_bits" , 0 );
ps.put( "accum_green_bits" , 0 );
ps.put( "accum_blue_bits" , 0 );
ps.put( "accum_alpha_bits" , 0 );
ps.put( "aux_buffers" , 0 );
ps.put( "samples" , 0 );
ps.put( "refresh_rate" , 0 );
ps.put( "stereo" , false );
ps.put( "srgb_capable" , false );
ps.put( "client_api" , GLFW_OPENGL_API );
ps.put( "context_version_major" , 1 );
ps.put( "context_version_minor" , 0 );
ps.put( "context_robustness" , GLFW_NO_ROBUSTNESS );
ps.put( "opengl_forward_compat" , false );
ps.put( "opengl_debug_context" , false );
ps.put( "opengl_profile" , GLFW_OPENGL_ANY_PROFILE );
}
auto default_initialize_params_window_position(initialize_params_t& ps) const
-> void
{
// http://www.glfw.org/docs/latest/group__window.html#ga1abb6d690e8c88e0c8cd1751356dbca8
ps.put( "x" , 0 );
ps.put( "y" , 0 );
}
auto default_initialize_params() const
-> initialize_params_t override
{
initialize_params_t ps;
default_initialize_params_window_position(ps);
default_initialize_params_window_hints(ps);
default_initialize_params_create_window(ps);
return ps;
}
auto initialize( initialize_params_t&& ps )
-> void override
{
initialize_glfw();
initialize_set_error_callback();
initialize_window_hints(ps);
initialize_create_window(ps);
window_position(ps);
initialize_make_contex_current();
initialize_set_scroll_callback();
initialize_set_frame_buffer_size_callback();
}
auto after_render()
-> void override
{
glfwSwapBuffers( _window );
glfwPollEvents();
process_input_states();
}
auto to_continue() const
-> bool override
{ return not glfwWindowShouldClose( _window ); }
auto to_continue(const bool b)
-> void override
{ glfwSetWindowShouldClose( _window, int( not b ) ); }
auto version() const
-> version_t override
{ return { GLFW_VERSION_MAJOR , GLFW_VERSION_MINOR , GLFW_VERSION_REVISION }; }
auto name() const
-> std::string override
{ return "GLFW3"; }
};
#ifndef WRP_WONDERLAND_SUBSYSTEM_T
#define WRP_WONDERLAND_SUBSYSTEM_T
using subsystem_t = GLFW3_t;
#endif
}
}
}<commit_msg>#2 support joystick in GLFW3<commit_after>#pragma once
#include <forward_list>
#include <unordered_map>
#include <limits>
#include <GLFW/glfw3.h>
#include "subsystem_base.hxx"
namespace
{
using window_owner_dictionary_t = std::unordered_map
< GLFWwindow*
, std::weak_ptr<wonder_rabbit_project::wonderland::subsystem::subsystem_base_t>
>;
window_owner_dictionary_t window_owner_dictionary;
}
namespace wonder_rabbit_project
{
namespace wonderland
{
namespace subsystem
{
struct glfw3_runtime_error_t
: subsystem_runtime_error_t
{
glfw3_runtime_error_t(const std::string& what)
: subsystem_runtime_error_t(what)
{ }
};
class GLFW3_t
: public subsystem_base_t
{
using dtor_hook_t = std::function<void()>;
using dtor_hooks_t = std::forward_list<dtor_hook_t>;
dtor_hooks_t _dtor_hooks;
GLFWwindow* _window;
public:
pointing_states_t::wheel_t temporary_wheel;
private:
auto initialize_glfw() -> void
{
const auto r = glfwInit();
if ( not r )
throw glfw3_runtime_error_t( std::string("glfwInit failed. return value: ") + std::to_string(r) );
_dtor_hooks.emplace_front( []{ glfwTerminate(); } );
}
auto initialize_set_error_callback() const -> void
{
glfwSetErrorCallback
( [](int error, const char* description)
{ throw glfw3_runtime_error_t
( std::string("glfw error: error = ") + std::to_string(error)
+ std::string(" , description = ") + std::string(description)
);
}
);
}
auto initialize_window_hints(initialize_params_t& ps) -> void
{
initialize_params_t dps;
default_initialize_params_window_hints(dps);
const auto get = [&ps, &dps](const char* name)
{ return ps.get(name, dps.get<int>(name)); };
const auto get_bool_as_int = [&ps, &dps](const char* name)
{ return int(ps.get(name, dps.get<bool>(name))); };
glfwWindowHint( GLFW_RESIZABLE , get_bool_as_int("resizable") );
glfwWindowHint( GLFW_VISIBLE , get_bool_as_int("visible" ) );
glfwWindowHint( GLFW_DECORATED , get_bool_as_int("decorated" ) );
glfwWindowHint( GLFW_RED_BITS , get("red_bits" ) );
glfwWindowHint( GLFW_GREEN_BITS , get("green_bits" ) );
glfwWindowHint( GLFW_BLUE_BITS , get("blue_bits" ) );
glfwWindowHint( GLFW_ALPHA_BITS , get("alpha_bits" ) );
glfwWindowHint( GLFW_DEPTH_BITS , get("depth_bits" ) );
glfwWindowHint( GLFW_STENCIL_BITS , get("stencil_bits" ) );
glfwWindowHint( GLFW_ACCUM_RED_BITS , get("accum_red_bits" ) );
glfwWindowHint( GLFW_ACCUM_GREEN_BITS , get("accum_green_bits" ) );
glfwWindowHint( GLFW_ACCUM_BLUE_BITS , get("accum_blue_bits" ) );
glfwWindowHint( GLFW_ACCUM_ALPHA_BITS , get("accum_alpha_bits" ) );
glfwWindowHint( GLFW_AUX_BUFFERS , get("aux_buffers" ) );
glfwWindowHint( GLFW_SAMPLES , get("samples" ) );
glfwWindowHint( GLFW_REFRESH_RATE , get("refresh_rate" ) );
glfwWindowHint( GLFW_STEREO , get_bool_as_int("stereo" ) );
glfwWindowHint( GLFW_SRGB_CAPABLE , get_bool_as_int("srgb_capable" ) );
glfwWindowHint( GLFW_CLIENT_API , get("client_api" ) );
glfwWindowHint( GLFW_CONTEXT_VERSION_MAJOR , get("context_version_major" ) );
glfwWindowHint( GLFW_CONTEXT_VERSION_MINOR , get("context_version_minor" ) );
glfwWindowHint( GLFW_CONTEXT_ROBUSTNESS , get("context_robustness" ) );
glfwWindowHint( GLFW_OPENGL_FORWARD_COMPAT , get_bool_as_int("opengl_forward_compat" ) );
glfwWindowHint( GLFW_OPENGL_DEBUG_CONTEXT , get_bool_as_int("opengl_debug_context" ) );
glfwWindowHint( GLFW_OPENGL_PROFILE , get("opengl_profile" ) );
}
auto initialize_create_window(initialize_params_t& ps) -> void
{
initialize_params_t dps;
default_initialize_params_create_window(dps);
const auto window = _window
= glfwCreateWindow
( ps.get("width" , dps.get<int>("width") )
, ps.get("height", dps.get<int>("height") )
, ps.get("title" , dps.get<std::string>("title") ).data()
, static_cast<GLFWmonitor*>(ps.get("GLFW.monitor", dps.get<void*>("GLFW.monitor")) )
, static_cast<GLFWwindow* >(ps.get("GLFW.window" , dps.get<void*>("GLFW.window")) )
);
if ( not window )
throw glfw3_runtime_error_t
( "glfwCreateWindow failed. window is nullptr." );
::window_owner_dictionary.emplace( window, shared_from_this() );
_dtor_hooks.emplace_front( [ window ]
{
::window_owner_dictionary.erase( window );
glfwDestroyWindow( window );
});
}
auto initialize_make_contex_current() const ->void
{ glfwMakeContextCurrent( _window ); }
auto initialize_set_scroll_callback() const -> void
{
glfwSetScrollCallback( _window, [](GLFWwindow* window, double xoffset, double yoffset)
{
std::dynamic_pointer_cast<wonder_rabbit_project::wonderland::subsystem::GLFW3_t>
( ::window_owner_dictionary
.at(window)
.lock()
)
-> temporary_wheel = { std::move(xoffset), std::move(yoffset) };
} );
}
auto initialize_set_frame_buffer_size_callback() const -> void
{
glfwSetFramebufferSizeCallback
( _window
, [](GLFWwindow* window, int width, int height)
{ glViewport(0, 0, width, height); }
);
}
auto window_position(initialize_params_t ps) const -> void
{
initialize_params_t dps;
default_initialize_params_window_position(dps);
// TODO: support SDL convertible flags
// 0x1FFF0000: UNDEFINED
// 0x2FFF0000: CENTERED
glfwSetWindowPos
( _window
, ps.get("x" , dps.get<int>("x") ) & 0x0000FFFF
, ps.get("y" , dps.get<int>("y") ) & 0x0000FFFF
);
}
auto process_input_states() -> void
{
process_input_states_keyboard();
process_input_states_pointing();
process_input_states_joystick();
}
auto process_input_states_keyboard() -> void
{
for ( int glfw3_key = GLFW_KEY_SPACE; glfw3_key < GLFW_KEY_LAST; ++glfw3_key )
{
const auto action = glfwGetKey( _window, glfw3_key );
const auto fixed_key = key_code_from_glfw3(glfw3_key);
keyboard_state( fixed_key, bool( action == GLFW_PRESS ) );
}
}
auto process_input_states_pointing() -> void
{
pointing_states_button<0>( glfwGetMouseButton( _window, 0) );
pointing_states_button<1>( glfwGetMouseButton( _window, 1) );
pointing_states_button<2>( glfwGetMouseButton( _window, 2) );
pointing_states_button<3>( glfwGetMouseButton( _window, 3) );
pointing_states_button<4>( glfwGetMouseButton( _window, 4) );
pointing_states_button<5>( glfwGetMouseButton( _window, 5) );
pointing_states_button<6>( glfwGetMouseButton( _window, 6) );
pointing_states_button<7>( glfwGetMouseButton( _window, 7) );
double x, y;
glfwGetCursorPos( _window, &x, &y );
pointing_states_position( { std::move(x), std::move(y) } );
pointing_states_wheel( std::move( temporary_wheel ) );
temporary_wheel = { 0, 0 };
}
auto process_input_states_joystick() -> void
{
for
( int index_of_joystick = 0
; glfwJoystickPresent(index_of_joystick) == GL_TRUE
; ++index_of_joystick
)
{
{ // digitals
int number_of_elements;
const auto actions = glfwGetJoystickButtons( index_of_joystick, &number_of_elements );
if ( actions not_eq nullptr )
for ( auto index_of_element = 0; index_of_element < number_of_elements; ++index_of_element )
joystick_state_digital( index_of_joystick, index_of_element, bool(actions[index_of_element]) );
}
{ // analogs
int number_of_elements;
const auto actions = glfwGetJoystickAxes( index_of_joystick, &number_of_elements );
if ( actions not_eq nullptr )
for ( auto index_of_element = 0; index_of_element < number_of_elements; ++index_of_element )
joystick_state_analog( index_of_joystick, index_of_element, actions[index_of_element] );
}
// name
joystick_state_name( index_of_joystick, glfwGetJoystickName( index_of_joystick ) );
}
}
public:
~GLFW3_t() override
{
while( not _dtor_hooks.empty() )
{
_dtor_hooks.front()();
_dtor_hooks.pop_front();
}
}
auto default_initialize_params_create_window(initialize_params_t& ps) const
-> void
{
// http://www.glfw.org/docs/latest/group__window.html#ga5c336fddf2cbb5b92f65f10fb6043344
ps.put( "width" , 320 );
ps.put( "height" , 240 );
ps.put( "title" , "some other wonderland with GLFW3" );
ps.put<GLFWmonitor*>( "GLFW.monitor", nullptr );
ps.put<GLFWwindow* >( "GLFW.window" , nullptr );
}
auto default_initialize_params_window_hints(initialize_params_t& ps) const
-> void
{
// http://www.glfw.org/docs/latest/window.html#window_hints_values
ps.put( "resizable" , true );
ps.put( "visible" , true );
ps.put( "decorated" , true );
ps.put( "red_bits" , 8 );
ps.put( "green_bits" , 8 );
ps.put( "blue_bits" , 8 );
ps.put( "alpha_bits" , 8 );
ps.put( "depth_bits" , 24 );
ps.put( "stencil_bits" , 8 );
ps.put( "accum_red_bits" , 0 );
ps.put( "accum_green_bits" , 0 );
ps.put( "accum_blue_bits" , 0 );
ps.put( "accum_alpha_bits" , 0 );
ps.put( "aux_buffers" , 0 );
ps.put( "samples" , 0 );
ps.put( "refresh_rate" , 0 );
ps.put( "stereo" , false );
ps.put( "srgb_capable" , false );
ps.put( "client_api" , GLFW_OPENGL_API );
ps.put( "context_version_major" , 1 );
ps.put( "context_version_minor" , 0 );
ps.put( "context_robustness" , GLFW_NO_ROBUSTNESS );
ps.put( "opengl_forward_compat" , false );
ps.put( "opengl_debug_context" , false );
ps.put( "opengl_profile" , GLFW_OPENGL_ANY_PROFILE );
}
auto default_initialize_params_window_position(initialize_params_t& ps) const
-> void
{
// http://www.glfw.org/docs/latest/group__window.html#ga1abb6d690e8c88e0c8cd1751356dbca8
ps.put( "x" , 0 );
ps.put( "y" , 0 );
}
auto default_initialize_params() const
-> initialize_params_t override
{
initialize_params_t ps;
default_initialize_params_window_position(ps);
default_initialize_params_window_hints(ps);
default_initialize_params_create_window(ps);
return ps;
}
auto initialize( initialize_params_t&& ps )
-> void override
{
initialize_glfw();
initialize_set_error_callback();
initialize_window_hints(ps);
initialize_create_window(ps);
window_position(ps);
initialize_make_contex_current();
initialize_set_scroll_callback();
initialize_set_frame_buffer_size_callback();
}
auto after_render()
-> void override
{
glfwSwapBuffers( _window );
glfwPollEvents();
process_input_states();
}
auto to_continue() const
-> bool override
{ return not glfwWindowShouldClose( _window ); }
auto to_continue(const bool b)
-> void override
{ glfwSetWindowShouldClose( _window, int( not b ) ); }
auto version() const
-> version_t override
{ return { GLFW_VERSION_MAJOR , GLFW_VERSION_MINOR , GLFW_VERSION_REVISION }; }
auto name() const
-> std::string override
{ return "GLFW3"; }
};
#ifndef WRP_WONDERLAND_SUBSYSTEM_T
#define WRP_WONDERLAND_SUBSYSTEM_T
using subsystem_t = GLFW3_t;
#endif
}
}
}<|endoftext|> |
<commit_before>#if defined(_MSC_VER) || defined(WINDOWS)
#define _USE_MATH_DEFINES
#endif
#include <cmath>
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <vector>
#include <cassert>
#include "lodepng.h"
#include <GL/glew.h>
#ifdef __APPLE__
#include <OpenGL/gl.h>
#include <OpenGl/glu.h>
#include <GLUT/glut.h>
#else
#include <GL/freeglut.h>
#endif
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
#if defined(_MSC_VER) || defined(WINDOWS)
#include <windows.h>
#include <rtcapi.h>
int
exception_handler(LPEXCEPTION_POINTERS p)
{
printf("Exception detected during test execution!\n");
exit(1);
}
int
runtime_check_handler(int errorType, const char *filename, int linenumber,
const char *moduleName, const char *format, ...)
{
printf("Error type %d at %s line %d in %s", errorType, filename, linenumber, moduleName);
exit(1);
}
#endif
#define WIDTH 640
#define HEIGHT 480
#define CHANNELS 4
#define OUTPUT_IMAGE_MAX_LINE_LEN 70
#define OUTPUT_IMAGE_MAX_PIXEL_VAL_LEN 4
#define OUTPUT_IMAGE_MAX_PIXEL_VAL 255
#define COMPILE_ERROR_EXIT_CODE 101
#define LINK_ERROR_EXIT_CODE 102
#define RENDER_ERROR_EXIT_CODE 103
std::string terminate_flag = "",
output = "output.png",
vertex_shader = "",
fragment_shader = "";
bool persist = false,
exit_compile = false,
exit_linking = false,
animate = false;
GLuint program;
const char* vertex_shader_wo_version = "attribute vec2 coord2d;\nvarying vec2 surfacePosition;\nvoid main(void) {\ngl_Position = vec4(coord2d, 0.0, 1.0);\nsurfacePosition = coord2d;\n}";
bool rendered = false;
bool
parse_args(int argc, char* argv[])
{
vertex_shader = "";
fragment_shader = "";
std::string curr_arg;
for (int i = 1; i < argc; i++) {
curr_arg = std::string(argv[i]);
if (!curr_arg.compare(0, 2, "--")) {
if (!curr_arg.compare("--persist")) {
persist = true;
continue;
}
else if (!curr_arg.compare("--animate")) {
animate = true;
continue;
}
else if (!curr_arg.compare("--exit_compile")) {
exit_compile = true;
continue;
}
else if (!curr_arg.compare("--exit_linking")) {
exit_linking = true;
continue;
}
else if (!curr_arg.compare("--output")) {
output = argv[++i];
continue;
}
else if (!curr_arg.compare("--vertex")) {
vertex_shader = argv[++i];
continue;
}
printf("Unknown argument %s\n", curr_arg.c_str());
continue;
}
if (fragment_shader == "")
fragment_shader = curr_arg;
else printf("Ignoring extra argument %s\n", curr_arg.c_str());
}
return (fragment_shader != "");
}
void
report_error_and_exit(GLuint oglPrg, int exitCode)
{
GLint maxLength = 0;
glGetShaderiv(oglPrg, GL_INFO_LOG_LENGTH, &maxLength);
// The maxLength includes the NULL character
std::vector<GLchar> errorLog(maxLength);
glGetShaderInfoLog(oglPrg, maxLength, &maxLength, &errorLog[0]);
// Provide the infolog in whatever manor you deem best.
for (GLchar c : errorLog)
std::cout << c;
std::cout << "\n";
// Exit with failure.
glDeleteShader(oglPrg);
exit(exitCode);
}
void
keyboard_listener(unsigned char key, int x, int y)
{
exit(0);
}
void init()
{
int compile_ok;
program = glCreateProgram();
// Shader start
GLuint shd1 = glCreateShader(GL_FRAGMENT_SHADER);
std::ifstream shdf1(fragment_shader);
if(!shdf1) {
fprintf(stderr, "Fragment shader %s not found\n", fragment_shader.c_str());
exit(1);
}
std::stringstream shds1;
shds1 << shdf1.rdbuf();
std::string shdstr1= shds1.str();
const char *shdchr1= shdstr1.c_str();
glShaderSource(shd1, 1, &shdchr1, NULL);
fprintf(stderr, "Compiling fragment shader\n");
glCompileShader(shd1);
glGetShaderiv(shd1, GL_COMPILE_STATUS, &compile_ok);
if (!compile_ok) {
fprintf(stderr, "Error compiling fragment shader\n");
report_error_and_exit(shd1, COMPILE_ERROR_EXIT_CODE);
}
fprintf(stderr, "Fragment shader compiled successfully\n");
if (exit_compile) {
fprintf(stdout, "Exiting after fragment shader compilation...\n");
exit(0);
}
glAttachShader(program, shd1);
// Shader end
// Start: construct vertex shader string
std::string shdstr0;
if(vertex_shader == "") {
// Use embedded vertex shader.
size_t i = shdstr1.find('\n');
if(i != std::string::npos && shdstr1[0] == '#') {
shdstr0 = shdstr1.substr(0,i);
shdstr0 += "\n";
} else {
fprintf(stderr, "Warning: Could not find #version string of fragment shader.\n");
}
shdstr0 += vertex_shader_wo_version;
} else {
std::ifstream shdf0(vertex_shader);
if(!shdf0) {
fprintf(stderr, "Vertex shader %s not found\n", vertex_shader.c_str());
exit(1);
}
std::stringstream shds0;
shds0 << shdf0.rdbuf();
shdstr0 = shds0.str();
}
// End: construct vertex shader string
// Shader start
GLuint shd0 = glCreateShader(GL_VERTEX_SHADER);
const char *shdchr0= shdstr0.c_str();
glShaderSource(shd0, 1, &shdchr0, NULL);
fprintf(stderr, "Compiling vertex shader\n");
glCompileShader(shd0);
glGetShaderiv(shd0, GL_COMPILE_STATUS, &compile_ok);
if (!compile_ok) {
fprintf(stderr, "Error compiling vertex shader\n");
report_error_and_exit(shd0, 1);
}
fprintf(stderr, "Vertex shader compiled successfully\n");
glAttachShader(program, shd0);
// Shader end
fprintf(stderr, "Linking program\n");
glLinkProgram(program);
glGetProgramiv(program, GL_LINK_STATUS, &compile_ok);
if (!compile_ok) {
fprintf(stderr, "Error in linking program\n");
report_error_and_exit(program, LINK_ERROR_EXIT_CODE);
}
fprintf(stderr, "Program linked successfully\n");
if (exit_linking) {
fprintf(stdout, "Exiting after program linking...\n");
exit(0);
}
// Program 5 end
glutKeyboardFunc(keyboard_listener);
}
void display()
{
static int num_display_calls = 0;
glClearColor(1.0, 1.0, 0.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(program);
const char* uniform_name;
GLint uniform_loc;
uniform_name = "resolution";
uniform_loc = glGetUniformLocation(program, uniform_name);
if (uniform_loc != -1)
glUniform2f(uniform_loc, WIDTH, HEIGHT);
uniform_name = "mouse";
uniform_loc = glGetUniformLocation(program, uniform_name);
if (uniform_loc != -1)
glUniform2f(uniform_loc, 0.0, 0.0);
uniform_name = "injectionSwitch";
uniform_loc = glGetUniformLocation(program, uniform_name);
if (uniform_loc != -1)
glUniform2f(uniform_loc, 0.0, 1.0);
uniform_name = "time";
uniform_loc = glGetUniformLocation(program, uniform_name);
if (uniform_loc != -1)
glUniform1f(uniform_loc, (animate ? glutGet(GLUT_ELAPSED_TIME) / 1000.0 * (2*M_PI) / 5 : 0));
glEnableVertexAttribArray(0);
GLfloat arr_5_0[] = {
-1, 1,
-1, -1,
1, -1,
};
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, arr_5_0);
glDrawArrays(GL_TRIANGLES, 0, 3.0);
GLfloat arr_5_1[] = {
-1, 1,
1, 1,
1, -1,
};
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, arr_5_1);
glDrawArrays(GL_TRIANGLES, 0, 3.0);
glDisableVertexAttribArray(0);
glFinish();
glutSwapBuffers();
num_display_calls++;
rendered = (num_display_calls >= 2);
}
void idle()
{
static bool saved = false;
if (rendered && !saved) {
saved = true;
std::vector<std::uint8_t> data(WIDTH * HEIGHT * CHANNELS);
glReadPixels(0, 0, WIDTH, HEIGHT, GL_RGBA, GL_UNSIGNED_BYTE, &data[0]);
std::vector<std::uint8_t> flipped_data(WIDTH * HEIGHT * CHANNELS);
for (int h = 0; h < HEIGHT ; h++)
for (int col = 0; col < WIDTH * CHANNELS; col++)
flipped_data[h * WIDTH + col] =
data[(HEIGHT - h - 1) * WIDTH + col];
unsigned png_error = lodepng::encode(output, flipped_data, WIDTH, HEIGHT);
if (png_error)
printf("Error producing PNG file: %s", lodepng_error_text(png_error));
if (persist)
printf("Press any key to exit...\n");
else
exit(0);
}
glutPostRedisplay();
}
int main(int argc, char* argv[])
{
#ifdef _MSC_VER
DWORD dwMode = SetErrorMode(SEM_NOGPFAULTERRORBOX);
SetErrorMode(dwMode | SEM_NOGPFAULTERRORBOX);
SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)&exception_handler);
_RTC_SetErrorFunc(&runtime_check_handler);
#endif
if(!parse_args(argc, argv)) {
std::cerr << "Requires fragment shader argument!" << std::endl;
exit(1);
}
glutInit(&argc, argv);
glutInitContextVersion(2,0);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowSize(WIDTH, HEIGHT);
glutCreateWindow("get_image");
glewInit();
init();
glutDisplayFunc(display);
glutIdleFunc(idle);
glutMainLoop();
return EXIT_SUCCESS;
}
<commit_msg>Fix for inverted image fix.<commit_after>#if defined(_MSC_VER) || defined(WINDOWS)
#define _USE_MATH_DEFINES
#endif
#include <cmath>
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <vector>
#include <cassert>
#include "lodepng.h"
#include <GL/glew.h>
#ifdef __APPLE__
#include <OpenGL/gl.h>
#include <OpenGl/glu.h>
#include <GLUT/glut.h>
#else
#include <GL/freeglut.h>
#endif
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
#if defined(_MSC_VER) || defined(WINDOWS)
#include <windows.h>
#include <rtcapi.h>
int
exception_handler(LPEXCEPTION_POINTERS p)
{
printf("Exception detected during test execution!\n");
exit(1);
}
int
runtime_check_handler(int errorType, const char *filename, int linenumber,
const char *moduleName, const char *format, ...)
{
printf("Error type %d at %s line %d in %s", errorType, filename, linenumber, moduleName);
exit(1);
}
#endif
#define WIDTH 640
#define HEIGHT 480
#define CHANNELS 4
#define OUTPUT_IMAGE_MAX_LINE_LEN 70
#define OUTPUT_IMAGE_MAX_PIXEL_VAL_LEN 4
#define OUTPUT_IMAGE_MAX_PIXEL_VAL 255
#define COMPILE_ERROR_EXIT_CODE 101
#define LINK_ERROR_EXIT_CODE 102
#define RENDER_ERROR_EXIT_CODE 103
std::string terminate_flag = "",
output = "output.png",
vertex_shader = "",
fragment_shader = "";
bool persist = false,
exit_compile = false,
exit_linking = false,
animate = false;
GLuint program;
const char* vertex_shader_wo_version = "attribute vec2 coord2d;\nvarying vec2 surfacePosition;\nvoid main(void) {\ngl_Position = vec4(coord2d, 0.0, 1.0);\nsurfacePosition = coord2d;\n}";
bool rendered = false;
bool
parse_args(int argc, char* argv[])
{
vertex_shader = "";
fragment_shader = "";
std::string curr_arg;
for (int i = 1; i < argc; i++) {
curr_arg = std::string(argv[i]);
if (!curr_arg.compare(0, 2, "--")) {
if (!curr_arg.compare("--persist")) {
persist = true;
continue;
}
else if (!curr_arg.compare("--animate")) {
animate = true;
continue;
}
else if (!curr_arg.compare("--exit_compile")) {
exit_compile = true;
continue;
}
else if (!curr_arg.compare("--exit_linking")) {
exit_linking = true;
continue;
}
else if (!curr_arg.compare("--output")) {
output = argv[++i];
continue;
}
else if (!curr_arg.compare("--vertex")) {
vertex_shader = argv[++i];
continue;
}
printf("Unknown argument %s\n", curr_arg.c_str());
continue;
}
if (fragment_shader == "")
fragment_shader = curr_arg;
else printf("Ignoring extra argument %s\n", curr_arg.c_str());
}
return (fragment_shader != "");
}
void
report_error_and_exit(GLuint oglPrg, int exitCode)
{
GLint maxLength = 0;
glGetShaderiv(oglPrg, GL_INFO_LOG_LENGTH, &maxLength);
// The maxLength includes the NULL character
std::vector<GLchar> errorLog(maxLength);
glGetShaderInfoLog(oglPrg, maxLength, &maxLength, &errorLog[0]);
// Provide the infolog in whatever manor you deem best.
for (GLchar c : errorLog)
std::cout << c;
std::cout << "\n";
// Exit with failure.
glDeleteShader(oglPrg);
exit(exitCode);
}
void
keyboard_listener(unsigned char key, int x, int y)
{
exit(0);
}
void init()
{
int compile_ok;
program = glCreateProgram();
// Shader start
GLuint shd1 = glCreateShader(GL_FRAGMENT_SHADER);
std::ifstream shdf1(fragment_shader);
if(!shdf1) {
fprintf(stderr, "Fragment shader %s not found\n", fragment_shader.c_str());
exit(1);
}
std::stringstream shds1;
shds1 << shdf1.rdbuf();
std::string shdstr1= shds1.str();
const char *shdchr1= shdstr1.c_str();
glShaderSource(shd1, 1, &shdchr1, NULL);
fprintf(stderr, "Compiling fragment shader\n");
glCompileShader(shd1);
glGetShaderiv(shd1, GL_COMPILE_STATUS, &compile_ok);
if (!compile_ok) {
fprintf(stderr, "Error compiling fragment shader\n");
report_error_and_exit(shd1, COMPILE_ERROR_EXIT_CODE);
}
fprintf(stderr, "Fragment shader compiled successfully\n");
if (exit_compile) {
fprintf(stdout, "Exiting after fragment shader compilation...\n");
exit(0);
}
glAttachShader(program, shd1);
// Shader end
// Start: construct vertex shader string
std::string shdstr0;
if(vertex_shader == "") {
// Use embedded vertex shader.
size_t i = shdstr1.find('\n');
if(i != std::string::npos && shdstr1[0] == '#') {
shdstr0 = shdstr1.substr(0,i);
shdstr0 += "\n";
} else {
fprintf(stderr, "Warning: Could not find #version string of fragment shader.\n");
}
shdstr0 += vertex_shader_wo_version;
} else {
std::ifstream shdf0(vertex_shader);
if(!shdf0) {
fprintf(stderr, "Vertex shader %s not found\n", vertex_shader.c_str());
exit(1);
}
std::stringstream shds0;
shds0 << shdf0.rdbuf();
shdstr0 = shds0.str();
}
// End: construct vertex shader string
// Shader start
GLuint shd0 = glCreateShader(GL_VERTEX_SHADER);
const char *shdchr0= shdstr0.c_str();
glShaderSource(shd0, 1, &shdchr0, NULL);
fprintf(stderr, "Compiling vertex shader\n");
glCompileShader(shd0);
glGetShaderiv(shd0, GL_COMPILE_STATUS, &compile_ok);
if (!compile_ok) {
fprintf(stderr, "Error compiling vertex shader\n");
report_error_and_exit(shd0, 1);
}
fprintf(stderr, "Vertex shader compiled successfully\n");
glAttachShader(program, shd0);
// Shader end
fprintf(stderr, "Linking program\n");
glLinkProgram(program);
glGetProgramiv(program, GL_LINK_STATUS, &compile_ok);
if (!compile_ok) {
fprintf(stderr, "Error in linking program\n");
report_error_and_exit(program, LINK_ERROR_EXIT_CODE);
}
fprintf(stderr, "Program linked successfully\n");
if (exit_linking) {
fprintf(stdout, "Exiting after program linking...\n");
exit(0);
}
// Program 5 end
glutKeyboardFunc(keyboard_listener);
}
void display()
{
static int num_display_calls = 0;
glClearColor(1.0, 1.0, 0.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(program);
const char* uniform_name;
GLint uniform_loc;
uniform_name = "resolution";
uniform_loc = glGetUniformLocation(program, uniform_name);
if (uniform_loc != -1)
glUniform2f(uniform_loc, WIDTH, HEIGHT);
uniform_name = "mouse";
uniform_loc = glGetUniformLocation(program, uniform_name);
if (uniform_loc != -1)
glUniform2f(uniform_loc, 0.0, 0.0);
uniform_name = "injectionSwitch";
uniform_loc = glGetUniformLocation(program, uniform_name);
if (uniform_loc != -1)
glUniform2f(uniform_loc, 0.0, 1.0);
uniform_name = "time";
uniform_loc = glGetUniformLocation(program, uniform_name);
if (uniform_loc != -1)
glUniform1f(uniform_loc, (animate ? glutGet(GLUT_ELAPSED_TIME) / 1000.0 * (2*M_PI) / 5 : 0));
glEnableVertexAttribArray(0);
GLfloat arr_5_0[] = {
-1, 1,
-1, -1,
1, -1,
};
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, arr_5_0);
glDrawArrays(GL_TRIANGLES, 0, 3.0);
GLfloat arr_5_1[] = {
-1, 1,
1, 1,
1, -1,
};
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, arr_5_1);
glDrawArrays(GL_TRIANGLES, 0, 3.0);
glDisableVertexAttribArray(0);
glFinish();
glutSwapBuffers();
num_display_calls++;
rendered = (num_display_calls >= 2);
}
void idle()
{
static bool saved = false;
if (rendered && !saved) {
saved = true;
std::vector<std::uint8_t> data(WIDTH * HEIGHT * CHANNELS);
glReadPixels(0, 0, WIDTH, HEIGHT, GL_RGBA, GL_UNSIGNED_BYTE, &data[0]);
std::vector<std::uint8_t> flipped_data(WIDTH * HEIGHT * CHANNELS);
for (int h = 0; h < HEIGHT ; h++)
for (int col = 0; col < WIDTH * CHANNELS; col++)
flipped_data[h * WIDTH * CHANNELS + col] =
data[(HEIGHT - h - 1) * WIDTH * CHANNELS + col];
unsigned png_error = lodepng::encode(output, flipped_data, WIDTH, HEIGHT);
if (png_error)
printf("Error producing PNG file: %s", lodepng_error_text(png_error));
if (persist)
printf("Press any key to exit...\n");
else
exit(0);
}
glutPostRedisplay();
}
int main(int argc, char* argv[])
{
#ifdef _MSC_VER
DWORD dwMode = SetErrorMode(SEM_NOGPFAULTERRORBOX);
SetErrorMode(dwMode | SEM_NOGPFAULTERRORBOX);
SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)&exception_handler);
_RTC_SetErrorFunc(&runtime_check_handler);
#endif
if(!parse_args(argc, argv)) {
std::cerr << "Requires fragment shader argument!" << std::endl;
exit(1);
}
glutInit(&argc, argv);
glutInitContextVersion(2,0);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowSize(WIDTH, HEIGHT);
glutCreateWindow("get_image");
glewInit();
init();
glutDisplayFunc(display);
glutIdleFunc(idle);
glutMainLoop();
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>//==============================================================================
// Single cell simulation view simulation worker
//==============================================================================
#include "cellmlfileruntime.h"
#include "coredaesolver.h"
#include "corenlasolver.h"
#include "coreodesolver.h"
#include "singlecellsimulationviewsimulation.h"
#include "singlecellsimulationviewsimulationworker.h"
#include "thread.h"
//==============================================================================
#include <QTime>
//==============================================================================
namespace OpenCOR {
namespace SingleCellSimulationView {
//==============================================================================
SingleCellSimulationViewSimulationWorker::SingleCellSimulationViewSimulationWorker(const SolverInterfaces &pSolverInterfaces,
CellMLSupport::CellmlFileRuntime *pCellmlFileRuntime,
SingleCellSimulationViewSimulationData *pData,
SingleCellSimulationViewSimulationResults *pResults) :
mStatus(Idling),
mSolverInterfaces(pSolverInterfaces),
mCellmlFileRuntime(pCellmlFileRuntime),
mData(pData),
mResults(pResults),
mError(false)
{
// Initialise our progress and let people know about it
updateAndEmitProgress(0.0);
}
//==============================================================================
SingleCellSimulationViewSimulationWorker::Status SingleCellSimulationViewSimulationWorker::status() const
{
// Return our status
return mStatus;
}
//==============================================================================
double SingleCellSimulationViewSimulationWorker::progress() const
{
// Return our progress
return mProgress;
}
//==============================================================================
void SingleCellSimulationViewSimulationWorker::updateAndEmitProgress(const double &pProgress)
{
// Set our progress
mProgress = pProgress;
// Let people know about our progress
emit progress(pProgress);
}
//==============================================================================
void SingleCellSimulationViewSimulationWorker::run()
{
// Run ourselves, but only if we are currently idling
if (mStatus == Idling) {
mData->reset();
mResults->reset();
//---GRY--- THE ABOVE IS TEMPORARY, JUST FOR OUR DEMO...
// We are running
mStatus = Running;
// Let people know that we are running
emit running();
// Set up our ODE/DAE solver
CoreSolver::CoreVoiSolver *voiSolver = 0;
CoreSolver::CoreOdeSolver *odeSolver = 0;
CoreSolver::CoreDaeSolver *daeSolver = 0;
if (mCellmlFileRuntime->needOdeSolver()) {
foreach (SolverInterface *solverInterface, mSolverInterfaces)
if (!solverInterface->name().compare(mData->odeSolverName())) {
// The requested ODE solver was found, so retrieve an
// instance of it
voiSolver = odeSolver = static_cast<CoreSolver::CoreOdeSolver *>(solverInterface->instance());
break;
}
} else {
foreach (SolverInterface *solverInterface, mSolverInterfaces)
if (!solverInterface->name().compare("IDA")) {
// The requested DAE solver was found, so retrieve an
// instance of it
voiSolver = daeSolver = static_cast<CoreSolver::CoreDaeSolver *>(solverInterface->instance());
break;
}
}
// Set up our NLA solver, if needed
CoreSolver::CoreNlaSolver *nlaSolver = 0;
if (mCellmlFileRuntime->needNlaSolver())
foreach (SolverInterface *solverInterface, mSolverInterfaces)
if (!solverInterface->name().compare(mData->nlaSolverName())) {
// The requested NLA solver was found, so retrieve an
// instance of it
nlaSolver = static_cast<CoreSolver::CoreNlaSolver *>(solverInterface->instance());
// Keep track of our NLA solver, so that doNonLinearSolve()
// can work as expected
CoreSolver::setNlaSolver(mCellmlFileRuntime->address(),
nlaSolver);
break;
}
// Keep track of any error that might be reported by any of our solvers
mError = false;
if (odeSolver)
connect(odeSolver, SIGNAL(error(const QString &)),
this, SLOT(emitError(const QString &)));
else
connect(daeSolver, SIGNAL(error(const QString &)),
this, SLOT(emitError(const QString &)));
if (nlaSolver)
connect(nlaSolver, SIGNAL(error(const QString &)),
this, SLOT(emitError(const QString &)));
// Retrieve our simulation properties
double startingPoint = mData->startingPoint();
double endingPoint = mData->endingPoint();
double pointInterval = mData->pointInterval();
bool increasingPoints = endingPoint > startingPoint;
const double oneOverPointRange = 1.0/(endingPoint-startingPoint);
int pointCounter = 0;
double currentPoint = startingPoint;
// Initialise our ODE/DAE solver
if (odeSolver) {
odeSolver->setProperties(mData->odeSolverProperties());
odeSolver->initialize(currentPoint,
mCellmlFileRuntime->statesCount(),
mData->constants(), mData->states(),
mData->rates(), mData->algebraic(),
mCellmlFileRuntime->computeRates());
} else {
daeSolver->setProperties(mData->daeSolverProperties());
daeSolver->initialize(currentPoint, endingPoint,
mCellmlFileRuntime->statesCount(),
mCellmlFileRuntime->condVarCount(),
mData->constants(), mData->states(),
mData->rates(), mData->algebraic(),
mData->condVar(),
mCellmlFileRuntime->computeEssentialVariables(),
mCellmlFileRuntime->computeResiduals(),
mCellmlFileRuntime->computeRootInformation(),
mCellmlFileRuntime->computeStateInformation());
}
// Initialise our NLA solver
if (nlaSolver)
nlaSolver->setProperties(mData->nlaSolverProperties());
// Now, we are ready to compute our model, but only if no error has
// occurred so far
if (!mError) {
// Start our timer
QTime timer;
int totalElapsedTime = 0;
timer.start();
// Our main work loop
//QString states;
//for (int i = 0, iMax = mCellmlFileRuntime->statesCount(); i < iMax; ++i)
// if (i)
// states += ",STATES["+QString::number(i)+"]";
// else
// states = "STATES["+QString::number(i)+"]";
//qDebug("time,%s", qPrintable(states));
while ( (currentPoint != endingPoint) && !mError
&& (mStatus != Stopped)) {
// Handle our current point after making sure that all the
// variables have been computed
mData->recomputeVariables(currentPoint);
mResults->addPoint(currentPoint);
//---GRY--- TO BE DONE...
//for (int i = 0, iMax = mCellmlFileRuntime->statesCount(); i < iMax; ++i)
// if (i)
// states += ","+QString::number(mData->results()[mData->resultsFilled()-1].states[i]);
// else
// states = QString::number(mData->results()[mData->resultsFilled()-1].states[i]);
//qDebug("%f,%s", mData->results()[mData->resultsFilled()-1].point, qPrintable(states));
// Let people know about our progress
updateAndEmitProgress((currentPoint-startingPoint)*oneOverPointRange);
// Check whether we should be pausing
if(mStatus == Pausing) {
// We have been asked to pause, so do just that after stopping
// our timer
totalElapsedTime += timer.elapsed();
mStatusMutex.lock();
mStatusCondition.wait(&mStatusMutex);
mStatusMutex.unlock();
// We are running again
mStatus = Running;
// Let people know that we are running again
emit running();
// Restart our timer
timer.restart();
}
// Determine our next point and compute our model up to it
++pointCounter;
voiSolver->solve(currentPoint,
increasingPoints?
qMin(endingPoint, startingPoint+pointCounter*pointInterval):
qMax(endingPoint, startingPoint+pointCounter*pointInterval));
// Delay things a bit, if (really) needed
if (mData->delay() && (mStatus != Stopped)) {
totalElapsedTime += timer.elapsed();
static_cast<Core::Thread *>(thread())->msleep(mData->delay());
timer.restart();
}
}
if (!mError && (mStatus != Stopped)) {
// Handle our last point after making sure that all the
// variables have been computed
mData->recomputeVariables(currentPoint);
mResults->addPoint(currentPoint);
//---GRY--- TO BE DONE...
//for (int i = 0, iMax = mCellmlFileRuntime->statesCount(); i < iMax; ++i)
// if (i)
// states += ","+QString::number(mData->results()[mData->resultsFilled()-1].states[i]);
// else
// states = QString::number(mData->results()[mData->resultsFilled()-1].states[i]);
//qDebug("%f,%s", mData->results()[mData->resultsFilled()-1].point, qPrintable(states));
// Let people know about our final progress, but only if we didn't stop
// the simulation
updateAndEmitProgress(1.0);
}
// Reset our progress
// Note: we would normally use updateAndEmitProgress(), but we don't
// want to emit the progress, so...
mProgress = 0.0;
// Retrieve the total elapsed time
if (!mError)
totalElapsedTime += timer.elapsed();
// We are done, so...
mStatus = Finished;
// Let people know that we are done and give them the total elapsed time too
emit finished(mError?-1:totalElapsedTime);
// Note: we use -1 as a way to indicate that something went wrong...
} else {
// An error occurred, so...
mStatus = Finished;
// Let people know that we are done
// Note: we use -1 as a way to indicate that something went wrong...
emit finished(-1);
}
// Delete our solver(s)
delete voiSolver;
if (nlaSolver) {
delete nlaSolver;
CoreSolver::unsetNlaSolver(mCellmlFileRuntime->address());
}
}
}
//==============================================================================
void SingleCellSimulationViewSimulationWorker::pause()
{
// Pause ourselves, but only if we are currently running
if (mStatus == Running) {
// We are pausing
mStatus = Pausing;
// Let people know that we are pausing
emit pausing();
}
}
//==============================================================================
void SingleCellSimulationViewSimulationWorker::resume()
{
// Resume ourselves, but only if are currently pausing
if (mStatus == Pausing) {
// Actually resume ourselves
mStatusCondition.wakeAll();
// We are running again
mStatus = Running;
// Let people know that we are running again
emit running();
}
}
//==============================================================================
void SingleCellSimulationViewSimulationWorker::stop()
{
// Check that we are either running or pausing
if ((mStatus == Running) || (mStatus == Pausing)) {
// Resume ourselves, if needed
if (mStatus == Pausing)
mStatusCondition.wakeAll();
// Stop ourselves
mStatus = Stopped;
}
}
//==============================================================================
void SingleCellSimulationViewSimulationWorker::emitError(const QString &pMessage)
{
// A solver error occurred, so keep track of it and let people know about it
mError = true;
emit error(pMessage);
}
//==============================================================================
} // namespace SingleCellSimulationView
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<commit_msg>Some minor cleaning up.<commit_after>//==============================================================================
// Single cell simulation view simulation worker
//==============================================================================
#include "cellmlfileruntime.h"
#include "coredaesolver.h"
#include "corenlasolver.h"
#include "coreodesolver.h"
#include "singlecellsimulationviewsimulation.h"
#include "singlecellsimulationviewsimulationworker.h"
#include "thread.h"
//==============================================================================
#include <QTime>
//==============================================================================
namespace OpenCOR {
namespace SingleCellSimulationView {
//==============================================================================
SingleCellSimulationViewSimulationWorker::SingleCellSimulationViewSimulationWorker(const SolverInterfaces &pSolverInterfaces,
CellMLSupport::CellmlFileRuntime *pCellmlFileRuntime,
SingleCellSimulationViewSimulationData *pData,
SingleCellSimulationViewSimulationResults *pResults) :
mStatus(Idling),
mSolverInterfaces(pSolverInterfaces),
mCellmlFileRuntime(pCellmlFileRuntime),
mData(pData),
mResults(pResults),
mError(false)
{
// Initialise our progress and let people know about it
updateAndEmitProgress(0.0);
}
//==============================================================================
SingleCellSimulationViewSimulationWorker::Status SingleCellSimulationViewSimulationWorker::status() const
{
// Return our status
return mStatus;
}
//==============================================================================
double SingleCellSimulationViewSimulationWorker::progress() const
{
// Return our progress
return mProgress;
}
//==============================================================================
void SingleCellSimulationViewSimulationWorker::updateAndEmitProgress(const double &pProgress)
{
// Set our progress
mProgress = pProgress;
// Let people know about our progress
emit progress(pProgress);
}
//==============================================================================
void SingleCellSimulationViewSimulationWorker::run()
{
// Run ourselves, but only if we are currently idling
if (mStatus == Idling) {
mData->reset();
mResults->reset();
//---GRY--- THE ABOVE IS TEMPORARY, JUST FOR OUR DEMO...
// We are running
mStatus = Running;
// Let people know that we are running
emit running();
// Set up our ODE/DAE solver
CoreSolver::CoreVoiSolver *voiSolver = 0;
CoreSolver::CoreOdeSolver *odeSolver = 0;
CoreSolver::CoreDaeSolver *daeSolver = 0;
if (mCellmlFileRuntime->needOdeSolver()) {
foreach (SolverInterface *solverInterface, mSolverInterfaces)
if (!solverInterface->name().compare(mData->odeSolverName())) {
// The requested ODE solver was found, so retrieve an
// instance of it
voiSolver = odeSolver = static_cast<CoreSolver::CoreOdeSolver *>(solverInterface->instance());
break;
}
} else {
foreach (SolverInterface *solverInterface, mSolverInterfaces)
if (!solverInterface->name().compare("IDA")) {
// The requested DAE solver was found, so retrieve an
// instance of it
voiSolver = daeSolver = static_cast<CoreSolver::CoreDaeSolver *>(solverInterface->instance());
break;
}
}
// Set up our NLA solver, if needed
CoreSolver::CoreNlaSolver *nlaSolver = 0;
if (mCellmlFileRuntime->needNlaSolver())
foreach (SolverInterface *solverInterface, mSolverInterfaces)
if (!solverInterface->name().compare(mData->nlaSolverName())) {
// The requested NLA solver was found, so retrieve an
// instance of it
nlaSolver = static_cast<CoreSolver::CoreNlaSolver *>(solverInterface->instance());
// Keep track of our NLA solver, so that doNonLinearSolve()
// can work as expected
CoreSolver::setNlaSolver(mCellmlFileRuntime->address(),
nlaSolver);
break;
}
// Keep track of any error that might be reported by any of our solvers
mError = false;
if (odeSolver)
connect(odeSolver, SIGNAL(error(const QString &)),
this, SLOT(emitError(const QString &)));
else
connect(daeSolver, SIGNAL(error(const QString &)),
this, SLOT(emitError(const QString &)));
if (nlaSolver)
connect(nlaSolver, SIGNAL(error(const QString &)),
this, SLOT(emitError(const QString &)));
// Retrieve our simulation properties
double startingPoint = mData->startingPoint();
double endingPoint = mData->endingPoint();
double pointInterval = mData->pointInterval();
bool increasingPoints = endingPoint > startingPoint;
const double oneOverPointRange = 1.0/(endingPoint-startingPoint);
int pointCounter = 0;
double currentPoint = startingPoint;
// Initialise our ODE/DAE solver
if (odeSolver) {
odeSolver->setProperties(mData->odeSolverProperties());
odeSolver->initialize(currentPoint,
mCellmlFileRuntime->statesCount(),
mData->constants(), mData->states(),
mData->rates(), mData->algebraic(),
mCellmlFileRuntime->computeRates());
} else {
daeSolver->setProperties(mData->daeSolverProperties());
daeSolver->initialize(currentPoint, endingPoint,
mCellmlFileRuntime->statesCount(),
mCellmlFileRuntime->condVarCount(),
mData->constants(), mData->states(),
mData->rates(), mData->algebraic(),
mData->condVar(),
mCellmlFileRuntime->computeEssentialVariables(),
mCellmlFileRuntime->computeResiduals(),
mCellmlFileRuntime->computeRootInformation(),
mCellmlFileRuntime->computeStateInformation());
}
// Initialise our NLA solver
if (nlaSolver)
nlaSolver->setProperties(mData->nlaSolverProperties());
// Now, we are ready to compute our model, but only if no error has
// occurred so far
if (!mError) {
// Start our timer
QTime timer;
int totalElapsedTime = 0;
timer.start();
// Our main work loop
while ( (currentPoint != endingPoint) && !mError
&& (mStatus != Stopped)) {
// Handle our current point after making sure that all the
// variables have been computed
mData->recomputeVariables(currentPoint);
mResults->addPoint(currentPoint);
// Let people know about our progress
updateAndEmitProgress((currentPoint-startingPoint)*oneOverPointRange);
// Check whether we should be pausing
if(mStatus == Pausing) {
// We have been asked to pause, so do just that after stopping
// our timer
totalElapsedTime += timer.elapsed();
mStatusMutex.lock();
mStatusCondition.wait(&mStatusMutex);
mStatusMutex.unlock();
// We are running again
mStatus = Running;
// Let people know that we are running again
emit running();
// Restart our timer
timer.restart();
}
// Determine our next point and compute our model up to it
++pointCounter;
voiSolver->solve(currentPoint,
increasingPoints?
qMin(endingPoint, startingPoint+pointCounter*pointInterval):
qMax(endingPoint, startingPoint+pointCounter*pointInterval));
// Delay things a bit, if (really) needed
if (mData->delay() && (mStatus != Stopped)) {
totalElapsedTime += timer.elapsed();
static_cast<Core::Thread *>(thread())->msleep(mData->delay());
timer.restart();
}
}
if (!mError && (mStatus != Stopped)) {
// Handle our last point after making sure that all the
// variables have been computed
mData->recomputeVariables(currentPoint);
mResults->addPoint(currentPoint);
// Let people know about our final progress, but only if we didn't stop
// the simulation
updateAndEmitProgress(1.0);
}
// Reset our progress
// Note: we would normally use updateAndEmitProgress(), but we don't
// want to emit the progress, so...
mProgress = 0.0;
// Retrieve the total elapsed time
if (!mError)
totalElapsedTime += timer.elapsed();
// We are done, so...
mStatus = Finished;
// Let people know that we are done and give them the total elapsed time too
emit finished(mError?-1:totalElapsedTime);
// Note: we use -1 as a way to indicate that something went wrong...
} else {
// An error occurred, so...
mStatus = Finished;
// Let people know that we are done
// Note: we use -1 as a way to indicate that something went wrong...
emit finished(-1);
}
// Delete our solver(s)
delete voiSolver;
if (nlaSolver) {
delete nlaSolver;
CoreSolver::unsetNlaSolver(mCellmlFileRuntime->address());
}
}
}
//==============================================================================
void SingleCellSimulationViewSimulationWorker::pause()
{
// Pause ourselves, but only if we are currently running
if (mStatus == Running) {
// We are pausing
mStatus = Pausing;
// Let people know that we are pausing
emit pausing();
}
}
//==============================================================================
void SingleCellSimulationViewSimulationWorker::resume()
{
// Resume ourselves, but only if are currently pausing
if (mStatus == Pausing) {
// Actually resume ourselves
mStatusCondition.wakeAll();
// We are running again
mStatus = Running;
// Let people know that we are running again
emit running();
}
}
//==============================================================================
void SingleCellSimulationViewSimulationWorker::stop()
{
// Check that we are either running or pausing
if ((mStatus == Running) || (mStatus == Pausing)) {
// Resume ourselves, if needed
if (mStatus == Pausing)
mStatusCondition.wakeAll();
// Stop ourselves
mStatus = Stopped;
}
}
//==============================================================================
void SingleCellSimulationViewSimulationWorker::emitError(const QString &pMessage)
{
// A solver error occurred, so keep track of it and let people know about it
mError = true;
emit error(pMessage);
}
//==============================================================================
} // namespace SingleCellSimulationView
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <Arduino.h>
#include "source.h"
#include "filter.h"
#include "function.h"
#include "generator.h"
#include "parse.h"
#define MAX_CODE_LEN 512
#define MAX_NUM_ARGS 8
#define VALUE_SIZE 4
#define ARG_VALUE 0
#define ARG_FUNC 1
#define ARG_COLOR 2
#define ARG_LOCAL 3
#define LOCAL_ID 0
#define LOCAL_POS_X 2
#define LOCAL_POS_Y 3
#define LOCAL_POS_Z 4
#define FILTER_FADE_IN 0
#define FILTER_FADE_OUT 1
#define FILTER_BRIGHTNESS 2
#define GEN_SIN 3
#define GEN_SQUARE 4
#define GEN_SAWTOOTH 5
#define SRC_CONSTANT_COLOR 6
#define SRC_RAND_COL_SEQ 7
#define SRC_HSV 8
#define SRC_RAINBOW 9
#define GEN_STEP 10
#define FUNC_SPARKLE 11
#define FUNC_GENOP 12
#define FUNC_SRCOP 13
#define FUNC_ABS 14
#define GEN_LINE 15
#define GEN_CONSTANT 16
#define FUNC_COMPLEMENTARY 17
#define FUNC_LOCAL_RANDOM 18
#define GEN_IMPULSE 19
#define FUNC_REPEAT_LOCAL_RANDOM 20
// variables to help manage the heap.
uint8_t *cur_heap = NULL;
uint16_t heap_offset = 0;
void heap_setup(uint8_t *heap)
{
heap_offset = 0;
cur_heap = heap;
}
void *heap_alloc(uint8_t bytes)
{
uint8_t *ptr = cur_heap + heap_offset;
if (bytes + heap_offset > HEAP_SIZE)
{
g_error = ERR_OUT_OF_HEAP;
return NULL;
}
heap_offset += bytes;
return ptr;
}
void *create_object(uint8_t id, uint8_t *is_local,
int32_t *values, uint8_t value_count,
void **gens, uint8_t gen_count,
color_t *colors, uint8_t color_count)
{
void *obj = NULL;
*is_local = 0;
switch(id)
{
case FILTER_FADE_IN:
{
if (value_count == 2)
{
obj = heap_alloc(sizeof(f_fade_in_t));
if (!obj)
return NULL;
f_fade_in_init((f_fade_in_t *)obj, f_fade_in_get, values[0], values[1]);
}
else
{
g_error = ERR_PARSE_FAILURE;
return NULL;
}
}
break;
case FILTER_FADE_OUT:
{
if (value_count == 2)
{
obj = heap_alloc(sizeof(f_fade_out_t));
if (!obj)
return NULL;
f_fade_out_init((f_fade_out_t *)obj, f_fade_out_get, values[0], values[1]);
}
else
{
g_error = ERR_PARSE_FAILURE;
return NULL;
}
}
break;
case FILTER_BRIGHTNESS:
{
if (gen_count == 1)
{
obj = heap_alloc(sizeof(f_brightness_t));
if (!obj)
return NULL;
f_brightness_init((f_brightness_t *)obj, (generator_t*)gens[0]);
}
else
{
g_error = ERR_PARSE_FAILURE;
return NULL;
}
}
break;
case SRC_CONSTANT_COLOR:
{
if (color_count == 1)
{
obj = heap_alloc(sizeof(s_constant_color_t));
if (!obj)
return NULL;
s_constant_color_init((s_constant_color_t *)obj, &colors[0]);
}
else
{
g_error = ERR_PARSE_FAILURE;
return NULL;
}
}
break;
case SRC_RAND_COL_SEQ:
{
if (value_count == 2)
{
obj = heap_alloc(sizeof(s_random_color_seq_t));
if (!obj)
return NULL;
s_random_color_seq_init((s_random_color_seq_t *)obj, values[0], values[1]);
}
else
{
g_error = ERR_PARSE_FAILURE;
return NULL;
}
}
break;
case SRC_HSV:
{
if (gen_count > 0)
{
obj = heap_alloc(sizeof(s_hsv_t));
if (!obj)
return NULL;
if (gen_count > 2)
s_hsv_init((s_hsv_t *)obj, (generator_t*)gens[0], (generator_t*)gens[1], (generator_t*)gens[2]);
else
if (gen_count > 1)
s_hsv_init((s_hsv_t *)obj, (generator_t*)gens[0], (generator_t*)gens[1], NULL);
else
s_hsv_init((s_hsv_t *)obj, (generator_t*)gens[0], NULL, NULL);
}
else
{
g_error = ERR_PARSE_FAILURE;
return NULL;
}
}
break;
case SRC_RAINBOW:
{
if (gen_count == 1)
{
obj = heap_alloc(sizeof(s_rainbow_t));
if (!obj)
return NULL;
s_rainbow_init((s_rainbow_t *)obj, (generator_t*)gens[0]);
}
else
{
g_error = ERR_PARSE_FAILURE;
return NULL;
}
}
break;
case GEN_SQUARE:
{
if (value_count == 5)
{
obj = heap_alloc(sizeof(square_t));
if (!obj)
return NULL;
g_square_init(obj, g_square, values[0], values[1], values[2], values[3], values[4]);
}
else
{
g_error = ERR_PARSE_FAILURE;
return NULL;
}
}
break;
case GEN_SIN:
{
if (value_count == 4)
{
obj = heap_alloc(sizeof(generator_t));
if (!obj)
return NULL;
g_sin_init(obj, g_sin, values[0], values[1], values[2], values[3]);
}
else
{
g_error = ERR_PARSE_FAILURE;
return NULL;
}
}
break;
case GEN_SAWTOOTH:
case GEN_STEP:
case GEN_LINE:
case GEN_IMPULSE:
{
if (value_count == 4)
{
obj = heap_alloc(sizeof(generator_t));
if (!obj)
return NULL;
switch(id)
{
case GEN_SIN:
g_generator_init(obj, g_sin, values[0], values[1], values[2], values[3]);
break;
case GEN_SAWTOOTH:
g_generator_init(obj, g_sawtooth, values[0], values[1], values[2], values[3]);
break;
case GEN_STEP:
g_generator_init(obj, g_step, values[0], values[1], values[2], values[3]);
break;
case GEN_LINE:
g_generator_init(obj, g_line, values[0], values[1], values[2], values[3]);
break;
case GEN_IMPULSE:
g_generator_init(obj, g_impulse, values[0], values[1], values[2], values[3]);
break;
}
}
else
{
g_error = ERR_PARSE_FAILURE;
return NULL;
}
}
break;
case FUNC_GENOP:
{
if (value_count == 1 && gen_count == 2)
{
obj = heap_alloc(sizeof(s_op_t));
if (!obj)
return NULL;
g_generator_op_init(obj, (uint8_t)values[0], (generator_t*)gens[0], (generator_t*)gens[1]);
}
else
{
g_error = ERR_PARSE_FAILURE;
return NULL;
}
}
break;
case FUNC_SRCOP:
{
if (value_count == 1 && gen_count == 2)
{
obj = heap_alloc(sizeof(s_op_t));
if (!obj)
return NULL;
s_op_init((s_op_t *)obj, (uint8_t)values[0], (s_source_t*)gens[0], (s_source_t*)gens[1]);
}
else
{
g_error = ERR_PARSE_FAILURE;
return NULL;
}
}
break;
case FUNC_ABS:
{
if (gen_count == 1)
{
obj = heap_alloc(sizeof(g_abs_t));
if (!obj)
return NULL;
g_abs_init(obj, (generator_t *)gens[0]);
}
else
{
g_error = ERR_PARSE_FAILURE;
return NULL;
}
}
break;
case GEN_CONSTANT:
{
if (value_count == 1)
{
obj = heap_alloc(sizeof(g_constant_t));
if (!obj)
return NULL;
g_constant_init((g_constant_t *)obj, (uint8_t)values[0]);
}
else
{
g_error = ERR_PARSE_FAILURE;
return NULL;
}
}
break;
case FUNC_LOCAL_RANDOM:
{
*is_local = 1;
if (value_count == 2)
{
int32_t ret = fu_local_random(values[0], values[1]);
return (void *)ret;
}
else
{
g_error = ERR_PARSE_FAILURE;
return NULL;
}
}
break;
case FUNC_REPEAT_LOCAL_RANDOM:
{
*is_local = 1;
if (value_count == 1)
{
int32_t ret = fu_repeat_local_random(values[0] / SCALE_FACTOR);
return (void *)ret;
}
else
{
g_error = ERR_PARSE_FAILURE;
return NULL;
}
}
break;
}
return obj;
}
/*
| 1 byte | 2 bytes |
| ID - ARG | FUNC SIG | (
*/
void *parse_func(uint8_t *code, uint16_t len, uint16_t *index, uint8_t *is_local)
{
uint8_t id, num_args, i, arg, value_count = 0, gen_count = 0, color_count = 0;
uint16_t arg_index;
uint32_t args, value;
int32_t values[MAX_NUM_ARGS];
void *gens[MAX_NUM_ARGS], *ret;
color_t colors[MAX_NUM_ARGS];
id = code[*index] >> 3;
num_args = code[*index] & 0x7;
args = (code[*index + 2] << 8) | code[*index + 1];
arg_index = *index + 3;
for(i = 0; i < num_args; i++)
{
arg = (args >> (i * 2)) & 0x3;
if (arg == ARG_VALUE)
{
values[value_count++] = *((uint32_t *)&code[arg_index]);
arg_index += VALUE_SIZE;
}
else if (arg == ARG_FUNC)
{
uint8_t local = 0;
gens[gen_count++] = parse_func(code, len, &arg_index, &local);
if (local)
{
gen_count--;
values[value_count++] = (uint32_t)gens[gen_count];
}
}
else if (arg == ARG_COLOR)
{
colors[color_count].c[0] = code[arg_index++];
colors[color_count].c[1] = code[arg_index++];
colors[color_count++].c[2] = code[arg_index++];
}
else
if (arg == ARG_LOCAL)
{
switch(*((uint32_t *)&code[arg_index]))
{
case LOCAL_ID:
values[value_count++] = g_node_id;
break;
case LOCAL_POS_X:
values[value_count++] = g_pos[0];
break;
case LOCAL_POS_Y:
values[value_count++] = g_pos[1];
break;
case LOCAL_POS_Z:
values[value_count++] = g_pos[2];
break;
default:
g_error = ERR_PARSE_FAILURE;
return NULL;
}
arg_index += VALUE_SIZE;
}
}
*index = arg_index;
return create_object(id, is_local, values, value_count, gens, gen_count, colors, color_count);
}
void *parse(uint8_t *code, uint16_t len, uint8_t *heap)
{
void *source, *ptr, *filter;
uint16_t offset = 0;
uint8_t local;
heap_setup(heap);
clear_local_random_values();
source = parse_func(code, len, &offset, &local);
if (!source)
return NULL;
for(; offset < len;)
{
filter = parse_func(code, len, &offset, &local);
if (!filter)
return NULL;
ptr = (s_source_t *)source;
while (((f_filter_t *)ptr)->next)
ptr = ((f_filter_t *)ptr)->next;
((f_filter_t *)ptr)->next = filter;
}
return source;
}
void evaluate(s_source_t *src, uint32_t _t, color_t *color)
{
color_t temp, dest;
void *filter;
uint32_t t;
t = (_t * g_speed) / SCALE_FACTOR;
src->method((void *)src, t, &dest);
filter = src->next;
while(filter)
{
temp.c[0] = dest.c[0];
temp.c[1] = dest.c[1];
temp.c[2] = dest.c[2];
((f_filter_t *)filter)->method(filter, t, &temp, &dest);
filter = ((f_filter_t *)filter)->next;
}
color->c[0] = dest.c[0];
color->c[1] = dest.c[1];
color->c[2] = dest.c[2];
}
<commit_msg>Don't cast the const value to 8 bit<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <Arduino.h>
#include "source.h"
#include "filter.h"
#include "function.h"
#include "generator.h"
#include "parse.h"
#define MAX_CODE_LEN 512
#define MAX_NUM_ARGS 8
#define VALUE_SIZE 4
#define ARG_VALUE 0
#define ARG_FUNC 1
#define ARG_COLOR 2
#define ARG_LOCAL 3
#define LOCAL_ID 0
#define LOCAL_POS_X 2
#define LOCAL_POS_Y 3
#define LOCAL_POS_Z 4
#define FILTER_FADE_IN 0
#define FILTER_FADE_OUT 1
#define FILTER_BRIGHTNESS 2
#define GEN_SIN 3
#define GEN_SQUARE 4
#define GEN_SAWTOOTH 5
#define SRC_CONSTANT_COLOR 6
#define SRC_RAND_COL_SEQ 7
#define SRC_HSV 8
#define SRC_RAINBOW 9
#define GEN_STEP 10
#define FUNC_SPARKLE 11
#define FUNC_GENOP 12
#define FUNC_SRCOP 13
#define FUNC_ABS 14
#define GEN_LINE 15
#define GEN_CONSTANT 16
#define FUNC_COMPLEMENTARY 17
#define FUNC_LOCAL_RANDOM 18
#define GEN_IMPULSE 19
#define FUNC_REPEAT_LOCAL_RANDOM 20
// variables to help manage the heap.
uint8_t *cur_heap = NULL;
uint16_t heap_offset = 0;
void heap_setup(uint8_t *heap)
{
heap_offset = 0;
cur_heap = heap;
}
void *heap_alloc(uint8_t bytes)
{
uint8_t *ptr = cur_heap + heap_offset;
if (bytes + heap_offset > HEAP_SIZE)
{
g_error = ERR_OUT_OF_HEAP;
return NULL;
}
heap_offset += bytes;
return ptr;
}
void *create_object(uint8_t id, uint8_t *is_local,
int32_t *values, uint8_t value_count,
void **gens, uint8_t gen_count,
color_t *colors, uint8_t color_count)
{
void *obj = NULL;
*is_local = 0;
switch(id)
{
case FILTER_FADE_IN:
{
if (value_count == 2)
{
obj = heap_alloc(sizeof(f_fade_in_t));
if (!obj)
return NULL;
f_fade_in_init((f_fade_in_t *)obj, f_fade_in_get, values[0], values[1]);
}
else
{
g_error = ERR_PARSE_FAILURE;
return NULL;
}
}
break;
case FILTER_FADE_OUT:
{
if (value_count == 2)
{
obj = heap_alloc(sizeof(f_fade_out_t));
if (!obj)
return NULL;
f_fade_out_init((f_fade_out_t *)obj, f_fade_out_get, values[0], values[1]);
}
else
{
g_error = ERR_PARSE_FAILURE;
return NULL;
}
}
break;
case FILTER_BRIGHTNESS:
{
if (gen_count == 1)
{
obj = heap_alloc(sizeof(f_brightness_t));
if (!obj)
return NULL;
f_brightness_init((f_brightness_t *)obj, (generator_t*)gens[0]);
}
else
{
g_error = ERR_PARSE_FAILURE;
return NULL;
}
}
break;
case SRC_CONSTANT_COLOR:
{
if (color_count == 1)
{
obj = heap_alloc(sizeof(s_constant_color_t));
if (!obj)
return NULL;
s_constant_color_init((s_constant_color_t *)obj, &colors[0]);
}
else
{
g_error = ERR_PARSE_FAILURE;
return NULL;
}
}
break;
case SRC_RAND_COL_SEQ:
{
if (value_count == 2)
{
obj = heap_alloc(sizeof(s_random_color_seq_t));
if (!obj)
return NULL;
s_random_color_seq_init((s_random_color_seq_t *)obj, values[0], values[1]);
}
else
{
g_error = ERR_PARSE_FAILURE;
return NULL;
}
}
break;
case SRC_HSV:
{
if (gen_count > 0)
{
obj = heap_alloc(sizeof(s_hsv_t));
if (!obj)
return NULL;
if (gen_count > 2)
s_hsv_init((s_hsv_t *)obj, (generator_t*)gens[0], (generator_t*)gens[1], (generator_t*)gens[2]);
else
if (gen_count > 1)
s_hsv_init((s_hsv_t *)obj, (generator_t*)gens[0], (generator_t*)gens[1], NULL);
else
s_hsv_init((s_hsv_t *)obj, (generator_t*)gens[0], NULL, NULL);
}
else
{
g_error = ERR_PARSE_FAILURE;
return NULL;
}
}
break;
case SRC_RAINBOW:
{
if (gen_count == 1)
{
obj = heap_alloc(sizeof(s_rainbow_t));
if (!obj)
return NULL;
s_rainbow_init((s_rainbow_t *)obj, (generator_t*)gens[0]);
}
else
{
g_error = ERR_PARSE_FAILURE;
return NULL;
}
}
break;
case GEN_SQUARE:
{
if (value_count == 5)
{
obj = heap_alloc(sizeof(square_t));
if (!obj)
return NULL;
g_square_init(obj, g_square, values[0], values[1], values[2], values[3], values[4]);
}
else
{
g_error = ERR_PARSE_FAILURE;
return NULL;
}
}
break;
case GEN_SIN:
{
if (value_count == 4)
{
obj = heap_alloc(sizeof(generator_t));
if (!obj)
return NULL;
g_sin_init(obj, g_sin, values[0], values[1], values[2], values[3]);
}
else
{
g_error = ERR_PARSE_FAILURE;
return NULL;
}
}
break;
case GEN_SAWTOOTH:
case GEN_STEP:
case GEN_LINE:
case GEN_IMPULSE:
{
if (value_count == 4)
{
obj = heap_alloc(sizeof(generator_t));
if (!obj)
return NULL;
switch(id)
{
case GEN_SIN:
g_generator_init(obj, g_sin, values[0], values[1], values[2], values[3]);
break;
case GEN_SAWTOOTH:
g_generator_init(obj, g_sawtooth, values[0], values[1], values[2], values[3]);
break;
case GEN_STEP:
g_generator_init(obj, g_step, values[0], values[1], values[2], values[3]);
break;
case GEN_LINE:
g_generator_init(obj, g_line, values[0], values[1], values[2], values[3]);
break;
case GEN_IMPULSE:
g_generator_init(obj, g_impulse, values[0], values[1], values[2], values[3]);
break;
}
}
else
{
g_error = ERR_PARSE_FAILURE;
return NULL;
}
}
break;
case FUNC_GENOP:
{
if (value_count == 1 && gen_count == 2)
{
obj = heap_alloc(sizeof(s_op_t));
if (!obj)
return NULL;
g_generator_op_init(obj, (uint8_t)values[0], (generator_t*)gens[0], (generator_t*)gens[1]);
}
else
{
g_error = ERR_PARSE_FAILURE;
return NULL;
}
}
break;
case FUNC_SRCOP:
{
if (value_count == 1 && gen_count == 2)
{
obj = heap_alloc(sizeof(s_op_t));
if (!obj)
return NULL;
s_op_init((s_op_t *)obj, (uint8_t)values[0], (s_source_t*)gens[0], (s_source_t*)gens[1]);
}
else
{
g_error = ERR_PARSE_FAILURE;
return NULL;
}
}
break;
case FUNC_ABS:
{
if (gen_count == 1)
{
obj = heap_alloc(sizeof(g_abs_t));
if (!obj)
return NULL;
g_abs_init(obj, (generator_t *)gens[0]);
}
else
{
g_error = ERR_PARSE_FAILURE;
return NULL;
}
}
break;
case GEN_CONSTANT:
{
if (value_count == 1)
{
obj = heap_alloc(sizeof(g_constant_t));
if (!obj)
return NULL;
g_constant_init((g_constant_t *)obj, values[0]);
}
else
{
g_error = ERR_PARSE_FAILURE;
return NULL;
}
}
break;
case FUNC_LOCAL_RANDOM:
{
*is_local = 1;
if (value_count == 2)
{
int32_t ret = fu_local_random(values[0], values[1]);
return (void *)ret;
}
else
{
g_error = ERR_PARSE_FAILURE;
return NULL;
}
}
break;
case FUNC_REPEAT_LOCAL_RANDOM:
{
*is_local = 1;
if (value_count == 1)
{
int32_t ret = fu_repeat_local_random(values[0] / SCALE_FACTOR);
return (void *)ret;
}
else
{
g_error = ERR_PARSE_FAILURE;
return NULL;
}
}
break;
}
return obj;
}
/*
| 1 byte | 2 bytes |
| ID - ARG | FUNC SIG | (
*/
void *parse_func(uint8_t *code, uint16_t len, uint16_t *index, uint8_t *is_local)
{
uint8_t id, num_args, i, arg, value_count = 0, gen_count = 0, color_count = 0;
uint16_t arg_index;
uint32_t args, value;
int32_t values[MAX_NUM_ARGS];
void *gens[MAX_NUM_ARGS], *ret;
color_t colors[MAX_NUM_ARGS];
id = code[*index] >> 3;
num_args = code[*index] & 0x7;
args = (code[*index + 2] << 8) | code[*index + 1];
arg_index = *index + 3;
for(i = 0; i < num_args; i++)
{
arg = (args >> (i * 2)) & 0x3;
if (arg == ARG_VALUE)
{
values[value_count++] = *((uint32_t *)&code[arg_index]);
arg_index += VALUE_SIZE;
}
else if (arg == ARG_FUNC)
{
uint8_t local = 0;
gens[gen_count++] = parse_func(code, len, &arg_index, &local);
if (local)
{
gen_count--;
values[value_count++] = (uint32_t)gens[gen_count];
}
}
else if (arg == ARG_COLOR)
{
colors[color_count].c[0] = code[arg_index++];
colors[color_count].c[1] = code[arg_index++];
colors[color_count++].c[2] = code[arg_index++];
}
else
if (arg == ARG_LOCAL)
{
switch(*((uint32_t *)&code[arg_index]))
{
case LOCAL_ID:
values[value_count++] = g_node_id;
break;
case LOCAL_POS_X:
values[value_count++] = g_pos[0];
break;
case LOCAL_POS_Y:
values[value_count++] = g_pos[1];
break;
case LOCAL_POS_Z:
values[value_count++] = g_pos[2];
break;
default:
g_error = ERR_PARSE_FAILURE;
return NULL;
}
arg_index += VALUE_SIZE;
}
}
*index = arg_index;
return create_object(id, is_local, values, value_count, gens, gen_count, colors, color_count);
}
void *parse(uint8_t *code, uint16_t len, uint8_t *heap)
{
void *source, *ptr, *filter;
uint16_t offset = 0;
uint8_t local;
heap_setup(heap);
clear_local_random_values();
source = parse_func(code, len, &offset, &local);
if (!source)
return NULL;
for(; offset < len;)
{
filter = parse_func(code, len, &offset, &local);
if (!filter)
return NULL;
ptr = (s_source_t *)source;
while (((f_filter_t *)ptr)->next)
ptr = ((f_filter_t *)ptr)->next;
((f_filter_t *)ptr)->next = filter;
}
return source;
}
void evaluate(s_source_t *src, uint32_t _t, color_t *color)
{
color_t temp, dest;
void *filter;
uint32_t t;
t = (_t * g_speed) / SCALE_FACTOR;
src->method((void *)src, t, &dest);
filter = src->next;
while(filter)
{
temp.c[0] = dest.c[0];
temp.c[1] = dest.c[1];
temp.c[2] = dest.c[2];
((f_filter_t *)filter)->method(filter, t, &temp, &dest);
filter = ((f_filter_t *)filter)->next;
}
color->c[0] = dest.c[0];
color->c[1] = dest.c[1];
color->c[2] = dest.c[2];
}
<|endoftext|> |
<commit_before>/*
* KatzIndex.cpp
*
* Created on: 30.01.2015
* Author: Kolja Esders (kolja.esders@student.kit.edu)
*/
#include <list>
#include "KatzIndex.h"
namespace NetworKit {
KatzIndex::KatzIndex(count maxPathLength, double dampingValue)
: maxPathLength(maxPathLength), dampingValue(dampingValue) {
calcDampingFactors();
}
KatzIndex::KatzIndex(const Graph& G, count maxPathLength, double dampingValue)
: LinkPredictor(G), maxPathLength(maxPathLength), dampingValue(dampingValue) {
calcDampingFactors();
}
double KatzIndex::getScore(node u, node v) const {
node endNode = lastStartNode == u ? v : u;
if (lastScores.find(endNode) == lastScores.end()) {
return 0;
}
return lastScores.at(endNode);
}
double KatzIndex::runImpl(node u, node v) {
if (validCache && (lastStartNode == u || lastStartNode == v)) {
return getScore(u, v);
}
lastScores.clear();
validCache = false;
std::list<node> toProcess;
// Start at the node with less neighbors to potentially increase performance
lastStartNode = G->degree(u) > G->degree(v) ? v : u;
toProcess.push_front(lastStartNode);
for (index pathLength = 1; pathLength <= maxPathLength; ++pathLength) {
std::unordered_map<node, count> hits;
for (std::list<node>::const_iterator it = toProcess.begin(); it != toProcess.end(); ++it) {
const node current = *it;
// TODO: Parallelize this part.
G->forNeighborsOf(current, [&](node neighbor) {
hits[neighbor] += 1;
});
}
// Add found nodes to the todo-list for the next round and update scores
toProcess.clear();
for (auto kv : hits) {
lastScores[kv.first] += dampingFactors[pathLength] * kv.second;
toProcess.push_front(kv.first);
}
}
validCache = true;
return getScore(u, v);
}
std::vector<LinkPredictor::node_dyad_score_pair> KatzIndex::runOnParallel(std::vector<std::pair<node, node>> nodePairs) {
// Make sure the nodePairs are sorted. This will make use of the caching of the Katz index
// and will exploit locality in the form of cpu caching as well.
std::sort(nodePairs.begin(), nodePairs.end());
std::vector<node_dyad_score_pair> predictions;
#pragma omp parallel
{
// Create local KatzIndex
KatzIndex katz(*G, maxPathLength, dampingValue);
std::vector<node_dyad_score_pair> predictionsPrivate;
#pragma omp for nowait
for (index i = 0; i < nodePairs.size(); ++i) {
predictionsPrivate.push_back(std::make_pair(nodePairs[i], katz.run(nodePairs[i].first, nodePairs[i].second)));
}
#pragma omp critical
predictions.insert(predictions.end(), predictionsPrivate.begin(), predictionsPrivate.end());
}
std::sort(predictions.begin(), predictions.end(), ConcreteNodeDyadScoreComp);
return predictions;
}
void KatzIndex::calcDampingFactors() {
dampingFactors.reserve(maxPathLength + 1);
dampingFactors[0] = 1;
for (count i = 1; i <= maxPathLength; ++i) {
dampingFactors[i] = std::pow(dampingValue, i);
}
}
} // namespace NetworKit<commit_msg>Increased Katz performance by ~25%<commit_after>/*
* KatzIndex.cpp
*
* Created on: 30.01.2015
* Author: Kolja Esders (kolja.esders@student.kit.edu)
*/
#include <list>
#include "KatzIndex.h"
namespace NetworKit {
KatzIndex::KatzIndex(count maxPathLength, double dampingValue)
: maxPathLength(maxPathLength), dampingValue(dampingValue) {
calcDampingFactors();
}
KatzIndex::KatzIndex(const Graph& G, count maxPathLength, double dampingValue)
: LinkPredictor(G), maxPathLength(maxPathLength), dampingValue(dampingValue) {
calcDampingFactors();
}
double KatzIndex::getScore(node u, node v) const {
node endNode = lastStartNode == u ? v : u;
if (lastScores.find(endNode) == lastScores.end()) {
return 0;
}
return lastScores.at(endNode);
}
double KatzIndex::runImpl(node u, node v) {
if (validCache && (lastStartNode == u || lastStartNode == v)) {
return getScore(u, v);
}
lastScores.clear();
validCache = false;
std::list<node> toProcess;
// Start at the node with less neighbors to potentially increase performance
lastStartNode = G->degree(u) > G->degree(v) ? v : u;
toProcess.push_front(lastStartNode);
for (index pathLength = 1; pathLength <= maxPathLength; ++pathLength) {
std::unordered_map<node, count> hits;
for (std::list<node>::const_iterator it = toProcess.begin(); it != toProcess.end(); ++it) {
const node current = *it;
// TODO: Parallelize this part.
G->forNeighborsOf(current, [&](node neighbor) {
hits[neighbor] += 1;
});
}
// Add found nodes to the todo-list for the next round and update scores
toProcess.clear();
for (auto kv : hits) {
lastScores[kv.first] += dampingFactors[pathLength] * kv.second;
toProcess.push_front(kv.first);
}
}
validCache = true;
return getScore(u, v);
}
std::vector<LinkPredictor::node_dyad_score_pair> KatzIndex::runOnParallel(std::vector<std::pair<node, node>> nodePairs) {
// Make sure the nodePairs are sorted. This will make use of the caching of the Katz index
// and will exploit locality in the form of cpu caching as well.
std::sort(nodePairs.begin(), nodePairs.end());
std::vector<node_dyad_score_pair> predictions(nodePairs.size());
KatzIndex katz(*G, maxPathLength, dampingValue);
#pragma omp parallel
{
KatzIndex katz(*G, maxPathLength, dampingValue);
#pragma omp for schedule(guided)
for (index i = 0; i < nodePairs.size(); ++i) {
predictions[i] = std::make_pair(nodePairs[i], katz.run(nodePairs[i].first, nodePairs[i].second));
}
}
return predictions;
}
void KatzIndex::calcDampingFactors() {
dampingFactors.reserve(maxPathLength + 1);
dampingFactors[0] = 1;
for (count i = 1; i <= maxPathLength; ++i) {
dampingFactors[i] = std::pow(dampingValue, i);
}
}
} // namespace NetworKit<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.