text
stringlengths 8
6.88M
|
|---|
//===-- OR1KRegisterInfo.cpp - OR1K Register Information --------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the OR1K implementation of the TargetRegisterInfo class.
//
//===----------------------------------------------------------------------===//
#include "OR1K.h"
#include "OR1KRegisterInfo.h"
#include "OR1KSubtarget.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/RegisterScavenging.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Type.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Target/TargetFrameLowering.h"
#include "llvm/Target/TargetInstrInfo.h"
#define GET_REGINFO_TARGET_DESC
#include "OR1KGenRegisterInfo.inc"
using namespace llvm;
OR1KRegisterInfo::OR1KRegisterInfo(const TargetInstrInfo &tii)
: OR1KGenRegisterInfo(OR1K::R9), TII(tii) {
}
const uint16_t*
OR1KRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
const TargetFrameLowering *TFI = MF->getTarget().getFrameLowering();
return TFI->hasFP(*MF) ? CSR_FP_SaveList : CSR_SaveList;
}
BitVector OR1KRegisterInfo::getReservedRegs(const MachineFunction &MF) const {
BitVector Reserved(getNumRegs());
const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
Reserved.set(OR1K::R0);
Reserved.set(OR1K::R1);
if (TFI->hasFP(MF))
Reserved.set(OR1K::R2);
Reserved.set(OR1K::R9);
Reserved.set(OR1K::R10);
Reserved.set(OR1K::R16); // Global pointer
if (hasBasePointer(MF))
Reserved.set(getBaseRegister());
return Reserved;
}
bool
OR1KRegisterInfo::requiresRegisterScavenging(const MachineFunction &MF) const {
return true;
}
void
OR1KRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
int SPAdj, unsigned FIOperandNum,
RegScavenger *RS) const {
assert(SPAdj == 0 && "Unexpected");
MachineInstr &MI = *II;
MachineFunction &MF = *MI.getParent()->getParent();
const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
bool HasFP = TFI->hasFP(MF);
DebugLoc dl = MI.getDebugLoc();
int FrameIndex = MI.getOperand(FIOperandNum).getIndex();
int Offset = MF.getFrameInfo()->getObjectOffset(FrameIndex) +
MI.getOperand(FIOperandNum+1).getImm();
// Addressable stack objects are addressed using neg. offsets from fp
// or pos. offsets from sp/basepointer
if (!HasFP || (needsStackRealignment(MF) && FrameIndex >= 0))
Offset += MF.getFrameInfo()->getStackSize();
unsigned FrameReg = getFrameRegister(MF);
if (FrameIndex >= 0) {
if (hasBasePointer(MF))
FrameReg = getBaseRegister();
else if (needsStackRealignment(MF))
FrameReg = OR1K::R1;
}
// Replace frame index with a frame pointer reference.
// If the offset is small enough to fit in the immediate field, directly
// encode it.
// Otherwise scavenge a register and encode it in to a MOVHI - ORI sequence
if (!isInt<16>(Offset)) {
assert(RS && "Register scavenging must be on");
unsigned Reg = RS->FindUnusedReg(&OR1K::GPRRegClass);
if (!Reg)
Reg = RS->scavengeRegister(&OR1K::GPRRegClass, II, SPAdj);
assert(Reg && "Register scavenger failed");
// Reg = hi(offset) | lo(offset)
BuildMI(*MI.getParent(), II, dl, TII.get(OR1K::MOVHI), Reg)
.addImm((uint32_t)Offset >> 16);
BuildMI(*MI.getParent(), II, dl, TII.get(OR1K::ORI), Reg)
.addReg(Reg).addImm(Offset & 0xffffU);
// Reg = Reg + Sp
MI.setDesc(TII.get(OR1K::ADD));
MI.getOperand(FIOperandNum).ChangeToRegister(Reg, false, false, true);
MI.getOperand(FIOperandNum+1).ChangeToRegister(FrameReg, false);
return;
}
MI.getOperand(FIOperandNum).ChangeToRegister(FrameReg, false);
MI.getOperand(FIOperandNum+1).ChangeToImmediate(Offset);
}
void OR1KRegisterInfo::
processFunctionBeforeFrameFinalized(MachineFunction &MF) const {}
bool OR1KRegisterInfo::hasBasePointer(const MachineFunction &MF) const {
const MachineFrameInfo *MFI = MF.getFrameInfo();
// When we need stack realignment and there are dynamic allocas, we can't
// reference off of the stack pointer, so we reserve a base pointer.
if (needsStackRealignment(MF) && MFI->hasVarSizedObjects())
return true;
return false;
}
bool OR1KRegisterInfo::needsStackRealignment(const MachineFunction &MF) const {
const MachineFrameInfo *MFI = MF.getFrameInfo();
const Function *F = MF.getFunction();
unsigned StackAlign = MF.getTarget().getFrameLowering()->getStackAlignment();
return ((MFI->getMaxAlignment() > StackAlign) ||
F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
Attribute::StackAlignment));
}
unsigned OR1KRegisterInfo::getRARegister() const {
return OR1K::R9;
}
unsigned OR1KRegisterInfo::getFrameRegister(const MachineFunction &MF) const {
const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
return TFI->hasFP(MF) ? OR1K::R2 : OR1K::R1;
}
unsigned OR1KRegisterInfo::getBaseRegister() const {
return OR1K::R14;
}
unsigned OR1KRegisterInfo::getEHExceptionRegister() const {
llvm_unreachable("What is the exception register");
return 0;
}
unsigned OR1KRegisterInfo::getEHHandlerRegister() const {
llvm_unreachable("What is the exception handler register");
return 0;
}
|
class BrowningHP_DZ: M9
{
scope = 2;
displayName = $STR_DZ_WPN_BROWNING_HP_NAME;
descriptionShort = $STR_DZ_WPN_BROWNING_HP_DESC;
model = "\RH_de\RH_browninghp.p3d";
picture = "\RH_de\inv\browninghp.paa";
begin1[] = {"\RH_de\sound\browninghp.wss",0.794328,1,700};
soundBegin[] = {"begin1",1};
drySound[] = {"\ca\Weapons\Data\Sound\T33_dry_v1",0.01,1,20};
reloadMagazineSound[] = {"\RH_de\sound\p226_reload.wss",0.1,1,20};
magazines[] = {"13Rnd_9x19_BHP"};
};
|
class Ka60_GL_BASE_PMC;
class Ka60_GL_PMC: Ka60_GL_BASE_PMC {
class Turrets;
class MainTurret;
};
class Ka60_GL_PMC_DZ: Ka60_GL_PMC {
displayName = "$STR_VEH_NAME_KA60";
vehicleClass = "DayZ Epoch Vehicles";
scope = 2;
crew = "";
typicalCargo[] = {};
radartype = 0;
class TransportMagazines{};
class TransportWeapons{};
weapons[] = {"CMFlareLauncher"};
magazines[] = {"120Rnd_CMFlareMagazine"};
commanderCanSee = 2+16+32;
gunnerCanSee = 2+16+32;
driverCanSee = 2+16+32;
transportMaxWeapons = 20;
transportMaxMagazines = 120;
transportMaxBackpacks = 6;
fuelCapacity = 2200;
supplyRadius = 2.6;
class Turrets: Turrets
{
class MainTurret: MainTurret
{
body = "mainTurret";
gun = "mainGun";
minElev = -50;
maxElev = 30;
initElev = 0;
minTurn = 20;
maxTurn = 155;
initTurn = 80;
soundServo[] = {"",0.01,1.0};
animationSourceHatch = "";
stabilizedInAxes = "StabilizedInAxesBoth";
gunBeg = "muzzle_1";
gunEnd = "chamber_1";
turretInfoType = "RscWeaponZeroing";
discreteDistance[] = {300,400,500,600,700,800};
discreteDistanceInitIndex = 1;
gunnerForceOptics = 0;
weapons[] = {"PKTBC"};
maxHorizontalRotSpeed = 1.6;
maxVerticalRotSpeed = 1.6;
magazines[] = {"100Rnd_762x54_PK","100Rnd_762x54_PK","100Rnd_762x54_PK"};
gunnerName = $STR_POSITION_DOORGUNNER;
gunnerOpticsModel = "\ca\air_e\gunnerOptics_ah64";
gunnerAction = "Mi8_Gunner";
gunnerInAction = "Mi8_Gunner";
commanding = -2;
primaryGunner = 1;
class OpticsIn
{
class Wide
{
opticsDisplayName = "W";
initAngleX = 0;
minAngleX = -30;
maxAngleX = 30;
initAngleY = -10;
minAngleY = -100;
maxAngleY = 100;
initFov = 0.1;
minFov = 0.1;
maxFov = 0.1;
visionMode[] = {"Normal"};
gunnerOpticsModel = "\ca\air_e\gunnerOptics_ah64";
};
class Medium: Wide
{
opticsDisplayName = "M";
initFov = 0.063;
minFov = 0.063;
maxFov = 0.063;
gunnerOpticsModel = "\ca\air_e\gunnerOptics_ah64";
};
class Narrow: Wide
{
opticsDisplayName = "N";
gunnerOpticsModel = "\ca\air_e\gunnerOptics_ah64";
initFov = 0.019;
minFov = 0.019;
maxFov = 0.019;
};
};
class OpticsOut
{
class Monocular
{
initAngleX = 0;
minAngleX = -30;
maxAngleX = 30;
initAngleY = -10;
minAngleY = -100;
maxAngleY = 100;
initFov = 1.1;
minFov = 0.133;
maxFov = 1.1;
visionMode[] = {"Normal"};
gunnerOpticsModel = "";
gunnerOpticsEffect[] = {};
};
};
class ViewOptics
{
initAngleX = 0;
minAngleX = -30;
maxAngleX = 30;
initAngleY = 0;
minAngleY = -100;
maxAngleY = 100;
initFov = 0.7;
minFov = 0.25;
maxFov = 1.1;
};
gunnerCompartments = "Compartment1";
};
};
};
class Ka60_GL_PMC_DZE: Ka60_GL_PMC_DZ {
class Turrets: Turrets
{
class MainTurret: MainTurret
{
magazines[] = {};
};
};
class Upgrades
{
ItemHeliAVE[] = {"Ka60_GL_PMC_DZE1",{"ItemToolbox","ItemSolder_DZE"},{},{{"ItemHeliAVE",1},{"equip_metal_sheet",5},{"ItemScrews",1},{"ItemTinBar",1},{"equip_scrapelectronics",2},{"equip_floppywire",2}}};
};
};
class Ka60_GL_PMC_DZE1: Ka60_GL_PMC_DZE
{
displayName = "$STR_VEH_NAME_KA60+";
original = "Ka60_GL_PMC_DZE";
armor = 70;
damageResistance = 0.02078;
class Upgrades
{
ItemHeliLRK[] = {"Ka60_GL_PMC_DZE2",{"ItemToolbox","ItemSolder_DZE"},{},{{"ItemHeliLRK",1},{"PartGeneric",2},{"ItemScrews",1},{"ItemWoodCrateKit",1},{"ItemGunRackKit",1},{"ItemTinBar",1},{"equip_scrapelectronics",2},{"equip_floppywire",2}}};
};
};
class Ka60_GL_PMC_DZE2: Ka60_GL_PMC_DZE1
{
displayName = "$STR_VEH_NAME_KA60++";
transportMaxWeapons = 40;
transportMaxMagazines = 240;
transportMaxBackpacks = 12;
class Upgrades
{
ItemHeliTNK[] = {"Ka60_GL_PMC_DZE3",{"ItemToolbox","ItemSolder_DZE"},{},{{"ItemHeliTNK",1},{"PartFueltank",2},{"PartGeneric",2},{"ItemFuelBarrel",1},{"ItemTinBar",1},{"equip_scrapelectronics",1},{"equip_floppywire",1}}};
};
};
class Ka60_GL_PMC_DZE3: Ka60_GL_PMC_DZE2
{
displayName = "$STR_VEH_NAME_KA60+++";
fuelCapacity = 4500;
};
|
#include <iostream>
#include <fstream>
using namespace std;
class liczba_zad
{
int liczba;
public:
int odwroc_liczbe();
bool czy_suma_jest_palindromem();
private:
string zamien_liczbe_na_string();
string odwroc_liczbe_str(string liczbastr);
bool czy_palindrom_string(string liczbastr);
};
void liczba_zad::odwroc_liczbe()
{
string wynik = odwroc_liczbe_str(zamien_liczbe_na_string(liczba));
string str = wynik;
int liczba_druga = strtol(str.c_str(), nullptr, 10);
int suma = liczba_druga+liczba;
string suma1 = zamien_liczbe_na_string(suma);
}
void liczba::czy_suma_jest_palindromem()
{
bool tak_czy_nie = czy_palindrom_string(string suma1);
}
void liczba_zad::odwroc_liczbe_str(string liczba)
{
ifstream plik;
plik.open("liczby.txt");
while(plik.good())
{
plik>>liczba;
do
{
cout << liczba % 10;
liczba /= 10;
}
while (liczba);
}
}
void liczba_zad::czy_palindrom_string(string liczba)
{
int back = liczba.length()-1;
bool palindrome = true;
for (int i=0; i<liczba.length()/2 && palindrome; i++)
if (liczba[i] != liczba[back--])
palindrome = false;
return palindrome;
}
void liczba_zad::zamien_liczbe_na_string()
{
string str = to_string(liczba);
}
int main(int argc, char** argv)
{
liczba_zad l;
l.odwroc_liczbe();
l.czy_suma_jest_palindromem();
return 0;
}
|
#include "stdafx.h"
#include "ICMP.h"
BOOL ICMP::Write(BYTE *link)
{
IP::Write(link);
memcpy(link + 20, &m_type, 1);
memcpy(link + 21, &m_code, 1);
memcpy(link + 22, &m_checksum, 2);
memcpy(link + 24, &m_id, 2);
memcpy(link + 26, &m_seq, 2);
memcpy(link + 28, m_data, 64);
return TRUE;
}
BOOL ICMP::Read(BYTE *link)
{
IP::Read(link);
memcpy(&m_type, link + 20, 1);
memcpy(&m_code, link + 21, 1);
memcpy(&m_checksum, link + 22, 2);
memcpy(&m_id, link + 24, 2);
memcpy(&m_seq, link + 26, 2);
memcpy(m_data, link + 28, 64);
return TRUE;
}
void ICMP::setType(BYTE type)
{
m_type = type;
}
void ICMP::setCode(BYTE code)
{
m_code = code;
}
void ICMP::setChecksum(WORD checksum)
{
m_checksum = checksum;
}
void ICMP::setId(WORD id)
{
m_id = id;
}
void ICMP::setSeq(WORD seq)
{
m_seq = seq;
}
void ICMP::setData(BYTE data[])
{
memcpy(m_data, data, 64);
}
BYTE ICMP::getType() const
{
return m_type;
}
BYTE ICMP::getCode() const
{
return m_code;
}
WORD ICMP::getChecksum() const
{
return m_checksum;
}
WORD ICMP::getId() const
{
return m_id;
}
WORD ICMP::getSeq() const
{
return m_seq;
}
const BYTE *ICMP::getData() const
{
return m_data;
}
|
#ifndef POINTDECOLLECTE_H
#define POINTDECOLLECTE_H
#include <vector>
#include "produit.h"
#include "gestionnaireproduits.h"
class Producteur;
/** @brief La classe PointDeCollecte.
**
** Elle contient un constructeur, le lieu, un @ref GestionnaireProduits, et un bool qui définit si il est ouvert ou fermé.
**
** @version 1
**
** @author P. Marty, M. Labalette, A. Larcher
**/
class PointDeCollecte
{
private:
std::string lieu;
std::string jourCycle;
GestionnaireProduits produitsDuPC;
bool ouvert;
public:
/// @brief Le constructeur par défaut attribue la valeur passée en paramètre.
///
/// Constructeur de la classe PointDeCollecte
///
/// @param l lieux du point de collecte
PointDeCollecte(std::string l);
/// @brief Mets a jour la date du cycle
///
/// @param jour un string pour mettre a jour la nouvelle date
void setDate(std::string jour) { jourCycle = jour; };
/// @brief Recupere le lieu du point de collecte
///
/// @return le lieu du point de collecte
std::string getLocation() { return lieu; };
/// @brief ferme temporairement un point de collecte en mettant sa date a FERME
///
/// @param pc PointDeCollecte le point de collecte a fermer temporairement
void fermerPCTemp() { jourCycle = std::string("closed"); };
/// @brief Regarde si le point de collecte n'est pas fermer
///
/// @return True si le point de collecte n'est pas fermer
bool pcOpen() { return (jourCycle.compare(std::string("closed")) == 0); };
~PointDeCollecte();
};
#endif // POINTDECOLLECTE_H
|
#include <conio.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <math.h>
#include <locale.h>
#include <ctype.h>
int x = 0;
float p1,p2,media;
int main()
{
printf("\nInsira a p1\n");
scanf("%f",&p1);
p2=((15-p1)/2);
printf("\nO aluno precisa de %f pontos para ser aprovado",p2);
}
|
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the demonstration applications of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QDebug>
#include "scene.h"
#include <QtGui/qmatrix4x4.h>
#include <QtGui/qvector3d.h>
#include <cmath>
#include "3rdparty/fbm.h"
void checkGLErrors(const QString& prefix)
{
switch (glGetError()) {
case GL_NO_ERROR:
//qDebug() << prefix << tr("No error.");
break;
case GL_INVALID_ENUM:
qDebug() << prefix << QObject::tr("Invalid enum.");
break;
case GL_INVALID_VALUE:
qDebug() << prefix << QObject::tr("Invalid value.");
break;
case GL_INVALID_OPERATION:
qDebug() << prefix << QObject::tr("Invalid operation.");
break;
case GL_STACK_OVERFLOW:
qDebug() << prefix << QObject::tr("Stack overflow.");
break;
case GL_STACK_UNDERFLOW:
qDebug() << prefix << QObject::tr("Stack underflow.");
break;
case GL_OUT_OF_MEMORY:
qDebug() << prefix << QObject::tr("Out of memory.");
break;
default:
qDebug() << prefix << QObject::tr("Unknown error.");
break;
}
}
//============================================================================//
// Scene //
//============================================================================//
Scene::Scene(int width, int height, int maxTextureSize)
: m_distExp(600)
, m_frame(0)
, m_maxTextureSize(maxTextureSize)
, m_currentShader(0)
, m_currentTexture(0)
, m_dynamicCubemap(false)
, m_updateAllCubemaps(true)
, m_box(0)
, m_vertexShader(0)
, m_environmentShader(0)
, m_environmentProgram(0)
{
setSceneRect(0, 0, width, height); // устанавливаем прямоугольник отсечения сцены
m_trackBalls[0] = TrackBall(0.05f, QVector3D(0, 1, 0), TrackBall::Sphere); // создаём орбиту (вокруг оси Y) для центрального куба (правильного гексаэдра) (угловая скорость, ось, модель вращения)
m_trackBalls[1] = TrackBall(0.005f, QVector3D(0, 0, 1), TrackBall::Sphere); // создаём орбиту для кольца гексаэдров (вокруг оси Z)
m_trackBalls[2] = TrackBall(0.0f, QVector3D(0, 1, 0), TrackBall::Plane); // создаём орбиту для камеры ???
m_renderOptions = new RenderOptionsDialog; // создаём панель управления №1
m_renderOptions->move(20, 120); // перемещаем её в угол
m_renderOptions->resize(m_renderOptions->sizeHint()); // устанавливаем размер по рекомендованному
// с диалоговыми панелями сцена OpenGL общается через систему сигналов
connect(m_renderOptions, SIGNAL(dynamicCubemapToggled(int)), this, SLOT(toggleDynamicCubemap(int))); //
connect(m_renderOptions, SIGNAL(colorParameterChanged(QString,QRgb)), this, SLOT(setColorParameter(QString,QRgb)));
connect(m_renderOptions, SIGNAL(floatParameterChanged(QString,float)), this, SLOT(setFloatParameter(QString,float)));
connect(m_renderOptions, SIGNAL(textureChanged(int)), this, SLOT(setTexture(int)));
connect(m_renderOptions, SIGNAL(shaderChanged(int)), this, SLOT(setShader(int)));
// создаём панель управления №2, которая также общается посредством сигналов
m_itemDialog = new ItemDialog;
connect(m_itemDialog, SIGNAL(newItemTriggered(ItemDialog::ItemType)), this, SLOT(newItem(ItemDialog::ItemType)));
// формируем двухсторонний виджет панели управления
TwoSidedGraphicsWidget *twoSided = new TwoSidedGraphicsWidget(this);
twoSided->setWidget(0, m_renderOptions);
twoSided->setWidget(1, m_itemDialog);
// связываем его сигналами
connect(m_renderOptions, SIGNAL(doubleClicked()), twoSided, SLOT(flip()));
connect(m_itemDialog, SIGNAL(doubleClicked()), twoSided, SLOT(flip()));
// добавляем на сцену кубики QT
addItem(new QtBox(64, width - 64, height - 64));
addItem(new QtBox(64, width - 64, 64));
addItem(new QtBox(64, 64, height - 64));
addItem(new QtBox(64, 64, 64));
initGL(); // инициализируем OpenGL
// запускаем таймер анимации и привязываем его к обновлению сцены
m_timer = new QTimer(this);
m_timer->setInterval(20);
connect(m_timer, SIGNAL(timeout()), this, SLOT(update()));
m_timer->start();
///m_time.start(); /// закоментируем лишнюю неиспользуемую переменную
}
Scene::~Scene()
{
if (m_box)
delete m_box;
foreach (GLTexture *texture, m_textures)
if (texture) delete texture;
if (m_mainCubemap)
delete m_mainCubemap;
foreach (QGLShaderProgram *program, m_programs)
if (program) delete program;
if (m_vertexShader)
delete m_vertexShader;
foreach (QGLShader *shader, m_fragmentShaders)
if (shader) delete shader;
foreach (GLRenderTargetCube *rt, m_cubemaps)
if (rt) delete rt;
if (m_environmentShader)
delete m_environmentShader;
if (m_environmentProgram)
delete m_environmentProgram;
}
void Scene::initGL()
{
m_box = new GLRoundedBox(0.25f, 1.0f, 10); // рисуем кексаэдры
m_vertexShader = new QGLShader(QGLShader::Vertex); // создаём переменную шейдеров
m_vertexShader->compileSourceFile(QLatin1String(":/res/boxes/basic.vsh")); // компилируем шейдеры
// рисуем фон
const static char environmentShaderText[] = // шейдер для куба фона
"uniform samplerCube env;"
"void main() {"
"gl_FragColor = textureCube(env, gl_TexCoord[1].xyz);"
"}";
QStringList list; // формируем список текстур фона
list << ":/res/boxes/cubemap_posx.jpg" << ":/res/boxes/cubemap_negx.jpg" << ":/res/boxes/cubemap_posy.jpg"
<< ":/res/boxes/cubemap_negy.jpg" << ":/res/boxes/cubemap_posz.jpg" << ":/res/boxes/cubemap_negz.jpg";
m_environment = new GLTextureCube(list, qMin(1024, m_maxTextureSize)); // создаём куб фона
m_environmentShader = new QGLShader(QGLShader::Fragment); //
m_environmentShader->compileSourceCode(environmentShaderText);
m_environmentProgram = new QGLShaderProgram;
m_environmentProgram->addShader(m_vertexShader); // добавляем программу
m_environmentProgram->addShader(m_environmentShader); // к ней ещё одну (в GPU программа одна, это у нас она разбита)
m_environmentProgram->link();
// формируем текстурную маску из шума
const int NOISE_SIZE = 128; // for a different size, B and BM in fbm.c must also be changed
m_noise = new GLTexture3D(NOISE_SIZE, NOISE_SIZE, NOISE_SIZE);
QRgb *data = new QRgb[NOISE_SIZE * NOISE_SIZE * NOISE_SIZE];
memset(data, 0, NOISE_SIZE * NOISE_SIZE * NOISE_SIZE * sizeof(QRgb));
QRgb *p = data;
float pos[3];
for (int k = 0; k < NOISE_SIZE; ++k) {
pos[2] = k * (0x20 / (float)NOISE_SIZE);
for (int j = 0; j < NOISE_SIZE; ++j) {
for (int i = 0; i < NOISE_SIZE; ++i) {
for (int byte = 0; byte < 4; ++byte) {
pos[0] = (i + (byte & 1) * 16) * (0x20 / (float)NOISE_SIZE);
pos[1] = (j + (byte & 2) * 8) * (0x20 / (float)NOISE_SIZE);
*p |= (int)(128.0f * (noise3(pos) + 1.0f)) << (byte * 8);
}
++p;
}
}
}
m_noise->load(NOISE_SIZE, NOISE_SIZE, NOISE_SIZE, data);
delete[] data;
m_mainCubemap = new GLRenderTargetCube(512); //
QStringList filter; // фильтр выбора файлов
QList<QFileInfo> files; // список файлов
// Load all .png files as textures // загружаем все png файлы как текстуры (куда грузим??)
m_currentTexture = 0; // индекс текущей текстуры
filter = QStringList("*.png");
files = QDir(":/res/boxes/").entryInfoList(filter, QDir::Files | QDir::Readable); // наполняем список в соответствии с фильтром из файлов зарегистрированных как ресурс
foreach (QFileInfo file, files) { // для каждого файла
GLTexture *texture = new GLTexture2D(file.absoluteFilePath(), qMin(256, m_maxTextureSize), qMin(256, m_maxTextureSize)); // m_maxTextureSize определено 1024 в main.cpp, вот только qMin вернёт 256
if (texture->failed()) {
delete texture;
continue;
}
m_textures << texture; // ??? закидываем в массив текстур (куда закидываем???)
m_renderOptions->addTexture(file.baseName()); // с соответствующим индексом будет имя текстуры в панели управления
}
if (m_textures.size() == 0) // если не удалось запихать текстуры
m_textures << new GLTexture2D(qMin(64, m_maxTextureSize), qMin(64, m_maxTextureSize)); // ??? формируем текстуру по умолчанию???
// Load all .fsh files as fragment shaders // загружаем все фрагментные шейдеры
m_currentShader = 0; // указатель индекса текущего шейдера
filter = QStringList("*.fsh"); // устанавливаем маску выбора файлов
files = QDir(":/res/boxes/").entryInfoList(filter, QDir::Files | QDir::Readable); //
foreach (QFileInfo file, files) {
QGLShaderProgram *program = new QGLShaderProgram; // создаём новую программу для каждого файла
QGLShader* shader = new QGLShader(QGLShader::Fragment); // создаём новый шейдер для каждого файла
shader->compileSourceFile(file.absoluteFilePath()); // компилируем шейдеры
/// The program does not take ownership over the shaders, so store them in a vector so they can be deleted afterwards.
program->addShader(m_vertexShader); // комбинируем программу из уже созданной основной вертексной и дополнительными фрагментными программами
program->addShader(shader); //
if (!program->link()) { // линкуем программу (куда?)
qWarning("Failed to compile and link shader program");
qWarning("Vertex shader log:");
qWarning() << m_vertexShader->log();
qWarning() << "Fragment shader log ( file =" << file.absoluteFilePath() << "):";
qWarning() << shader->log();
qWarning("Shader program log:");
qWarning() << program->log();
delete shader;
delete program;
continue; // дальше обрабатывать файл бесполезно, возвращаемся к началу цикла
}
m_fragmentShaders << shader; // запихиваем фрагментный шейдер в массив фрагментных шейдеров
m_programs << program; // программу в массив программ
m_renderOptions->addShader(file.baseName()); // имя файлов в массив списка эффектов
program->bind(); // связываем программу (с чем???)
m_cubemaps << ((program->uniformLocation("env") != -1) // если в шейдерной программе есть переменная "env" то в массив (??? cubemaps)
? new GLRenderTargetCube(qMin(256, m_maxTextureSize)) : 0); // пихаем новый объект (??? карты текстур) либо 0
program->release(); // удаляем уже ненужный экземпляр программы
}
if (m_programs.size() == 0) // если с программами потерпели фиаско,
m_programs << new QGLShaderProgram; // ???? запихиваем в массив программу по умолчанию
m_renderOptions->emitParameterChanged(); // отсылаем сигналы изменения параметров отрисовки (для рисования)
}
static void loadMatrix(const QMatrix4x4& m) //// грузим массив данных из матрицы одного типа в другой
{
// static to prevent glLoadMatrixf to fail on certain drivers
static GLfloat mat[16];
const float *data = m.constData();
for (int index = 0; index < 16; ++index)
mat[index] = data[index];
glLoadMatrixf(mat); // грузим массив данных из матрицы одного типа в другой (зачем????)
}
/// Рисуем все кубики разом
// If one of the boxes should not be rendered, set excludeBox to its index.
// If the main box should not be rendered, set excludeBox to -1.
void Scene::renderBoxes(const QMatrix4x4 &view, int excludeBox)
{
QMatrix4x4 invView = view.inverted(); //
//excludeBox=2;
// If multi-texturing is supported, use three saplers.
//if (glActiveTexture) { // старьё выкидываем
glActiveTexture(GL_TEXTURE0);
m_textures[m_currentTexture]->bind();
glActiveTexture(GL_TEXTURE2);
m_noise->bind();
glActiveTexture(GL_TEXTURE1);
/*} else {
m_textures[m_currentTexture]->bind();
}*/
glDisable(GL_LIGHTING);
glDisable(GL_CULL_FACE); // без этого не отрисовывается фон, почему ???
QMatrix4x4 viewRotation(view); // создаём матрицу viewRotation из матрицы view
viewRotation(3, 0) = viewRotation(3, 1) = viewRotation(3, 2) = 0.0f; // инициализируем матрицу поворота
viewRotation(0, 3) = viewRotation(1, 3) = viewRotation(2, 3) = 0.0f; //
viewRotation(3, 3) = 1.0f;
loadMatrix(viewRotation); // грузим сформированную матрицу glLoadMatrixf(mat);
glScalef(20.0f, 20.0f, 20.0f); // растягиваем куб (сцены???) если взять 10, фигуры тонут, если взять 50, пропадает фон
// РИСУЕМ ФОН
// Don't render the environment if the environment texture can't be set for the correct sampler.
// if (glActiveTexture) { // старьё выкидываем
m_environment->bind();
m_environmentProgram->bind();
m_environmentProgram->setUniformValue("tex", GLint(0));
m_environmentProgram->setUniformValue("env", GLint(1));
m_environmentProgram->setUniformValue("noise", GLint(2));
m_box->draw();
m_environmentProgram->release();
m_environment->unbind();
//}
loadMatrix(view);
glEnable(GL_CULL_FACE);
glEnable(GL_LIGHTING);
// РИСУЕМ КРУГ ИЗ КУБОВ, по одному на каждую шейдерную программу
for (int i = 0; i < m_programs.size(); ++i) {
if (i == excludeBox)
continue;
glPushMatrix();
QMatrix4x4 m;
m.rotate(m_trackBalls[1].rotation());
glMultMatrixf(m.constData());
glRotatef(360.0f * i / m_programs.size(), 0.0f, 0.0f, 1.0f);
glTranslatef(2.0f, 0.0f, 0.0f);
glScalef(0.3f, 0.6f, 0.6f);
// if (glActiveTexture) { // старьё выкидываем
if (m_dynamicCubemap && m_cubemaps[i])
m_cubemaps[i]->bind();
else
m_environment->bind();
//}
m_programs[i]->bind();
m_programs[i]->setUniformValue("tex", GLint(0));
m_programs[i]->setUniformValue("env", GLint(1));
m_programs[i]->setUniformValue("noise", GLint(2));
m_programs[i]->setUniformValue("view", view);
m_programs[i]->setUniformValue("invView", invView);
m_box->draw();
m_programs[i]->release();
// if (glActiveTexture) { // старьё выкидываем
if (m_dynamicCubemap && m_cubemaps[i])
m_cubemaps[i]->unbind();
else
m_environment->unbind();
//}
glPopMatrix();
}
// РИСУЕМ ГЛАВНЫЙ КУБ
if (-1 != excludeBox) {
QMatrix4x4 m;
m.rotate(m_trackBalls[0].rotation()); // получаем текущую матрицу поворота
glMultMatrixf(m.constData());
// if (glActiveTexture) { // старьё выкидываем
if (m_dynamicCubemap)
m_mainCubemap->bind();
else
m_environment->bind();
//}
m_programs[m_currentShader]->bind();
m_programs[m_currentShader]->setUniformValue("tex", GLint(0));
m_programs[m_currentShader]->setUniformValue("env", GLint(1));
m_programs[m_currentShader]->setUniformValue("noise", GLint(2));
m_programs[m_currentShader]->setUniformValue("view", view);
m_programs[m_currentShader]->setUniformValue("invView", invView);
m_box->draw();
m_programs[m_currentShader]->release();
// if (glActiveTexture) { // старьё выкидываем
if (m_dynamicCubemap)
m_mainCubemap->unbind();
else
m_environment->unbind();
//}
}
// if (glActiveTexture) { // старьё выкидываем
glActiveTexture(GL_TEXTURE2);
m_noise->unbind();
glActiveTexture(GL_TEXTURE0);
//}
m_textures[m_currentTexture]->unbind();
}
void Scene::setStates()
{
//glClearColor(0.25f, 0.25f, 0.5f, 1.0f);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glEnable(GL_LIGHTING);
//glEnable(GL_COLOR_MATERIAL);
glEnable(GL_TEXTURE_2D);
glEnable(GL_NORMALIZE);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
setLights();
float materialSpecular[] = {0.5f, 0.5f, 0.5f, 1.0f};
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, materialSpecular);
glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 32.0f);
}
void Scene::setLights()
{
glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
float lightColour[] = {1.0f, 0.9f, 0.9f, 1.0f};
//float lightColour[] = {1.0f, 1.0f, 1.0f, 1.0f};
//float lightDir[] = {0.0f, 0.0f, 1.0f, 0.0f};
glLightfv(GL_LIGHT0, GL_DIFFUSE, lightColour);
//glLightfv(GL_LIGHT0, GL_SPECULAR, lightColour);
//glLightfv(GL_LIGHT0, GL_POSITION, lightDir);
glLightModelf(GL_LIGHT_MODEL_LOCAL_VIEWER, 1.0f);
glEnable(GL_LIGHT0);
}
void Scene::defaultStates()
{
//glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glDisable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
glDisable(GL_LIGHTING);
//glDisable(GL_COLOR_MATERIAL);
glDisable(GL_TEXTURE_2D);
glDisable(GL_LIGHT0);
glDisable(GL_NORMALIZE);
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glLightModelf(GL_LIGHT_MODEL_LOCAL_VIEWER, 0.0f);
float defaultMaterialSpecular[] = {0.0f, 0.0f, 0.0f, 1.0f};
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, defaultMaterialSpecular);
glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 0.0f);
}
void Scene::renderCubemaps()
{
// To speed things up, only update the cubemaps for the small cubes every N frames.
const int N = (m_updateAllCubemaps ? 1 : 3);
QMatrix4x4 mat;
GLRenderTargetCube::getProjectionMatrix(mat, 0.1f, 100.0f);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
loadMatrix(mat);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
QVector3D center;
for (int i = m_frame % N; i < m_cubemaps.size(); i += N) {
if (0 == m_cubemaps[i])
continue;
float angle = 2.0f * PI * i / m_cubemaps.size();
center = m_trackBalls[1].rotation().rotatedVector(QVector3D(std::cos(angle), std::sin(angle), 0.0f));
for (int face = 0; face < 6; ++face) {
m_cubemaps[i]->begin(face);
GLRenderTargetCube::getViewMatrix(mat, face);
QVector4D v = QVector4D(-center.x(), -center.y(), -center.z(), 1.0);
mat.setColumn(3, mat * v);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
renderBoxes(mat, i);
m_cubemaps[i]->end();
}
}
for (int face = 0; face < 6; ++face) {
m_mainCubemap->begin(face);
GLRenderTargetCube::getViewMatrix(mat, face);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
renderBoxes(mat, -1);
m_mainCubemap->end();
}
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
m_updateAllCubemaps = false;
}
void Scene::drawBackground(QPainter *painter, const QRectF &)
{
float width = float(painter->device()->width());
float height = float(painter->device()->height());
painter->beginNativePainting();
setStates();
if (m_dynamicCubemap)
renderCubemaps();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
qgluPerspective(60.0, width / height, 0.01, 15.0);
glMatrixMode(GL_MODELVIEW);
QMatrix4x4 view;
view.rotate(m_trackBalls[2].rotation());
view(2, 3) -= 2.0f * std::exp(m_distExp / 1200.0f);
renderBoxes(view);
defaultStates();
++m_frame;
painter->endNativePainting();
}
// ArcBall Rotation
// http://pmg.org.ru/nehe/nehe48.htm
// масштабируем, координаты мыши из диапазона [0…ширина], [0...высота] в диапазон [-1...1], [1...-1]
// (запомните, что мы меняем знак координаты Y, чтобы получить корректный результат в OpenGL)
QPointF Scene::pixelPosToViewPos(const QPointF& p)
{
return QPointF(2.0 * float(p.x()) / width() - 1.0,
1.0 - 2.0 * float(p.y()) / height());
}
void Scene::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
QGraphicsScene::mouseMoveEvent(event);
if (event->isAccepted())
return;
if (event->buttons() & Qt::LeftButton) {
m_trackBalls[0].move(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate());
event->accept();
} else {
m_trackBalls[0].release(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate());
}
if (event->buttons() & Qt::RightButton) {
m_trackBalls[1].move(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate());
event->accept();
} else {
m_trackBalls[1].release(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate());
}
if (event->buttons() & Qt::MidButton) {
m_trackBalls[2].move(pixelPosToViewPos(event->scenePos()), QQuaternion());
event->accept();
} else {
m_trackBalls[2].release(pixelPosToViewPos(event->scenePos()), QQuaternion());
}
}
void Scene::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
QGraphicsScene::mousePressEvent(event);
if (event->isAccepted())
return;
if (event->buttons() & Qt::LeftButton) {
m_trackBalls[0].push(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate());
event->accept(); // если убрать ничего не меняется, движение не компенсируется
qDebug() << "X=" << pixelPosToViewPos(event->scenePos()).x() << " Y=" << pixelPosToViewPos(event->scenePos()).y() << " x=" << event->scenePos().x() << " y=" << event->scenePos().y();
}
if (event->buttons() & Qt::RightButton) {
m_trackBalls[1].push(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate());
event->accept();
}
if (event->buttons() & Qt::MidButton) {
m_trackBalls[2].push(pixelPosToViewPos(event->scenePos()), QQuaternion());
event->accept();
}
}
void Scene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
QGraphicsScene::mouseReleaseEvent(event);
if (event->isAccepted())
return;
if (event->button() == Qt::LeftButton) {
m_trackBalls[0].release(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate());
event->accept();
}
if (event->button() == Qt::RightButton) {
m_trackBalls[1].release(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate());
event->accept();
}
if (event->button() == Qt::MidButton) {
m_trackBalls[2].release(pixelPosToViewPos(event->scenePos()), QQuaternion());
event->accept();
}
}
void Scene::wheelEvent(QGraphicsSceneWheelEvent * event)
{
QGraphicsScene::wheelEvent(event);
if (!event->isAccepted()) {
m_distExp += event->delta();
if (m_distExp < -8 * 120)
m_distExp = -8 * 120;
if (m_distExp > 10 * 120)
m_distExp = 10 * 120;
event->accept();
}
}
/// это моя вставка
QPointF point=QPointF(0,0); // задаём переменную точки смещения для задания угловой скорости и расчёта вектора оси вращения
void Scene::keyPressEvent(QKeyEvent *event)
{
QGraphicsScene::keyPressEvent(event);
if (event->isAccepted()) return; // блокирует приём обработанных сообщений, например из диалогового окна
m_trackBalls[0].push(QPointF(0,0), m_trackBalls[2].rotation().conjugate()); // воспользуемся уже имеющейся функцией запоминания текущей позиции сферы вращения
m_trackBalls[0].k_pressed=true; // указываем что работаем клавиатурой (по этому флагу задаётся время расчёта угловой скорости)
switch (event->key()) {
case Qt::Key_Up:
point.setY(point.y()+0.001); // устанавливаем координаты точки смещения
break;
case Qt::Key_Left:
point.setX(point.x()-0.001);
break;
case Qt::Key_Right:
point.setX(point.x()+0.001);
break;
case Qt::Key_Down:
point.setY(point.y()-0.001);
break;
case Qt::Key_W:
break;
case Qt::Key_S:
break;
case Qt::Key_A:
//--m_angle;
//if (m_angle<0) m_angle=359;
break;
case Qt::Key_D:
//++m_angle;
//if (m_angle>=360) m_angle=0;
break;
default:
break;
}
m_trackBalls[0].release(point, m_trackBalls[2].rotation().conjugate()); // вызываем функцию расчёта угловой скорости и расчёта вектора оси вращения
event->accept(); //блокируем передачу сообщения конкретно дальше по сцене
m_trackBalls[0].k_pressed=false; // сбрасываем флаг работы с клавиатурой
}//*/
/// *** это моя вставка end
void Scene::setShader(int index)
{
if (index >= 0 && index < m_fragmentShaders.size())
m_currentShader = index;
}
void Scene::setTexture(int index)
{
if (index >= 0 && index < m_textures.size())
m_currentTexture = index;
}
void Scene::toggleDynamicCubemap(int state)
{
if ((m_dynamicCubemap = (state == Qt::Checked)))
m_updateAllCubemaps = true;
}
void Scene::setColorParameter(const QString &name, QRgb color)
{
// set the color in all programs
foreach (QGLShaderProgram *program, m_programs) {
program->bind();
program->setUniformValue(program->uniformLocation(name), QColor(color));
program->release();
}
}
void Scene::setFloatParameter(const QString &name, float value)
{
// set the color in all programs
foreach (QGLShaderProgram *program, m_programs) {
program->bind();
program->setUniformValue(program->uniformLocation(name), value);
program->release();
}
}
void Scene::newItem(ItemDialog::ItemType type)
{
QSize size = sceneRect().size().toSize();
switch (type) {
case ItemDialog::QtBoxItem:
addItem(new QtBox(64, rand() % (size.width() - 64) + 32, rand() % (size.height() - 64) + 32));
break;
case ItemDialog::CircleItem:
addItem(new CircleItem(64, rand() % (size.width() - 64) + 32, rand() % (size.height() - 64) + 32));
break;
case ItemDialog::SquareItem:
addItem(new SquareItem(64, rand() % (size.width() - 64) + 32, rand() % (size.height() - 64) + 32));
break;
default:
break;
}
}
|
#include "ofApp.h"
using namespace cv;
using namespace ofxCv;
//--------------------------------------------------------------
void ofApp::setup(){
ofSetFullscreen(false);
ofSetVerticalSync(false);
ofSetFrameRate(200);
screenFbo.allocate(viewWidth, viewHeight);
screenFbo.begin();
ofClear(50, 0, 0, 255);
screenFbo.end();
silhouette.load("images/henryford.png");
//silhouettePos.set((viewWidth - silhouette.getWidth()) / 2, viewHeight - silhouette.getHeight());
silhouettePos.set(0);
//if (bDoHeadshots) {
// ofDirectory imgDir;
// imgDir.listDir("headshots");
// cout << "loading headshots..." << endl;
// for (int i = 0; i < (int)imgDir.size(); i++) {
// headshots.push_back(ofImage());
// cout << "loading " << imgDir.getPath(i) << endl;
// headshotFilenames.push_back(imgDir.getPath(i));
// headshots.back().load(imgDir.getPath(i));
// }
// cout << headshots.size() << " headshots loaded" << endl;
//}
aspect = viewWidth / viewHeight;
viewScale = 1.0f;
origin.set(300, 0);
bIsFullRes = true;
bShowCVPipeline = true;
// GUI SETUP
guiFilename = "settings.xml";
gui.setup("settings", guiFilename);
int guiWidth = 250;
gui.setPosition(15, 60);
gui.setSize(guiWidth, 60);
gui.add(saveFbo.setup("Save FBO to File", guiWidth));
saveFbo.addListener(this, &ofApp::saveFboToFile);
gui.add(drawingLabel.setup(" DRAW TO SCREEN", ""));
gui.add(bDrawRaw.setup("Draw Raw Image", true, guiWidth));
gui.add(bDrawThreshold.setup("Draw Thresh Pixels", true, guiWidth));
gui.add(bDrawContours.setup("Draw ContourFinder", false, guiWidth));
gui.add(bDrawEdges.setup("Draw Canny Edges", false, guiWidth));
gui.add(bDrawPolyline.setup("Draw Outline", false, guiWidth));
gui.add(bDrawTriangles.setup("Draw Mesh Filled", false, guiWidth));
gui.add(bDrawTriangleWires.setup("Draw Mesh Wireframe", false, guiWidth));
gui.add(bDrawDelaunay.setup("Draw Delaunay", false, guiWidth));
gui.add(meshCompositionLabel.setup(" MESH COMPOSITION", ""));
gui.add(bAddOutlinePoints.setup("Add Outline Pts to Mesh", false));
gui.add(outlineSpacing.setup("Outline Resample Spacing", 10, 1, 100, guiWidth));
gui.add(bAddRandomPoints.setup("Add Random Pts to Mesh", false, guiWidth));
gui.add(numRandomPoints.setup("Num Randomized Points", 2000, 10, 8000, guiWidth));
gui.add(bAddCannyPoints.setup("Add Canny Edge Pts to Mesh", false, guiWidth));
gui.add(cannyThresh1.setup("Canny Thresh 1", 100, 0, 500, guiWidth));
gui.add(cannyThresh2.setup("Canny Thresh 2", 100, 0, 500, guiWidth));
gui.add(cannyCullRes.setup("Canny Cull Resolution", 10, 1, 20, guiWidth));
gui.add(bAddFeaturePoints.setup("Add CV Feature Pts to Mesh", false, guiWidth));
gui.add(sift_numFeatures.setup("SIFT features", 2000, 1, 3000, guiWidth));
gui.add(sift_octaveLayers.setup("SIFT octaves", 3, 1, 10, guiWidth));
gui.add(sift_contrastThresh.setup("SIFT contrast", 0.04, 0, 0.4, guiWidth));
gui.add(sift_edgeThresh.setup("SIFT edge", 10, 0, 100, guiWidth));
gui.add(sift_sigma.setup("SIFT sigma", 1.6, 0, 10, guiWidth));
gui.add(meshConstructionLabel.setup(" MESH CONSTRUCTION", ""));
gui.add(bResetMesh.setup("Reset Mesh", guiWidth));
bResetMesh.addListener(this, &ofApp::resetMesh);
//formatting
gui.setHeaderBackgroundColor(255);
//color applies to gui title only
gui.setDefaultTextColor(ofColor(255));
//color of the labels
drawingLabel.setDefaultTextColor(ofColor(0));
drawingLabel.setBackgroundColor(255);
meshCompositionLabel.setDefaultTextColor(ofColor(0));
meshCompositionLabel.setBackgroundColor(255);
meshConstructionLabel.setDefaultTextColor(ofColor(0));
meshConstructionLabel.setBackgroundColor(255);
gui.loadFromFile(guiFilename);
cout << "SETTINGS LOADED" << endl;
triangles = getTrisFromImg(silhouette);
}
void ofApp::resetMesh() {
triangles = getTrisFromImg(silhouette);
}
deque<Tri> ofApp::getTrisFromImg(ofImage &img) {
cout << "----------CREATING MESH----------" << endl;
cout << "Image dimensions: (" << img.getWidth() << ", " << img.getHeight() << ")" << endl;
meshPoints.clear();
randFillPts.clear();
featurePts.clear();
culledCanny.clear();
triangles.clear();
outlines.clear();
//go through the pixels of the image and get the points using the blob finder
ofPixels grayPix = img.getPixels();
//go through the pixels and drop any that are transparent
if (img.getPixels().getNumChannels() == 4) {
for (int i = 0; i < grayPix.getWidth() * grayPix.getHeight() * 4; i += 4) {
//if alpha isnt zero, set to white so we can threshold it
if (grayPix[i + 3] != 0) {
//make any black regions 1 at the very least
grayPix[i ] = MAX(1, grayPix[i ]);
grayPix[i + 1] = MAX(1, grayPix[i + 1]);
grayPix[i + 2] = MAX(1, grayPix[i + 2]);
} else {
grayPix[i] = 0;
grayPix[i + 1] = 0;
grayPix[i + 2] = 0;
}
}
}
//convert to grayscale
grayPix.setImageType(OF_IMAGE_GRAYSCALE);
silhouetteGray.setFromPixels(grayPix);
silhouetteGray.update();
ofxCv::threshold(grayPix, threshPix, 0);
//run through the contour finder
contours.setThreshold(254);
contours.setMinAreaRadius(10);
contours.setMaxAreaRadius(10000);
contours.setFindHoles(true);
contours.findContours(threshPix);
threshImg.setFromPixels(threshPix);
//go through the blobs and add the points to the vector
if(bAddOutlinePoints){
int totalPoints = 0;
for (int i = 0; i < contours.getContours().size(); i++) {
auto &pts = contours.getContour(i);
ofPolyline line;
for (int j = 0; j < pts.size(); j += 1) {
line.addVertex(toOf(pts[j]));
}
//cout << "Contour[" << i << "] is hole: " << contours.getHole(i) << endl;
line = line.getResampledBySpacing(outlineSpacing);
outlines.push_back(line);
//add the outline points to the meshPoints vector
meshPoints.insert(meshPoints.end(), outlines.back().getVertices().begin(), outlines.back().getVertices().end());
totalPoints += outlines.back().getVertices().size();
}
cout << "Outline points added: " << totalPoints << endl;
}
//--------------------add a bunch of points inside the silhouette--------------------
if (bAddRandomPoints) {
int pointsAdded = 0;
while(pointsAdded < numRandomPoints) {
ofPoint p(ofRandom(img.getWidth()), ofRandom(img.getHeight()));
if (threshPix[threshPix.getPixelIndex(p.x, p.y)] > 128) {
meshPoints.push_back(p);
randFillPts.push_back(p);
pointsAdded++;
//cout << "Random Point added: " << meshPoints.back() << endl;
}
}
cout << "Random points added: " << meshPoints.size() << endl;
}
//--------------------add points using OpenCV feature detection--------------------
if (bAddFeaturePoints) {
auto pts = findFeaturePoints(silhouetteGray);
for (auto &point : pts) {
ofPoint p( (int)point.x, (int)point.y, 0 );
bool validIndex = p.x >= 0 && p.x < threshPix.getWidth() && p.y >= 0 && p.y < threshPix.getHeight();
if (validIndex) {
if(threshPix[threshPix.getPixelIndex(p.x, p.y)] > 128) {
featurePts.push_back(p);
}
}
}
//remove duplicate entries
int pointsRemoved = 0;
for (int i = 0; i < featurePts.size(); i++) {
//loop from the last to current index
for (int j = featurePts.size()-1; j > i; j--) {
if (featurePts[i] == featurePts[j]) {
//cout << i << " == " << j << ", Removing feature point index: " << j << endl;
featurePts.erase(featurePts.begin() + j);
pointsRemoved++;
}
}
}
meshPoints.insert(meshPoints.end(), featurePts.begin(), featurePts.end());
cout << "Feature points added: " << featurePts.size() << " (removed "<<pointsRemoved<<" duplicates)" << endl;
}
//--------------------canny edge detection--------------------
if (bAddCannyPoints) {
Canny(silhouetteGray, canny, cannyThresh1, cannyThresh2);
canny.update();
//go through the canny image and black out pixels at a regular spacing
//THIS COULD TAKE A WHILE
ofPixels &cPix = canny.getPixels();
int w = cPix.getWidth();
int h = cPix.getHeight();
int num = w * h;
for(int i = 0; i < num; i++){
int x = i % w;
int y = (i - x)/w;
if (x % cannyCullRes == 0 && y % cannyCullRes == 0) {
//if this pixel is white
if (cPix[i] > 0) {
//add point to canny pts
culledCanny.push_back(ofPoint(x,y));
} else {
cPix[i] = 0;
}
}
}
canny.update();
cout << "Canny edge points added: " << culledCanny.size() << endl;;
//add canny points to mesh for triangulation
meshPoints.insert(meshPoints.end(), culledCanny.begin(), culledCanny.end());
}
cout << "Total Points added: " << meshPoints.size() << endl;
//do delaunay triangulation on found points
triangulation.reset();
triangulation.addPoints(meshPoints);
triangulation.triangulate();
//triangulation is done. steal the triangles from the mesh
ofMesh &mesh = triangulation.triangleMesh;
deque<Tri> tris;
for (int i = 0; i < mesh.getNumIndices(); i += 3) {
if (i < mesh.getNumIndices() - 2) {
ofPoint p1 = mesh.getVertex(mesh.getIndex(i ));
ofPoint p2 = mesh.getVertex(mesh.getIndex(i + 1));
ofPoint p3 = mesh.getVertex(mesh.getIndex(i + 2));
//only add triangles whose midpoint is
//INSIDE the silhouette of the image
ofPoint mid = (p1 + p2 + p3) / 3.0f;
bool validIndex = mid.x >= 0 && mid.x < threshPix.getWidth() && mid.y >= 0 && mid.y < threshPix.getHeight();
if (validIndex){
if(threshPix[threshPix.getPixelIndex(mid.x, mid.y)] > 128) {
Tri tri;
tri.setup(p1, p2, p3, img.getColor(mid.x, mid.y));
tris.push_back(tri);
}
}
}
}
cout << tris.size() << " triangles created" << endl;
return tris;
}
vector<ofPoint> ofApp::findFeaturePoints(ofImage & image) {
vector<ofPoint> points;
cv::Mat toProcess = ofxCv::toCv(image);
vector<cv::KeyPoint> objectKeypoints;
// Extract key points
// The detector can be any of (see OpenCV features2d.hpp):
// cv::FeatureDetector * detector = new cv::DenseFeatureDetector();
// cv::FeatureDetector * detector = new cv::FastFeatureDetector();
// cv::FeatureDetector * detector = new cv::GFTTDetector();
// cv::FeatureDetector * detector = new cv::MSER();
// cv::FeatureDetector * detector = new cv::ORB();
// cv::FeatureDetector * detector = new cv::StarFeatureDetector();
// cv::FeatureDetector * detector = new cv::SURF(600.0);
//const cv::SIFT::DetectorParams& detectorParams = cv::SIFT::DetectorParams(threshold, 10.0);
//cv::FeatureDetector * detector = new cv::SiftFeatureDetector(sift_numFeatures,
// sift_octaveLayers,
// sift_contrastThresh,
// sift_edgeThresh,
// sift_sigma);
//delete detector;
auto detector = make_shared<cv::SiftFeatureDetector>(sift_numFeatures,
sift_octaveLayers,
sift_contrastThresh,
sift_edgeThresh,
sift_sigma);
detector->detect(toProcess, objectKeypoints);
// convert to ofPoint vector
for (int i = 0, len = objectKeypoints.size(); i<len; i++) {
points.push_back(ofPoint(objectKeypoints[i].pt.x, objectKeypoints[i].pt.y));
}
return points;
}
//--------------------------------------------------------------
void ofApp::update(){
for (auto &tri : triangles) {
tri.update();
}
if (bShowCVPipeline) {
// if (bDrawContours) {
// contours.setThreshold(thresh);
// contours.setMinAreaRadius(minArea);
// contours.setMaxAreaRadius(maxArea);
// contours.setFindHoles(bFindHoles);
// contours.findContours(threshPix);
// }
if (bDrawEdges) {
Canny(silhouetteGray, canny, cannyThresh1, cannyThresh2);
canny.update();
}
}
}
void ofApp::drawContours() {
ofSetColor(255, 0, 0);
contours.draw();
for (int i = 0; i < contours.getContours().size(); i++) {
string s = "ID: " + ofToString(i) + "\nHole: " + ofToString(contours.getHole(i));
cv::Rect rect = contours.getBoundingRect(i);
ofVec2f pos = toOf(contours.getCentroid(i)) + ofVec2f(-rect.width / 2, rect.height / 2);
ofDrawBitmapString(s, pos);
}
}
void ofApp::renderToFbo(ofFbo &fbo) {
fbo.begin();
ofClear(0, 0, 0, 0);
ofPushMatrix();{
if (bDrawRaw) {
ofSetColor(255);
silhouette.draw(silhouettePos);
}
ofTranslate(silhouettePos);
//draw thresholded pixel object
if (bDrawThreshold) {
ofSetColor(255);
threshImg.draw(0, 0);
}
if (bDrawEdges) {
ofSetColor(0, 150, 0);
canny.draw(0,0);
}
if (bDrawPolyline) {
ofSetColor(255, 0, 0);
for (auto &line : outlines) {
line.draw();
}
}
if (bDrawContours) {
drawContours();
}
if (bDrawDelaunay) {
ofSetColor(0, 255, 0);
ofNoFill();
triangulation.draw();
}
if (bDrawTriangles) {
for (auto &tri : triangles) {
tri.draw();
}
}
if (bDrawTriangleWires) {
for (auto &tri : triangles) {
tri.drawWireframe();
//tri.drawMidPt();
}
}
} ofPopMatrix();
fbo.end();
}
void ofApp::saveFboToFile() {
ofFbo exportFbo;
exportFbo.allocate(silhouette.getWidth(), silhouette.getHeight());
exportFbo.begin();
ofClear(0,0,0,255);
exportFbo.end();
renderToFbo(exportFbo);
ofPixels tempPix;
tempPix.clear();
exportFbo.readToPixels(tempPix);
cout << "Saving FBO to file..." << endl;
ofSaveImage(tempPix, "saved_images/" + ofGetTimestampString() + ".png");
}
//--------------------------------------------------------------
void ofApp::draw(){
ofBackground(0);
if (bShowCVPipeline) {
//draw the different CV elements
int leftMargin = 275;
int w = silhouetteGray.getWidth();
int h = silhouetteGray.getHeight();
float scale = (ofGetWidth() - leftMargin)/(float)(w*5);
int titleY = h + 20/scale;
ofPushMatrix();{
ofTranslate(leftMargin, 0);
ofScale(scale, scale);
//base image
ofSetColor(255);
silhouetteGray.draw(0, 0);
ofDrawBitmapString("Raw Image", 0, titleY);
//threshold + contours
if (bAddCannyPoints) {
ofSetColor(0, 255, 0);
canny.draw(w, 0);
}
ofSetColor(255, 100);
threshImg.draw(w, 0);
ofPushMatrix();{
ofTranslate(w, 0);
drawContours();
}ofPopMatrix();
ofSetColor(255);
string s = "Threshold + \nContours";
if (bAddCannyPoints) s += " + \nCanny Edges";
ofDrawBitmapString(s, w, titleY);
//culled canny + polyline
ofPushMatrix();{
ofTranslate(w * 2, 0);
ofSetColor(255, 0, 0);
for (auto &line : outlines) {
line.draw();
}
ofSetCircleResolution(3);
ofSetColor(0, 128, 255);
for (auto &pt : randFillPts) {
ofDrawCircle(pt, 5);
}
ofSetColor(0, 255, 0);
for (auto &pt : culledCanny) {
ofDrawCircle(pt, 5);
}
ofSetColor(255, 200, 0);
for (auto &pt : featurePts) {
ofDrawCircle(pt, 5);
}
}ofPopMatrix();
ofSetColor(255);
string c = "";
if (outlines.size()) c += "\nContour Outline";
if (culledCanny.size()) c += "\nCulled Canny Pts (green)";
if (featurePts.size()) c += "\nCV Feature Pts (yellow)";
if (randFillPts.size()) c += "\nRandom Fill Pts (blue)";
ofDrawBitmapString(c, w * 2, titleY);
//delaunay triangulation
ofPushMatrix();{
ofTranslate(w * 3, 0);
ofSetColor(0, 255, 0);
ofNoFill();
triangulation.draw();
}ofPopMatrix();
ofSetColor(255);
ofDrawBitmapString("Delaunay Triangulation", w * 3, titleY);
//Triangle Mesh
ofPushMatrix();{
ofTranslate(w * 4, 0);
for (auto &tri : triangles) {
tri.draw();
}
}ofPopMatrix();
ofSetColor(255);
ofDrawBitmapString("Culled Triangles + \nColor Sampling", w * 4, titleY);
}ofPopMatrix();
} else {
renderToFbo(screenFbo);
//draw frame around fbo
ofSetColor(255);
screenFbo.draw(origin, viewWidth * viewScale, viewHeight * viewScale);
ofNoFill();
ofSetLineWidth(1);
ofDrawRectangle(origin, viewWidth * viewScale, viewHeight * viewScale);
}
ofSetColor(255);
ofDrawBitmapString("Framerate: " + ofToString(ofGetFrameRate(), 2), 15, 20);
ofDrawBitmapString("Num Triangles: " + ofToString(triangles.size()), 15, 35);
gui.draw();
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
if (key == 'l') {
gui.loadFromFile(guiFilename);
cout << "SETTINGS LOADED" << endl;
}
if (key == 's') {
gui.saveToFile(guiFilename);
cout << "SETTING SAVED" << endl;
}
if (key == '-') {
viewScale -= 0.05;
}
if (key == '=') {
viewScale += 0.05;
}
if (key == '0') {
if (bIsFullRes) {
//fit full screen
viewScale = ofGetHeight() / (float)viewHeight;
origin.set(300,0);
bIsFullRes = false;
} else {
viewScale = 1.0f;
bIsFullRes = true;
}
}
if (key == 'r') {
resetMesh();
}
if (key == OF_KEY_LEFT) {
origin.x += 50;
}
if (key == OF_KEY_RIGHT) {
origin.x -= 50;
}
if (key == OF_KEY_UP) {
origin.y += 50;
}
if (key == OF_KEY_DOWN) {
origin.y -= 50;
}
if (key == ' ') {
//ofToggleFullscreen();
//origin.set(0);
//viewScale = ofGetHeight() / (float)viewHeight;
bShowCVPipeline = !bShowCVPipeline;
}
//if (bDoHeadshots && headshots.size() > 0 && key == 'b') {
// ofFbo headshotFbo;
// headshotFbo.allocate(headshots[0].getWidth(), headshots[0].getHeight());
// ofPixels tempPix;
// for (int i = 0; i < headshots.size(); i++) {
// cout << "Processing " << headshotFilenames[i] << endl;
// deque<Tri> tris = getTrisFromImg(headshots[i]);
// headshotFbo.begin();
// ofClear(0,0,0,255);
// for (auto &t : tris) {
// t.draw();
// }
// headshotFbo.end();
// tempPix.clear();
// headshotFbo.readToPixels(tempPix);
// ofSaveImage(tempPix, "meshes/" + headshotFilenames[i]);
// }
//}
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
if (dragInfo.files.size() > 0) {
ofImage newImg;
newImg.load(dragInfo.files[0]);
triangles = getTrisFromImg(newImg);
silhouette = newImg;
}
}
|
#pragma once
#include "bricks/core/types.h"
#if BRICKS_CONFIG_LOGGING_ZOMBIES
#include "bricks/core/sfinae.h"
#endif
#include <stdlib.h>
namespace Bricks {
class Object;
class String;
namespace Internal {
class ReferenceCounter
{
private:
u32 referenceCount;
ReferenceCounter() : referenceCount(1) { }
ReferenceCounter(const ReferenceCounter& count) : referenceCount(1) { }
ReferenceCounter& operator =(const ReferenceCounter& count) { return *this; }
u32 operator ++(int) { return referenceCount++; }
u32 operator ++() { return ++referenceCount; }
u32 operator --() { return --referenceCount; }
u32 operator --(int) { return referenceCount--; }
operator u32() const { return referenceCount; }
friend class Bricks::Object;
};
}
class Object
{
private:
Internal::ReferenceCounter referenceCount;
protected:
Object(const Object& object) : referenceCount(object.referenceCount) { }
Object& operator =(const Object& object) { referenceCount = object.referenceCount; return *this; }
public:
Object() { BRICKS_FEATURE_LOG_HEAVY("> %p [%d]", this, GetReferenceCount());}
virtual ~Object() { BRICKS_FEATURE_LOG_HEAVY("< %p [%d]", this, GetReferenceCount()); }
#if BRICKS_ENV_RELEASE
void Retain() { referenceCount++; BRICKS_FEATURE_LOG_HEAVY("+ %p [%d]", this, GetReferenceCount()); }
void Release() { BRICKS_FEATURE_LOG_HEAVY("- %p [%d]", this, GetReferenceCount() - 1); if (!--referenceCount) delete this; }
#else
void Retain();
void Release();
#endif
#if BRICKS_CONFIG_LOGGING_ZOMBIES
void __BricksZombie();
template<typename T> static void __BricksZombie(T* value, typename SFINAE::EnableIf<SFINAE::IsCompatibleType<Object, T>::Value>::Type* dummy = NULL) { Object* obj = value; if (obj && !obj->GetReferenceCount()) obj->__BricksZombie(); }
template<typename T> static void __BricksZombie(T* value, typename SFINAE::DisableIf<SFINAE::IsCompatibleType<Object, T>::Value>::Type* dummy = NULL) { }
#endif
int GetReferenceCount() const { return referenceCount; }
virtual bool operator ==(const Object& rhs) const { return this == &rhs; }
virtual bool operator !=(const Object& rhs) const { return this != &rhs; }
void* operator new(size_t size) { return malloc(size); }
void operator delete(void* data) { free(data); }
virtual String GetDebugString() const;
// virtual int GetHash() const;
};
}
|
#ifndef ASS2_COMPLETE_H
#define ASS2_COMPLETE_H
#include "Question.h"
#include <bits/stdc++.h>
using namespace std;
class Complete : public Question
{
private:
static int Com_num;
int Q_ID;
public:
Complete()
{
Com_num++;
Q_ID = Q_num;
}
int getQuestionNumber()
{
return Com_num;
}
void setID(int ID)
{
Q_ID = ID;
}
int getID()
{
return Q_ID;
}
friend ostream &operator << (ostream &out, Complete& source);
};
int Complete::Com_num = 0;
ostream &operator << (ostream &out, Complete& source)
{
out<<"["<<++source.printedIDX<<"]"<<"(ID: "<<source.Q_ID<<") "<<source.question_text<<"\tAnswer: "<<source.correct_answer<<"\n";
return out;
}
#endif
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include "mp4v2/mp4v2.h"
#include "sps_pps_parser.h"
#include "Mp4Parser.h"
#define NL_LOGE printf
static unsigned const samplingFrequencyTable[16] = {
96000, 88200, 64000, 48000,
44100, 32000, 24000, 22050,
16000, 12000, 11025, 8000,
7350, 0, 0, 0
};
CMP4Parser::CMP4Parser()
:m_File(NULL),m_TrackId(0),m_FrameRate(25.0),m_Sps(NULL),m_Pps(NULL)
{
}
CMP4Parser::~CMP4Parser()
{
if(m_File != NULL)
{
MP4Close(m_File);
m_File = NULL;
}
if(m_Sps != NULL)
{
delete[] m_Sps;
m_Sps = NULL;
}
if(m_Pps != NULL)
{
delete[] m_Pps;
m_Pps = NULL;
}
}
int CMP4Parser::GetTrackCount()
{
if(m_File != NULL)
{
return MP4GetNumberOfTracks(m_File);
}
NL_LOGE("GetTrackCount error\n");
return -1;
}
int CMP4Parser::GetTrackFormat(int idx)
{
}
void CMP4Parser::ParserVideoParams()
{
uint8_t **seqheader;
uint8_t **pictheader;
uint32_t *seqheadersize;
uint32_t *pictheadersize;
MP4GetTrackH264SeqPictHeaders(m_File, m_TrackId, &seqheader, &seqheadersize, &pictheader,&pictheadersize);
NL_LOGE("sps %p %d",*seqheader, *seqheadersize);
for (int ix = 0; ix < *seqheadersize; ix++) {
NL_LOGE("%x ",(*seqheader)[ix]);
}
NL_LOGE("\n");
NL_LOGE("pps %p %d",*pictheader, *pictheadersize);
for (int ix = 0; ix < *pictheadersize; ix++) {
NL_LOGE("%x ",(*pictheader)[ix]);
}
NL_LOGE("\n");
//exit(0);
if(m_Sps != NULL)
{
delete[] m_Sps;
}
m_Sps = new uint8_t[(*seqheadersize) + 1];
memcpy(m_Sps, *seqheader, *seqheadersize);
m_SpsLen = *seqheadersize;
if(m_Pps != NULL)
{
delete[] m_Pps;
}
m_Pps = new uint8_t[(*pictheadersize) + 1];
memcpy(m_Pps, *pictheader, *pictheadersize);
m_PpsLen = *pictheadersize;
free(seqheader);
free(seqheadersize);
free(pictheader);
free(pictheadersize);
GetFrameRate();
}
void CMP4Parser::ParserAudioParams()
{
uint8_t *conf;
uint32_t confsize;
/*
MP4GetTrackESConfiguration(m_File, 1, &conf, &confsize);
NL_LOGE("conf %p %d :",conf, confsize);
for (int ix = 0; ix < confsize; ix++) {
NL_LOGE("%x ",(conf)[ix]);
}
NL_LOGE("\n");
*/
MP4GetTrackESConfiguration(m_File, 2, &conf, &confsize);
NL_LOGE("conf %p %d :",conf, confsize);
for (int ix = 0; ix < confsize; ix++) {
NL_LOGE("%x ",(conf)[ix]);
}
NL_LOGE("\n");
//audioSpecificConfig[0] = ((profile+1) << 3) | (sampling_frequency_index >> 1);
//audioSpecificConfig[1] = (sampling_frequency_index << 7) | (channel_configuration << 3);
m_profile = conf[0]>>3 & 0x1F;
m_channles = conf[1]>>3 & 0xF;
m_freIdx = ((conf[0] & 0x3) << 1) | (conf[1] >> 7 & 0x1);
NL_LOGE("profile:%d channles:%d freIdx:%d\n", m_profile, m_channles, m_freIdx);
/*
packet[0] = (byte)0xFF;
packet[1] = (byte)0xF9;
packet[2] = (byte)(((profile-1)<<6) + (freqIdx<<2) +(chanCfg>>2));
packet[3] = (byte)(((chanCfg&3)<<6) + (packetLen>>11));
packet[4] = (byte)((packetLen&0x7FF) >> 3);
packet[5] = (byte)(((packetLen&7)<<5) + 0x1F);
packet[6] = (byte)0xFC;
*/
free(conf);
m_FrameRate = (float)samplingFrequencyTable[m_freIdx]/1024.0;
}
int CMP4Parser::SelectTrack(int type)
{
if(m_File == NULL)
{
NL_LOGE("SelectTrack error\n");
return -1;
}
uint32_t numOfTracks = MP4GetNumberOfTracks(m_File);
NL_LOGE("numOfTracks %d \n", numOfTracks);
for (uint32_t id = 1; id <= numOfTracks; id++) {
const char* trackType = MP4GetTrackType(m_File, id);
NL_LOGE("trackType:%s\n",trackType);
if(type == 0)//video
{
if (MP4_IS_VIDEO_TRACK_TYPE(trackType)) {
m_TrackId = id;
m_CurSampleId = 1;
ParserVideoParams();
break;
}
}
else//audio
{
if (MP4_IS_AUDIO_TRACK_TYPE(trackType)) {
m_TrackId = id;
m_CurSampleId = 1;
ParserAudioParams();
break;
}
}
}
m_NumSamples = MP4GetTrackNumberOfSamples(m_File, m_TrackId);
return m_TrackId;
}
bool CMP4Parser::SetDataSource(char* file)
{
if (m_File != NULL) {
MP4Close(m_File);
}
m_File = MP4Read(file);
if(m_File == MP4_INVALID_FILE_HANDLE)
{
NL_LOGE("mp4 file read error");
return false;
}
return true;
}
bool CMP4Parser::UnselectTrack(int idx)
{
m_TrackId = 0;
m_CurSampleId = 1;
}
bool CMP4Parser::ReadSampleData(unsigned char* data, int& length, uint64_t& pts)
{
if(m_CurSampleId > m_NumSamples)
{
return false;
}
bool isIframe;
if (!MP4ReadSample(m_File, m_TrackId, m_CurSampleId, (uint8_t**)&data,(uint32_t*)&length, NULL, NULL, NULL, &isIframe)) {
NL_LOGE("read sampleId %u error\n", m_CurSampleId);
return false;
}
//char nalHeader[] = {0x00, 0x00, 0x00, 0x01};
//memcpy(data, nalHeader, 4);
pts = MP4GetSampleTime(m_File, m_TrackId, m_CurSampleId);
pts = pts*1000/(int)(m_FrameRate*1000);
NL_LOGE("read sampleSize %u isIframe:%d pts:%d\n", length, isIframe, pts);
m_CurSampleId++;
}
bool CMP4Parser::SeekTo()
{
return true;
}
float CMP4Parser::GetFrameRate()
{
if(m_Sps == NULL)
{
NL_LOGE("m_Sps == NULL\n");
//exit(0);
return 0.0;
}
float fps = 0.0;
get_bit_context buffer;
memset(&buffer, 0, sizeof(get_bit_context));
SPS _sps;
buffer.buf = m_Sps + 1;
buffer.buf_size = m_SpsLen-1;
int ret = h264dec_seq_parameter_set(&buffer, &_sps);
int m_nWidth = h264_get_width(&_sps);
int m_nHeight = h264_get_height(&_sps);
ret = h264_get_framerate(&fps, &_sps);
NL_LOGE("m_nWidth:%d m_nHeight:%d fps:%f\n",m_nWidth, m_nHeight, fps);
//exit(0);
if (ret == 0)
{
m_FrameRate = fps;
}
return fps;
}
bool CMP4Parser::GetSpsAndPps(u_int8_t* &sps, uint32_t& spsLen, u_int8_t* &pps,uint32_t& ppsLen)
{
if(m_Sps == NULL || m_Pps == NULL)
{
return false;
}
else
{
sps = m_Sps;
pps = m_Pps;
spsLen = m_SpsLen;
ppsLen = m_PpsLen;
}
return true;
}
|
// Copyright (c) 2021 ICHIRO ITS
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include <gtest/gtest.h>
#include <shisen_cpp/shisen_cpp.hpp>
TEST(CaptureSettingTest, FromMsg) {
shisen_cpp::CaptureSettingMsg msg;
msg.brightness.push_back(10);
msg.contrast.push_back(20);
msg.temperature.push_back(30);
msg.hue.push_back(40);
shisen_cpp::CaptureSetting capture_setting(msg);
ASSERT_TRUE(capture_setting.brightness.is_not_empty());
ASSERT_TRUE(capture_setting.contrast.is_not_empty());
ASSERT_TRUE(capture_setting.saturation.is_empty());
ASSERT_TRUE(capture_setting.temperature.is_not_empty());
ASSERT_TRUE(capture_setting.hue.is_not_empty());
ASSERT_TRUE(capture_setting.gain.is_empty());
ASSERT_EQ(10, capture_setting.brightness);
ASSERT_EQ(20, capture_setting.contrast);
ASSERT_EQ(30, capture_setting.temperature);
ASSERT_EQ(40, capture_setting.hue);
}
TEST(CaptureSettingTest, ToMsg) {
shisen_cpp::CaptureSetting capture_setting;
capture_setting.brightness = 10;
capture_setting.contrast = 20;
capture_setting.saturation = 30;
capture_setting.gain = 40;
shisen_cpp::CaptureSettingMsg msg = capture_setting;
ASSERT_EQ(1u, msg.brightness.size());
ASSERT_EQ(1u, msg.contrast.size());
ASSERT_EQ(1u, msg.saturation.size());
ASSERT_EQ(0u, msg.temperature.size());
ASSERT_EQ(0u, msg.hue.size());
ASSERT_EQ(1u, msg.gain.size());
ASSERT_EQ(10, msg.brightness.front());
ASSERT_EQ(20, msg.contrast.front());
ASSERT_EQ(30, msg.saturation.front());
ASSERT_EQ(40, msg.gain.front());
}
TEST(CaptureSettingTest, UpdateWith) {
shisen_cpp::CaptureSetting a;
a.brightness = 10;
a.contrast = 20;
a.temperature = 30;
a.hue = 40;
shisen_cpp::CaptureSetting b;
b.brightness = 40;
b.contrast = 30;
b.saturation = 20;
b.gain = 10;
a.update_with(b);
ASSERT_EQ(40, a.brightness);
ASSERT_EQ(30, a.contrast);
ASSERT_EQ(20, a.saturation);
ASSERT_EQ(30, a.temperature);
ASSERT_EQ(40, a.hue);
ASSERT_EQ(10, a.gain);
}
|
#include <iostream>
#include <string>
#include <cstdio>
#include <memory.h>
#include <string.h>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <algorithm>
#include <functional>
#include <climits>
typedef long long LL;
typedef long long ll;
typedef unsigned long long ULL;
typedef unsigned long long ull;
typedef unsigned uint;
typedef long double LD;
typedef long double ld;
const LD PI = 3.1415926535897932384626433832795;
template<typename T>
T sqr(const T& x) { return x * x; }
using namespace std;
const int N = 2222;
int n;
int a[N];
int s[N];
ll f[N][N];
bool alive[N];
ll point = -2000000;
struct cell {
ll first, second, value;
cell(ll a, ll b) {
first = a;
second = b;
value = a * point + b;
}
bool operator<(const cell& A) const {
return value < A.value;
}
};
int l[N], r[N];
priority_queue< pair<ld, pair<int, int> > > q;
vector< cell > g;
ld cur;
void doit(int x, int y) {
if (g[x].first == g[y].first) return;
ld t = ld(g[x].second - g[y].second) / (g[y].first - g[x].first);
if (t >= cur) q.push(make_pair(-t, make_pair(x, y)));
}
int main() {
//freopen("in","r", stdin);
//freopen(".out","w", stdout);
int n;
scanf("%d", &n);
for (int i = 1; i <= n; ++i) {
scanf("%d", a + i);
s[i] = s[i - 1] + a[i];
}
memset(f, 63 + 128, sizeof(f));
for (int i = 1; i <= n; ++i) f[1][i] = 0;
for (int i = 2; i <= n; ++i) {
memset(alive, true, sizeof(alive));
g.clear();
while (!q.empty()) q.pop();
cur = point;
for (int k = 1; k < i; ++k) {
g.push_back(cell(ll(s[i - 1] - s[k - 1]), f[k][i - 1]));
}
sort(g.begin(), g.end());
int m = g.size();
for (int j = 0; j < m; ++j) {
l[j] = j - 1;
r[j] = j + 1;
}
for (int j = 1; j < m; ++j) {
doit(j, l[j]);
}
vector< pair<ld, int> > cans;
int best = m - 1;
while (q.size()) {
ld t = -q.top().first;
int x = q.top().second.first;
int y = q.top().second.second;
q.pop();
if (t < cur || !alive[x] || !alive[y]) continue;
cans.push_back(make_pair(t, best));
if (g[x].first < g[y].first) swap(x, y);
int wasl = l[x];
int wasr = r[x];
if (l[y] != -1) r[ l[y] ] = r[y];
if (r[y] != m) l[ r[y] ] = l[y];
else best = l[y];
alive[y] = false;
if (l[x] != wasl && l[x] != -1) {
doit(x, l[x]);
}
if (r[x] != wasr && r[x] != m) {
doit(x, r[x]);
}
}
ld t = max(ld(-point), cur + 100);
cans.push_back(make_pair(t, best));
ll S = 0;
for (int j = i; j <= n; ++j) {
S += a[j];
int pos = lower_bound(cans.begin(), cans.end(), make_pair(ld(S), -1000)) - cans.begin();
int delta = 2;
for (int k = max(0, pos - delta); k < min(int(cans.size()), pos + delta); ++k) {
int who = cans[k].second;
f[i][j] = max(f[i][j], S * g[who].first + g[who].second);
}
}
}
/*
for (int i = 1; i <= n; ++i)
for (int j = i; j <= n; ++j) cerr << i << " " << j << ": " << f[i][j] << endl;
*/
ll ans = 0;
for (int i = 1; i <= n; ++i) ans = max(ans, f[i][n]);
cout << ans << endl;
//cerr << clock() << endl;
return 0;
}
|
// vnqdptd.cpp : 定义 DLL 应用程序的导出函数。
//
#include "vnqdptd.h"
///-------------------------------------------------------------------------------------
///从Python对象到C++类型转换用的函数
///-------------------------------------------------------------------------------------
void getInt(dict d, string key, int *value)
{
if (d.has_key(key)) //检查字典中是否存在该键值
{
object o = d[key]; //获取该键值
extract<int> x(o); //创建提取器
if (x.check()) //如果可以提取
{
*value = x(); //对目标整数指针赋值
}
}
}
void getDouble(dict d, string key, double *value)
{
if (d.has_key(key))
{
object o = d[key];
extract<double> x(o);
if (x.check())
{
*value = x();
}
}
}
void getStr(dict d, string key, char *value)
{
if (d.has_key(key))
{
object o = d[key];
extract<string> x(o);
if (x.check())
{
string s = x();
const char *buffer = s.c_str();
//对字符串指针赋值必须使用strcpy_s, vs2013使用strcpy编译通不过
//+1应该是因为C++字符串的结尾符号?不是特别确定,不加这个1会出错
#ifdef _MSC_VER //WIN32
strcpy_s(value, strlen(buffer) + 1, buffer);
#elif __GNUC__
strncpy(value, buffer, strlen(buffer) + 1);
#endif
}
}
}
void getChar(dict d, string key, char *value)
{
if (d.has_key(key))
{
object o = d[key];
extract<string> x(o);
if (x.check())
{
string s = x();
const char *buffer = s.c_str();
*value = *buffer;
}
}
}
///-------------------------------------------------------------------------------------
///C++的回调函数将数据保存到队列中
///-------------------------------------------------------------------------------------
void TdApi::OnFrontConnected()
{
Task task = Task();
task.task_name = ONFRONTCONNECTED;
this->task_queue.push(task);
};
void TdApi::OnFrontDisconnected(int nReason)
{
Task task = Task();
task.task_name = ONFRONTDISCONNECTED;
task.task_id = nReason;
this->task_queue.push(task);
};
void TdApi::OnHeartBeatWarning(int nTimeLapse)
{
Task task = Task();
task.task_name = ONHEARTBEATWARNING;
task.task_id = nTimeLapse;
this->task_queue.push(task);
};
void TdApi::OnRspUserLogin(CQdpFtdcRspUserLoginField *pRspUserLogin, CQdpFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
Task task = Task();
task.task_name = ONRSPUSERLOGIN;
if (pRspUserLogin)
{
task.task_data = *pRspUserLogin;
}
else
{
CQdpFtdcRspUserLoginField empty_data = CQdpFtdcRspUserLoginField();
memset(&empty_data, 0, sizeof(empty_data));
task.task_data = empty_data;
}
if (pRspInfo)
{
task.task_error = *pRspInfo;
}
else
{
CQdpFtdcRspInfoField empty_error = CQdpFtdcRspInfoField();
memset(&empty_error, 0, sizeof(empty_error));
task.task_error = empty_error;
}
task.task_id = nRequestID;
task.task_last = bIsLast;
this->task_queue.push(task);
};
void TdApi::OnRspUserLogout(CQdpFtdcRspUserLogoutField *pUserLogout, CQdpFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
Task task = Task();
task.task_name = ONRSPUSERLOGOUT;
if (pUserLogout)
{
task.task_data = *pUserLogout;
}
else
{
CQdpFtdcRspUserLogoutField empty_data = CQdpFtdcRspUserLogoutField();
memset(&empty_data, 0, sizeof(empty_data));
task.task_data = empty_data;
}
if (pRspInfo)
{
task.task_error = *pRspInfo;
}
else
{
CQdpFtdcRspInfoField empty_error = CQdpFtdcRspInfoField();
memset(&empty_error, 0, sizeof(empty_error));
task.task_error = empty_error;
}
task.task_id = nRequestID;
task.task_last = bIsLast;
this->task_queue.push(task);
};
void TdApi::OnRspUserPasswordUpdate(CQdpFtdcUserPasswordUpdateField *pUserPasswordUpdate, CQdpFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
Task task = Task();
task.task_name = ONRSPUSERPASSWORDUPDATE;
if (pUserPasswordUpdate)
{
task.task_data = *pUserPasswordUpdate;
}
else
{
CQdpFtdcUserPasswordUpdateField empty_data = CQdpFtdcUserPasswordUpdateField();
memset(&empty_data, 0, sizeof(empty_data));
task.task_data = empty_data;
}
if (pRspInfo)
{
task.task_error = *pRspInfo;
}
else
{
CQdpFtdcRspInfoField empty_error = CQdpFtdcRspInfoField();
memset(&empty_error, 0, sizeof(empty_error));
task.task_error = empty_error;
}
task.task_id = nRequestID;
task.task_last = bIsLast;
this->task_queue.push(task);
};
void TdApi::OnRspOrderInsert(CQdpFtdcInputOrderField *pInputOrder, CQdpFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
Task task = Task();
task.task_name = ONRSPORDERINSERT;
if (pInputOrder)
{
task.task_data = *pInputOrder;
}
else
{
CQdpFtdcInputOrderField empty_data = CQdpFtdcInputOrderField();
memset(&empty_data, 0, sizeof(empty_data));
task.task_data = empty_data;
}
if (pRspInfo)
{
task.task_error = *pRspInfo;
}
else
{
CQdpFtdcRspInfoField empty_error = CQdpFtdcRspInfoField();
memset(&empty_error, 0, sizeof(empty_error));
task.task_error = empty_error;
}
task.task_id = nRequestID;
task.task_last = bIsLast;
this->task_queue.push(task);
};
void TdApi::OnRspOrderAction(CQdpFtdcOrderActionField *pInputOrderAction, CQdpFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
Task task = Task();
task.task_name = ONRSPORDERACTION;
if (pInputOrderAction)
{
task.task_data = *pInputOrderAction;
}
else
{
CQdpFtdcOrderActionField empty_data = CQdpFtdcOrderActionField();
memset(&empty_data, 0, sizeof(empty_data));
task.task_data = empty_data;
}
if (pRspInfo)
{
task.task_error = *pRspInfo;
}
else
{
CQdpFtdcRspInfoField empty_error = CQdpFtdcRspInfoField();
memset(&empty_error, 0, sizeof(empty_error));
task.task_error = empty_error;
}
task.task_id = nRequestID;
task.task_last = bIsLast;
this->task_queue.push(task);
};
void TdApi::OnRspQryOrder(CQdpFtdcOrderField *pOrder, CQdpFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
Task task = Task();
task.task_name = ONRSPQRYORDER;
if (pOrder)
{
task.task_data = *pOrder;
}
else
{
CQdpFtdcOrderField empty_data = CQdpFtdcOrderField();
memset(&empty_data, 0, sizeof(empty_data));
task.task_data = empty_data;
}
if (pRspInfo)
{
task.task_error = *pRspInfo;
}
else
{
CQdpFtdcRspInfoField empty_error = CQdpFtdcRspInfoField();
memset(&empty_error, 0, sizeof(empty_error));
task.task_error = empty_error;
}
task.task_id = nRequestID;
task.task_last = bIsLast;
this->task_queue.push(task);
};
void TdApi::OnRspQryTrade(CQdpFtdcTradeField *pTrade, CQdpFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
Task task = Task();
task.task_name = ONRSPQRYTRADE;
if (pTrade)
{
task.task_data = *pTrade;
}
else
{
CQdpFtdcTradeField empty_data = CQdpFtdcTradeField();
memset(&empty_data, 0, sizeof(empty_data));
task.task_data = empty_data;
}
if (pRspInfo)
{
task.task_error = *pRspInfo;
}
else
{
CQdpFtdcRspInfoField empty_error = CQdpFtdcRspInfoField();
memset(&empty_error, 0, sizeof(empty_error));
task.task_error = empty_error;
}
task.task_id = nRequestID;
task.task_last = bIsLast;
this->task_queue.push(task);
};
void TdApi::OnRspQryUserInvestor(CQdpFtdcRspUserInvestorField *pUserInvestor, CQdpFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
Task task = Task();
task.task_name = ONRSPQRYUSERINVESTOR;
if (pUserInvestor)
{
task.task_data = *pUserInvestor;
}
else
{
CQdpFtdcRspUserInvestorField empty_data = CQdpFtdcRspUserInvestorField();
memset(&empty_data, 0, sizeof(empty_data));
task.task_data = empty_data;
}
if (pRspInfo)
{
task.task_error = *pRspInfo;
}
else
{
CQdpFtdcRspInfoField empty_error = CQdpFtdcRspInfoField();
memset(&empty_error, 0, sizeof(empty_error));
task.task_error = empty_error;
}
task.task_id = nRequestID;
task.task_last = bIsLast;
this->task_queue.push(task);
};
void TdApi::OnRspQryInvestorPosition(CQdpFtdcRspInvestorPositionField *pInvestorPosition, CQdpFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
Task task = Task();
task.task_name = ONRSPQRYINVESTORPOSITION;
if (pInvestorPosition)
{
task.task_data = *pInvestorPosition;
}
else
{
CQdpFtdcRspInvestorPositionField empty_data = CQdpFtdcRspInvestorPositionField();
memset(&empty_data, 0, sizeof(empty_data));
task.task_data = empty_data;
}
if (pRspInfo)
{
task.task_error = *pRspInfo;
}
else
{
CQdpFtdcRspInfoField empty_error = CQdpFtdcRspInfoField();
memset(&empty_error, 0, sizeof(empty_error));
task.task_error = empty_error;
}
task.task_id = nRequestID;
task.task_last = bIsLast;
this->task_queue.push(task);
};
void TdApi::OnRspQryInvestorAccount(CQdpFtdcRspInvestorAccountField *pInvestor, CQdpFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
Task task = Task();
task.task_name = ONRSPQRYINVESTOR;
if (pInvestor)
{
task.task_data = *pInvestor;
}
else
{
CQdpFtdcRspInvestorAccountField empty_data = CQdpFtdcRspInvestorAccountField();
memset(&empty_data, 0, sizeof(empty_data));
task.task_data = empty_data;
}
if (pRspInfo)
{
task.task_error = *pRspInfo;
}
else
{
CQdpFtdcRspInfoField empty_error = CQdpFtdcRspInfoField();
memset(&empty_error, 0, sizeof(empty_error));
task.task_error = empty_error;
}
task.task_id = nRequestID;
task.task_last = bIsLast;
this->task_queue.push(task);
};
void TdApi::OnRspQryExchange(CQdpFtdcRspExchangeField *pExchange, CQdpFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
Task task = Task();
task.task_name = ONRSPQRYEXCHANGE;
if (pExchange)
{
task.task_data = *pExchange;
}
else
{
CQdpFtdcRspExchangeField empty_data = CQdpFtdcRspExchangeField();
memset(&empty_data, 0, sizeof(empty_data));
task.task_data = empty_data;
}
if (pRspInfo)
{
task.task_error = *pRspInfo;
}
else
{
CQdpFtdcRspInfoField empty_error = CQdpFtdcRspInfoField();
memset(&empty_error, 0, sizeof(empty_error));
task.task_error = empty_error;
}
task.task_id = nRequestID;
task.task_last = bIsLast;
this->task_queue.push(task);
};
void TdApi::OnRspQryInstrument(CQdpFtdcRspInstrumentField *pInstrument, CQdpFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
Task task = Task();
task.task_name = ONRSPQRYINSTRUMENT;
if (pInstrument)
{
task.task_data = *pInstrument;
}
else
{
CQdpFtdcRspInstrumentField empty_data = CQdpFtdcRspInstrumentField();
memset(&empty_data, 0, sizeof(empty_data));
task.task_data = empty_data;
}
if (pRspInfo)
{
task.task_error = *pRspInfo;
}
else
{
CQdpFtdcRspInfoField empty_error = CQdpFtdcRspInfoField();
memset(&empty_error, 0, sizeof(empty_error));
task.task_error = empty_error;
}
task.task_id = nRequestID;
task.task_last = bIsLast;
this->task_queue.push(task);
};
void TdApi::OnRspQryMarketData(CQdpFtdcMarketDataField *pDepthMarketData, CQdpFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
Task task = Task();
task.task_name = ONRSPQRYDEPTHMARKETDATA;
if (pDepthMarketData)
{
task.task_data = *pDepthMarketData;
}
else
{
CQdpFtdcMarketDataField empty_data = CQdpFtdcMarketDataField();
memset(&empty_data, 0, sizeof(empty_data));
task.task_data = empty_data;
}
if (pRspInfo)
{
task.task_error = *pRspInfo;
}
else
{
CQdpFtdcRspInfoField empty_error = CQdpFtdcRspInfoField();
memset(&empty_error, 0, sizeof(empty_error));
task.task_error = empty_error;
}
task.task_id = nRequestID;
task.task_last = bIsLast;
this->task_queue.push(task);
};
void TdApi::OnRspQryTransferSerial(CQdpFtdcTransferSerialField *pTransferSerial, CQdpFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
Task task = Task();
task.task_name = ONRSPQRYTRANSFERSERIAL;
if (pTransferSerial)
{
task.task_data = *pTransferSerial;
}
else
{
CQdpFtdcTransferSerialField empty_data = CQdpFtdcTransferSerialField();
memset(&empty_data, 0, sizeof(empty_data));
task.task_data = empty_data;
}
if (pRspInfo)
{
task.task_error = *pRspInfo;
}
else
{
CQdpFtdcRspInfoField empty_error = CQdpFtdcRspInfoField();
memset(&empty_error, 0, sizeof(empty_error));
task.task_error = empty_error;
}
task.task_id = nRequestID;
task.task_last = bIsLast;
this->task_queue.push(task);
};
void TdApi::OnRspError(CQdpFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
Task task = Task();
task.task_name = ONRSPERROR;
if (pRspInfo)
{
task.task_error = *pRspInfo;
}
else
{
CQdpFtdcRspInfoField empty_error = CQdpFtdcRspInfoField();
memset(&empty_error, 0, sizeof(empty_error));
task.task_error = empty_error;
}
task.task_id = nRequestID;
task.task_last = bIsLast;
this->task_queue.push(task);
};
void TdApi::OnRtnOrder(CQdpFtdcOrderField *pOrder)
{
Task task = Task();
task.task_name = ONRTNORDER;
if (pOrder)
{
task.task_data = *pOrder;
}
else
{
CQdpFtdcOrderField empty_data = CQdpFtdcOrderField();
memset(&empty_data, 0, sizeof(empty_data));
task.task_data = empty_data;
}
this->task_queue.push(task);
};
void TdApi::OnRtnTrade(CQdpFtdcTradeField *pTrade)
{
Task task = Task();
task.task_name = ONRTNTRADE;
if (pTrade)
{
task.task_data = *pTrade;
}
else
{
CQdpFtdcTradeField empty_data = CQdpFtdcTradeField();
memset(&empty_data, 0, sizeof(empty_data));
task.task_data = empty_data;
}
this->task_queue.push(task);
};
void TdApi::OnErrRtnOrderInsert(CQdpFtdcInputOrderField *pInputOrder, CQdpFtdcRspInfoField *pRspInfo)
{
Task task = Task();
task.task_name = ONERRRTNORDERINSERT;
if (pInputOrder)
{
task.task_data = *pInputOrder;
}
else
{
CQdpFtdcInputOrderField empty_data = CQdpFtdcInputOrderField();
memset(&empty_data, 0, sizeof(empty_data));
task.task_data = empty_data;
}
if (pRspInfo)
{
task.task_error = *pRspInfo;
}
else
{
CQdpFtdcRspInfoField empty_error = CQdpFtdcRspInfoField();
memset(&empty_error, 0, sizeof(empty_error));
task.task_error = empty_error;
}
this->task_queue.push(task);
};
void TdApi::OnErrRtnOrderAction(CQdpFtdcOrderActionField *pOrderAction, CQdpFtdcRspInfoField *pRspInfo)
{
Task task = Task();
task.task_name = ONERRRTNORDERACTION;
if (pOrderAction)
{
task.task_data = *pOrderAction;
}
else
{
CQdpFtdcOrderActionField empty_data = CQdpFtdcOrderActionField();
memset(&empty_data, 0, sizeof(empty_data));
task.task_data = empty_data;
}
if (pRspInfo)
{
task.task_error = *pRspInfo;
}
else
{
CQdpFtdcRspInfoField empty_error = CQdpFtdcRspInfoField();
memset(&empty_error, 0, sizeof(empty_error));
task.task_error = empty_error;
}
this->task_queue.push(task);
};
void TdApi::OnRtnInstrumentStatus(CQdpFtdcInstrumentStatusField *pInstrumentStatus)
{
Task task = Task();
task.task_name = ONRTNINSTRUMENTSTATUS;
if (pInstrumentStatus)
{
task.task_data = *pInstrumentStatus;
}
else
{
CQdpFtdcInstrumentStatusField empty_data = CQdpFtdcInstrumentStatusField();
memset(&empty_data, 0, sizeof(empty_data));
task.task_data = empty_data;
}
this->task_queue.push(task);
};
void TdApi::OnRspQryContractBank(CQdpFtdcContractBankField *pContractBank, CQdpFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
Task task = Task();
task.task_name = ONRSPQRYCONTRACTBANK;
if (pContractBank)
{
task.task_data = *pContractBank;
}
else
{
CQdpFtdcContractBankField empty_data = CQdpFtdcContractBankField();
memset(&empty_data, 0, sizeof(empty_data));
task.task_data = empty_data;
}
if (pRspInfo)
{
task.task_error = *pRspInfo;
}
else
{
CQdpFtdcRspInfoField empty_error = CQdpFtdcRspInfoField();
memset(&empty_error, 0, sizeof(empty_error));
task.task_error = empty_error;
}
task.task_id = nRequestID;
task.task_last = bIsLast;
this->task_queue.push(task);
};
void TdApi::OnRtnFromBankToFutureByBank(CQdpFtdcRspTransferField *pRspTransfer)
{
Task task = Task();
task.task_name = ONRTNFROMBANKTOFUTUREBYBANK;
if (pRspTransfer)
{
task.task_data = *pRspTransfer;
}
else
{
CQdpFtdcRspTransferField empty_data = CQdpFtdcRspTransferField();
memset(&empty_data, 0, sizeof(empty_data));
task.task_data = empty_data;
}
this->task_queue.push(task);
};
void TdApi::OnRtnFromFutureToBankByBank(CQdpFtdcRspTransferField *pRspTransfer)
{
Task task = Task();
task.task_name = ONRTNFROMFUTURETOBANKBYBANK;
if (pRspTransfer)
{
task.task_data = *pRspTransfer;
}
else
{
CQdpFtdcRspTransferField empty_data = CQdpFtdcRspTransferField();
memset(&empty_data, 0, sizeof(empty_data));
task.task_data = empty_data;
}
this->task_queue.push(task);
};
void TdApi::OnRtnFromBankToFutureByFuture(CQdpFtdcRspTransferField *pRspTransfer)
{
Task task = Task();
task.task_name = ONRTNFROMBANKTOFUTUREBYFUTURE;
if (pRspTransfer)
{
task.task_data = *pRspTransfer;
}
else
{
CQdpFtdcRspTransferField empty_data = CQdpFtdcRspTransferField();
memset(&empty_data, 0, sizeof(empty_data));
task.task_data = empty_data;
}
this->task_queue.push(task);
};
void TdApi::OnRtnFromFutureToBankByFuture(CQdpFtdcRspTransferField *pRspTransfer)
{
Task task = Task();
task.task_name = ONRTNFROMFUTURETOBANKBYFUTURE;
if (pRspTransfer)
{
task.task_data = *pRspTransfer;
}
else
{
CQdpFtdcRspTransferField empty_data = CQdpFtdcRspTransferField();
memset(&empty_data, 0, sizeof(empty_data));
task.task_data = empty_data;
}
this->task_queue.push(task);
};
void TdApi::OnRtnQueryBankBalanceByFuture(CQdpFtdcNotifyQueryAccountField *pNotifyQueryAccount)
{
Task task = Task();
task.task_name = ONRTNQUERYBANKBALANCEBYFUTURE;
if (pNotifyQueryAccount)
{
task.task_data = *pNotifyQueryAccount;
}
else
{
CQdpFtdcNotifyQueryAccountField empty_data = CQdpFtdcNotifyQueryAccountField();
memset(&empty_data, 0, sizeof(empty_data));
task.task_data = empty_data;
}
this->task_queue.push(task);
};
void TdApi::OnErrRtnBankToFutureByFuture(CQdpFtdcReqTransferField *pReqTransfer, CQdpFtdcRspInfoField *pRspInfo)
{
Task task = Task();
task.task_name = ONERRRTNBANKTOFUTUREBYFUTURE;
if (pReqTransfer)
{
task.task_data = *pReqTransfer;
}
else
{
CQdpFtdcReqTransferField empty_data = CQdpFtdcReqTransferField();
memset(&empty_data, 0, sizeof(empty_data));
task.task_data = empty_data;
}
if (pRspInfo)
{
task.task_error = *pRspInfo;
}
else
{
CQdpFtdcRspInfoField empty_error = CQdpFtdcRspInfoField();
memset(&empty_error, 0, sizeof(empty_error));
task.task_error = empty_error;
}
this->task_queue.push(task);
};
void TdApi::OnErrRtnFutureToBankByFuture(CQdpFtdcReqTransferField *pReqTransfer, CQdpFtdcRspInfoField *pRspInfo)
{
Task task = Task();
task.task_name = ONERRRTNFUTURETOBANKBYFUTURE;
if (pReqTransfer)
{
task.task_data = *pReqTransfer;
}
else
{
CQdpFtdcReqTransferField empty_data = CQdpFtdcReqTransferField();
memset(&empty_data, 0, sizeof(empty_data));
task.task_data = empty_data;
}
if (pRspInfo)
{
task.task_error = *pRspInfo;
}
else
{
CQdpFtdcRspInfoField empty_error = CQdpFtdcRspInfoField();
memset(&empty_error, 0, sizeof(empty_error));
task.task_error = empty_error;
}
this->task_queue.push(task);
};
void TdApi::OnErrRtnQueryBankBalanceByFuture(CQdpFtdcReqQueryAccountField *pReqQueryAccount, CQdpFtdcRspInfoField *pRspInfo)
{
Task task = Task();
task.task_name = ONERRRTNQUERYBANKBALANCEBYFUTURE;
if (pReqQueryAccount)
{
task.task_data = *pReqQueryAccount;
}
else
{
CQdpFtdcReqQueryAccountField empty_data = CQdpFtdcReqQueryAccountField();
memset(&empty_data, 0, sizeof(empty_data));
task.task_data = empty_data;
}
if (pRspInfo)
{
task.task_error = *pRspInfo;
}
else
{
CQdpFtdcRspInfoField empty_error = CQdpFtdcRspInfoField();
memset(&empty_error, 0, sizeof(empty_error));
task.task_error = empty_error;
}
this->task_queue.push(task);
};
void TdApi::OnRspFromBankToFutureByFuture(CQdpFtdcReqTransferField *pReqTransfer, CQdpFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
Task task = Task();
task.task_name = ONRSPFROMBANKTOFUTUREBYFUTURE;
if (pReqTransfer)
{
task.task_data = *pReqTransfer;
}
else
{
CQdpFtdcReqTransferField empty_data = CQdpFtdcReqTransferField();
memset(&empty_data, 0, sizeof(empty_data));
task.task_data = empty_data;
}
if (pRspInfo)
{
task.task_error = *pRspInfo;
}
else
{
CQdpFtdcRspInfoField empty_error = CQdpFtdcRspInfoField();
memset(&empty_error, 0, sizeof(empty_error));
task.task_error = empty_error;
}
task.task_id = nRequestID;
task.task_last = bIsLast;
this->task_queue.push(task);
};
void TdApi::OnRspFromFutureToBankByFuture(CQdpFtdcReqTransferField *pReqTransfer, CQdpFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
Task task = Task();
task.task_name = ONRSPFROMFUTURETOBANKBYFUTURE;
if (pReqTransfer)
{
task.task_data = *pReqTransfer;
}
else
{
CQdpFtdcReqTransferField empty_data = CQdpFtdcReqTransferField();
memset(&empty_data, 0, sizeof(empty_data));
task.task_data = empty_data;
}
if (pRspInfo)
{
task.task_error = *pRspInfo;
}
else
{
CQdpFtdcRspInfoField empty_error = CQdpFtdcRspInfoField();
memset(&empty_error, 0, sizeof(empty_error));
task.task_error = empty_error;
}
task.task_id = nRequestID;
task.task_last = bIsLast;
this->task_queue.push(task);
};
void TdApi::OnRspQueryBankAccountMoneyByFuture(CQdpFtdcReqQueryAccountField *pReqQueryAccount, CQdpFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
Task task = Task();
task.task_name = ONRSPQUERYBANKACCOUNTMONEYBYFUTURE;
if (pReqQueryAccount)
{
task.task_data = *pReqQueryAccount;
}
else
{
CQdpFtdcReqQueryAccountField empty_data = CQdpFtdcReqQueryAccountField();
memset(&empty_data, 0, sizeof(empty_data));
task.task_data = empty_data;
}
if (pRspInfo)
{
task.task_error = *pRspInfo;
}
else
{
CQdpFtdcRspInfoField empty_error = CQdpFtdcRspInfoField();
memset(&empty_error, 0, sizeof(empty_error));
task.task_error = empty_error;
}
task.task_id = nRequestID;
task.task_last = bIsLast;
this->task_queue.push(task);
};
///-------------------------------------------------------------------------------------
///工作线程从队列中取出数据,转化为python对象后,进行推送
///-------------------------------------------------------------------------------------
void TdApi::processTask()
{
while (1)
{
Task task = this->task_queue.wait_and_pop();
switch (task.task_name)
{
case ONFRONTCONNECTED:
{
this->processFrontConnected(task);
break;
}
case ONFRONTDISCONNECTED:
{
this->processFrontDisconnected(task);
break;
}
case ONHEARTBEATWARNING:
{
this->processHeartBeatWarning(task);
break;
}
case ONRSPUSERLOGIN:
{
this->processRspUserLogin(task);
break;
}
case ONRSPUSERLOGOUT:
{
this->processRspUserLogout(task);
break;
}
case ONRSPUSERPASSWORDUPDATE:
{
this->processRspUserPasswordUpdate(task);
break;
}
case ONRSPTRADINGACCOUNTPASSWORDUPDATE:
{
this->processRspTradingAccountPasswordUpdate(task);
break;
}
case ONRSPORDERINSERT:
{
this->processRspOrderInsert(task);
break;
}
case ONRSPORDERACTION:
{
this->processRspOrderAction(task);
break;
}
case ONRSPQRYORDER:
{
this->processRspQryOrder(task);
break;
}
case ONRSPQRYTRADE:
{
this->processRspQryTrade(task);
break;
}
case ONRSPQRYINVESTORPOSITION:
{
this->processRspQryInvestorPosition(task);
break;
}
case ONRSPQRYTRADINGACCOUNT:
{
this->processRspQryInvestorAccount(task);
break;
}
case ONRSPQRYEXCHANGE:
{
this->processRspQryExchange(task);
break;
}
case ONRSPQRYINSTRUMENT:
{
this->processRspQryInstrument(task);
break;
}
case ONRSPQRYDEPTHMARKETDATA:
{
this->processRspQryMarketData(task);
break;
}
case ONRSPERROR:
{
this->processRspError(task);
break;
}
case ONRTNORDER:
{
this->processRtnOrder(task);
break;
}
case ONRTNTRADE:
{
this->processRtnTrade(task);
break;
}
case ONERRRTNORDERINSERT:
{
this->processErrRtnOrderInsert(task);
break;
}
case ONERRRTNORDERACTION:
{
this->processErrRtnOrderAction(task);
break;
}
case ONRTNINSTRUMENTSTATUS:
{
this->processRtnInstrumentStatus(task);
break;
}
case ONRTNFROMBANKTOFUTUREBYFUTURE:
{
this->processRtnFromBankToFutureByFuture(task);
break;
}
case ONRTNFROMFUTURETOBANKBYFUTURE:
{
this->processRtnFromFutureToBankByFuture(task);
break;
}
case ONRTNQUERYBANKBALANCEBYFUTURE:
{
this->processRtnQueryBankBalanceByFuture(task);
break;
}
case ONERRRTNBANKTOFUTUREBYFUTURE:
{
this->processErrRtnBankToFutureByFuture(task);
break;
}
case ONERRRTNFUTURETOBANKBYFUTURE:
{
this->processErrRtnFutureToBankByFuture(task);
break;
}
case ONERRRTNQUERYBANKBALANCEBYFUTURE:
{
this->processErrRtnQueryBankBalanceByFuture(task);
break;
}
case ONRSPFROMBANKTOFUTUREBYFUTURE:
{
this->processRspFromBankToFutureByFuture(task);
break;
}
case ONRSPFROMFUTURETOBANKBYFUTURE:
{
this->processRspFromFutureToBankByFuture(task);
break;
}
case ONRSPQUERYBANKACCOUNTMONEYBYFUTURE:
{
this->processRspQueryBankAccountMoneyByFuture(task);
break;
}
case ONRSPQRYUSERINVESTOR:
{
this->processRspQryUserInvestor(task);
break;
}
}
}
}
void TdApi::processFrontConnected(Task task)
{
PyLock lock;
this->onFrontConnected();
};
void TdApi::processFrontDisconnected(Task task)
{
PyLock lock;
this->onFrontDisconnected(task.task_id);
};
void TdApi::processHeartBeatWarning(Task task)
{
PyLock lock;
this->onHeartBeatWarning(task.task_id);
};
void TdApi::processRspUserLogin(Task task)
{
PyLock lock;
CQdpFtdcRspUserLoginField task_data = any_cast<CQdpFtdcRspUserLoginField>(task.task_data);
dict data;
data["MaxOrderLocalID"] = task_data.MaxOrderLocalID;
data["UserID"] = task_data.UserID;
data["TradingDay"] = task_data.TradingDay;
data["TradingSystemName"] = task_data.TradingSystemName;
data["BrokerID"] = task_data.BrokerID;
data["LoginTime"] = task_data.LoginTime;
data["FrontID"] = task_data.FrontID;
data["SessionID"] = task_data.SessionID;
CQdpFtdcRspInfoField task_error = any_cast<CQdpFtdcRspInfoField>(task.task_error);
dict error;
error["ErrorMsg"] = task_error.ErrorMsg;
error["ErrorID"] = task_error.ErrorID;
this->onRspUserLogin(data, error, task.task_id, task.task_last);
};
void TdApi::processRspUserLogout(Task task)
{
PyLock lock;
CQdpFtdcRspUserLogoutField task_data = any_cast<CQdpFtdcRspUserLogoutField>(task.task_data);
dict data;
data["UserID"] = task_data.UserID;
data["BrokerID"] = task_data.BrokerID;
CQdpFtdcRspInfoField task_error = any_cast<CQdpFtdcRspInfoField>(task.task_error);
dict error;
error["ErrorMsg"] = task_error.ErrorMsg;
error["ErrorID"] = task_error.ErrorID;
this->onRspUserLogout(data, error, task.task_id, task.task_last);
};
void TdApi::processRspUserPasswordUpdate(Task task)
{
PyLock lock;
CQdpFtdcUserPasswordUpdateField task_data = any_cast<CQdpFtdcUserPasswordUpdateField>(task.task_data);
dict data;
data["UserID"] = task_data.UserID;
data["NewPassword"] = task_data.NewPassword;
data["OldPassword"] = task_data.OldPassword;
data["BrokerID"] = task_data.BrokerID;
CQdpFtdcRspInfoField task_error = any_cast<CQdpFtdcRspInfoField>(task.task_error);
dict error;
error["ErrorMsg"] = task_error.ErrorMsg;
error["ErrorID"] = task_error.ErrorID;
this->onRspUserPasswordUpdate(data, error, task.task_id, task.task_last);
};
void TdApi::processRspTradingAccountPasswordUpdate(Task task)
{
PyLock lock;
CQdpFtdcUserPasswordUpdateField task_data = any_cast<CQdpFtdcUserPasswordUpdateField>(task.task_data);
dict data;
data["NewPassword"] = task_data.NewPassword;
data["OldPassword"] = task_data.OldPassword;
data["BrokerID"] = task_data.BrokerID;
data["UserID"] = task_data.UserID;
CQdpFtdcRspInfoField task_error = any_cast<CQdpFtdcRspInfoField>(task.task_error);
dict error;
error["ErrorMsg"] = task_error.ErrorMsg;
error["ErrorID"] = task_error.ErrorID;
this->onRspTradingAccountPasswordUpdate(data, error, task.task_id, task.task_last);
};
void TdApi::processRspOrderInsert(Task task)
{
PyLock lock;
CQdpFtdcInputOrderField task_data = any_cast<CQdpFtdcInputOrderField>(task.task_data);
dict data;
data["OffsetFlag"] = task_data.OffsetFlag;
data["UserID"] = task_data.UserID;
data["LimitPrice"] = task_data.LimitPrice;
data["Direction"] = task_data.Direction;
data["Volume"] = task_data.Volume;
data["OrderPriceType"] = task_data.OrderPriceType;
data["TimeCondition"] = task_data.TimeCondition;
data["IsAutoSuspend"] = task_data.IsAutoSuspend;
data["StopPrice"] = task_data.StopPrice;
data["InstrumentID"] = task_data.InstrumentID;
data["ExchangeID"] = task_data.ExchangeID;
data["MinVolume"] = task_data.MinVolume;
data["ForceCloseReason"] = task_data.ForceCloseReason;
data["BrokerID"] = task_data.BrokerID;
data["HedgeFlag"] = task_data.HedgeFlag;
data["GTDDate"] = task_data.GTDDate;
data["BusinessUnit"] = task_data.BusinessUnit;
data["UserOrderLocalID"] = task_data.UserOrderLocalID;
data["InvestorID"] = task_data.InvestorID;
data["VolumeCondition"] = task_data.VolumeCondition;
CQdpFtdcRspInfoField task_error = any_cast<CQdpFtdcRspInfoField>(task.task_error);
dict error;
error["ErrorMsg"] = task_error.ErrorMsg;
error["ErrorID"] = task_error.ErrorID;
this->onRspOrderInsert(data, error, task.task_id, task.task_last);
};
void TdApi::processRspQryUserInvestor(Task task)
{
PyLock lock;
CQdpFtdcRspUserInvestorField task_data = any_cast<CQdpFtdcRspUserInvestorField>(task.task_data);
dict data;
data["UserID"] = task_data.UserID;
data["BrokerID"] = task_data.BrokerID;
data["InvestorID"] = task_data.InvestorID;
CQdpFtdcRspInfoField task_error = any_cast<CQdpFtdcRspInfoField>(task.task_error);
dict error;
error["ErrorMsg"] = task_error.ErrorMsg;
error["ErrorID"] = task_error.ErrorID;
this->onRspQryUserInvestor(data, error, task.task_id, task.task_last);
};
void TdApi::processRspOrderAction(Task task)
{
PyLock lock;
CQdpFtdcOrderActionField task_data = any_cast<CQdpFtdcOrderActionField>(task.task_data);
dict data;
data["InstrumentID"] = task_data.InstrumentID;
data["ExchangeID"] = task_data.ExchangeID;
data["ActionFlag"] = task_data.ActionFlag;
data["UserOrderActionLocalID"] = task_data.UserOrderActionLocalID;
data["UserID"] = task_data.UserID;
data["LimitPrice"] = task_data.LimitPrice;
data["UserOrderLocalID"] = task_data.UserOrderLocalID;
data["InvestorID"] = task_data.InvestorID;
data["VolumeChange"] = task_data.VolumeChange;
data["BrokerID"] = task_data.BrokerID;
data["OrderSysID"] = task_data.OrderSysID;
CQdpFtdcRspInfoField task_error = any_cast<CQdpFtdcRspInfoField>(task.task_error);
dict error;
error["ErrorMsg"] = task_error.ErrorMsg;
error["ErrorID"] = task_error.ErrorID;
this->onRspOrderAction(data, error, task.task_id, task.task_last);
};
void TdApi::processRspQryOrder(Task task)
{
PyLock lock;
CQdpFtdcOrderField task_data = any_cast<CQdpFtdcOrderField>(task.task_data);
dict data;
data["VolumeTraded"] = task_data.VolumeTraded;
data["OffsetFlag"] = task_data.OffsetFlag;
data["UserID"] = task_data.UserID;
data["LimitPrice"] = task_data.LimitPrice;
data["Direction"] = task_data.Direction;
data["ParticipantID"] = task_data.ParticipantID;
data["Volume"] = task_data.Volume;
data["ClientID"] = task_data.ClientID;
data["OrderPriceType"] = task_data.OrderPriceType;
data["TimeCondition"] = task_data.TimeCondition;
data["OrderStatus"] = task_data.OrderStatus;
data["OrderSysID"] = task_data.OrderSysID;
data["IsAutoSuspend"] = task_data.IsAutoSuspend;
data["StopPrice"] = task_data.StopPrice;
data["InstrumentID"] = task_data.InstrumentID;
data["ExchangeID"] = task_data.ExchangeID;
data["MinVolume"] = task_data.MinVolume;
data["ForceCloseReason"] = task_data.ForceCloseReason;
data["TradingDay"] = task_data.TradingDay;
data["BrokerID"] = task_data.BrokerID;
data["InsertTime"] = task_data.InsertTime;
data["HedgeFlag"] = task_data.HedgeFlag;
data["CancelTime"] = task_data.CancelTime;
data["GTDDate"] = task_data.GTDDate;
data["OrderLocalID"] = task_data.OrderLocalID;
data["BranchID"] = task_data.BranchID;
data["BusinessUnit"] = task_data.BusinessUnit;
data["UserOrderLocalID"] = task_data.UserOrderLocalID;
data["InvestorID"] = task_data.InvestorID;
data["VolumeCondition"] = task_data.VolumeCondition;
data["OrderSource"] = task_data.OrderSource;
CQdpFtdcRspInfoField task_error = any_cast<CQdpFtdcRspInfoField>(task.task_error);
dict error;
error["ErrorMsg"] = task_error.ErrorMsg;
error["ErrorID"] = task_error.ErrorID;
this->onRspQryOrder(data, error, task.task_id, task.task_last);
};
void TdApi::processRspQryTrade(Task task)
{
PyLock lock;
CQdpFtdcTradeField task_data = any_cast<CQdpFtdcTradeField>(task.task_data);
dict data;
data["HedgeFlag"] = task_data.HedgeFlag;
data["TradeTime"] = task_data.TradeTime;
data["Direction"] = task_data.Direction;
data["ParticipantID"] = task_data.ParticipantID;
data["TradePrice"] = task_data.TradePrice;
data["ClientID"] = task_data.ClientID;
data["TradeVolume"] = task_data.TradeVolume;
data["OrderSysID"] = task_data.OrderSysID;
data["ClearingPartID"] = task_data.ClearingPartID;
data["InstrumentID"] = task_data.InstrumentID;
data["ExchangeID"] = task_data.ExchangeID;
data["UserID"] = task_data.UserID;
data["TradingDay"] = task_data.TradingDay;
data["BrokerID"] = task_data.BrokerID;
data["OffsetFlag"] = task_data.OffsetFlag;
data["TradeID"] = task_data.TradeID;
data["UserOrderLocalID"] = task_data.UserOrderLocalID;
data["InvestorID"] = task_data.InvestorID;
CQdpFtdcRspInfoField task_error = any_cast<CQdpFtdcRspInfoField>(task.task_error);
dict error;
error["ErrorMsg"] = task_error.ErrorMsg;
error["ErrorID"] = task_error.ErrorID;
this->onRspQryTrade(data, error, task.task_id, task.task_last);
};
void TdApi::processRspQryInvestorPosition(Task task)
{
PyLock lock;
CQdpFtdcRspInvestorPositionField task_data = any_cast<CQdpFtdcRspInvestorPositionField>(task.task_data);
dict data;
data["FrozenMargin"] = task_data.FrozenMargin;
data["HedgeFlag"] = task_data.HedgeFlag;
data["YdPosition"] = task_data.YdPosition;
data["ParticipantID"] = task_data.ParticipantID;
data["ClientID"] = task_data.ClientID;
data["Direction"] = task_data.Direction;
data["HedgeFlag"] = task_data.HedgeFlag;
data["UsedMargin"] = task_data.UsedMargin;
data["InstrumentID"] = task_data.InstrumentID;
data["Position"] = task_data.Position;
data["ExchangeID"] = task_data.ExchangeID;
data["PositionCost"] = task_data.PositionCost;
data["YdPosition"] = task_data.YdPosition;
data["YdPositionCost"] = task_data.YdPositionCost;
data["FrozenMargin"] = task_data.FrozenMargin;
data["FrozenPosition"] = task_data.FrozenPosition;
data["FrozenClosing"] = task_data.FrozenClosing;
data["PositionCost"] = task_data.PositionCost;
data["BrokerID"] = task_data.BrokerID;
data["FrozenPremium"] = task_data.FrozenPremium;
data["LastTradeID"] = task_data.LastTradeID;
data["LastOrderLocalID"] = task_data.LastOrderLocalID;
data["Currency"] = task_data.Currency;
CQdpFtdcRspInfoField task_error = any_cast<CQdpFtdcRspInfoField>(task.task_error);
dict error;
error["ErrorMsg"] = task_error.ErrorMsg;
error["ErrorID"] = task_error.ErrorID;
this->onRspQryInvestorPosition(data, error, task.task_id, task.task_last);
};
void TdApi::processRspQryInvestorAccount(Task task)
{
PyLock lock;
CQdpFtdcRspInvestorAccountField task_data = any_cast<CQdpFtdcRspInvestorAccountField>(task.task_data);
dict data;
data["Mortgage"] = task_data.Mortgage;
data["FrozenMargin"] = task_data.FrozenMargin;
data["PositionProfit"] = task_data.PositionProfit;
data["Fee"] = task_data.Fee;
data["AccountID"] = task_data.AccountID;
data["Available"] = task_data.Available;
data["BrokerID"] = task_data.BrokerID;
data["FrozenPremium"] = task_data.FrozenPremium;
data["Withdraw"] = task_data.Withdraw;
data["Balance"] = task_data.Balance;
data["Currency"] = task_data.Currency;
data["PreBalance"] = task_data.PreBalance;
data["Margin"] = task_data.Margin;
data["FrozenFee"] = task_data.FrozenFee;
data["CloseProfit"] = task_data.CloseProfit;
data["Deposit"] = task_data.Deposit;
CQdpFtdcRspInfoField task_error = any_cast<CQdpFtdcRspInfoField>(task.task_error);
dict error;
error["ErrorMsg"] = task_error.ErrorMsg;
error["ErrorID"] = task_error.ErrorID;
this->onRspQryInvestorAccount(data, error, task.task_id, task.task_last);
};
void TdApi::processRspQryExchange(Task task)
{
PyLock lock;
CQdpFtdcRspExchangeField task_data = any_cast<CQdpFtdcRspExchangeField>(task.task_data);
dict data;
data["TradingDay"] = task_data.TradingDay;
data["ExchangeID"] = task_data.ExchangeID;
data["ExchangeName"] = task_data.ExchangeName;
CQdpFtdcRspInfoField task_error = any_cast<CQdpFtdcRspInfoField>(task.task_error);
dict error;
error["ErrorMsg"] = task_error.ErrorMsg;
error["ErrorID"] = task_error.ErrorID;
this->onRspQryExchange(data, error, task.task_id, task.task_last);
};
void TdApi::processRspQryInstrument(Task task)
{
PyLock lock;
CQdpFtdcRspInstrumentField task_data = any_cast<CQdpFtdcRspInstrumentField>(task.task_data);
dict data;
data["IsTrading"] = task_data.IsTrading;
data["ExpireDate"] = task_data.ExpireDate;
data["StrikePrice"] = task_data.StrikePrice;
data["UnderlyingMultiple"] = task_data.UnderlyingMultiple;
data["PositionType"] = task_data.PositionType;
data["InstrumentName"] = task_data.InstrumentName;;
data["VolumeMultiple"] = task_data.VolumeMultiple;
data["DeliveryYear"] = task_data.DeliveryYear;
data["CreateDate"] = task_data.CreateDate;
data["InstrumentID"] = task_data.InstrumentID;
data["MaxLimitOrderVolume"] = task_data.MaxLimitOrderVolume;
data["ExchangeID"] = task_data.ExchangeID;
data["MinLimitOrderVolume"] = task_data.MinLimitOrderVolume;
data["MaxMarketOrderVolume"] = task_data.MaxMarketOrderVolume;
data["OptionsType"] = task_data.OptionsType;
data["StartDelivDate"] = task_data.StartDelivDate;
data["DeliveryMonth"] = task_data.DeliveryMonth;
data["PriceTick"] = task_data.PriceTick;
data["MinMarketOrderVolume"] = task_data.MinMarketOrderVolume;
data["EndDelivDate"] = task_data.EndDelivDate;
data["UnderlyingInstrID"] = task_data.UnderlyingInstrID;
data["OpenDate"] = task_data.OpenDate;
data["ProductID"] = task_data.ProductID;
CQdpFtdcRspInfoField task_error = any_cast<CQdpFtdcRspInfoField>(task.task_error);
dict error;
error["ErrorMsg"] = task_error.ErrorMsg;
error["ErrorID"] = task_error.ErrorID;
this->onRspQryInstrument(data, error, task.task_id, task.task_last);
};
void TdApi::processRspQryMarketData(Task task)
{
PyLock lock;
CQdpFtdcMarketDataField task_data = any_cast<CQdpFtdcMarketDataField>(task.task_data);
dict data;
data["HighestPrice"] = task_data.HighestPrice;
data["LowerLimitPrice"] = task_data.LowerLimitPrice;
data["OpenPrice"] = task_data.OpenPrice;
data["PreClosePrice"] = task_data.PreClosePrice;
data["PreSettlementPrice"] = task_data.PreSettlementPrice;
data["UpdateTime"] = task_data.UpdateTime;
data["PreOpenInterest"] = task_data.PreOpenInterest;;
data["Volume"] = task_data.Volume;
data["UpperLimitPrice"] = task_data.UpperLimitPrice;
data["InstrumentID"] = task_data.InstrumentID;
data["ExchangeID"] = task_data.ExchangeID;
data["TradingDay"] = task_data.TradingDay;
data["OpenInterest"] = task_data.OpenInterest;
data["LastPrice"] = task_data.LastPrice;
data["SettlementPrice"] = task_data.SettlementPrice;
data["LowestPrice"] = task_data.LowestPrice;
data["HighestPrice"] = task_data.HighestPrice;
CQdpFtdcRspInfoField task_error = any_cast<CQdpFtdcRspInfoField>(task.task_error);
dict error;
error["ErrorMsg"] = task_error.ErrorMsg;
error["ErrorID"] = task_error.ErrorID;
this->onRspQryMarketData(data, error, task.task_id, task.task_last);
};
void TdApi::processRspQryTransferSerial(Task task)
{
PyLock lock;
CQdpFtdcTransferSerialField task_data = any_cast<CQdpFtdcTransferSerialField>(task.task_data);
dict data;
data["BankNewAccount"] = task_data.BankNewAccount;
data["BrokerBranchID"] = task_data.BrokerBranchID;
data["OperatorCode"] = task_data.OperatorCode;
data["AccountID"] = task_data.AccountID;
data["BankAccount"] = task_data.BankAccount;
data["TradeCode"] = task_data.TradeCode;
data["SessionID"] = task_data.SessionID;
data["BankID"] = task_data.BankID;
data["PlateSerial"] = task_data.PlateSerial;
data["FutureAccType"] = task_data.FutureAccType;
data["ErrorID"] = task_data.ErrorID;
data["BankSerial"] = task_data.BankSerial;
data["IdentifiedCardNo"] = task_data.IdentifiedCardNo;
data["TradingDay"] = task_data.TradingDay;
data["BrokerID"] = task_data.BrokerID;
data["IdCardType"] = task_data.IdCardType;
data["TradeDate"] = task_data.TradeDate;
data["BrokerFee"] = task_data.BrokerFee;
data["BankAccType"] = task_data.BankAccType;
data["FutureSerial"] = task_data.FutureSerial;
data["InvestorID"] = task_data.InvestorID;
data["ErrorMsg"] = task_data.ErrorMsg;
data["CustFee"] = task_data.CustFee;
data["TradeAmount"] = task_data.TradeAmount;
data["AvailabilityFlag"] = task_data.AvailabilityFlag;
CQdpFtdcRspInfoField task_error = any_cast<CQdpFtdcRspInfoField>(task.task_error);
dict error;
error["ErrorMsg"] = task_error.ErrorMsg;
error["ErrorID"] = task_error.ErrorID;
this->onRspQryTransferSerial(data, error, task.task_id, task.task_last);
};
void TdApi::processRspError(Task task)
{
PyLock lock;
CQdpFtdcRspInfoField task_error = any_cast<CQdpFtdcRspInfoField>(task.task_error);
dict error;
error["ErrorMsg"] = task_error.ErrorMsg;
error["ErrorID"] = task_error.ErrorID;
this->onRspError(error, task.task_id, task.task_last);
};
void TdApi::processRtnOrder(Task task)
{
PyLock lock;
CQdpFtdcOrderField task_data = any_cast<CQdpFtdcOrderField>(task.task_data);
dict data;
data["VolumeTraded"] = task_data.VolumeTraded;
data["OffsetFlag"] = task_data.OffsetFlag;
data["UserID"] = task_data.UserID;
data["LimitPrice"] = task_data.LimitPrice;
data["Direction"] = task_data.Direction;
data["ParticipantID"] = task_data.ParticipantID;
data["Volume"] = task_data.Volume;
data["ClientID"] = task_data.ClientID;
data["OrderPriceType"] = task_data.OrderPriceType;
data["TimeCondition"] = task_data.TimeCondition;
data["OrderStatus"] = task_data.OrderStatus;
data["OrderSysID"] = task_data.OrderSysID;
data["IsAutoSuspend"] = task_data.IsAutoSuspend;
data["StopPrice"] = task_data.StopPrice;
data["InstrumentID"] = task_data.InstrumentID;
data["ExchangeID"] = task_data.ExchangeID;
data["MinVolume"] = task_data.MinVolume;
data["ForceCloseReason"] = task_data.ForceCloseReason;
data["TradingDay"] = task_data.TradingDay;
data["BrokerID"] = task_data.BrokerID;
data["InsertTime"] = task_data.InsertTime;
data["HedgeFlag"] = task_data.HedgeFlag;
data["CancelTime"] = task_data.CancelTime;
data["GTDDate"] = task_data.GTDDate;
data["OrderLocalID"] = task_data.OrderLocalID;
data["BranchID"] = task_data.BranchID;
data["BusinessUnit"] = task_data.BusinessUnit;
data["UserOrderLocalID"] = task_data.UserOrderLocalID;
data["InvestorID"] = task_data.InvestorID;
data["VolumeCondition"] = task_data.VolumeCondition;
data["OrderSource"] = task_data.OrderSource;
data["FrontID"] = task_data.FrontID;
data["SessionID"] = task_data.SessionID;
this->onRtnOrder(data);
};
void TdApi::processRtnTrade(Task task)
{
PyLock lock;
CQdpFtdcTradeField task_data = any_cast<CQdpFtdcTradeField>(task.task_data);
dict data;
data["HedgeFlag"] = task_data.HedgeFlag;
data["TradeTime"] = task_data.TradeTime;
data["Direction"] = task_data.Direction;
data["ParticipantID"] = task_data.ParticipantID;
data["TradePrice"] = task_data.TradePrice;
data["ClientID"] = task_data.ClientID;
data["SeatID"] = task_data.SeatID;
data["TradeVolume"] = task_data.TradeVolume;
data["OrderSysID"] = task_data.OrderSysID;
data["ClearingPartID"] = task_data.ClearingPartID;
data["InstrumentID"] = task_data.InstrumentID;
data["ExchangeID"] = task_data.ExchangeID;
data["UserID"] = task_data.UserID;
data["TradingDay"] = task_data.TradingDay;
data["BrokerID"] = task_data.BrokerID;
data["OffsetFlag"] = task_data.OffsetFlag;
data["TradeID"] = task_data.TradeID;
data["UserOrderLocalID"] = task_data.UserOrderLocalID;
data["InvestorID"] = task_data.InvestorID;
data["TradeAmnt"] = task_data.TradeAmnt;
this->onRtnTrade(data);
};
void TdApi::processErrRtnOrderInsert(Task task)
{
PyLock lock;
CQdpFtdcInputOrderField task_data = any_cast<CQdpFtdcInputOrderField>(task.task_data);
dict data;
data["OffsetFlag"] = task_data.OffsetFlag;
data["UserID"] = task_data.UserID;
data["LimitPrice"] = task_data.LimitPrice;
data["Direction"] = task_data.Direction;
data["Volume"] = task_data.Volume;
data["OrderPriceType"] = task_data.OrderPriceType;
data["TimeCondition"] = task_data.TimeCondition;
data["IsAutoSuspend"] = task_data.IsAutoSuspend;
data["StopPrice"] = task_data.StopPrice;
data["InstrumentID"] = task_data.InstrumentID;
data["ExchangeID"] = task_data.ExchangeID;
data["MinVolume"] = task_data.MinVolume;
data["ForceCloseReason"] = task_data.ForceCloseReason;
data["BrokerID"] = task_data.BrokerID;
data["HedgeFlag"] = task_data.HedgeFlag;
data["GTDDate"] = task_data.GTDDate;
data["BusinessUnit"] = task_data.BusinessUnit;
data["UserOrderLocalID"] = task_data.UserOrderLocalID;
data["InvestorID"] = task_data.InvestorID;
data["VolumeCondition"] = task_data.VolumeCondition;
CQdpFtdcRspInfoField task_error = any_cast<CQdpFtdcRspInfoField>(task.task_error);
dict error;
error["ErrorMsg"] = task_error.ErrorMsg;
error["ErrorID"] = task_error.ErrorID;
this->onErrRtnOrderInsert(data, error);
};
void TdApi::processErrRtnOrderAction(Task task)
{
PyLock lock;
CQdpFtdcOrderActionField task_data = any_cast<CQdpFtdcOrderActionField>(task.task_data);
dict data;
data["InvestorID"] = task_data.InvestorID;
data["UserID"] = task_data.UserID;
data["LimitPrice"] = task_data.LimitPrice;
data["UserOrderActionLocalID"] = task_data.UserOrderActionLocalID;
data["VolumeChange"] = task_data.VolumeChange;
data["ActionFlag"] = task_data.ActionFlag;
data["InstrumentID"] = task_data.InstrumentID;
data["ExchangeID"] = task_data.ExchangeID;;
data["OrderSysID"] = task_data.OrderSysID;
data["BrokerID"] = task_data.BrokerID;
data["UserOrderLocalID"] = task_data.UserOrderLocalID;
CQdpFtdcRspInfoField task_error = any_cast<CQdpFtdcRspInfoField>(task.task_error);
dict error;
error["ErrorMsg"] = task_error.ErrorMsg;
error["ErrorID"] = task_error.ErrorID;
this->onErrRtnOrderAction(data, error);
};
void TdApi::processRtnInstrumentStatus(Task task)
{
PyLock lock;
CQdpFtdcInstrumentStatusField task_data = any_cast<CQdpFtdcInstrumentStatusField>(task.task_data);
dict data;
data["InstrumentID"] = task_data.InstrumentID;
data["ExchangeID"] = task_data.ExchangeID;
data["InstrumentStatus"] = task_data.InstrumentStatus;
this->onRtnInstrumentStatus(data);
};
void TdApi::processRspQryContractBank(Task task)
{
PyLock lock;
CQdpFtdcContractBankField task_data = any_cast<CQdpFtdcContractBankField>(task.task_data);
dict data;
data["BankName"] = task_data.BankName;
data["BrokerID"] = task_data.BrokerID;
data["BankBrchID"] = task_data.BankBrchID;
data["BankID"] = task_data.BankID;
CQdpFtdcRspInfoField task_error = any_cast<CQdpFtdcRspInfoField>(task.task_error);
dict error;
error["ErrorMsg"] = task_error.ErrorMsg;
error["ErrorID"] = task_error.ErrorID;
this->onRspQryContractBank(data, error, task.task_id, task.task_last);
};
void TdApi::processRtnFromBankToFutureByBank(Task task)
{
PyLock lock;
CQdpFtdcRspTransferField task_data = any_cast<CQdpFtdcRspTransferField>(task.task_data);
dict data;
data["BrokerBranchID"] = task_data.BrokerBranchID;
data["UserID"] = task_data.UserID;
data["BankPassWord"] = task_data.BankPassWord;
data["VerifyCertNoFlag"] = task_data.VerifyCertNoFlag;
data["TID"] = task_data.TID;
data["AccountID"] = task_data.AccountID;
data["BankAccount"] = task_data.BankAccount;
data["InstallID"] = task_data.InstallID;
data["CustomerName"] = task_data.CustomerName;
data["TradeCode"] = task_data.TradeCode;
data["SessionID"] = task_data.SessionID;
data["BankID"] = task_data.BankID;
data["Password"] = task_data.Password;
data["BankPwdFlag"] = task_data.BankPwdFlag;
data["ErrorID"] = task_data.ErrorID;
data["RequestID"] = task_data.RequestID;
data["CustType"] = task_data.CustType;
data["IdentifiedCardNo"] = task_data.IdentifiedCardNo;
data["FeePayFlag"] = task_data.FeePayFlag;
data["BankSerial"] = task_data.BankSerial;
data["OperNo"] = task_data.OperNo;
data["TradingDay"] = task_data.TradingDay;
data["BankSecuAcc"] = task_data.BankSecuAcc;
data["BrokerID"] = task_data.BrokerID;
data["DeviceID"] = task_data.DeviceID;
data["TransferStatus"] = task_data.TransferStatus;
data["IdCardType"] = task_data.IdCardType;
data["PlateSerial"] = task_data.PlateSerial;
data["FutureFetchAmount"] = task_data.FutureFetchAmount;
data["TradeDate"] = task_data.TradeDate;
data["BrokerFee"] = task_data.BrokerFee;
data["BankAccType"] = task_data.BankAccType;
data["LastFragment"] = task_data.LastFragment;
data["FutureSerial"] = task_data.FutureSerial;
data["ErrorMsg"] = task_data.ErrorMsg;
data["BankSecuAccType"] = task_data.BankSecuAccType;
data["SecuPwdFlag"] = task_data.SecuPwdFlag;
data["Message"] = task_data.Message;
data["CustFee"] = task_data.CustFee;
data["TradeAmount"] = task_data.TradeAmount;
data["Digest"] = task_data.Digest;
this->onRtnFromBankToFutureByBank(data);
};
void TdApi::processRtnFromFutureToBankByBank(Task task)
{
PyLock lock;
CQdpFtdcRspTransferField task_data = any_cast<CQdpFtdcRspTransferField>(task.task_data);
dict data;
data["BrokerBranchID"] = task_data.BrokerBranchID;
data["UserID"] = task_data.UserID;
data["BankPassWord"] = task_data.BankPassWord;
data["VerifyCertNoFlag"] = task_data.VerifyCertNoFlag;
data["TID"] = task_data.TID;
data["AccountID"] = task_data.AccountID;
data["BankAccount"] = task_data.BankAccount;
data["InstallID"] = task_data.InstallID;
data["CustomerName"] = task_data.CustomerName;
data["TradeCode"] = task_data.TradeCode;
data["SessionID"] = task_data.SessionID;
data["BankID"] = task_data.BankID;
data["Password"] = task_data.Password;
data["BankPwdFlag"] = task_data.BankPwdFlag;
data["ErrorID"] = task_data.ErrorID;
data["RequestID"] = task_data.RequestID;
data["CustType"] = task_data.CustType;
data["IdentifiedCardNo"] = task_data.IdentifiedCardNo;
data["FeePayFlag"] = task_data.FeePayFlag;
data["BankSerial"] = task_data.BankSerial;
data["OperNo"] = task_data.OperNo;
data["TradingDay"] = task_data.TradingDay;
data["BankSecuAcc"] = task_data.BankSecuAcc;
data["BrokerID"] = task_data.BrokerID;
data["DeviceID"] = task_data.DeviceID;
data["TransferStatus"] = task_data.TransferStatus;
data["IdCardType"] = task_data.IdCardType;
data["PlateSerial"] = task_data.PlateSerial;
data["FutureFetchAmount"] = task_data.FutureFetchAmount;
data["TradeDate"] = task_data.TradeDate;
data["BrokerFee"] = task_data.BrokerFee;
data["BankAccType"] = task_data.BankAccType;
data["LastFragment"] = task_data.LastFragment;
data["FutureSerial"] = task_data.FutureSerial;
data["ErrorMsg"] = task_data.ErrorMsg;
data["BankSecuAccType"] = task_data.BankSecuAccType;
data["SecuPwdFlag"] = task_data.SecuPwdFlag;
data["Message"] = task_data.Message;
data["CustFee"] = task_data.CustFee;
data["TradeAmount"] = task_data.TradeAmount;
data["Digest"] = task_data.Digest;
this->onRtnFromFutureToBankByBank(data);
};
void TdApi::processRtnFromBankToFutureByFuture(Task task)
{
PyLock lock;
CQdpFtdcRspTransferField task_data = any_cast<CQdpFtdcRspTransferField>(task.task_data);
dict data;
data["BrokerBranchID"] = task_data.BrokerBranchID;
data["UserID"] = task_data.UserID;
data["BankPassWord"] = task_data.BankPassWord;
data["VerifyCertNoFlag"] = task_data.VerifyCertNoFlag;
data["TID"] = task_data.TID;
data["AccountID"] = task_data.AccountID;
data["BankAccount"] = task_data.BankAccount;
data["InstallID"] = task_data.InstallID;
data["CustomerName"] = task_data.CustomerName;
data["TradeCode"] = task_data.TradeCode;
data["SessionID"] = task_data.SessionID;
data["BankID"] = task_data.BankID;
data["Password"] = task_data.Password;
data["BankPwdFlag"] = task_data.BankPwdFlag;
data["ErrorID"] = task_data.ErrorID;
data["RequestID"] = task_data.RequestID;
data["CustType"] = task_data.CustType;
data["IdentifiedCardNo"] = task_data.IdentifiedCardNo;
data["FeePayFlag"] = task_data.FeePayFlag;
data["BankSerial"] = task_data.BankSerial;
data["OperNo"] = task_data.OperNo;
data["TradingDay"] = task_data.TradingDay;
data["BankSecuAcc"] = task_data.BankSecuAcc;
data["BrokerID"] = task_data.BrokerID;
data["DeviceID"] = task_data.DeviceID;
data["TransferStatus"] = task_data.TransferStatus;
data["IdCardType"] = task_data.IdCardType;
data["PlateSerial"] = task_data.PlateSerial;
data["FutureFetchAmount"] = task_data.FutureFetchAmount;
data["TradeDate"] = task_data.TradeDate;
data["BrokerFee"] = task_data.BrokerFee;
data["BankAccType"] = task_data.BankAccType;
data["LastFragment"] = task_data.LastFragment;
data["FutureSerial"] = task_data.FutureSerial;
data["ErrorMsg"] = task_data.ErrorMsg;
data["BankSecuAccType"] = task_data.BankSecuAccType;
data["SecuPwdFlag"] = task_data.SecuPwdFlag;
data["Message"] = task_data.Message;
data["CustFee"] = task_data.CustFee;
data["TradeAmount"] = task_data.TradeAmount;
data["Digest"] = task_data.Digest;
this->onRtnFromBankToFutureByFuture(data);
};
void TdApi::processRtnFromFutureToBankByFuture(Task task)
{
PyLock lock;
CQdpFtdcRspTransferField task_data = any_cast<CQdpFtdcRspTransferField>(task.task_data);
dict data;
data["BrokerBranchID"] = task_data.BrokerBranchID;
data["UserID"] = task_data.UserID;
data["BankPassWord"] = task_data.BankPassWord;
data["VerifyCertNoFlag"] = task_data.VerifyCertNoFlag;
data["TID"] = task_data.TID;
data["AccountID"] = task_data.AccountID;
data["BankAccount"] = task_data.BankAccount;
data["InstallID"] = task_data.InstallID;
data["CustomerName"] = task_data.CustomerName;
data["TradeCode"] = task_data.TradeCode;
data["SessionID"] = task_data.SessionID;
data["BankID"] = task_data.BankID;
data["Password"] = task_data.Password;
data["BankPwdFlag"] = task_data.BankPwdFlag;
data["ErrorID"] = task_data.ErrorID;
data["RequestID"] = task_data.RequestID;
data["CustType"] = task_data.CustType;
data["IdentifiedCardNo"] = task_data.IdentifiedCardNo;
data["FeePayFlag"] = task_data.FeePayFlag;
data["BankSerial"] = task_data.BankSerial;
data["OperNo"] = task_data.OperNo;
data["TradingDay"] = task_data.TradingDay;
data["BankSecuAcc"] = task_data.BankSecuAcc;
data["BrokerID"] = task_data.BrokerID;
data["DeviceID"] = task_data.DeviceID;
data["TransferStatus"] = task_data.TransferStatus;
data["IdCardType"] = task_data.IdCardType;
data["PlateSerial"] = task_data.PlateSerial;
data["FutureFetchAmount"] = task_data.FutureFetchAmount;
data["TradeDate"] = task_data.TradeDate;
data["BrokerFee"] = task_data.BrokerFee;
data["BankAccType"] = task_data.BankAccType;
data["LastFragment"] = task_data.LastFragment;
data["FutureSerial"] = task_data.FutureSerial;
data["ErrorMsg"] = task_data.ErrorMsg;
data["BankSecuAccType"] = task_data.BankSecuAccType;
data["SecuPwdFlag"] = task_data.SecuPwdFlag;
data["Message"] = task_data.Message;
data["CustFee"] = task_data.CustFee;
data["TradeAmount"] = task_data.TradeAmount;
data["Digest"] = task_data.Digest;
this->onRtnFromFutureToBankByFuture(data);
};
void TdApi::processRtnQueryBankBalanceByFuture(Task task)
{
PyLock lock;
CQdpFtdcNotifyQueryAccountField task_data = any_cast<CQdpFtdcNotifyQueryAccountField>(task.task_data);
dict data;
data["BrokerBranchID"] = task_data.BrokerBranchID;
data["UserID"] = task_data.UserID;
data["BankPassWord"] = task_data.BankPassWord;
data["TradeTime"] = task_data.TradeTime;
data["VerifyCertNoFlag"] = task_data.VerifyCertNoFlag;
data["TID"] = task_data.TID;
data["AccountID"] = task_data.AccountID;
data["BankAccount"] = task_data.BankAccount;
data["InstallID"] = task_data.InstallID;
data["CustomerName"] = task_data.CustomerName;
data["TradeCode"] = task_data.TradeCode;
data["SessionID"] = task_data.SessionID;
data["BankID"] = task_data.BankID;
data["Password"] = task_data.Password;
data["BankPwdFlag"] = task_data.BankPwdFlag;
data["ErrorID"] = task_data.ErrorID;
data["RequestID"] = task_data.RequestID;
data["CustType"] = task_data.CustType;
data["IdentifiedCardNo"] = task_data.IdentifiedCardNo;
data["BankSerial"] = task_data.BankSerial;
data["OperNo"] = task_data.OperNo;
data["TradingDay"] = task_data.TradingDay;
data["BankSecuAcc"] = task_data.BankSecuAcc;
data["BrokerID"] = task_data.BrokerID;
data["DeviceID"] = task_data.DeviceID;
data["BankUseAmount"] = task_data.BankUseAmount;
data["IdCardType"] = task_data.IdCardType;
data["PlateSerial"] = task_data.PlateSerial;
data["TradeDate"] = task_data.TradeDate;
data["ErrorMsg"] = task_data.ErrorMsg;
data["BankAccType"] = task_data.BankAccType;
data["LastFragment"] = task_data.LastFragment;
data["FutureSerial"] = task_data.FutureSerial;
data["BankSecuAccType"] = task_data.BankSecuAccType;
data["SecuPwdFlag"] = task_data.SecuPwdFlag;
data["Digest"] = task_data.Digest;
data["BankFetchAmount"] = task_data.BankFetchAmount;
this->onRtnQueryBankBalanceByFuture(data);
};
void TdApi::processErrRtnBankToFutureByFuture(Task task)
{
PyLock lock;
CQdpFtdcReqTransferField task_data = any_cast<CQdpFtdcReqTransferField>(task.task_data);
dict data;
data["BrokerBranchID"] = task_data.BrokerBranchID;
data["UserID"] = task_data.UserID;
data["BankPassWord"] = task_data.BankPassWord;
data["VerifyCertNoFlag"] = task_data.VerifyCertNoFlag;
data["TID"] = task_data.TID;
data["AccountID"] = task_data.AccountID;
data["BankAccount"] = task_data.BankAccount;
data["InstallID"] = task_data.InstallID;
data["CustomerName"] = task_data.CustomerName;
data["TradeCode"] = task_data.TradeCode;
data["SessionID"] = task_data.SessionID;
data["BankID"] = task_data.BankID;
data["Password"] = task_data.Password;
data["BankPwdFlag"] = task_data.BankPwdFlag;
data["RequestID"] = task_data.RequestID;
data["CustType"] = task_data.CustType;
data["IdentifiedCardNo"] = task_data.IdentifiedCardNo;
data["FeePayFlag"] = task_data.FeePayFlag;
data["BankSerial"] = task_data.BankSerial;
data["OperNo"] = task_data.OperNo;
data["TradingDay"] = task_data.TradingDay;
data["BankSecuAcc"] = task_data.BankSecuAcc;
data["BrokerID"] = task_data.BrokerID;
data["DeviceID"] = task_data.DeviceID;
data["TransferStatus"] = task_data.TransferStatus;
data["IdCardType"] = task_data.IdCardType;
data["PlateSerial"] = task_data.PlateSerial;
data["FutureFetchAmount"] = task_data.FutureFetchAmount;
data["TradeDate"] = task_data.TradeDate;
data["BrokerFee"] = task_data.BrokerFee;
data["BankAccType"] = task_data.BankAccType;
data["LastFragment"] = task_data.LastFragment;
data["FutureSerial"] = task_data.FutureSerial;
data["BankSecuAccType"] = task_data.BankSecuAccType;
data["SecuPwdFlag"] = task_data.SecuPwdFlag;
data["Message"] = task_data.Message;
data["CustFee"] = task_data.CustFee;
data["TradeAmount"] = task_data.TradeAmount;
data["Digest"] = task_data.Digest;
CQdpFtdcRspInfoField task_error = any_cast<CQdpFtdcRspInfoField>(task.task_error);
dict error;
error["ErrorMsg"] = task_error.ErrorMsg;
error["ErrorID"] = task_error.ErrorID;
this->onErrRtnBankToFutureByFuture(data, error);
};
void TdApi::processErrRtnFutureToBankByFuture(Task task)
{
PyLock lock;
CQdpFtdcReqTransferField task_data = any_cast<CQdpFtdcReqTransferField>(task.task_data);
dict data;
data["BrokerBranchID"] = task_data.BrokerBranchID;
data["UserID"] = task_data.UserID;
data["BankPassWord"] = task_data.BankPassWord;
data["VerifyCertNoFlag"] = task_data.VerifyCertNoFlag;
data["TID"] = task_data.TID;
data["AccountID"] = task_data.AccountID;
data["BankAccount"] = task_data.BankAccount;
data["InstallID"] = task_data.InstallID;
data["CustomerName"] = task_data.CustomerName;
data["TradeCode"] = task_data.TradeCode;
data["SessionID"] = task_data.SessionID;
data["BankID"] = task_data.BankID;
data["Password"] = task_data.Password;
data["BankPwdFlag"] = task_data.BankPwdFlag;
data["RequestID"] = task_data.RequestID;
data["CustType"] = task_data.CustType;
data["IdentifiedCardNo"] = task_data.IdentifiedCardNo;
data["FeePayFlag"] = task_data.FeePayFlag;
data["BankSerial"] = task_data.BankSerial;
data["OperNo"] = task_data.OperNo;
data["TradingDay"] = task_data.TradingDay;
data["BankSecuAcc"] = task_data.BankSecuAcc;
data["BrokerID"] = task_data.BrokerID;
data["DeviceID"] = task_data.DeviceID;
data["TransferStatus"] = task_data.TransferStatus;
data["IdCardType"] = task_data.IdCardType;
data["PlateSerial"] = task_data.PlateSerial;
data["FutureFetchAmount"] = task_data.FutureFetchAmount;
data["TradeDate"] = task_data.TradeDate;
data["BrokerFee"] = task_data.BrokerFee;
data["BankAccType"] = task_data.BankAccType;
data["LastFragment"] = task_data.LastFragment;
data["FutureSerial"] = task_data.FutureSerial;
data["BankSecuAccType"] = task_data.BankSecuAccType;
data["SecuPwdFlag"] = task_data.SecuPwdFlag;
data["Message"] = task_data.Message;
data["CustFee"] = task_data.CustFee;
data["TradeAmount"] = task_data.TradeAmount;
data["Digest"] = task_data.Digest;
CQdpFtdcRspInfoField task_error = any_cast<CQdpFtdcRspInfoField>(task.task_error);
dict error;
error["ErrorMsg"] = task_error.ErrorMsg;
error["ErrorID"] = task_error.ErrorID;
this->onErrRtnFutureToBankByFuture(data, error);
};
void TdApi::processErrRtnQueryBankBalanceByFuture(Task task)
{
PyLock lock;
CQdpFtdcReqQueryAccountField task_data = any_cast<CQdpFtdcReqQueryAccountField>(task.task_data);
dict data;
data["BrokerBranchID"] = task_data.BrokerBranchID;
data["UserID"] = task_data.UserID;
data["BankPassWord"] = task_data.BankPassWord;
data["TradeTime"] = task_data.TradeTime;
data["VerifyCertNoFlag"] = task_data.VerifyCertNoFlag;
data["TID"] = task_data.TID;
data["AccountID"] = task_data.AccountID;
data["BankAccount"] = task_data.BankAccount;
data["InstallID"] = task_data.InstallID;
data["CustomerName"] = task_data.CustomerName;
data["TradeCode"] = task_data.TradeCode;
data["SessionID"] = task_data.SessionID;
data["BankID"] = task_data.BankID;
data["Password"] = task_data.Password;
data["BankPwdFlag"] = task_data.BankPwdFlag;
data["RequestID"] = task_data.RequestID;
data["CustType"] = task_data.CustType;
data["IdentifiedCardNo"] = task_data.IdentifiedCardNo;
data["BankSerial"] = task_data.BankSerial;
data["OperNo"] = task_data.OperNo;
data["TradingDay"] = task_data.TradingDay;
data["BankSecuAcc"] = task_data.BankSecuAcc;
data["BrokerID"] = task_data.BrokerID;
data["DeviceID"] = task_data.DeviceID;
data["IdCardType"] = task_data.IdCardType;
data["PlateSerial"] = task_data.PlateSerial;
data["TradeDate"] = task_data.TradeDate;
data["BankAccType"] = task_data.BankAccType;
data["LastFragment"] = task_data.LastFragment;
data["FutureSerial"] = task_data.FutureSerial;
data["BankSecuAccType"] = task_data.BankSecuAccType;
data["SecuPwdFlag"] = task_data.SecuPwdFlag;
data["Digest"] = task_data.Digest;
CQdpFtdcRspInfoField task_error = any_cast<CQdpFtdcRspInfoField>(task.task_error);
dict error;
error["ErrorMsg"] = task_error.ErrorMsg;
error["ErrorID"] = task_error.ErrorID;
this->onErrRtnQueryBankBalanceByFuture(data, error);
};
void TdApi::processRspFromFutureToBankByFuture(Task task)
{
PyLock lock;
CQdpFtdcReqTransferField task_data = any_cast<CQdpFtdcReqTransferField>(task.task_data);
dict data;
data["BrokerBranchID"] = task_data.BrokerBranchID;
data["UserID"] = task_data.UserID;
data["BankPassWord"] = task_data.BankPassWord;
data["VerifyCertNoFlag"] = task_data.VerifyCertNoFlag;
data["TID"] = task_data.TID;
data["AccountID"] = task_data.AccountID;
data["BankAccount"] = task_data.BankAccount;
data["InstallID"] = task_data.InstallID;
data["CustomerName"] = task_data.CustomerName;
data["TradeCode"] = task_data.TradeCode;
data["SessionID"] = task_data.SessionID;
data["BankID"] = task_data.BankID;
data["Password"] = task_data.Password;
data["BankPwdFlag"] = task_data.BankPwdFlag;
data["RequestID"] = task_data.RequestID;
data["CustType"] = task_data.CustType;
data["IdentifiedCardNo"] = task_data.IdentifiedCardNo;
data["FeePayFlag"] = task_data.FeePayFlag;
data["BankSerial"] = task_data.BankSerial;
data["OperNo"] = task_data.OperNo;
data["TradingDay"] = task_data.TradingDay;
data["BankSecuAcc"] = task_data.BankSecuAcc;
data["BrokerID"] = task_data.BrokerID;
data["DeviceID"] = task_data.DeviceID;
data["TransferStatus"] = task_data.TransferStatus;
data["IdCardType"] = task_data.IdCardType;
data["PlateSerial"] = task_data.PlateSerial;
data["FutureFetchAmount"] = task_data.FutureFetchAmount;
data["TradeDate"] = task_data.TradeDate;
data["Currency"] = task_data.Currency;
data["BrokerFee"] = task_data.BrokerFee;
data["BankAccType"] = task_data.BankAccType;
data["LastFragment"] = task_data.LastFragment;
data["FutureSerial"] = task_data.FutureSerial;
data["BankSecuAccType"] = task_data.BankSecuAccType;
data["SecuPwdFlag"] = task_data.SecuPwdFlag;
data["Message"] = task_data.Message;
data["CustFee"] = task_data.CustFee;
data["TradeAmount"] = task_data.TradeAmount;
data["Digest"] = task_data.Digest;
CQdpFtdcRspInfoField task_error = any_cast<CQdpFtdcRspInfoField>(task.task_error);
dict error;
error["ErrorMsg"] = task_error.ErrorMsg;
error["ErrorID"] = task_error.ErrorID;
this->onRspFromFutureToBankByFuture(data, error, task.task_id, task.task_last);
};
void TdApi::processRspFromBankToFutureByFuture(Task task)
{
PyLock lock;
CQdpFtdcReqTransferField task_data = any_cast<CQdpFtdcReqTransferField>(task.task_data);
dict data;
data["BrokerBranchID"] = task_data.BrokerBranchID;
data["UserID"] = task_data.UserID;
data["BankPassWord"] = task_data.BankPassWord;
data["VerifyCertNoFlag"] = task_data.VerifyCertNoFlag;
data["TID"] = task_data.TID;
data["AccountID"] = task_data.AccountID;
data["BankAccount"] = task_data.BankAccount;
data["InstallID"] = task_data.InstallID;
data["CustomerName"] = task_data.CustomerName;
data["TradeCode"] = task_data.TradeCode;
data["SessionID"] = task_data.SessionID;
data["BankID"] = task_data.BankID;
data["Password"] = task_data.Password;
data["BankPwdFlag"] = task_data.BankPwdFlag;
data["RequestID"] = task_data.RequestID;
data["CustType"] = task_data.CustType;
data["IdentifiedCardNo"] = task_data.IdentifiedCardNo;
data["FeePayFlag"] = task_data.FeePayFlag;
data["BankSerial"] = task_data.BankSerial;
data["OperNo"] = task_data.OperNo;
data["TradingDay"] = task_data.TradingDay;
data["BankSecuAcc"] = task_data.BankSecuAcc;
data["BrokerID"] = task_data.BrokerID;
data["DeviceID"] = task_data.DeviceID;
data["TransferStatus"] = task_data.TransferStatus;
data["IdCardType"] = task_data.IdCardType;
data["PlateSerial"] = task_data.PlateSerial;
data["FutureFetchAmount"] = task_data.FutureFetchAmount;
data["TradeDate"] = task_data.TradeDate;
data["Currency"] = task_data.Currency;
data["BrokerFee"] = task_data.BrokerFee;
data["BankAccType"] = task_data.BankAccType;
data["LastFragment"] = task_data.LastFragment;
data["FutureSerial"] = task_data.FutureSerial;
data["BankSecuAccType"] = task_data.BankSecuAccType;
data["SecuPwdFlag"] = task_data.SecuPwdFlag;
data["Message"] = task_data.Message;
data["CustFee"] = task_data.CustFee;
data["TradeAmount"] = task_data.TradeAmount;
data["Digest"] = task_data.Digest;
CQdpFtdcRspInfoField task_error = any_cast<CQdpFtdcRspInfoField>(task.task_error);
dict error;
error["ErrorMsg"] = task_error.ErrorMsg;
error["ErrorID"] = task_error.ErrorID;
this->onRspFromBankToFutureByFuture(data, error, task.task_id, task.task_last);
};
void TdApi::processRspQueryBankAccountMoneyByFuture(Task task)
{
PyLock lock;
CQdpFtdcReqQueryAccountField task_data = any_cast<CQdpFtdcReqQueryAccountField>(task.task_data);
dict data;
data["BrokerBranchID"] = task_data.BrokerBranchID;
data["UserID"] = task_data.UserID;
data["BankPassWord"] = task_data.BankPassWord;
data["TradeTime"] = task_data.TradeTime;
data["VerifyCertNoFlag"] = task_data.VerifyCertNoFlag;
data["TID"] = task_data.TID;
data["AccountID"] = task_data.AccountID;
data["BankAccount"] = task_data.BankAccount;
data["InstallID"] = task_data.InstallID;
data["CustomerName"] = task_data.CustomerName;
data["TradeCode"] = task_data.TradeCode;
data["SessionID"] = task_data.SessionID;
data["BankID"] = task_data.BankID;
data["Password"] = task_data.Password;
data["BankPwdFlag"] = task_data.BankPwdFlag;
data["RequestID"] = task_data.RequestID;
data["CustType"] = task_data.CustType;
data["IdentifiedCardNo"] = task_data.IdentifiedCardNo;
data["BankSerial"] = task_data.BankSerial;
data["OperNo"] = task_data.OperNo;
data["TradingDay"] = task_data.TradingDay;
data["BankSecuAcc"] = task_data.BankSecuAcc;
data["BrokerID"] = task_data.BrokerID;
data["DeviceID"] = task_data.DeviceID;
data["IdCardType"] = task_data.IdCardType;
data["PlateSerial"] = task_data.PlateSerial;
data["TradeDate"] = task_data.TradeDate;
data["Currency"] = task_data.Currency;
data["BankAccType"] = task_data.BankAccType;
data["LastFragment"] = task_data.LastFragment;
data["FutureSerial"] = task_data.FutureSerial;
data["BankSecuAccType"] = task_data.BankSecuAccType;
data["SecuPwdFlag"] = task_data.SecuPwdFlag;
data["Digest"] = task_data.Digest;
CQdpFtdcRspInfoField task_error = any_cast<CQdpFtdcRspInfoField>(task.task_error);
dict error;
error["ErrorMsg"] = task_error.ErrorMsg;
error["ErrorID"] = task_error.ErrorID;
this->onRspQueryBankAccountMoneyByFuture(data, error, task.task_id, task.task_last);
};
///-------------------------------------------------------------------------------------
///主动函数
///-------------------------------------------------------------------------------------
void TdApi::createFtdcTraderApi(string pszFlowPath)
{
this->api = CQdpFtdcTraderApi::CreateFtdcTraderApi(pszFlowPath.c_str());
this->api->RegisterSpi(this);
};
void TdApi::release()
{
this->api->Release();
};
void TdApi::init()
{
this->api->Init();
};
int TdApi::join()
{
int i = this->api->Join();
return i;
};
int TdApi::exit()
{
//该函数在原生API里没有,用于安全退出API用,原生的join似乎不太稳定
this->api->RegisterSpi(NULL);
this->api->Release();
this->api = NULL;
return 1;
};
string TdApi::getTradingDay()
{
string day = this->api->GetTradingDay();
return day;
};
void TdApi::registerFront(string pszFrontAddress)
{
this->api->RegisterFront((char*)pszFrontAddress.c_str());
};
void TdApi::subscribePrivateTopic(int nType)
{
//该函数为手动编写
QDP_TE_RESUME_TYPE type;
switch (nType)
{
case 0:
{
type = QDP_TERT_RESTART;
break;
};
case 1:
{
type = QDP_TERT_RESUME;
break;
};
case 2:
{
type = QDP_TERT_QUICK;
break;
};
}
this->api->SubscribePrivateTopic(type);
};
void TdApi::subscribePublicTopic(int nType)
{
//该函数为手动编写
QDP_TE_RESUME_TYPE type;
switch (nType)
{
case 0:
{
type = QDP_TERT_RESTART;
break;
};
case 1:
{
type = QDP_TERT_RESUME;
break;
};
case 2:
{
type = QDP_TERT_QUICK;
break;
};
}
this->api->SubscribePublicTopic(type);
};
int TdApi::reqUserLogin(dict req, int nRequestID)
{
CQdpFtdcReqUserLoginField myreq = CQdpFtdcReqUserLoginField();
memset(&myreq, 0, sizeof(myreq));
getStr(req, "MacAddress", myreq.MacAddress);
getStr(req, "UserProductInfo", myreq.UserProductInfo);
getStr(req, "UserID", myreq.UserID);
getStr(req, "TradingDay", myreq.TradingDay);
getStr(req, "InterfaceProductInfo", myreq.InterfaceProductInfo);
getStr(req, "BrokerID", myreq.BrokerID);
getStr(req, "ClientIPAddress", myreq.ClientIPAddress);
getStr(req, "OneTimePassword", myreq.OneTimePassword);
getStr(req, "ProtocolInfo", myreq.ProtocolInfo);
getStr(req, "Password", myreq.Password);
int i = this->api->ReqUserLogin(&myreq, nRequestID);
return i;
};
int TdApi::reqQryUserInvestor(dict req, int nRequestID)
{
CQdpFtdcQryUserInvestorField myreq = CQdpFtdcQryUserInvestorField();
memset(&myreq, 0, sizeof(myreq));
getStr(req, "UserID", myreq.UserID);
getStr(req, "BrokerID", myreq.BrokerID);
int i = this->api->ReqQryUserInvestor(&myreq, nRequestID);
return i;
};
int TdApi::reqUserLogout(dict req, int nRequestID)
{
CQdpFtdcReqUserLogoutField myreq = CQdpFtdcReqUserLogoutField();
memset(&myreq, 0, sizeof(myreq));
getStr(req, "UserID", myreq.UserID);
getStr(req, "BrokerID", myreq.BrokerID);
int i = this->api->ReqUserLogout(&myreq, nRequestID);
return i;
};
int TdApi::reqUserPasswordUpdate(dict req, int nRequestID)
{
CQdpFtdcUserPasswordUpdateField myreq = CQdpFtdcUserPasswordUpdateField();
memset(&myreq, 0, sizeof(myreq));
getStr(req, "UserID", myreq.UserID);
getStr(req, "NewPassword", myreq.NewPassword);
getStr(req, "OldPassword", myreq.OldPassword);
getStr(req, "BrokerID", myreq.BrokerID);
int i = this->api->ReqUserPasswordUpdate(&myreq, nRequestID);
return i;
};
int TdApi::reqTradingAccountPasswordUpdate(dict req, int nRequestID)
{
CQdpFtdcUserPasswordUpdateField myreq = CQdpFtdcUserPasswordUpdateField();
memset(&myreq, 0, sizeof(myreq));
getStr(req, "NewPassword", myreq.NewPassword);
getStr(req, "OldPassword", myreq.OldPassword);
getStr(req, "BrokerID", myreq.BrokerID);
getStr(req, "UserID", myreq.UserID);
int i = this->api->ReqUserPasswordUpdate(&myreq, nRequestID);
return i;
};
int TdApi::reqOrderInsert(dict req, int nRequestID)
{
CQdpFtdcInputOrderField myreq = CQdpFtdcInputOrderField();
memset(&myreq, 0, sizeof(myreq));
getStr(req, "OffsetFlag", &myreq.OffsetFlag);
getStr(req, "UserID", myreq.UserID);
getDouble(req, "LimitPrice", &myreq.LimitPrice);
getChar(req, "Direction", &myreq.Direction);
getInt(req, "Volume", &myreq.Volume);
getChar(req, "OrderPriceType", &myreq.OrderPriceType);
getChar(req, "TimeCondition", &myreq.TimeCondition);
getInt(req, "IsAutoSuspend", &myreq.IsAutoSuspend);
getDouble(req, "StopPrice", &myreq.StopPrice);
getStr(req, "InstrumentID", myreq.InstrumentID);
getStr(req, "ExchangeID", myreq.ExchangeID);
getInt(req, "MinVolume", &myreq.MinVolume);
getChar(req, "ForceCloseReason", &myreq.ForceCloseReason);
getStr(req, "BrokerID", myreq.BrokerID);
getStr(req, "HedgeFlag", &myreq.HedgeFlag);
getStr(req, "GTDDate", myreq.GTDDate);
getStr(req, "BusinessUnit", myreq.BusinessUnit);
getStr(req, "UserOrderLocalID", myreq.UserOrderLocalID);
getStr(req, "InvestorID", myreq.InvestorID);
getChar(req, "VolumeCondition", &myreq.VolumeCondition);
int i = this->api->ReqOrderInsert(&myreq, nRequestID);
return i;
};
int TdApi::reqOrderAction(dict req, int nRequestID)
{
CQdpFtdcOrderActionField myreq = CQdpFtdcOrderActionField();
memset(&myreq, 0, sizeof(myreq));
getStr(req, "InstrumentID", myreq.InstrumentID);
getStr(req, "ExchangeID", myreq.ExchangeID);
getChar(req, "ActionFlag", &myreq.ActionFlag);
getStr(req, "UserOrderActionLocalID", myreq.UserOrderActionLocalID);
getStr(req, "UserID", myreq.UserID);
getDouble(req, "LimitPrice", &myreq.LimitPrice);
getStr(req, "UserOrderLocalID", myreq.UserOrderLocalID);
getStr(req, "InvestorID", myreq.InvestorID);
getInt(req, "VolumeChange", &myreq.VolumeChange);
getStr(req, "BrokerID", myreq.BrokerID);
getStr(req, "OrderSysID", myreq.OrderSysID);
getInt(req, "FrontID", &myreq.FrontID);
getInt(req, "SessionID", &myreq.SessionID);
int i = this->api->ReqOrderAction(&myreq, nRequestID);
return i;
};
int TdApi::reqQryOrder(dict req, int nRequestID)
{
CQdpFtdcQryOrderField myreq = CQdpFtdcQryOrderField();
memset(&myreq, 0, sizeof(myreq));
getStr(req, "InstrumentID", myreq.InstrumentID);
getStr(req, "ExchangeID", myreq.ExchangeID);
getStr(req, "InvestorID", myreq.InvestorID);
getStr(req, "BrokerID", myreq.BrokerID);
getStr(req, "OrderSysID", myreq.OrderSysID);
int i = this->api->ReqQryOrder(&myreq, nRequestID);
return i;
};
int TdApi::reqQryTrade(dict req, int nRequestID)
{
CQdpFtdcQryTradeField myreq = CQdpFtdcQryTradeField();
memset(&myreq, 0, sizeof(myreq));
getStr(req, "InstrumentID", myreq.InstrumentID);
getStr(req, "ExchangeID", myreq.ExchangeID);
getStr(req, "TradeID", myreq.TradeID);
getStr(req, "InvestorID", myreq.InvestorID);
getStr(req, "BrokerID", myreq.BrokerID);
int i = this->api->ReqQryTrade(&myreq, nRequestID);
return i;
};
int TdApi::reqQryInvestorPosition(dict req, int nRequestID)
{
CQdpFtdcQryInvestorPositionField myreq = CQdpFtdcQryInvestorPositionField();
memset(&myreq, 0, sizeof(myreq));
getStr(req, "InstrumentID", myreq.InstrumentID);
getStr(req, "InvestorID", myreq.InvestorID);
getStr(req, "ExchangeID", myreq.ExchangeID);
getStr(req, "BrokerID", myreq.BrokerID);
int i = this->api->ReqQryInvestorPosition(&myreq, nRequestID);
return i;
};
int TdApi::reqQryInvestorAccount(dict req, int nRequestID)
{
CQdpFtdcQryInvestorAccountField myreq = CQdpFtdcQryInvestorAccountField();
memset(&myreq, 0, sizeof(myreq));
getStr(req, "UserID", myreq.UserID);
getStr(req, "InvestorID", myreq.InvestorID);
getStr(req, "BrokerID", myreq.BrokerID);
int i = this->api->ReqQryInvestorAccount(&myreq, nRequestID);
return i;
};
int TdApi::reqQryExchange(dict req, int nRequestID)
{
CQdpFtdcQryExchangeField myreq = CQdpFtdcQryExchangeField();
memset(&myreq, 0, sizeof(myreq));
getStr(req, "ExchangeID", myreq.ExchangeID);
int i = this->api->ReqQryExchange(&myreq, nRequestID);
return i;
};
int TdApi::reqQryInstrument(dict req, int nRequestID)
{
CQdpFtdcQryInstrumentField myreq = CQdpFtdcQryInstrumentField();
memset(&myreq, 0, sizeof(myreq));
getStr(req, "InstrumentID", myreq.InstrumentID);
getStr(req, "ExchangeID", myreq.ExchangeID);
getStr(req, "ProductID", myreq.ProductID);
int i = this->api->ReqQryInstrument(&myreq, nRequestID);
return i;
};
int TdApi::reqQryMarketData(dict req, int nRequestID)
{
CQdpFtdcQryMarketDataField myreq = CQdpFtdcQryMarketDataField();
memset(&myreq, 0, sizeof(myreq));
getStr(req, "InstrumentID", myreq.InstrumentID);
getStr(req, "ExchangeID", myreq.ExchangeID);
int i = this->api->ReqQryMarketData(&myreq, nRequestID);
return i;
};
int TdApi::reqQryContractBank(dict req, int nRequestID)
{
CQdpFtdcQryContractBankField myreq = CQdpFtdcQryContractBankField();
memset(&myreq, 0, sizeof(myreq));
getStr(req, "BrokerID", myreq.BrokerID);
getStr(req, "BankBrchID", myreq.BankBrchID);
getStr(req, "BankID", myreq.BankID);
int i = this->api->ReqQryContractBank(&myreq, nRequestID);
return i;
};
int TdApi::reqFromBankToFutureByFuture(dict req, int nRequestID)
{
CQdpFtdcReqTransferField myreq = CQdpFtdcReqTransferField();
memset(&myreq, 0, sizeof(myreq));
getStr(req, "BrokerBranchID", myreq.BrokerBranchID);
getStr(req, "UserID", myreq.UserID);
getStr(req, "BankPassWord", myreq.BankPassWord);
getStr(req, "VerifyCertNoFlag", myreq.VerifyCertNoFlag);
getInt(req, "TID", &myreq.TID);
getStr(req, "AccountID", myreq.AccountID);
getStr(req, "BankAccount", myreq.BankAccount);
getInt(req, "InstallID", &myreq.InstallID);
getStr(req, "CustomerName", myreq.CustomerName);
getStr(req, "TradeCode", myreq.TradeCode);
getInt(req, "SessionID", &myreq.SessionID);
getStr(req, "BankID", myreq.BankID);
getStr(req, "Password", myreq.Password);
getChar(req, "BankPwdFlag", &myreq.BankPwdFlag);
getInt(req, "RequestID", &myreq.RequestID);
getStr(req, "CustType", myreq.CustType);
getStr(req, "IdentifiedCardNo", myreq.IdentifiedCardNo);
getChar(req, "FeePayFlag", &myreq.FeePayFlag);
getStr(req, "BankSerial", myreq.BankSerial);
getStr(req, "OperNo", myreq.OperNo);
getStr(req, "TradingDay", myreq.TradingDay);
getStr(req, "BankSecuAcc", myreq.BankSecuAcc);
getStr(req, "BrokerID", myreq.BrokerID);
getStr(req, "DeviceID", myreq.DeviceID);
getChar(req, "TransferStatus", &myreq.TransferStatus);
getStr(req, "IdCardType", myreq.IdCardType);
getInt(req, "PlateSerial", &myreq.PlateSerial);
getDouble(req, "FutureFetchAmount", &myreq.FutureFetchAmount);
getStr(req, "TradeDate", myreq.TradeDate);
getStr(req, "Currency", myreq.Currency);
getDouble(req, "BrokerFee", &myreq.BrokerFee);
getChar(req, "BankAccType", &myreq.BankAccType);
getChar(req, "LastFragment", &myreq.LastFragment);
getInt(req, "FutureSerial", &myreq.FutureSerial);
getChar(req, "BankSecuAccType", &myreq.BankSecuAccType);
getChar(req, "SecuPwdFlag", &myreq.SecuPwdFlag);
getStr(req, "Message", myreq.Message);
getDouble(req, "CustFee", &myreq.CustFee);
getDouble(req, "TradeAmount", &myreq.TradeAmount);
getStr(req, "Digest", myreq.Digest);
int i = this->api->ReqFromBankToFutureByFuture(&myreq, nRequestID);
return i;
};
int TdApi::reqFromFutureToBankByFuture(dict req, int nRequestID)
{
CQdpFtdcReqTransferField myreq = CQdpFtdcReqTransferField();
memset(&myreq, 0, sizeof(myreq));
getStr(req, "BrokerBranchID", myreq.BrokerBranchID);
getStr(req, "UserID", myreq.UserID);
getStr(req, "BankPassWord", myreq.BankPassWord);
getStr(req, "VerifyCertNoFlag", myreq.VerifyCertNoFlag);
getInt(req, "TID", &myreq.TID);
getStr(req, "AccountID", myreq.AccountID);
getStr(req, "BankAccount", myreq.BankAccount);
getInt(req, "InstallID", &myreq.InstallID);
getStr(req, "CustomerName", myreq.CustomerName);
getStr(req, "TradeCode", myreq.TradeCode);
getInt(req, "SessionID", &myreq.SessionID);
getStr(req, "BankID", myreq.BankID);
getStr(req, "Password", myreq.Password);
getChar(req, "BankPwdFlag", &myreq.BankPwdFlag);
getInt(req, "RequestID", &myreq.RequestID);
getStr(req, "CustType", myreq.CustType);
getStr(req, "IdentifiedCardNo", myreq.IdentifiedCardNo);
getChar(req, "FeePayFlag", &myreq.FeePayFlag);
getStr(req, "BankSerial", myreq.BankSerial);
getStr(req, "OperNo", myreq.OperNo);
getStr(req, "TradingDay", myreq.TradingDay);
getStr(req, "BankSecuAcc", myreq.BankSecuAcc);
getStr(req, "BrokerID", myreq.BrokerID);
getStr(req, "DeviceID", myreq.DeviceID);
getChar(req, "TransferStatus", &myreq.TransferStatus);
getStr(req, "IdCardType", myreq.IdCardType);
getInt(req, "PlateSerial", &myreq.PlateSerial);
getDouble(req, "FutureFetchAmount", &myreq.FutureFetchAmount);
getStr(req, "TradeDate", myreq.TradeDate);
getStr(req, "Currency", myreq.Currency);
getDouble(req, "BrokerFee", &myreq.BrokerFee);
getChar(req, "BankAccType", &myreq.BankAccType);
getChar(req, "LastFragment", &myreq.LastFragment);
getInt(req, "FutureSerial", &myreq.FutureSerial);
getChar(req, "BankSecuAccType", &myreq.BankSecuAccType);
getChar(req, "SecuPwdFlag", &myreq.SecuPwdFlag);
getStr(req, "Message", myreq.Message);
getDouble(req, "CustFee", &myreq.CustFee);
getDouble(req, "TradeAmount", &myreq.TradeAmount);
getStr(req, "Digest", myreq.Digest);
int i = this->api->ReqFromFutureToBankByFuture(&myreq, nRequestID);
return i;
};
int TdApi::reqQueryBankAccountMoneyByFuture(dict req, int nRequestID)
{
CQdpFtdcReqQueryAccountField myreq = CQdpFtdcReqQueryAccountField();
memset(&myreq, 0, sizeof(myreq));
getStr(req, "BrokerBranchID", myreq.BrokerBranchID);
getStr(req, "UserID", myreq.UserID);
getStr(req, "BankPassWord", myreq.BankPassWord);
getStr(req, "TradeTime", myreq.TradeTime);
getStr(req, "VerifyCertNoFlag", myreq.VerifyCertNoFlag);
getInt(req, "TID", &myreq.TID);
getStr(req, "AccountID", myreq.AccountID);
getStr(req, "BankAccount", myreq.BankAccount);
getInt(req, "InstallID", &myreq.InstallID);
getStr(req, "CustomerName", myreq.CustomerName);
getStr(req, "TradeCode", myreq.TradeCode);
getInt(req, "SessionID", &myreq.SessionID);
getStr(req, "BankID", myreq.BankID);
getStr(req, "Password", myreq.Password);
getChar(req, "BankPwdFlag", &myreq.BankPwdFlag);
getInt(req, "RequestID", &myreq.RequestID);
getStr(req, "CustType", myreq.CustType);
getStr(req, "IdentifiedCardNo", myreq.IdentifiedCardNo);
getStr(req, "BankSerial", myreq.BankSerial);
getStr(req, "OperNo", myreq.OperNo);
getStr(req, "TradingDay", myreq.TradingDay);
getStr(req, "BankSecuAcc", myreq.BankSecuAcc);
getStr(req, "BrokerID", myreq.BrokerID);
getStr(req, "DeviceID", myreq.DeviceID);
getStr(req, "IdCardType", myreq.IdCardType);
getInt(req, "PlateSerial", &myreq.PlateSerial);
getStr(req, "TradeDate", myreq.TradeDate);
getStr(req, "Currency", myreq.Currency);
getChar(req, "BankAccType", &myreq.BankAccType);
getChar(req, "LastFragment", &myreq.LastFragment);
getInt(req, "FutureSerial", &myreq.FutureSerial);
getChar(req, "BankSecuAccType", &myreq.BankSecuAccType);
getChar(req, "SecuPwdFlag", &myreq.SecuPwdFlag);
getStr(req, "Digest", myreq.Digest);
int i = this->api->ReqQueryBankAccountMoneyByFuture(&myreq, nRequestID);
return i;
};
///-------------------------------------------------------------------------------------
///Boost.Python封装
///-------------------------------------------------------------------------------------
struct TdApiWrap : TdApi, wrapper < TdApi >
{
virtual void onFrontConnected()
{
//在向python环境中调用回调函数推送数据前,需要先获取全局锁GIL,防止解释器崩溃
PyLock lock;
//以下的try...catch...可以实现捕捉python环境中错误的功能,防止C++直接出现原因未知的崩溃
try
{
this->get_override("onFrontConnected")();
}
catch (error_already_set const &)
{
PyErr_Print();
}
};
virtual void onFrontDisconnected(int i)
{
PyLock lock;
try
{
this->get_override("onFrontDisconnected")(i);
}
catch (error_already_set const &)
{
PyErr_Print();
}
};
virtual void onHeartBeatWarning(int i)
{
PyLock lock;
try
{
this->get_override("onHeartBeatWarning")(i);
}
catch (error_already_set const &)
{
PyErr_Print();
}
};
virtual void onRspUserLogin(dict data, dict error, int id, bool last)
{
try
{
this->get_override("onRspUserLogin")(data, error, id, last);
}
catch (error_already_set const &)
{
PyErr_Print();
}
};
virtual void onRspUserLogout(dict data, dict error, int id, bool last)
{
try
{
this->get_override("onRspUserLogout")(data, error, id, last);
}
catch (error_already_set const &)
{
PyErr_Print();
}
};
virtual void onRspUserPasswordUpdate(dict data, dict error, int id, bool last)
{
try
{
this->get_override("onRspUserPasswordUpdate")(data, error, id, last);
}
catch (error_already_set const &)
{
PyErr_Print();
}
};
virtual void onRspOrderInsert(dict data, dict error, int id, bool last)
{
try
{
this->get_override("onRspOrderInsert")(data, error, id, last);
}
catch (error_already_set const &)
{
PyErr_Print();
}
};
virtual void onRspOrderAction(dict data, dict error, int id, bool last)
{
try
{
this->get_override("onRspOrderAction")(data, error, id, last);
}
catch (error_already_set const &)
{
PyErr_Print();
}
};
virtual void onRspQryUserInvestor(dict data, dict error, int id, bool last)
{
try
{
this->get_override("onRspQryUserInvestor")(data, error, id, last);
}
catch (error_already_set const &)
{
PyErr_Print();
}
};
virtual void onRspQryOrder(dict data, dict error, int id, bool last)
{
try
{
this->get_override("onRspQryOrder")(data, error, id, last);
}
catch (error_already_set const &)
{
PyErr_Print();
}
};
virtual void onRspQryTrade(dict data, dict error, int id, bool last)
{
try
{
this->get_override("onRspQryTrade")(data, error, id, last);
}
catch (error_already_set const &)
{
PyErr_Print();
}
};
virtual void onRspQryInvestorPosition(dict data, dict error, int id, bool last)
{
try
{
this->get_override("onRspQryInvestorPosition")(data, error, id, last);
}
catch (error_already_set const &)
{
PyErr_Print();
}
};
virtual void onRspQryInvestorAccount(dict data, dict error, int id, bool last)
{
try
{
this->get_override("onRspQrynvestorAccount")(data, error, id, last);
}
catch (error_already_set const &)
{
PyErr_Print();
}
};
virtual void onRspQryInvestor(dict data, dict error, int id, bool last)
{
try
{
this->get_override("onRspQryInvestor")(data, error, id, last);
}
catch (error_already_set const &)
{
PyErr_Print();
}
};
virtual void onRspQryExchange(dict data, dict error, int id, bool last)
{
try
{
this->get_override("onRspQryExchange")(data, error, id, last);
}
catch (error_already_set const &)
{
PyErr_Print();
}
};
virtual void onRspQryInstrument(dict data, dict error, int id, bool last)
{
try
{
this->get_override("onRspQryInstrument")(data, error, id, last);
}
catch (error_already_set const &)
{
PyErr_Print();
}
};
virtual void onRspQryMarketData(dict data, dict error, int id, bool last)
{
try
{
this->get_override("onRspQryMarketData")(data, error, id, last);
}
catch (error_already_set const &)
{
PyErr_Print();
}
};
virtual void onRspQryTransferBank(dict data, dict error, int id, bool last)
{
try
{
this->get_override("onRspQryTransferBank")(data, error, id, last);
}
catch (error_already_set const &)
{
PyErr_Print();
}
};
virtual void onRspQryTransferSerial(dict data, dict error, int id, bool last)
{
try
{
this->get_override("onRspQryTransferSerial")(data, error, id, last);
}
catch (error_already_set const &)
{
PyErr_Print();
}
};
virtual void onRspError(dict error, int id, bool last)
{
try
{
this->get_override("onRspError")(error, id, last);
}
catch (error_already_set const &)
{
PyErr_Print();
}
};
virtual void onRtnOrder(dict data)
{
try
{
this->get_override("onRtnOrder")(data);
}
catch (error_already_set const &)
{
PyErr_Print();
}
};
virtual void onRtnTrade(dict data)
{
try
{
this->get_override("onRtnTrade")(data);
}
catch (error_already_set const &)
{
PyErr_Print();
}
};
virtual void onErrRtnOrderInsert(dict data, dict error)
{
try
{
this->get_override("onErrRtnOrderInsert")(data, error);
}
catch (error_already_set const &)
{
PyErr_Print();
}
};
virtual void onErrRtnOrderAction(dict data, dict error)
{
try
{
this->get_override("onErrRtnOrderAction")(data, error);
}
catch (error_already_set const &)
{
PyErr_Print();
}
};
virtual void onRtnInstrumentStatus(dict data)
{
try
{
this->get_override("onRtnInstrumentStatus")(data);
}
catch (error_already_set const &)
{
PyErr_Print();
}
};
virtual void onRspQryContractBank(dict data, dict error, int id, bool last)
{
try
{
this->get_override("onRspQryContractBank")(data, error, id, last);
}
catch (error_already_set const &)
{
PyErr_Print();
}
};
virtual void onRtnFromBankToFutureByBank(dict data)
{
try
{
this->get_override("onRtnFromBankToFutureByBank")(data);
}
catch (error_already_set const &)
{
PyErr_Print();
}
};
virtual void onRtnFromFutureToBankByBank(dict data)
{
try
{
this->get_override("onRtnFromFutureToBankByBank")(data);
}
catch (error_already_set const &)
{
PyErr_Print();
}
};
virtual void onRtnFromBankToFutureByFuture(dict data)
{
try
{
this->get_override("onRtnFromBankToFutureByFuture")(data);
}
catch (error_already_set const &)
{
PyErr_Print();
}
};
virtual void onRtnFromFutureToBankByFuture(dict data)
{
try
{
this->get_override("onRtnFromFutureToBankByFuture")(data);
}
catch (error_already_set const &)
{
PyErr_Print();
}
};
virtual void onRtnQueryBankBalanceByFuture(dict data)
{
try
{
this->get_override("onRtnQueryBankBalanceByFuture")(data);
}
catch (error_already_set const &)
{
PyErr_Print();
}
};
virtual void onErrRtnBankToFutureByFuture(dict data, dict error)
{
try
{
this->get_override("onErrRtnBankToFutureByFuture")(data, error);
}
catch (error_already_set const &)
{
PyErr_Print();
}
};
virtual void onErrRtnFutureToBankByFuture(dict data, dict error)
{
try
{
this->get_override("onErrRtnFutureToBankByFuture")(data, error);
}
catch (error_already_set const &)
{
PyErr_Print();
}
};
virtual void onErrRtnQueryBankBalanceByFuture(dict data, dict error)
{
try
{
this->get_override("onErrRtnQueryBankBalanceByFuture")(data, error);
}
catch (error_already_set const &)
{
PyErr_Print();
}
};
virtual void onRspFromBankToFutureByFuture(dict data, dict error, int id, bool last)
{
try
{
this->get_override("onRspFromBankToFutureByFuture")(data, error, id, last);
}
catch (error_already_set const &)
{
PyErr_Print();
}
};
virtual void onRspFromFutureToBankByFuture(dict data, dict error, int id, bool last)
{
try
{
this->get_override("onRspFromFutureToBankByFuture")(data, error, id, last);
}
catch (error_already_set const &)
{
PyErr_Print();
}
};
virtual void onRspQueryBankAccountMoneyByFuture(dict data, dict error, int id, bool last)
{
try
{
this->get_override("onRspQueryBankAccountMoneyByFuture")(data, error, id, last);
}
catch (error_already_set const &)
{
PyErr_Print();
}
};
};
BOOST_PYTHON_MODULE(vnqdptd)
{
PyEval_InitThreads(); //导入时运行,保证先创建GIL
class_<TdApiWrap, boost::noncopyable>("TdApi")
.def("createFtdcTraderApi", &TdApiWrap::createFtdcTraderApi)
.def("release", &TdApiWrap::release)
.def("init", &TdApiWrap::init)
.def("join", &TdApiWrap::join)
.def("exit", &TdApiWrap::exit)
.def("getTradingDay", &TdApiWrap::getTradingDay)
.def("registerFront", &TdApiWrap::registerFront)
.def("subscribePrivateTopic", &TdApiWrap::subscribePrivateTopic)
.def("subscribePublicTopic", &TdApiWrap::subscribePublicTopic)
.def("reqUserLogin", &TdApiWrap::reqUserLogin)
.def("reqUserLogout", &TdApiWrap::reqUserLogout)
.def("reqQryUserInvestor", &TdApiWrap::reqQryUserInvestor)
.def("reqUserPasswordUpdate", &TdApiWrap::reqUserPasswordUpdate)
.def("reqTradingAccountPasswordUpdate", &TdApiWrap::reqTradingAccountPasswordUpdate)
.def("reqOrderInsert", &TdApiWrap::reqOrderInsert)
.def("reqOrderAction", &TdApiWrap::reqOrderAction)
.def("reqQryOrder", &TdApiWrap::reqQryOrder)
.def("reqQryTrade", &TdApiWrap::reqQryTrade)
.def("reqQryInvestorPosition", &TdApiWrap::reqQryInvestorPosition)
.def("reqQryInvestorAccount", &TdApiWrap::reqQryInvestorAccount)
.def("reqQryExchange", &TdApiWrap::reqQryExchange)
.def("reqQryInstrument", &TdApiWrap::reqQryInstrument)
.def("reqQryMarketData", &TdApiWrap::reqQryMarketData)
.def("reqQryContractBank", &TdApiWrap::reqQryContractBank)
.def("reqFromBankToFutureByFuture", &TdApiWrap::reqFromBankToFutureByFuture)
.def("reqFromFutureToBankByFuture", &TdApiWrap::reqFromFutureToBankByFuture)
.def("reqQueryBankAccountMoneyByFuture", &TdApiWrap::reqQueryBankAccountMoneyByFuture)
.def("onFrontConnected", pure_virtual(&TdApiWrap::onFrontConnected))
.def("onFrontDisconnected", pure_virtual(&TdApiWrap::onFrontDisconnected))
.def("onHeartBeatWarning", pure_virtual(&TdApiWrap::onHeartBeatWarning))
.def("onRspUserLogin", pure_virtual(&TdApiWrap::onRspUserLogin))
.def("onRspQryUserInvestor", pure_virtual(&TdApiWrap::onRspQryUserInvestor))
.def("onRspUserLogout", pure_virtual(&TdApiWrap::onRspUserLogout))
.def("onRspUserPasswordUpdate", pure_virtual(&TdApiWrap::onRspUserPasswordUpdate))
.def("onRspOrderInsert", pure_virtual(&TdApiWrap::onRspOrderInsert))
.def("onRspOrderAction", pure_virtual(&TdApiWrap::onRspOrderAction))
.def("onRspQryOrder", pure_virtual(&TdApiWrap::onRspQryOrder))
.def("onRspQryTrade", pure_virtual(&TdApiWrap::onRspQryTrade))
.def("onRspQryInvestorPosition", pure_virtual(&TdApiWrap::onRspQryInvestorPosition))
.def("onRspQryInvestorAccount", pure_virtual(&TdApiWrap::onRspQryInvestorAccount))
.def("onRspQryInvestor", pure_virtual(&TdApiWrap::onRspQryInvestor))
.def("onRspQryExchange", pure_virtual(&TdApiWrap::onRspQryExchange))
.def("onRspQryInstrument", pure_virtual(&TdApiWrap::onRspQryInstrument))
.def("onRspQryMarketData", pure_virtual(&TdApiWrap::onRspQryMarketData))
.def("onRspQryTransferBank", pure_virtual(&TdApiWrap::onRspQryTransferBank))
.def("onRspQryTransferSerial", pure_virtual(&TdApiWrap::onRspQryTransferSerial))
.def("onRspError", pure_virtual(&TdApiWrap::onRspError))
.def("onRtnOrder", pure_virtual(&TdApiWrap::onRtnOrder))
.def("onRtnTrade", pure_virtual(&TdApiWrap::onRtnTrade))
.def("onErrRtnOrderInsert", pure_virtual(&TdApiWrap::onErrRtnOrderInsert))
.def("onErrRtnOrderAction", pure_virtual(&TdApiWrap::onErrRtnOrderAction))
.def("onRtnInstrumentStatus", pure_virtual(&TdApiWrap::onRtnInstrumentStatus))
.def("onRspQryContractBank", pure_virtual(&TdApiWrap::onRspQryContractBank))
.def("onRtnFromBankToFutureByBank", pure_virtual(&TdApiWrap::onRtnFromBankToFutureByBank))
.def("onRtnFromFutureToBankByBank", pure_virtual(&TdApiWrap::onRtnFromFutureToBankByBank))
.def("onRtnFromBankToFutureByFuture", pure_virtual(&TdApiWrap::onRtnFromBankToFutureByFuture))
.def("onRtnFromFutureToBankByFuture", pure_virtual(&TdApiWrap::onRtnFromFutureToBankByFuture))
.def("onRtnQueryBankBalanceByFuture", pure_virtual(&TdApiWrap::onRtnQueryBankBalanceByFuture))
.def("onErrRtnBankToFutureByFuture", pure_virtual(&TdApiWrap::onErrRtnBankToFutureByFuture))
.def("onErrRtnFutureToBankByFuture", pure_virtual(&TdApiWrap::onErrRtnFutureToBankByFuture))
.def("onErrRtnQueryBankBalanceByFuture", pure_virtual(&TdApiWrap::onErrRtnQueryBankBalanceByFuture))
.def("onRspFromBankToFutureByFuture", pure_virtual(&TdApiWrap::onRspFromBankToFutureByFuture))
.def("onRspFromFutureToBankByFuture", pure_virtual(&TdApiWrap::onRspFromFutureToBankByFuture))
.def("onRspQueryBankAccountMoneyByFuture", pure_virtual(&TdApiWrap::onRspQueryBankAccountMoneyByFuture))
;
}
|
#pragma once
#include <string>
using namespace std;
class Complejo{
private:
int real, imag;
public:
Complejo();
Complejo(int r, int i);
int getReal();
int getImg();
Complejo operator+ (Complejo operando){
return suma(*this, operando);
}
Complejo operator* (Complejo operando){
return mult(*this, operando);
}
Complejo suma(Complejo r1, Complejo r2);
Complejo mult(Complejo r1, Complejo r2);
string toString();
};
|
//camera zoom mode
#include<iostream>
#include<SFML\graphics.hpp>
#include<GL\glew.h>
#include "inc\LoadShaders.h"
using namespace std;
using namespace sf;
const int CheckPeriodms=20;
const int RefreshTimeMaxms=30;
const int Time_BufsPerInput=0;//this doesnot sem to affect performance but why??
const int ProcessTimeMaxms=CheckPeriodms-RefreshTimeMaxms;
const int max_toBdrawn=20;
const int TeamSize=7;
const int winLen=1920/2;
const int winWid=1080/2;
const int fieldScale=winWid/3*.95;
const float playerFieldWidR=.02;
const float playerSize=playerFieldWidR*3;
const float playerOtlnSzR=.1;//outline size ratio
const float posIncUnit=playerSize*.04;
sf::Vector2i FieldCenter(winLen/2,winWid/2);
sf::Vector2f Scale((2-playerSize)*fieldScale,(1.5-playerSize)*fieldScale);//(fieldScale*2-playerSize-playerOutline,fieldScale*1.5-playerSize-playerOutline);
//Drawable toBdrawn[];
enum formation {attack,defense,hold};
void init();
void display();
int gameEventHandle(Event event);
class player{
public:
//Sprite jerseyS;
player(){
MaxSpeed=7;
Speed=sf::Vector2i(3,3);
Cir.setPointCount(20);
Cir.setRadius(playerSize);
Cir.setOrigin(playerSize*(1-playerOtlnSzR),playerSize*(1-playerOtlnSzR));
Cir.setFillColor(Color(255,0,0,100));
Cir.setOutlineThickness(playerSize*playerOtlnSzR);
Cir.setOutlineColor(Color(0,255,0,100));
Cir.scale(fieldScale,fieldScale);
}
void setName(string naam){
name=naam;
}
void setNum(short int anka){
num=anka;
}
void setPosition(sf::Vector2f v){
posInField=v;
setPosition();
}
void incPosition(int x=1,int y=1){
posInField.x+=Speed.x*x*posIncUnit;
posInField.y+=Speed.y*y*posIncUnit;
setPosition();
}
void incSpeed(int x,int y){
Speed.x+=(MaxSpeed>=(Speed.x+x)&&(Speed.x+x)>0)?x:0;
Speed.y+=(MaxSpeed>=(Speed.y+y)&&(Speed.y+y)>0)?y:0;
}
void setOcolor(Color Oc){
Cir.setOutlineColor(Oc);
}
void setIcolor(Color Ic){
Cir.setFillColor(Ic);
}
void draw(RenderWindow* tar) const{
tar->draw(Cir);
}
private:
inline void update_posInWin(){
posInWin=sf::Vector2f(FieldCenter.x+posInField.x*Scale.x,FieldCenter.y+posInField.y*Scale.y);
}
void setPosition(){
if(posInField.x<-1||posInField.x>1){
posInField.x=(posInField.x>1)?1:-1;
}
if(posInField.y<-1||posInField.y>1){
posInField.y=(posInField.y>1)?1:-1;
}
update_posInWin();
Cir.setPosition(posInWin);
}
string name;
short int num;
//Texture jerseyT;
sf::Vector2f posInField;
sf::Vector2f posInWin;
CircleShape Cir;
int MaxSpeed;
sf::Vector2i Speed;
};
class team{
public:
team(string naam,int s):name(naam),side(s){
side=(side>=0)?1:-1;
for(int i=0;i<TeamSize;i++){
players[i].setName(string(1,'A'+i));
players[i].setNum(i+1);
switch(i){
case 0:
players[i].setPosition(Vector2f(side*.1,0));
break;
case 1:
players[i].setPosition(Vector2f(side*.4,.5));
break;
case 2:
players[i].setPosition(Vector2f(side*.4,-.5));
break;
case 3:
players[i].setPosition(Vector2f(side*.7,.7));
break;
case 4:
players[i].setPosition(Vector2f(side*.7,0));
break;
case 5:players[i].setPosition(Vector2f(side*.7,-.7));
break;
case 6:players[i].setPosition(Vector2f(side*.9,0));
break;
}
}
aktv=0;
}
void set_name(string naam){
name=naam;
}
void move(int x,int y){
players[aktv].incPosition(x,y);
}
void draw(RenderWindow* tar){
for(int i=0;i<TeamSize;i++)
players[i].draw(tar);
}
void set_aktv(){}
private:
int formation;
int side;
player players[TeamSize];//field1.jpg","img//field1.jpg",};
int aktv;
string name;
};
class Field{
public:
Field(){
set();
FieldS.setTexture(FieldT);
FieldS.setOrigin(1367/2,937/2);
FieldS.scale(fieldScale*float(4)/1367,fieldScale*float(3)/937);//--(4) | (3)
//FieldS.setOrigin(4*fieldScale,3*fieldScale);
FieldS.setPosition(Vector2f(FieldCenter));
}
void draw(RenderTarget* tar){
//FieldS.scale(fieldScale,fieldScale);
//FieldS.scale(fieldScale,fieldScale);
tar->draw(FieldS);
}
void set(){
if(!FieldT.loadFromFile("img\\field1.jpg"))
cout<<"err loading texture";
}
private:
Texture FieldT;
Sprite FieldS;
};
class game{
public:
game():A("A",1),B("B",-1){
//A.players[0].setPosition(Vector2f(0,0));
}
void play();
void pause();
void refresh(RenderWindow* w){
w->clear();
field.draw(w);
A.draw(w);
B.draw(w);
w->display();
}
int eventHandle(Event);
private:
team A;
team B;
Field field;
float time;
};
int main()
{
sf::RenderWindow w(sf::VideoMode(winLen,winWid),"Foo2Y",Style::Default);
w.clear();
//initialise glew
GLenum err = glewInit();
if (GLEW_OK != err)
{
/* Problem: glewInit failed, something is seriously wrong. */
fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
}
//cout>>"Status: Using GLEW %s\n"<<glewGetString(GLEW_VERSION);
//cout<<"Opengl version: "<<glGetString(GL_VERSION);
sf::Event event,event1;
game g;
Clock clk;
while(w.isOpen()){/*
while(w.pollEvent(event)){
if(event.type==Event::Closed)
w.close();
else
g.eventHandle(event);
if(clk.getElapsedTime().asMilliseconds()>=80){
g.refresh(&w);
clk.restart();
}
}
if(clk.getElapsedTime().asMilliseconds()>=80){
g.refresh(&w);
clk.restart();
}*/
w.pollEvent(event);
while(w.pollEvent(event1)&&event.type==(event=event1).type){
if(clk.getElapsedTime().asMilliseconds()>=Time_BufsPerInput){
//clk.restart();
break;
}
}
g.eventHandle(event);
while(clk.getElapsedTime().asMilliseconds()<=ProcessTimeMaxms);
g.refresh(&w);
while(clk.getElapsedTime().asMilliseconds()<=CheckPeriodms);
clk.restart();
}
return 0;
}
int game::eventHandle(Event event){
switch(event.type){
case Event::KeyPressed:
switch(event.key.code){
case Keyboard::Left:
A.move(-1,0);
break;
case Keyboard::Right:
A.move(1,0);
break;
case Keyboard::Up:
A.move(0,-1);
break;
case Keyboard::Down:
A.move(0,1);
break;
default:
;
}
case Event::MouseButtonPressed:
default:
;
}
}
/*
if(event.type==sf::Event::Closed){
return 1;
}
else if(event.type==sf::Event::Resized){
//w.setSize(w.getSize());
}
else if(event.type==sf::Event::MouseButtonPressed){
}/*
else if(event.type==Event::KeyPressed){
if(event.key.code==Keyboard::A){
sf::Vector2f pos=player.getPosition();
player.setPosition(pos.x-10,pos.y);
}
else if(event.key.code==Keyboard::D){
sf::Vector2f pos=player.getPosition();
player.setPosition(pos.x+10,pos.y);
}
else if(event.key.code==Keyboard::S){
sf::Vector2f pos=player.getPosition();
player.setPosition(pos.x,pos.y+10);
}
else if(event.key.code==Keyboard::W){
sf::Vector2f pos=player.getPosition();
player.setPosition(pos.x,pos.y-10);
}
else if(event.key.code==Keyboard::R){
if(event.key.shift)
player.setRotation(player.getRotation()-10);
else
player.setRotation(player.getRotation()+10);
}
else if(event.key.code==Keyboard::Q){
}*/
/*
int gameExecute(Window& w){
Event event;
//Handle Events
while(w.pollEvent(event)){
if(event.type=Event::Closed)
return -1;
else if(event.type==Event::KeyPressed){
if(event.key=='a'){}
else if(event.key=='d'){player.}
else if(event.key=='w'){}
else if(event.key=='s'){}
}
}
//draw
return 0;
}
/*
CircleShape player(77,77);
player.setFillColor(Color::Red);
player.setPosition(200,300);
w.draw(player);
sf::VideoMode::getFullscreenModes
(
)
*/
|
#include <iostream>
#include <vector>
#include <list>
#include <queue>
#include <algorithm>
#include <iomanip>
#include <map>
#include <string>
#include <cstdio>
#include <cstring>
using namespace std;
struct Rank {
int id;
char name[10];
int score;
};
bool comps(Rank& a, Rank& b) {
if (a.score != b.score)
return a.score < b.score;
else return a.id < b.id;
}
bool compn(Rank& a, Rank& b) {
if (strcmp(a.name, b.name) != 0)
return strcmp(a.name, b.name) < 0;
else return a.id < b.id;
}
bool compi(Rank& a, Rank& b) {
return a.id < b.id;
}
int main() {
int n, k, score, id;
char name[10];
while (cin >> n >> k) {
Rank* v = new Rank[n];
for (int i = 0; i < n; i++) {
scanf("%d %s %d", &v[i].id, &v[i].name, &v[i].score);
}
switch (k) {
case 1: sort(v, v + n, compi); break;
case 2: sort(v, v + n, compn); break;
case 3: sort(v, v + n, comps); break;
default: break;
}
for (auto it = v; it != v + n; it++)
printf("%06d %s %d\n", it->id, it->name, it->score);
}
return 0;
}
|
#ifndef GNDX9DATASTREAM_H
#define GNDX9DATASTREAM_H
#include "GnMeshData.h"
class GnDX9DataStream;
class GNDIRECTX9RENDERER_ENTRY GnDX9MeshData : public GnMeshData
{
protected:
enum
{
MAX_DECLARATION_SIZE = 10,
};
protected:
LPDIRECT3DVERTEXDECLARATION9 mpDeclaration;
public:
GnDX9MeshData();
virtual ~GnDX9MeshData();
virtual GnDataStream* CreateDataStream(GnDataStream::eFormat format, guint32 vertexCount);
// IsChangedDataStream가 true면 GnDataStream의 버퍼만 다시 만들고
// IsAddDataStream이 true이면 LPDIRECT3DVERTEXDECLARATION9다시 생성하고 GnDataStream의 버퍼도 다시 만든다
virtual void UpdateData();
inline LPDIRECT3DVERTEXDECLARATION9 GetDeclaration() const { return mpDeclaration; }
protected:
// 데이터 스트림을 토대로
bool GetVertexElement9(GnDX9DataStream* pDataStream, D3DVERTEXELEMENT9& outVertexElement);
};
#endif // GNDX9DATASTREAM_H
|
/*
-----------------------------------------------------------------------------------------
Laboratory : POO2 - Laboratoire 14
File : cstring.h
Author : Thomas Benjamin, Gobet Alain
Date : 22.03.2018
Class : POO - A
Goal : Declaration of a class String similar to std::string
Remark(s) : -
----------------------------------------------------------------------------------------
*/
#ifndef STRING_CSTRING_H
#define STRING_CSTRING_H
//Pre-declaration of the class String for the << overload
class String;
//Declaration of the operator << overload
std::ostream& operator << (std::ostream& os, const String& s);
std::ostream& operator << (std::ostream& os, const String* s);
std::istream& operator >> (std::istream& is, String& s);
class String{
private:
char* str; //Contains the string value of this
public:
//------------------------Constructor/Destructor---------------------------
//Goal: Constructor
//Arguments: -
//Exceptions: -
String();
//Goal: Constructor
//Arguments: the value to assign to str
//Exceptions: -
String(const char* s);
//Goal: Constructor
//Arguments: the value to assign to str
//Exceptions: -
String(const String& s);
//Goal: Constructor
//Arguments: the value to assign to str
//Exceptions: -
String(char);
//Goal: Constructor
//Arguments: the value to assign to str
//Exceptions: -
String(int);
//Goal: Constructor
//Arguments: the value to assign to str
//Exceptions: -
String(double);
//Goal: Constructor
//Arguments: the value to assign to str
//Exceptions: -
String(bool);
//Goal: Constructor
//Arguments: the value to assign to str, the number of char to copy
//Exceptions: -
String(const String& s, size_t nb);
//Goal: Destructor
//Arguments: -
//Exceptions: -
~String();
//------------------------Methods-----------------------------------------
//Goal: Return the length of str
//Arguments: -
//Exceptions: -
size_t len() const;
//Goal: Return str
//Arguments: -
//Exceptions: -
char* getStr() const;
//Goal: Return the ith char of str (reassignable)
//Arguments: the position of the char in str
//Exceptions: invalid_argument
char& getChar(size_t i);
//Goal: Return the substring of str between begin and end (limits included)
//Arguments: the position of the first char, the position of the last
//Exceptions: invalid_argument
String subString(size_t begin, size_t end) const;
//Goal: Return true if s and this are equals
//Arguments: The String to compare with this
//Exceptions: -
bool equals(const String& s) const;
//Goal: Return true if c and str are equals
//Arguments: The char* to compare str with
//Exceptions: -
bool equals(const char* c) const;
//Goal: Copy the content of s in this and return a reference to this
//Arguments: The String that need to be copy in this
//Exceptions: -
String& copy(const String& s);
//Goal: Copy the content of c in this and return a reference to this
//Arguments: The char* that need to be copy in this
//Exceptions: -
String& copy(const char* c);
//Goal: Return a new String resulting from the concatenation of this and s
//Arguments: The String that need to be append
//Exceptions: -
String append(const String& s) const;
//Goal: Return a new String resulting from the concatenation of this and c
//Arguments: The char* that need to be append
//Exceptions: -
String append(const char* c) const;
//Goal: Append to this the content of s
//Arguments: -
//Exceptions: -
void appendSelf(const String& s);
//Goal: Append to this the content of c
//Arguments: -
//Exceptions: -
void appendSelf(const char* c);
//Goal: Reserve the size of s char to str and copy the content in str
//Arguments: The char to copy in str
//Exceptions: -
void reserveAndCopy(const char* s);
//------------------------Opertor overload-------------------------------
//Goal: Overload of the operator +
//Arguments: The String to concatenate with this
//Exceptions: -
String operator + (const String&) const;
//Goal: Overload of the operator +
//Arguments: The char* to concatenate with this
//Exceptions: -
String operator + (const char*) const;
//Goal: Overload of the operator +
//Arguments: The char*, the String to concatenate
//Exceptions: -
friend String operator + (const char* c, const String& s);
//Goal: Overload of the operator =
//Arguments: The String to assign to this
//Exceptions: -
String& operator = (const String&);
//Goal: Overload of the operator =
//Arguments: The char* to assign to this
//Exceptions: -
String& operator = (const char*);
//Goal: Overload of the operator +=
//Arguments: The String to concatenate with this
//Exceptions: -
void operator += (const String&);
//Goal: Overload of the operator +=
//Arguments: The char* to concatenate with this
//Exceptions: -
void operator += (const char*);
//Goal: Overload of the operator <<
//Arguments: the output stream, the String to print
//Exceptions: -
friend std::ostream& operator << (std::ostream& os, const String& s);
//Goal: Overload of the operator <<
//Arguments: the output stream, the String* to print
//Exceptions: -
friend std::ostream& operator << (std::ostream& os, const String* s);
//Goal: Overload of the operator >>
//Arguments: the input stream, the String to assign
//Exceptions: -
friend std::istream& operator >> (std::istream& is, String& s);
};
#endif //STRING_CSTRING_H
|
// Created on: 1993-01-13
// Created by: CKY / Contract Toubro-Larsen ( Deepak PRABHU )
// Copyright (c) 1993-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// 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, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _IGESDimen_FlagNote_HeaderFile
#define _IGESDimen_FlagNote_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <gp_XYZ.hxx>
#include <IGESDimen_HArray1OfLeaderArrow.hxx>
#include <IGESData_IGESEntity.hxx>
#include <Standard_Integer.hxx>
class IGESDimen_GeneralNote;
class gp_Pnt;
class IGESDimen_LeaderArrow;
class IGESDimen_FlagNote;
DEFINE_STANDARD_HANDLE(IGESDimen_FlagNote, IGESData_IGESEntity)
//! defines FlagNote, Type <208> Form <0>
//! in package IGESDimen
//! Is label information formatted in different ways
class IGESDimen_FlagNote : public IGESData_IGESEntity
{
public:
Standard_EXPORT IGESDimen_FlagNote();
//! This method is used to set the fields of the class
//! FlagNote
//! - leftCorner : Lower left corner of the Flag
//! - anAngle : Rotation angle in radians
//! - aNote : General Note Entity
//! - someLeaders : Leader Entities
Standard_EXPORT void Init (const gp_XYZ& leftCorner, const Standard_Real anAngle, const Handle(IGESDimen_GeneralNote)& aNote, const Handle(IGESDimen_HArray1OfLeaderArrow)& someLeaders);
//! returns Lower Left coordinate of Flag as Pnt from package gp
Standard_EXPORT gp_Pnt LowerLeftCorner() const;
//! returns Lower Left coordinate of Flag as Pnt from package gp
//! after Transformation.
Standard_EXPORT gp_Pnt TransformedLowerLeftCorner() const;
//! returns Rotation angle in radians
Standard_EXPORT Standard_Real Angle() const;
//! returns General Note Entity
Standard_EXPORT Handle(IGESDimen_GeneralNote) Note() const;
//! returns number of Arrows (Leaders) or zero
Standard_EXPORT Standard_Integer NbLeaders() const;
//! returns Leader Entity
//! raises exception if Index <= 0 or Index > NbLeaders()
Standard_EXPORT Handle(IGESDimen_LeaderArrow) Leader (const Standard_Integer Index) const;
//! returns Height computed by the formula :
//! Height = 2 * CH where CH is from theNote
Standard_EXPORT Standard_Real Height() const;
//! returns the Character Height (from General Note)
Standard_EXPORT Standard_Real CharacterHeight() const;
//! returns Length computed by the formula :
//! Length = TW + 0.4*CH where CH is from theNote
//! and TW is from theNote
Standard_EXPORT Standard_Real Length() const;
//! returns the Text Width (from General Note)
Standard_EXPORT Standard_Real TextWidth() const;
//! returns TipLength computed by the formula :
//! TipLength = 0.5 * H / tan 35(deg) where H is Height()
Standard_EXPORT Standard_Real TipLength() const;
DEFINE_STANDARD_RTTIEXT(IGESDimen_FlagNote,IGESData_IGESEntity)
protected:
private:
gp_XYZ theLowerLeftcorner;
Standard_Real theAngle;
Handle(IGESDimen_GeneralNote) theNote;
Handle(IGESDimen_HArray1OfLeaderArrow) theLeaders;
};
#endif // _IGESDimen_FlagNote_HeaderFile
|
//===================================== Bibliotecas E Definições =====================================
#include <EEPROM.h> //EEPROM
#include <SPI.h> //Biblioteca necessária para comunicação SPI
#include <SD.h> //Biblioteca necessária para comunicação SD card
#include <Wire.h> //Biblioteca para comunicação I2C com módulo RTC
#include <LiquidCrystal.h> //Biblioteca para display 16x2
//#include <avr/wdt.h> //Biblioteca referente ao Timer WatchDog
//============================================= HARDWARE =============================================
//Constantes
#define DS1307_ADDRESS 0x68
#define AtualizacaoDisplay 100
#define AtrasoBotoes 190
#define EnderecoTempoSalvar 0
#define EnderecoCalibracao 1
//Pinos
#define rs 2 //D2
#define en 3 //D3
#define d4 4 //D4
#define d5 5 //D5
#define d6 6 //D6
#define d7 7 //D7
#define up 8 //D8
#define select 9 //D9
#define mais 0 //D0
#define menos 1 //D1
#define SelecaoChip 10 //D10 -Chip Select
#define MOSI 11 //D11 - MOSI
#define MISO 12 //D12 - MISO
#define SCK 13 //D13 - SCk
#define Bateria_1 14 //A0
#define Bateria_2 15 //A1
#define Bateria_3 16 //A2
#define Bateria_4 17 //A3
//============================================= Variáveis ============================================
LiquidCrystal lcd (rs, en, d4, d5, d6, d7); //Crio o objeto lcd com seus respectivos pinos
const byte SelecionadorOpcao[8] = //Lista para o caractere especial (O quadrado)
{
0b00000,
0b00000,
0b01110,
0b01110,
0b01110,
0b01110,
0b00000,
0b00000
};
//Caracteres especiais
const byte C_Cedilhado[8] { //Lista para o caractere especial ("Ç")
0b00000,
0b01110,
0b10000,
0b10000,
0b10000,
0b01110,
0b00100,
0b00100
};
const byte O_Til[8] { //Lista para o caractere especial ("Õ")
0b01110,
0b00000,
0b01110,
0b10001,
0b10001,
0b10001,
0b01110,
0b00000
};
const byte A_Til[8] { //Lista para o caractere especial ("Ã")
0b01110,
0b00000,
0b01110,
0b00001,
0b01111,
0b10001,
0b01111,
0b00000
};
const byte A_Agudo[8] { //Lista para o caractere especial ("Ã")
0b00010,
0b00100,
0b01110,
0b00001,
0b01111,
0b10001,
0b01111,
0b00000
};
//Seletores para os menus
byte SeletorPrincipal = 0;
byte SeletorDadosBateria = 1;
byte SeletorConfiguracoes = 0;
//De tempo
byte Timer_salvar = 0;
byte HoraAnterior_salvar = 0;
byte MinutoAnterior_salvar = 0;
byte TempoParaSalvar = 1;
//Calibracao do filtro ADC
byte CalibracaoADC = 20; //de 0 à 40. 20 Seria é o equivalente de '0'
const float TensaoADC = 5.00f;
float offset = 0.00f;
//Número de amostras para o filtro ADC. Quanto maior, melhor, mas terá impacto no desempenho do sistema.
byte Amostras_Filtro = 30;
//Das baterias
float Bateria1 = 0.00f;
float Bateria2 = 0.00f;
float Bateria3 = 0.00f;
float Bateria4 = 0.00f;
//float Teste[20] = {0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f};
//Do relogio RTC
byte segundo = 0; //0~59
byte minuto = 0; //0~59
byte hora = 0; //Formato 24 horas
byte diasemana = 0; //0-6 -> Domingo - Sábado
byte dia = 0; //Dependendo do mês, de 1~31
byte mes = 0; //1~12
byte ano = 0; //0~99
//=================================== Inicio do Programa ==========================================
void setup() {
Wire.begin();
/* DEBUG
Serial.begin(9600);
*/
//Botões de interação
pinMode(up, INPUT_PULLUP);
pinMode(mais, INPUT_PULLUP);
pinMode(menos, INPUT_PULLUP);
pinMode(select, INPUT_PULLUP);
//Pinos ADC para as baterias
pinMode(Bateria_1, INPUT);
pinMode(Bateria_2, INPUT);
pinMode(Bateria_3, INPUT);
pinMode(Bateria_4, INPUT);
//pinMode(en, OUTPUT);
//Criação de caracteres especiais
lcd.createChar(1, SelecionadorOpcao);
lcd.createChar(2, C_Cedilhado);
lcd.createChar(3, O_Til);
lcd.createChar(4, A_Til);
lcd.createChar(5 , A_Agudo);
//Mensagem inicial display
lcd.clear();
lcd.begin(16, 2);
//Boas vindas
lcd.setCursor(2, 0);
lcd.print("Iniciando");
for(byte i = 0; i < 3; i++) {
lcd.write('.');
delay(1);
}
//Verifico e atualizo o tempo
if(EEPROM.read(EnderecoTempoSalvar) == 0) {
TempoParaSalvar = 1;
EEPROM.update(EnderecoTempoSalvar, 1);
}
TempoParaSalvar = EEPROM.read(EnderecoTempoSalvar);
//Enquanto o cartão não for inserido eu mostro o erro
while(!SD.begin(SelecaoChip)) {
erroAbrirCartao();
}
//Se for encontrado:
lcd.clear();
lcd.setCursor(3, 0);
lcd.print("Cartao SD ");
lcd.setCursor(2, 1);
lcd.print("encontrado.");
delay(50);
//Verifico e atualizo a calibracao
//CalibracaoADC = EEPROM.read(EnderecoCalibracao);
if(CalibracaoADC != 20) {
for(byte i = 0; i < (abs(CalibracaoADC-20)); i++) {
if(CalibracaoADC > 20) {
offset += 0.001;
}
else {
offset -= 0.001;
}
}
}
}
void loop() {
menuPrincipal();
}
|
#include "stdafx.h"
#include "CMemory.h"
#include <chrono>
#include <fstream>
#include <thread>
#include <unordered_map>
#include "alt-log.h"
#include "scripting/CScriptManager.h"
using namespace alt;
std::wstring _moduleDir;
static std::wstring GetModulePath(HMODULE module)
{
DWORD size = MAX_PATH;
std::vector<wchar_t> buffer(size);
do
{
buffer.resize(size);
GetModuleFileNameW(module, buffer.data(), size);
size = (DWORD)(size * 1.5);
} while (GetLastError() == ERROR_INSUFFICIENT_BUFFER);
std::wstring modulePath = std::wstring(buffer.begin(), buffer.end());
size_t slashPos = modulePath.size();
for (int i = int(modulePath.size() - 1); i >= 0; --i)
{
if (modulePath[i] == L'/' || modulePath[i] == L'\\') {
slashPos = i;
break;
}
}
std::wstring moduleDir = modulePath.substr(0, slashPos);
return moduleDir;
}
void Init()
{
CMemory::RunHooks();
CScriptManager::Instance().Init();
Log::Info << "Inited" << Log::Endl;
}
LPSTR (*GetCommandLineA_Orig)() = nullptr;
LPSTR WINAPI GetCommandLineA_Hook()
{
static bool inited = false;
if (!inited) {
inited = true;
Init();
}
return GetCommandLineA_Orig();
}
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
{
_moduleDir = GetModulePath(hModule);
CScriptManager::Instance().SetClientPath(_moduleDir);
CMemory::Base() = (uintptr_t)GetModuleHandle(NULL);
std::wstring logPath = _moduleDir + L"/log.txt";
Log::Push(new Log::FileStream(logPath));
std::wstring crossMapPath = _moduleDir + L"/crossmap.dat";
std::ifstream crossIn(crossMapPath, std::ifstream::binary);
uint64_t oldHash;
uint64_t newHash;
if (crossIn.good())
{
while (!crossIn.eof())
{
crossIn.read((char*)& oldHash, sizeof(uint64_t));
crossIn.read((char*)& newHash, sizeof(uint64_t));
CScriptManager::Instance().AddCrossMapEntry(oldHash, newHash);
}
}
Log::Info << "RDR2 Scripthook initialized" << Log::Endl;
MH_Initialize();
CMemory(GetCommandLineA).Detour(GetCommandLineA_Hook, &GetCommandLineA_Orig);
break;
}
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
MH_Uninitialize();
Log::Info << "RDR2 Scripthook deinitialized" << Log::Endl;
break;
}
return TRUE;
}
|
// Copyright (c) 2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// 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, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _Graphic3d_BoundBuffer_HeaderFile
#define _Graphic3d_BoundBuffer_HeaderFile
#include <Graphic3d_Buffer.hxx>
//! Bounds buffer.
class Graphic3d_BoundBuffer : public NCollection_Buffer
{
DEFINE_STANDARD_RTTIEXT(Graphic3d_BoundBuffer, NCollection_Buffer)
public:
//! Empty constructor.
Graphic3d_BoundBuffer (const Handle(NCollection_BaseAllocator)& theAlloc)
: NCollection_Buffer (theAlloc),
Colors (NULL),
Bounds (NULL),
NbBounds (0),
NbMaxBounds (0) {}
//! Allocates new empty array
bool Init (const Standard_Integer theNbBounds,
const Standard_Boolean theHasColors)
{
Colors = NULL;
Bounds = NULL;
NbBounds = 0;
NbMaxBounds = 0;
Free();
if (theNbBounds < 1)
{
return false;
}
const size_t aBoundsSize = sizeof(Standard_Integer) * theNbBounds;
const size_t aColorsSize = theHasColors
? sizeof(Graphic3d_Vec4) * theNbBounds
: 0;
if (!Allocate (aColorsSize + aBoundsSize))
{
Free();
return false;
}
NbBounds = theNbBounds;
NbMaxBounds = theNbBounds;
Colors = theHasColors ? reinterpret_cast<Graphic3d_Vec4* >(myData) : NULL;
Bounds = reinterpret_cast<Standard_Integer* >(theHasColors ? (myData + aColorsSize) : myData);
return true;
}
//! Dumps the content of me into the stream
virtual void DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth = -1) const Standard_OVERRIDE
{
OCCT_DUMP_TRANSIENT_CLASS_BEGIN (theOStream)
OCCT_DUMP_BASE_CLASS (theOStream, theDepth, NCollection_Buffer)
OCCT_DUMP_FIELD_VALUE_POINTER (theOStream, Colors)
OCCT_DUMP_FIELD_VALUE_POINTER (theOStream, Bounds)
OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, NbBounds)
OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, NbMaxBounds)
}
public:
Graphic3d_Vec4* Colors; //!< pointer to facet color values
Standard_Integer* Bounds; //!< pointer to bounds array
Standard_Integer NbBounds; //!< number of bounds
Standard_Integer NbMaxBounds; //!< number of allocated bounds
};
DEFINE_STANDARD_HANDLE(Graphic3d_BoundBuffer, NCollection_Buffer)
#endif // _Graphic3d_BoundBuffer_HeaderFile
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "Population.h"
#include "Specimen.h"
#include "../NeuralNetwork/Manager/NeuralNetworkManager.h"
#include "../NeuralNetwork/NeuralNetwork.h"
#include "../NeuralNetwork/Objects/Neuron/Neuron.h"
#include "../NeuralNetwork/Objects/Synapse/Synapse.h"
void UPopulation::Populate(uint8 NumberOfSpecies, ANeuralNetworkManager& NeuralnetworkManager)
{
for (uint8 i = 0; i < NumberOfSpecies; ++i)
{
USpecimen* Specimen = NewObject<USpecimen>(this);
Specimen->InitSpecimen(i + 1, NeuralnetworkManager);
Specimens.Add(Specimen);
}
}
void UPopulation::EvolveSpecimens(uint8 NumberOfSpecimensToKeep, uint8 NumberOfSpecimensToCross, uint8 SynapseMutationChance, uint8 BiasMutationChance,float MutationStep, uint8 CurrentGeneration)
{
//Array that contains the next generation of specimens
TArray<USpecimen*>NewSpecimens;
//Select bthe best specimens
Selection(NewSpecimens, NumberOfSpecimensToKeep);
// Make them have children
Crossover(NewSpecimens, NumberOfSpecimensToKeep, NumberOfSpecimensToCross, CurrentGeneration);
// Mutate all the specimens
Mutation(NewSpecimens, SynapseMutationChance, BiasMutationChance, MutationStep);
uint8 NumberOfSpecimens = Specimens.Num();
// Randomize the left specimens
for (uint8 i = NumberOfSpecimensToKeep + NumberOfSpecimensToCross; i < NumberOfSpecimens; ++i)
{
Specimens[i]->NeuralNetwork->Randomize();
NewSpecimens.Add(Specimens[i]);
NewSpecimens[i]->NumberOfSpecimen = i + 1;
NewSpecimens[i]->GenerationBorn = CurrentGeneration;
}
Specimens = NewSpecimens;
//PRINT_ST("Size: " + FString::FromInt(Specimens.Num()), 5.f, INFO);
}
void UPopulation::Selection(TArray<USpecimen*>& NewSpecimens, uint8 NumberOfSpecimensToKeep)
{
// As they are sorted by fitness, we'll keep the best ones.
for (uint8 i = 0; i < NumberOfSpecimensToKeep; ++i)
{
NewSpecimens.Add(Specimens[i]);
NewSpecimens[i]->NumberOfSpecimen = i + 1;
}
}
void UPopulation::Crossover(TArray<USpecimen*>& NewSpecimens, uint8 NumberOfParents, uint8 NumberOfSpecimensToMix, uint8 CurrentGeneration)
{
uint8 FirstParentIndex, SecondParentIndex;
// For every new child specimen
for (uint8 i = 0; i < NumberOfSpecimensToMix; ++i)
{
// Reset generation and index
Specimens[NumberOfParents + i]->ResetSpecimen(CurrentGeneration, NumberOfParents + i + 1);
// Meet his new random parents
FirstParentIndex = FMath::RandRange(0, NumberOfParents - 1);
SecondParentIndex = FMath::RandRange(0, NumberOfParents - 1);
// If they are the same, choose another one
if(FirstParentIndex == SecondParentIndex)
{
SecondParentIndex = (SecondParentIndex + 1) % NumberOfParents;
}
USpecimen* Parent = nullptr;
// For every neuron in the specimen
for (int8 k = 0; k < Specimens[NumberOfParents + i]->NeuralNetwork->NumberOfNeurons; ++k)
{
// Select which parent will set this neuron
if (FMath::RandBool())
{
Parent = Specimens[FirstParentIndex];
}
else
{
Parent = Specimens[SecondParentIndex];
}
//Set new Bias
Specimens[NumberOfParents + i]->NeuralNetwork->Neurons[k]->Bias = Parent->NeuralNetwork->Neurons[k]->Bias;
uint8 NumberOfSynapses = Specimens[NumberOfParents + i]->NeuralNetwork->Neurons[k]->Synapses.Num();
//Set new Synapses Weights
for (uint8 j = 0; j < NumberOfSynapses; ++j)
{
Specimens[NumberOfParents + i]->NeuralNetwork->Neurons[k]->Synapses[j]->Weight = Parent->NeuralNetwork->Neurons[k]->Synapses[j]->Weight;
}
}
NewSpecimens.Add(Specimens[NumberOfParents + i]);
NewSpecimens[i]->NumberOfSpecimen = i + 1;
//This algorithm is the real proof that having children is expensive
}
}
void UPopulation::Mutation(TArray<USpecimen*>& NewSpecimens, uint8 SynapseMutationChance, uint8 BiasMutationChance, float MutationStep)
{
// for every new specimen
for(USpecimen* Specimen: NewSpecimens)
{
//for every neuron
for(UNeuron* Neuron: Specimen->NeuralNetwork->Neurons)
{
//mutate all the synapses
for(USynapse* Synapse: Neuron->Synapses)
{
if (FMath::RandRange(1, 100) < SynapseMutationChance)
{
Synapse->Weight += FMath::FRandRange(-1.f, 1.f) * MutationStep;
}
}
// mutate the bias
if(FMath::RandRange(0,100)< BiasMutationChance)
{
Neuron->Bias += FMath::FRandRange(-1.f, 1.f) * MutationStep;
}
}
}
}
|
/*Team name: KitKat*/
#include <iostream>
#include <queue>
#include <cstdio>
using namespace std;
queue<int> q;
int main(){
int t, n, m, curmin, served, maxwait, totalwait, mechtime;
double ave;
cin >> t;
for(int tc = 1; tc <= t; tc++){
cin >> n;
curmin = served = 0;
for(int i = 0; i < n; i++){
cin >> m;
curmin += m;
if(curmin <= 240){
q.push(curmin);
served++;
}
}
maxwait = totalwait = 0;
if(!q.empty()){
mechtime = q.front (); q.pop();
}
while(!q.empty()){
m = q.front(); q.pop();
mechtime += 13;
if(m < mechtime){
totalwait += mechtime - m;
maxwait = max(maxwait, mechtime-m);
}
else{
mechtime = m;
}
}
if(served == 0){
ave = 0.0;
}
else{
ave = ((double)(totalwait))/((double)(served));
}
printf("Case #%d: %d %d %.2lf\n", tc, served, maxwait, ave);
}
}
|
//
// autotestscene.cpp
// AutoCaller
//
// Created by Micheal Chen on 2017/7/28.
//
//
#include "autotestscene.hpp"
#include "autocontroller.hpp"
#include "platform/CCApplication.h"
#include "imcases.hpp"
#include "talkservice.hpp"
USING_NS_CC;
using namespace ui;
using namespace std;
cocos2d::Scene* IMAutoTestScene::createScene()
{
auto scene = Scene::create();
auto layer = IMAutoTestScene::create();
scene->addChild(layer);
return scene;
}
bool IMAutoTestScene::init()
{
if (!Layer::init()) {
return false;
}
auto visibleSize = Director::getInstance()->getVisibleSize();
auto origin = Director::getInstance()->getVisibleOrigin();
_btn_start_1 = Button::create();
_btn_start_1->setTitleText("IM自动化测试");
_btn_start_1->addClickEventListener(CC_CALLBACK_0(IMAutoTestScene::startImTest, this));
_btn_start_1->setPosition(Vec2(origin.x + visibleSize.width /2.0, origin.y + visibleSize.height / 2.0));
_btn_start_1->setTitleFontSize(20.0);
addChild(_btn_start_1);
_btn_start_2 = Button::create();
_btn_start_2->setTitleText("Talk自动化测试");
_btn_start_2->addClickEventListener(CC_CALLBACK_0(IMAutoTestScene::startTalkTest, this));
_btn_start_2->setPosition(Vec2(origin.x + visibleSize.width /2.0, origin.y + visibleSize.height / 2.0 + 25.0));
_btn_start_2->setTitleFontSize(20.0);
addChild(_btn_start_2);
_btn_report = Button::create();
_btn_report->setTitleText("测试报告目录");
_btn_report->addClickEventListener(CC_CALLBACK_0(IMAutoTestScene::report, this));
_btn_report->setPosition(Vec2(origin.x + visibleSize.width/2.0,
origin.y + visibleSize.height / 2.0 - 30));
_btn_report->setTitleFontSize(20.0);
addChild(_btn_report);
_btn_send_email = Button::create();
_btn_send_email->setTitleText("发送IM报告邮件");
_btn_send_email->addClickEventListener(CC_CALLBACK_0(IMAutoTestScene::sendEmail, this));
_btn_send_email->setPosition(Vec2(origin.x + visibleSize.width/2.0,
origin.y + visibleSize.height / 2.0 - 80));
_btn_send_email->setTitleFontSize(20.0);
addChild(_btn_send_email);
_btn_stable_test = Button::create();
_btn_stable_test->setTitleText("稳定性测试Demo");
_btn_stable_test->setPosition(Vec2(origin.x + visibleSize.width /2.0,
origin.y + visibleSize.height/2.0 + 55));
_btn_stable_test->addClickEventListener(CC_CALLBACK_0(IMAutoTestScene::stableTest, this));
_btn_stable_test->setTitleFontSize(20.0);
addChild(_btn_stable_test);
_btn_voice = Button::create();
_btn_voice->setTitleText("发送语音");
_btn_voice->setPosition(Vec2(origin.x + visibleSize.width / 2.0 - 180, origin.y + visibleSize.height / 2.0 ));
_btn_voice->addClickEventListener(CC_CALLBACK_0(IMAutoTestScene::voiceTest, this));
_btn_voice->setTitleFontSize(20.0f);
addChild(_btn_voice);
_btn_geo = Button::create();
_btn_geo->setTitleText("获取地理位置");
_btn_geo->addClickEventListener(CC_CALLBACK_0(IMAutoTestScene::geoTest, this));
_btn_geo->setPosition(Vec2(origin.x + visibleSize.width / 2.0 + 180,
origin.y + visibleSize.height / 2.0));
_btn_geo->setTitleFontSize(20.0f);
addChild(_btn_geo);
_label = Label::createWithTTF("S:", "fonts/arial.ttf", 10.0);
std::string ver = cocos2d::StringUtils::format("IM Ver: %d; Talk Ver: %s", YIMManager::CreateInstance()->GetSDKVersion(), verToString(IYouMeVoiceEngine::getInstance()->getSDKVersion()).c_str());
_label->setString(ver);
_label->setPosition(Vec2(origin.x + visibleSize.width /2.0,
origin.y + visibleSize.height/2.0 + 70.0));
addChild(_label);
_label_for_progress = Label::createWithTTF("Progress", "fonts/arial.ttf", 12.0);
_label_for_progress->setString("Click button to begin...");
_label_for_progress->setPosition(Vec2(origin.x + visibleSize.width / 3,
origin.y + visibleSize.height/2.0 + 80.0));
addChild(_label_for_progress);
return true;
}
void IMAutoTestScene::startImTest()
{
_label_for_progress->setString("running im autotest... ");
im_controller.runTests();
_label_for_progress->setString("Finished!");
}
void IMAutoTestScene::startTalkTest()
{
_label_for_progress->setString("running talk autotest... ");
talk_controller.runTests();
_label_for_progress->setString("Finished!");
}
void IMAutoTestScene::geoTest()
{
im_controller.actionGetCurrentLocation();
}
void IMAutoTestScene::voiceTest()
{
im_controller.actionSendVoiceMsgChat();
}
void IMAutoTestScene::report()
{
std::string filename = ::filename();
cocos2d::log("Local file path : %s", filename.c_str());
_label->setString(filename);
Application::getInstance()->openURL(filename);
}
void IMAutoTestScene::sendEmail()
{
im_controller.sendemail();
}
#include "testbase/controller.h"
void IMAutoTestScene::stableTest()
{
static bool flag = false;
if (!flag) {
TestController::getInstance();
flag = true;
}
else {
TestController::destroyInstance();
TestController::getInstance();
}
}
|
#pragma once
#include "Interface/IRuntimeModule.h"
#include "Common/ConfigLoader.h"
namespace Rocket
{
Interface IApplication : implements IRuntimeModule
{
public:
IApplication() : m_IsRunning(true) {}
virtual ~IApplication() = default;
virtual void LoadConfig(const Ref<ConfigLoader>& config) = 0;
virtual void PreInitialize() = 0;
virtual void PostInitialize() = 0;
virtual void PreInitializeModule() = 0;
virtual int InitializeModule() = 0;
virtual void PostInitializeModule() = 0;
virtual void FinalizeModule() = 0;
bool IsRunning() { return m_IsRunning; }
void SetRunningState(bool state) { m_IsRunning = state; }
protected:
bool m_IsRunning;
};
IApplication *CreateApplicationInstance();
} // namespace Rocket
|
#include "settingdialog.h"
#include "ui_settingdialog.h"
SettingDialog::SettingDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::SettingDialog)
{
ui->setupUi(this);
}
SettingDialog::~SettingDialog()
{
delete ui;
}
void SettingDialog::setMaxH(const int & val)
{
ui->barMaxH->setValue(val);
}
void SettingDialog::setMinH(const int & val)
{
ui->barMinH->setValue(val);
}
void SettingDialog::setMaxS(const int & val)
{
ui->barMaxS->setValue(val);
}
void SettingDialog::setMinS(const int & val)
{
ui->barMinS->setValue(val);
}
void SettingDialog::setMaxV(const int & val)
{
ui->barMaxV->setValue(val);
}
void SettingDialog::setMinV(const int & val)
{
ui->barMinV->setValue(val);
}
void SettingDialog::setMaxROIHorizon(const int & val)
{
ui->barMaxHorizon->setValue(val);
}
void SettingDialog::setMinROIHorizon(const int & val)
{
ui->barMinHorizon->setValue(val);
}
void SettingDialog::setMaxROIVertical(const int & val)
{
ui->barMaxVertical->setValue(val);
}
void SettingDialog::setMinROIVertical(const int & val)
{
ui->barMinVertical->setValue(val);
}
void SettingDialog::setDetectionArea(const int & val)
{
ui->boxDetectionArea->setValue(val);
}
void SettingDialog::setSensitivity(const int & val)
{
ui->boxSensitivity->setValue(val);
}
int SettingDialog::getSensitivity()
{
return ui->boxSensitivity->value();
}
void SettingDialog::setSamplingFPS(const int & val)
{
ui->boxFPS->setValue(val);
}
void SettingDialog::setActionInterval(const int & val)
{
ui->boxInterval->setValue(val);
}
void SettingDialog::_emitColorBoundSignal()
{
emit changeColorUpperBound(_min_H > _max_H ? _min_H : _max_H,
_min_S > _max_S ? _min_S : _max_S,
_min_V > _max_V ? _min_V : _max_V);
emit changeColorLowerBound(_min_H < _max_H ? _min_H : _max_H,
_min_S < _max_S ? _min_S : _max_S,
_min_V < _max_V ? _min_V : _max_V);
}
void SettingDialog::_emitROISignal()
{
emit changeROI(_min_ROI_horizon < _max_ROI_horizon ? _min_ROI_horizon : _max_ROI_horizon,
_min_ROI_vertical < _max_ROI_vertical ? _min_ROI_vertical : _max_ROI_vertical,
_min_ROI_horizon > _max_ROI_horizon ? _min_ROI_horizon : _max_ROI_horizon,
_min_ROI_vertical > _max_ROI_vertical ? _min_ROI_vertical : _max_ROI_vertical);
}
void SettingDialog::on_btnReset_clicked()
{
emit resetSetting();
}
void SettingDialog::on_barMinH_valueChanged(const int &value)
{
ui->lblMinH->setText(QString::number(value));
_min_H = value;
_emitColorBoundSignal();
}
void SettingDialog::on_barMaxH_valueChanged(const int &value)
{
ui->lblMaxH->setText(QString::number(value));
_max_H = value;
_emitColorBoundSignal();
}
void SettingDialog::on_barMinS_valueChanged(const int &value)
{
ui->lblMinS->setText(QString::number(value));
_min_S = value;
_emitColorBoundSignal();
}
void SettingDialog::on_barMaxS_valueChanged(const int &value)
{
ui->lblMaxS->setText(QString::number(value));
_max_S = value;
_emitColorBoundSignal();
}
void SettingDialog::on_barMinV_valueChanged(const int &value)
{
ui->lblMinV->setText(QString::number(value));
_min_V = value;
_emitColorBoundSignal();
}
void SettingDialog::on_barMaxV_valueChanged(const int &value)
{
ui->lblMaxV->setText(QString::number(value));
_max_V = value;
_emitColorBoundSignal();
}
void SettingDialog::on_barMinHorizon_valueChanged(const int &value)
{
ui->lblMinHorizon->setText(QString::number(value) + QString("%"));
_min_ROI_horizon = value;
_emitROISignal();
}
void SettingDialog::on_barMaxHorizon_valueChanged(const int &value)
{
ui->lblMaxHorizon->setText(QString::number(value) + QString("%"));
_max_ROI_horizon = value;
_emitROISignal();
}
void SettingDialog::on_barMinVertical_valueChanged(const int &value)
{
ui->lblMinVertical->setText(QString::number(value) + QString("%"));
_min_ROI_vertical = value;
_emitROISignal();
}
void SettingDialog::on_barMaxVertical_valueChanged(const int &value)
{
ui->lblMaxVertical->setText(QString::number(value) + QString("%"));
_max_ROI_vertical = value;
_emitROISignal();
}
void SettingDialog::on_boxDetectionArea_valueChanged(const int &arg1)
{
emit changeDetectionArea(arg1);
}
void SettingDialog::on_boxInterval_valueChanged(const int & arg1)
{
emit changeActionInterval(arg1);
}
void SettingDialog::on_boxSensitivity_valueChanged(const int & arg1)
{
emit changeSensitivity(arg1);
}
void SettingDialog::on_boxFPS_valueChanged(const int &arg1)
{
emit changeSamplingFPS(arg1);
}
|
#include "town.h"
/*----------------------------------------------------------
If given a char value the constructor will initialize
the map array to the char, otherwise set to 'G'
----------------------------------------------------------*/
Town::Town(char type){
map = new char*[H_ACRE];
for (int i = 0; i < H_ACRE; i++){
map[i] = new char[V_ACRE];
}
for (int h = 0; h < H_ACRE; h++){
for (int v = 0; v < V_ACRE; v++){
set_map_value(h,v,type);
}
}
pwp_count_set(0);
}
Town::~Town(){
for (int i = 0; i < H_ACRE; i++){
delete [] map[i];
}
delete [] map;
}
/*----------------------------------------------------------
Returns the array of characters of the map. DANGEROUS only
use if full control of map is needed.
----------------------------------------------------------*/
char ***Town::get_map_array(){
return ↦
}
/*----------------------------------------------------------
Sets a field on the map array.
Returns 1 if the field could not be set.
----------------------------------------------------------*/
int Town::set_map_value(int h_location, int v_location, char value){
//make sure the location is valid, otherwise return 1
if (h_location >= H_ACRE || v_location >= V_ACRE || h_location < 0 || v_location < 0)
return 1;
else{
map[h_location][v_location] = value;
return 0;
}
}
/*----------------------------------------------------------
Returns the value at a location. Returns '\0' if
location is not valid
----------------------------------------------------------*/
char Town::get_map_value(int h_location, int v_location) {
if (h_location >= H_ACRE || v_location >= V_ACRE || h_location < 0 || v_location < 0)
return '\0';
else{
return map[h_location][v_location];
}
return '\0';
}
/*----------------------------------------------------------
Returns the number of tiles have a matching value; used
to count quantity of a type
----------------------------------------------------------*/
int Town::count_value(char type){
int count = 0;
for (int h = 0; h < H_ACRE; h++){
for (int v = 0; v < V_ACRE; v++){
if (type == map[h][v])
++count;
}
}
return count;
}
/*----------------------------------------------------------
saves the map to a specified file location.
----------------------------------------------------------*/
int Town::save_map(std::string file){
std::ofstream mapfile;
mapfile.open(file);
//Check to make sure it can be opened
if (!mapfile.is_open())
return 1;
std::string* mapstring = get_map_string();
mapfile << *mapstring;
for (std::vector<Entity*>::iterator it = entity_list.begin(); it != entity_list.end(); ++it){
Entity* ent = (Entity*) *it;
mapfile << *(ent->get_name()) << ',' << ent->get_x() << " ," << ent->get_y() << '\n';
}
//no failure!
mapfile.close();
delete mapstring;
return 0;
}
/*----------------------------------------------------------
loads the map from a specified file location.
----------------------------------------------------------*/
int Town::load_map(std::string file,std::map <QString, Entity*> *feature_list){
std::ifstream mapfile;
mapfile.open(file);
//Check that file exists
if (!mapfile.is_open())
return 1;
//begin reading
for (int v = 0; v < V_ACRE; v++){
for (int h = 0; h < H_ACRE; h++){
set_map_value(h, v, (char) mapfile.get());
if (h == H_ACRE -1)
mapfile.get(); //get rid of the newline
}
}
//read for entitys
std::string* line = new std::string();
std::getline(mapfile, *line);
while (line != NULL && !line->empty()){
Read_data data(line, 3);
Entity* object = new Entity(feature_list->at(QString::fromStdString(*data.get_string(0))));
object->move(data.get_int(1), data.get_int(2));
entity_list.push_back(object);
pwp_count_add(object->is_pwp());
std::getline(mapfile, *line);
}
return 0;
}
/*----------------------------------------------------------
Returns the map in a string format, useful for debug. IS
NOT AUTOMATICALLY DEALLOCATED.
----------------------------------------------------------*/
std::string* Town::get_map_string(){
std::string* lin = new std::string("");
for (int v = 0; v < V_ACRE; v++){
for (int h = 0; h < H_ACRE; h++){
*lin += get_map_value(h,v);
}
*lin += '\n';
}
return lin;
}
/*----------------------------------------------------------
Adds an entity to the list of entitys
----------------------------------------------------------*/
void Town::add_entity(Entity* entity) {
entity_list.push_back(entity);
}
/*----------------------------------------------------------
Returns the entity list
----------------------------------------------------------*/
std::vector<Entity *> *Town::get_entity_list() {
return &entity_list;
}
void Town::pwp_count_set(int num){
pwps = num;
}
void Town::pwp_count_add(int increment){
pwps+= increment;
}
int Town::get_pwp_count(){
return pwps;
}
Entity* Town::find_entity(int x, int y, int radius){
int low_x = x - radius;
int high_x = x + radius;
int low_y = y - radius;
int high_y = y + radius;
for (std::vector<Entity*>::iterator it = entity_list.begin(); it != entity_list.end(); ++it){
Entity* current = (Entity*) *it;
//check to see if current entity is in range
if (current->get_x() < high_x && current->get_x() > low_x && current->get_y() < high_y && current->get_y() > low_y){
return current;
}
}
//fail condition
return NULL;
}
|
#include "f3lib/io/TerrainIncReader.h"
#include <fstream>
#include <sstream>
#include <iostream>
#include <codecvt>
#include <regex>
bool f3::io::readTerrainInc(const std::string& filepath, f3::types::TerrainTextureIdMap& terrainIdMap)
{
std::wifstream ifs(filepath.c_str());
ifs.imbue(std::locale(ifs.getloc(), new std::codecvt_utf16<wchar_t, 0xffff, std::consume_header>));
using convert_type = std::codecvt_utf8<wchar_t>;
std::wstring_convert<convert_type, wchar_t> converter;
std::wregex regex(L"\\s*(\\d+)\\s+(\\d+)\\s+\"([\\w|.|-]+)\"\\s+\\d+\\s+\"\"\\s*");
bool success = false;
if (ifs.is_open())
{
while (ifs.good())
{
std::wstring line;
std::wsmatch m;
std::getline(ifs, line);
if (std::regex_match(line, m, regex))
{
int textureId = std::stoi(m[1]);
std::string s = converter.to_bytes(m[3].str());
terrainIdMap.insert(std::make_pair(textureId, s));
}
}
ifs.close();
success = true;
}
return success;
}
|
#ifndef RANDOM_NUMBER_GENERATOR_H
#define RANDOM_NUMBER_GENERATOR_H
class RandomNumberGenerator
{
public:
RandomNumberGenerator(unsigned int seed);
void setSeed(unsigned int seed);
void reset();
int getInt(int min, int max);
float getFloat(float min = 0.0f, float max = 1.0f);
bool getBool();
private:
int getNext();
unsigned int m_seed;
unsigned int m_value;
unsigned int m_a;
unsigned int m_b;
unsigned int m_m;
};
#endif // RANDOM_NUMBER_GENERATOR_H
|
void defineCor(int pwmRed, int pwmGreen, int pwmBlue){
//setColor(pwmRed,pwmGreen,pwmBlue);
/*
if (msg == "1"){
digitalWrite(Rele1, HIGH);
}else if (msg == "2"){
digitalWrite(Rele1, LOW);
}else if (msg == "3"){
digitalWrite(Rele2, HIGH);
}else if (msg == "4"){
digitalWrite(Rele2, LOW);
}else if(msg == "5"){
digitalWrite(Rele3, HIGH);
}else if(msg == "6"){
digitalWrite(Rele3, LOW);
}else if (msg == "restart"){
ESP.reset();
}*/
}
void setColor(int vermelho, int verde, int azul){
analogWrite(Rele1, vermelho); //
analogWrite(Rele2, verde);
analogWrite(Rele3, azul);
}
|
#ifndef WHILENODE_H
#define WHILENODE_H
#include <vector>
#include <string>
#include <iostream>
#include "Node.hpp"
using namespace std;
class WhileNode : public Node {
private:
Node *condition = nullptr;
Node *value = nullptr;
public:
WhileNode(Node *condition, Node *value);
/** isinteger checks whether or not a string given as parameter represents a number.
*
* @param n any sort of string
* @return - true if this string represents a number
* - false otherwise
*/
bool isinteger(std::string const &n) noexcept;
void printTree() override;
string printCheck(ClassNode *classNode) override;
};
#endif
|
// SPDX-FileCopyrightText: 2021 Samuel Cabrero <samuel@orica.es>
//
// SPDX-License-Identifier: MIT
#include <Buzzer.h>
#include "armoring.h"
#include "config.h"
#include "global.h"
#include "auth.h"
TArmoring::TArmoring() {
}
const char *TArmoring::name() const {
return STATE_ARMORING_STR;
}
bool TArmoring::timedout() {
return (millis() - m_timestamp > ARMORING_TIMEOUT_MS);
}
void TArmoring::enter() {
m_timestamp = millis();
Buzzer.warning();
}
void TArmoring::loop() {
if (Auth.authorized()) {
Global.setState(&Global.StateUnarmored);
return;
}
if (!timedout()) {
return;
}
Global.setState(&Global.StateArmored);
}
void TArmoring::exit() {
Buzzer.shutup();
}
|
#include "engine/graphics/ProgressBar.hpp"
ProgressBar::ProgressBar(int total, Uint8 r, Uint8 g, Uint8 b, Uint8 a, int x_pos, int y_pos){
x = x_pos;
y = y_pos;
red = r;
green = g;
blue = b;
alpha = a;
progressBar = new SDL_Rect();
BarBoundary = new SDL_Rect();
progressTimer = new LTimer();
progressTimer->start();
totalTime = total;
timeElapsed = 0;
progressBar->x = x;
progressBar->y = y;
BarBoundary->x = x;
BarBoundary->y = y;
BarBoundary->w = SCREEN_WIDTH/2;
BarBoundary->h = 20;
}
ProgressBar::~ProgressBar(){
}
void ProgressBar::render(){
UpdateBar();
SDL_SetRenderDrawColor(gEngine->gRenderer, red, green, blue, alpha );
SDL_RenderFillRect(gEngine->gRenderer, progressBar);
SDL_SetRenderDrawColor(gEngine->gRenderer, 0, 0, 0, 255);
SDL_RenderDrawRect(gEngine->gRenderer, BarBoundary);
}
void ProgressBar::UpdateBar(){
timeElapsed = progressTimer->getTicks();
progressBar->w = ((timeElapsed*SCREEN_WIDTH)/(2*totalTime));
progressBar->h = (20);
}
bool ProgressBar::isComplete(){
if (timeElapsed>totalTime){
return true;
}
return false;
}
|
#include <catch2/catch.hpp>
#include <replay/vector2.hpp>
using namespace replay;
TEST_CASE("vector2: Can read values from single-parameter ctor")
{
v2<float> v{ 4.32f };
REQUIRE(v[0] == 4.32f);
REQUIRE(v[1] == 4.32f);
}
TEST_CASE("vector2: Can read values from multi-parameter ctor")
{
v2<float> v{7.1f, 13.9f};
REQUIRE(v[0] == 7.1f);
REQUIRE(v[1] == 13.9f);
}
|
//
// Boat.hpp
// GAME2
//
// Created by ruby on 2017. 11. 11..
// Copyright © 2017년 ruby. All rights reserved.
//
#ifndef Boat_hpp
#define Boat_hpp
#include <iostream>
#include "Object.hpp"
using namespace std;
class Boat : public Object {
private:
bool hasShot;
int crtX, crtY;
public:
Boat(){}
Boat(int startX, int startY) : Object(startX, startY) {}
~Boat() {}
bool visibility();
bool get_hasShot() { return hasShot; }
void move();
char getShape() { return 'U'; }
};
#endif /* Boat_hpp */
|
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
const int DENOM = 7;
const int RMAP[DENOM][2] = {{'I', 1},
{'V', 5},
{'X', 10},
{'L', 50},
{'C', 100},
{'D', 500},
{'M', 1000}};
inline int r2n(char r)
{
for (int i = 0; i < DENOM; i++)
if (r == RMAP[i][0])
return RMAP[i][1];
return 0;
}
int get_value(const string& s)
{
int value = 0;
for (int i = 0; i < s.size(); i++) {
int curn = r2n(s[i]);
int nextn = i+1 < s.size() ? r2n(s[i+1]) : 0;
if (curn < nextn) {
value += nextn - curn;
i++;
}
else
value += curn;
}
return value;
}
string get_roman(int value)
{
stringstream roman;
while (value > 0) {
for (int i = DENOM-1; i >= 0; i--) {
int sub = i-1-(i+1)%2;
if (value >= RMAP[i][1]) {
value -= RMAP[i][1];
roman << (char)RMAP[i][0];
break;
}
else if (value >= RMAP[i][1]-RMAP[sub][1]) {
value -= RMAP[i][1]-RMAP[sub][1];
roman << (char)RMAP[sub][0] << (char)RMAP[i][0];
break;
}
}
}
return roman.str();
}
int main()
{
ifstream fin("C:/Users/s521059/CLionProjects/Euler Project/EulerP89/p089_roman.txt");
if (!fin) {
cerr << "Cannot open roman.txt!\n";
return 1;
}
string s;
int sum = 0;
while (fin >> s) {
int value = get_value(s);
string roman = get_roman(value);
sum += s.size() - roman.size();
}
cout << sum << endl;
}
|
//Слова называются анаграммами, если одно из них можно получить перестановкой букв в другом.
//Например, "eat" и "tea" — анаграммы, потому что состоят из одних и тех же букв в разном порядке.
//Даны пары слов. Проверьте, можно ли назвать слова в каждой паре анаграммами.
//Формат ввода:
//Сначала дано число пар слов N, затем в N - строках содержатся пары слов, которые необходимо проверить.Гарантируется, что все слова состоят из строчных латинских букв.
//
//Формат вывода:
//Выведите N строк : для каждой введённой пары слов напечатайте YES, если эти слова — анаграммы, и NO в противном случае.
//
//Примеры:
//ВВОД ВЫВОД
//3
//hare rhea YES
//pig squid NO
//wolf fowl YES
#include <iostream>
#include <map>
#include <string>
using namespace std;
map<char, int> BuildCharMapCounters(string& w) {
map<char, int> m;
for (char& s : w) {
/*if (m.count(s) == 0) {
m[s] = 1;
}
else {
++m[s];
}*/
++m[s];//эквивалент условия
}
return m;
}
int main() {
int n;
cin >> n;
for (int i = 0; i < n; ++i) {
string first_word, second_word;
cin >> first_word >> second_word;
const map<char, int> map_char_fst_word = BuildCharMapCounters(first_word);
const map<char, int> map_char_snd_word = BuildCharMapCounters(second_word);
if (map_char_fst_word == map_char_snd_word) {
cout << "YES"s << endl;
}
else {
cout << "NO"s << endl;
}
}
return 0;
}
|
#include "stdafx.h"
#include "powerUp.h"
#include "consoleFunctions.h"
#include <iostream>
using namespace std;
void powerUp::powerUpTypeRandomize()
{
powerUpType = rand() % 3;
}
int powerUp::getPowerUpType()
{
return powerUpType;
}
int powerUp::getPowerUpX()
{
return powerUpX;
}
int powerUp::getPowerUpY()
{
return powerUpY;
}
void powerUp::powerUpUpdatePosition(int x, int y)
{
powerUpX = x;
powerUpY = y;
}
void powerUp::spawnPowerUp()
{
gotoxy(powerUpX, powerUpY);
setColor(15);
switch (powerUpType)
{
case 0:
cout << 'G';
break;
case 1:
cout << 'S';
break;
case 2:
cout << 'P';
break;
}
setColor(2);
}
void powerUp::deletePowerUp()
{
gotoxy(powerUpX, powerUpY);
cout << ' ';
}
void powerUp::movePowerUp()
{
deletePowerUp();
powerUpX--;
spawnPowerUp();
}
|
#include "bishop.h"
#include "board.h"
//Implementation of Bishop class, includes functions that get all possible moves for the rook (based on how to piece is allowed to move following the conventional rules of chess)
void bishop::setMoves(board* bin) //gets possible moves
{
for( int xdir = -1; xdir <= 1; xdir +=2 )
{
for( int ydir = -1; ydir <= 1; ydir +=2 )
{
int x, y;
for( int dis = 1; dis <= 7; dis++ )
{
x = getX() + xdir * dis; //bishops move diagonally
y = getY() + ydir * dis;
if(inbounds(x,y) && bin -> isOccupied(x,y))
{
if(bin -> getTeam(x,y) != getTeam())
{
addMove(x,y); //adds move if open and in bounds
}
break;
}
if(inbounds(x,y))
{
addMove(x,y);
}
else
{
break;
}
}
}
}
}
void bishop::setAttacks(board* bin) //gets all possible attacks
{
for( int xdir = -1; xdir <= 1; xdir +=2 )
{
for( int ydir = -1; ydir <= 1; ydir +=2 )
{
int x, y;
for( int dis = 1; dis <= 7; dis++ )
{
x = getX() + xdir * dis;
y = getY() + ydir * dis;
if(inbounds(x,y) && bin -> isOccupied(x,y))
{
addAttack(x,y);
break;
}
if(inbounds(x,y))
{
addAttack(x,y);
}
else
{
break;
}
}
}
}
}
void bishop::print() //prints out the piece
{
if(!getTeam())
std::cout<<'b';
else
std::cout<<'B';
}
bool bishop::operator==(const piece& pin) const
{
if(pin.getType() == BISHOP)
{
bishop* p = (bishop*) (&pin);
if(p -> x == x && p->y == y && p->team==team && p->hasmoved == hasmoved)
return true;
}
return false;
}
bishop::bishop(int x, int y, bool team) : piece(x,y,team) //constructor
{
setType(BISHOP);
}
bishop::bishop(const bishop& bin) : piece(bin.x,bin.y,bin.team)
{
setType(BISHOP);
copyData((piece*)(&bin));
}
bishop::~bishop(){} //deconstructor
|
#include "compiler/steps.hpp"
#include "compiler/exceptions.hpp"
#include "shared/optional_apply.hpp"
#include "vm/instruction_pointer.hpp"
#include <boost/variant/apply_visitor.hpp>
#include <utility>
#include <tuple>
#include <sstream>
namespace perseus
{
namespace detail
{
namespace clean = perseus::detail::ast::clean;
namespace parser = perseus::detail::ast::parser;
namespace art = perseus::detail::ast;
using namespace std::string_literals;
/// tag: any type allowed
struct tag_any_type
{
};
/// tag: any type except type_id::void_ allowed (for variable type deduction)
struct tag_not_void
{
};
/// Requirements for traversed expressions - must they be pure, according to the function? what type is expected?
struct expectations
{
/// requirements on the type - none, not void, or must be a given type.
typedef boost::variant<
tag_any_type,
tag_not_void,
// specific type expected
type_id
> expected_type;
expectations( bool pure, expected_type&& type )
: pure( pure )
, type( std::move( type ) )
{
}
/// whether the expression must be pure (if false, it may be either)
bool pure = true;
expected_type type{ tag_any_type{} };
bool is_purity_accepted( const bool actual_pure ) const
{
return actual_pure || !pure;
}
bool is_type_accepted( type_id actual_type ) const
{
/// visitor checking whether the type is valid
struct type_check
{
const type_id& actual;
bool operator()( const tag_any_type& ) const
{
return true;
}
bool operator()( const tag_not_void& ) const
{
return actual != type_id::void_;
}
bool operator()( const type_id& expected ) const
{
return actual == expected;
}
};
return boost::apply_visitor( type_check{ actual_type }, type );
}
};
struct variable
{
int offset;
type_id type;
};
using scope = std::map< std::string, variable >;
struct context
{
/// change expectations
context expect( expectations::expected_type type ) const
{
return context{ expectations{ expected.pure, std::move( type ) }, functions, return_type, stack_size, variables };
}
context push( int bytes ) const
{
return context{ expected, functions, return_type, stack_size + bytes, variables };
}
const expectations expected;
function_manager& functions;
/// return type of current function, for return expressions
const type_id return_type;
int stack_size;
scope variables;
};
/// @throws semantic_error on unknown signature
static function_manager::function_pointer find_function( const context& context, const function_signature& signature, const file_position& pos )
{
function_manager::function_pointer function;
if( !context.functions.get_function( signature, function ) )
{
function_manager::function_map::const_iterator begin, end;
std::tie( begin, end ) = context.functions.get_functions( signature.name );
std::stringstream error;
error << "Could not find " << signature << "!";
if( begin != end )
{
error << " Candidates:";
while( begin != end )
{
error << "\n " << begin->first;
++begin;
}
}
throw semantic_error( error.str(), pos );
}
return function;
}
static void check_function( const context& context, function_manager::function_pointer function, const file_position& pos )
{
if( !context.expected.is_type_accepted( function->second.return_type ) )
{
std::stringstream error;
error << function->first << " returns incorrect type " << get_name( function->second.return_type ) << "!";
throw type_error{ error.str(), pos };
}
if( !context.expected.is_purity_accepted( function->second.pure ) )
{
std::stringstream error;
error << "Can't call impure function " << function->first << " from pure function!";
throw semantic_error{ error.str(), pos };
}
}
static clean::expression convert( parser::expression&& exp, const context& context );
static clean::expression convert( parser::operand&& op, const context& context );
// Block Member conversion (expression/variable declaration)
struct convert_block_member
{
clean::block_member operator()( parser::expression& exp ) const
{
return convert( std::move( exp ), static_cast< const perseus::detail::context& >( context ) );
}
clean::block_member operator()( parser::explicit_variable_declaration& dec ) const
{
check_declaration_valid( dec.variable );
type_id type = get_type( dec.type );
// declared variable not yet visible in initial value expression
clean::expression initial_value = convert( std::move( dec.initial_value ), context.expect( type ) );
add_variable_to_context( std::move( dec.variable ), type );
return clean::variable_declaration{ std::move( initial_value ) };
}
clean::block_member operator()( parser::deduced_variable_declaration& dec ) const
{
check_declaration_valid( dec.variable );
clean::expression initial_value = convert( std::move( dec.initial_value ), context.expect( tag_not_void{} ) );
add_variable_to_context( std::move( dec.variable ), initial_value.type );
return clean::variable_declaration{ std::move( initial_value ) };
}
context& context;
private:
void check_declaration_valid( const file_position& pos ) const
{
if( !context.expected.is_type_accepted( type_id::void_ ) )
{
throw semantic_error{ "Variable declaration not valid here!", pos };
}
}
void add_variable_to_context( std::string&& name, type_id type ) const
{
context.variables[ std::move( name ) ] = { context.stack_size, type };
context.stack_size += get_size( type );
}
};
static clean::block_member convert( parser::block_member&& member, context& context )
{
// this should really be std::move( member ), but apply_visitor does not support rvalues
// see https://svn.boost.org/trac/boost/ticket/6971
return boost::apply_visitor( convert_block_member{ context }, member );
}
// Operand conversion (constants, variables, control structures etc.)
struct convert_operand
{
// Constants
clean::expression operator()( const std::int32_t& i ) const
{
// TODO: track position
if( !context.expected.is_type_accepted( type_id::i32 ) )
{
throw type_error{ "i32 type not valid here!", { 0, 0 } };
}
return { type_id::i32, { 0, 0 }, i };
}
clean::expression operator()( const bool& b ) const
{
// TODO: track position
if( !context.expected.is_type_accepted( type_id::bool_ ) )
{
throw type_error{ "bool type not valid here!",{ 0, 0 } };
}
return{ type_id::bool_, { 0, 0 }, b };
}
clean::expression operator()( const ast::void_expression& ) const
{
// TODO: track position
if( !context.expected.is_type_accepted( type_id::void_ ) )
{
throw type_error{ "void type not valid here!",{ 0, 0 } };
}
return{ type_id::void_, { 0, 0 }, ast::void_expression{} };
}
clean::expression operator()( const ast::string_literal& lit ) const
{
// TODO: string support
throw semantic_error( "Strings not yet supported!"s, lit );
}
// Variable references
clean::expression operator()( const ast::identifier& identifier ) const
{
// TODO: first class functions
auto it = context.variables.find( identifier );
if( it == context.variables.end() )
{
throw semantic_error( "No such variable: "s + identifier, identifier );
}
if( !context.expected.is_type_accepted( it->second.type ) )
{
throw type_error{ "Variable "s + identifier + " has incorrect type "s + get_name( it->second.type ), identifier };
}
return clean::expression{ it->second.type, identifier, clean::local_variable_reference{ it->second.offset - context.stack_size } };
}
// Unary Operation
clean::expression operator()( parser::unary_operation& op ) const
{
file_position pos = std::move( static_cast< file_position& >( op.operation ) );
clean::expression operand = convert( std::move( op.operand ), context.expect( tag_not_void{} ) );
function_signature signature{ std::move( static_cast< std::string& >( op.operation ) ), { operand.type } };
auto function = find_function( context, signature, pos );
check_function( context, function, pos );
return{ function->second.return_type, std::move( pos ), clean::call_expression{ function, { std::move( operand ) } } };
}
// If Expression
clean::expression operator()( parser::if_expression& exp ) const
{
clean::expression condition = convert( std::move( exp.condition ), context.expect( type_id::bool_ ) );
clean::expression then_expression = convert( std::move( exp.then_expression ), context );
clean::expression else_expression = convert( std::move( exp.else_expression ), context );
if( then_expression.type != else_expression.type )
{
throw type_error( "\"if\" branch types do not match: then branch returns "s + get_name( then_expression.type ) + ", else branch returns "s + get_name( else_expression.type ) + "!"s, condition.position );
}
return{ then_expression.type, condition.position, clean::if_expression{ std::move( condition ), std::move( then_expression ), std::move( else_expression ) } };
}
// While Expression
clean::expression operator()( parser::while_expression& exp ) const
{
clean::expression condition = convert( std::move( exp.condition ), context.expect( type_id::bool_ ) );
if( !context.expected.is_type_accepted( type_id::void_ ) )
{
throw type_error{ "Can't use while expression, void type illegal here!"s, condition.position };
}
clean::expression body = convert( std::move( exp.body ), context.expect( tag_any_type{} ) );
return{ type_id::void_, condition.position, clean::while_expression{ std::move( condition ), std::move( body ) } };
}
// Return Expression
clean::expression operator()( parser::return_expression& exp ) const
{
clean::expression return_value = convert( std::move( exp.value ), context.expect( context.return_type ) );
return{ context.return_type, return_value.position, clean::return_expression{ std::move( return_value ) } };
}
// Block Expression
clean::expression operator()( parser::block_expression& block ) const
{
std::vector< clean::block_member > members;
// TODO: track position
file_position pos{ 0, 0 };
// use the same context for all members since its stack size and variables change
perseus::detail::context member_context = context.expect( tag_any_type{} );
for( auto it = block.body.begin(); it != block.body.end(); )
{
parser::block_member& member = *it;
bool first = it == block.body.begin();
++it;
// type only matters for last member
if( it == block.body.end() )
{
perseus::detail::context type_context = member_context.expect( context.expected.type );
members.emplace_back( convert( std::move( member ), type_context ) );
}
else
{
members.emplace_back( convert( std::move( member ), member_context ) );
}
}
if( members.empty() )
{
if( !context.expected.is_type_accepted( type_id::void_ ) )
{
// TODO: track position
throw type_error( "Block can't be empty, void type illegal here!", pos );
}
return{ type_id::void_, pos, clean::block_expression{ std::move( members ) } };
}
struct block_type
{
type_id operator()( const clean::variable_declaration& ) const
{
return type_id::void_;
}
type_id operator()( const clean::expression& exp ) const
{
return exp.type;
}
};
type_id type = boost::apply_visitor( block_type{}, members.back() );
return{ type, pos, clean::block_expression{ std::move( members ) } };
}
// Expression
clean::expression operator()( parser::expression& exp ) const
{
return convert( std::move( exp ), context );
}
const context& context;
};
static clean::expression convert( parser::operand&& op, const context& context )
{
// this should really be std::move( op ), but apply_visitor does not support rvalues
// see https://svn.boost.org/trac/boost/ticket/6971
return boost::apply_visitor( convert_operand{ context }, op );
}
// Operation conversion
static clean::expression generate_call( const context& context, const std::string& name, std::vector< clean::expression >&& arguments, file_position position )
{
function_signature signature{ std::move( name ),{} };
signature.parameters.reserve( arguments.size() );
for( const clean::expression& argument : arguments )
{
signature.parameters.push_back( argument.type );
}
auto function = find_function( context, signature, position );
check_function( context, function, position );
return{ function->second.return_type, std::move( position ), clean::call_expression{ function, std::move( arguments ) } };
}
struct convert_operation
{
clean::expression operator()( parser::binary_operation& bin ) const
{
return generate_call(
context,
// name
std::move( static_cast< std::string& >( bin.operation ) ),
// arguments
{ std::move( lhs ), convert( std::move( bin.operand ), context.expect( tag_not_void{} ) ) },
// position
std::move( static_cast< file_position& >( bin.operation ) )
);
}
clean::expression operator()( parser::index_expression& exp ) const
{
return generate_call(
context,
"[]"s,
{ std::move( lhs ), convert( std::move( exp.index ), context.expect( tag_not_void{} ) ) },
lhs.position
);
}
clean::expression operator()( parser::call_expression& exp ) const
{
throw std::logic_error( "Should have been handled separately!" );
}
clean::expression lhs;
const context& context;
};
static clean::expression convert( parser::expression&& exp, const context& context )
{
// TODO FIXME: support more than 2 operands, i.e. handle precedence & associativity
if( exp.tail.empty() )
{
// simple operand
return convert( std::move( exp.head ), context );
}
else if( exp.tail.size() == 1 )
{
// binary expression, including call & index
parser::operation& operation = exp.tail.front();
parser::call_expression* call_exp = boost::get< parser::call_expression >( &operation );
if( call_exp )
{
// since we have no first class functions yet, we need to handle this separately
ast::identifier* function_name = boost::get< ast::identifier >( &exp.head );
if( !function_name )
{
throw semantic_error{ "Functions must be referred to by identifier! (No first-class functions yet.)"s, {0,0} };
}
function_signature signature{ std::move( static_cast< std::string& >( *function_name ) ),{} };
signature.parameters.reserve( call_exp->arguments.size() );
for( const parser::expression& argument : call_exp->arguments )
{
// this expression tree is unusable due to invalid local variable stack offsets, but we need to create it to determinate the type
// the offsets are off by the size of the function's return value, for which memory is allocated on the stack prior to the call
// but since we need the parameter types to determine the return type, some duplicate work is required
// (luckily function call arguments are typically rather simple, so this isn't totally terrible)
clean::expression exp = convert( parser::expression( argument ), context.expect( tag_not_void{} ) );
signature.parameters.push_back( exp.type );
}
file_position& position = *function_name;
auto function = find_function( context, signature, position );
check_function( context, function, position );
std::vector< clean::expression > arguments;
arguments.reserve( call_exp->arguments.size() );
// stack grows due to multiple arguments being pushed
int stack_offset = get_size( function->second.return_type );
for( auto& arg : call_exp->arguments )
{
clean::expression exp = convert( std::move( arg ), context.expect( tag_not_void{} ).push( stack_offset ) );
stack_offset += get_size( exp.type );
arguments.emplace_back( std::move( exp ) );
}
return{ function->second.return_type, std::move( position ), clean::call_expression{ function, std::move( arguments ) } };
}
else
{
clean::expression lhs = convert( std::move( exp.head ), context.expect( tag_not_void{} ) );
const perseus::detail::context convert_context = context.push( get_size( lhs.type ) );
// this should really be std::move( exp.tail.front() ), but apply_visitor does not support rvalues
// see https://svn.boost.org/trac/boost/ticket/6971
return boost::apply_visitor( convert_operation{ std::move( lhs ), convert_context }, exp.tail.front() );
}
}
else
{
// n-ary expression (n > 2)
throw semantic_error{ "Sorry, but for now operator precedence must be explicitly defined using parens."s, { 0, 0 } };
}
}
clean::file simplify_and_annotate( parser::file&& file, function_manager& functions )
{
ast::clean::file result;
result.functions.reserve( file.functions.size() );
for( auto& function : file.functions )
{
scope initial_scope;
{
int offset = -static_cast< int >( sizeof( instruction_pointer::value_type ) ); // return address
for( auto it = function.arguments.rbegin(); it != function.arguments.rend(); ++it )
{
auto& arg = *it;
type_id type = get_type( arg.type );
offset -= get_size( type );
initial_scope.emplace( scope::value_type{ std::move( arg.name ), variable{ offset, type } } );
}
}
// set up context: expected return type, purity
type_id return_type = function.manager_entry->second.return_type;
expectations expected{ function.manager_entry->second.pure, return_type };
context initial_context{ expected, functions, return_type, 0, std::move( initial_scope ) };
result.functions.emplace_back(
clean::function_definition{ convert( std::move( function.body ), static_cast< const context& >( initial_context ) ), function.manager_entry }
);
}
return result;
}
}
}
|
#include "../inc.h"
#include "../linear/matrix.h"
#include "../linear/square.h"
#include "../linear/vector.h"
#include "affine.h"
#include "line.h"
#include "surface_plane.h"
#include <math.h>
#include <initializer_list>
#include <vector>
#ifndef CLASS_TRANSFORM
#define CLASS_TRANSFORM
#if defined(_T) && !defined(_3D_LIB_FOR_EGE_TEMP__T)
#define _3D_LIB_FOR_EGE_TEMP__T _T
#undef _T
#endif
#if defined(_I) && !defined(_3D_LIB_FOR_EGE_TEMP__I)
#define _3D_LIB_FOR_EGE_TEMP__I _I
#undef _I
#endif
#if defined(_X) && !defined(_3D_LIB_FOR_EGE_TEMP__X)
#define _3D_LIB_FOR_EGE_TEMP__X _X
#undef _X
#endif
namespace Z_3D_LIB_FOR_EGE {
class _transform;
class _transform {
typedef _transform _Tself;
typedef double _Titem;
typedef _square < 4, _Titem > _Tsquare4;
typedef _square < 3, _Titem > _Tsquare3;
typedef _affine_vector _Tv4;
typedef _vector < 3, _Titem > _Tv3;
typedef _line _Tline;
typedef _plane _Tplane;
public :
static _Tsquare4 exec(
const std::initializer_list< _Tsquare4 >& ms,
std::vector< _Tv4 >& vs = std::vector< _Tv4 >(),
std::vector< _Tv4 >& tg_vs = std::vector< _Tv4 >()) {
_Tsquare4 _m = _Tself::_J(ms);
if (vs != std::vector< _Tv4 >())
return _m;
int i = 0;
if (tg_vs == std::vector< _Tv4 >()) {
for (_Tv4 v : vs) {
tg_vs[i] = *((_Tv4*)&((_matrix< 1, 4, _Titem >)v * _m));
i++;
}
} else {
for (_Tv4& v : vs) {
v = *((_Tv4*)&((_matrix< 1, 4, _Titem >)v * _m));
}
}
return _m;
}
static _Tsquare3 _I() {
_Tsquare3 _m(IDENTITY_MATRIX);
return _m;
}
static _Tsquare3 _T(const _Tv3& src) {
return *((_Tsquare3*)&(_Tv3::trans(src) * src));
}
static _Tsquare3 _X(const _Tv3& src) {
_Tsquare3 _m;
_m[0][1] = src[2];
_m[0][2] = -1 * src[1];
_m[1][0] = -1 * src[2];
_m[1][2] = src[0];
_m[2][0] = src[1];
_m[2][1] = -1 * src[0];
return _m;
}
static _Tsquare4 _J(const std::initializer_list< _Tsquare4 >& ms) {
_Tsquare4 _t(IDENTITY_MATRIX);
for (_Tsquare4 m : ms) {
_t = _t * m;
}
return _t;
}
template < int s, int t, int u, int v >
static _matrix < s + t, u + v, _Titem > _join(
const _matrix < s, u, _Titem > & m11,
const _matrix < s, v, _Titem > & m12,
const _matrix < t, u, _Titem > & m21,
const _matrix < t, v, _Titem > & m22
) {
_Titem _t[s + t][u + v];
for (int i = 0; i < s + t; i++)
for (int j = 0; j < u + v; j++)
if (i < s)
if (j < u)
_t[i][j] = m11[i][j];
else
_t[i][j] = m12[i][j - u];
else
if (j < u)
_t[i][j] = m21[i - s][j];
else
_t[i][j] = m22[i - s][j - u];
return _matrix < s + t, u + v, _Titem > (_t);
}
static _Tsquare4 trans (const _Tv4& w) {
_matrix < 3, 3, _Titem > _11 = _square < 3, _Titem > (IDENTITY_MATRIX);
_matrix < 3, 1, _Titem > _12;
_matrix < 1, 3, _Titem > _21( w.down() );
_matrix < 1, 1, _Titem > _22 = _square < 1, _Titem > (IDENTITY_MATRIX);
return *(_Tsquare4*)&(_join(_11, _12, _21, _22));
}
static _Tv4 trans(const _Tv4& src, const _Tv4& w) {
return src * trans(w);
}
static _Tsquare4 rot(const _Tline& axis, double a) {
_matrix < 3, 3, _Titem > _11 = _I() * cos(a) + _T(axis.v.down()) * (_Titem(1) - cos(a)) + _X(axis.v.down()) * sin(a);
_matrix < 3, 1, _Titem > _12;
_matrix < 1, 3, _Titem > _21 = axis.p.down() * (_11 * -1 + _I());
_matrix < 1, 1, _Titem > _22 = _square < 1, _Titem > (IDENTITY_MATRIX);
return *(_Tsquare4*)&(_join(_11, _12, _21, _22));
}
static _Tv4 rot(const _Tv4& src, const _Tline& axis, double a) {
return src * rot(axis, a);
}
static _Tsquare4 mirror(const _Tplane& l) {
_matrix < 3, 3, _Titem > _11 = _I() - _T(l.n().down()) * 2;
_matrix < 3, 1, _Titem > _12;
_matrix < 1, 3, _Titem > _21 = l.n().down() * 2 * (l.p().down() PRO_DOT l.n().down());
_matrix < 1, 1, _Titem > _22 = _square < 1, _Titem > (IDENTITY_MATRIX);
return *(_Tsquare4*)&(_join(_11, _12, _21, _22));
}
static _Tv4 mirror(const _Tv4& src, const _Tplane& l) {
return src * mirror(l);
}
static _Tsquare4 scale(double s, _Tv4& q, const _Tv4& w = _Tv4()) {
if (w == _Tv4()) {
_matrix < 3, 3, _Titem > _11 = _I() * s;
_matrix < 3, 1, _Titem > _12;
_matrix < 1, 3, _Titem > _21 = q.down() * (_Titem(1) - s);
_matrix < 1, 1, _Titem > _22 { { _Titem(1) } };
return *(_Tsquare4*)&(_join(_11, _12, _21, _22));
} else {
_matrix < 3, 3, _Titem > _11 = _I() + _T(w.down()) * (s - _Titem(1));
_matrix < 3, 1, _Titem > _12;
_matrix < 1, 3, _Titem > _21 = w.down() * (q.down() PRO_DOT w.down()) * (_Titem(1) - s);
_matrix < 1, 1, _Titem > _22 { { _Titem(1) } };
return *(_Tsquare4*)&(_join(_11, _12, _21, _22));
}
}
static _Tv4 scale(const _Tv4& src, double s, _Tv4& q, const _Tv4& w = _Tv4()) {
return src * scale(s, q, w);
}
static _Tsquare4 shear(const _Tplane& l, const _Tv4& u, double a) {
_matrix < 3, 3, _Titem > _11 = (_Tv3::trans(l.n().down()) * u.down()) * tan(a) + _I();
_matrix < 3, 1, _Titem > _12;
_matrix < 1, 3, _Titem > _21 = u.down() * (l.p().down() PRO_DOT l.n().down()) * tan(a) * -1;
_matrix < 1, 1, _Titem > _22 { { _Titem(1) } };
return *(_Tsquare4*)&(_join(_11, _12, _21, _22));
}
static _Tv4 shear(const _Tv4&src, const _Tplane& l, const _Tv4& u, double a) {
return src * shear(l, u, a);
}
static _Tsquare4 ortho(const _Tplane& l) {
_matrix < 3, 3, _Titem > _11 = _I() - _T(l.n().down());
_matrix < 3, 1, _Titem > _12;
_matrix < 1, 3, _Titem > _21 = l.n().down() * (l.p().down() PRO_DOT l.n().down());
_matrix < 1, 1, _Titem > _22 { { _Titem(1) } };
return *(_Tsquare4*)&(_join(_11, _12, _21, _22));
}
static _Tv4 ortho(const _Tv4& src, const _Tplane& l) {
return src * ortho(l);
}
static _Tsquare4 persp(const _Tplane& l, const _Tv4& v) {
_matrix < 3, 3, _Titem > _11 = _Tv3::trans(l.n().down()) * v.down() * -1 + _I() * ((v.down() - l.p().down()) PRO_DOT l.n().down());
_matrix < 3, 1, _Titem > _12 = _matrix < 1, 3, _Titem >::trans(l.n().down()) * -1;
_matrix < 1, 3, _Titem > _21 = v.down() * (l.p().down() PRO_DOT l.n().down());
_matrix < 1, 1, _Titem > _22 { { v.down() PRO_DOT l.n().down() } };
return *(_Tsquare4*)&(_join(_11, _12, _21, _22));
}
static _Tv4 persp(const _Tv4& src, const _Tplane& l, const _Tv4& v) {
return src * persp(l, v);
}
static _Tsquare4 pseudodepth(const _Tplane& l, const _Tv4& v) {
_matrix < 3, 3, _Titem > _11 = _T(l.n().down()) * -1;
_matrix < 3, 1, _Titem > _12 = _matrix < 1, 3, _Titem >::trans(l.n().down()) * -1;
_matrix < 1, 3, _Titem > _21 = v.down() * (l.p().down() PRO_DOT l.n().down());
_matrix < 1, 1, _Titem > _22 { { v.down() PRO_DOT l.n().down() } };
return *(_Tsquare4*)&(_join(_11, _12, _21, _22));
}
static _Titem pseudodepth(const _Tplane& l, const _Tv4& v, const _Tv4& q) {
return ((q.down() - l.p().down()) PRO_DOT l.n().down()) / ((v.down() - l.p().down()) PRO_DOT l.n().down());
}
};
}
#if defined(_3D_LIB_FOR_EGE_TEMP__T)
#define _T _3D_LIB_FOR_EGE_TEMP__T
#undef _3D_LIB_FOR_EGE_TEMP__T
#endif
#if defined(_3D_LIB_FOR_EGE_TEMP__I)
#define _I _3D_LIB_FOR_EGE_TEMP__I
#undef _3D_LIB_FOR_EGE_TEMP__I
#endif
#if defined(_3D_LIB_FOR_EGE_TEMP__X)
#define _X _3D_LIB_FOR_EGE_TEMP__X
#undef _3D_LIB_FOR_EGE_TEMP__X
#endif
#endif;
|
//Copyright Yandex 2012
#ifndef LTR_CLIENT_UTILITY_DATA_INFO_H_
#define LTR_CLIENT_UTILITY_DATA_INFO_H_
#include <string>
using std::string;
/**
* Contains the information about the dataset, including
* name of the dataset, approach in the dataset,
* the format of the dataset and the file name.
*/
struct DataInfo {
/**
* Basic constructor.
*/
DataInfo() { }
// C++11 -> we have no initializer, so we MUST write
// stupid conctructor manually
/**
* Another implementation of the basic constructor.
* @param name_ - string containing the name
* @param approach_ - string containing approach information
* @param format_ - string containing format information
* @param file_name_ - string containing file name information
*/
DataInfo(const string& name_, const string& approach_,
const string& format_, const string& file_name_)
: name(name_)
, approach(approach_)
, format(format_)
, file(file_name_) { }
string name;
string approach;
string format;
string file;
};
/**
* Converts DataInfo object into the printable string
* @param Info - TDataInfo to convert
* @returns converted string
*/
string ToString(const DataInfo& Info);
#endif LTR_CLIENT_DATA_UTILITY_INFO_H_
|
#include<iostream>
#include<vector>
#include<algorithm>
#include<ctime>
#include<cstdlib>
#include<set>
using namespace std;
void row(vector<int> &v, set<int> &s, int i) {
int r = i / 9;
for(int j = 0; j<9; j++) {
if(v[r*9+j] !=0) {
s.insert(v[r*9+j]);
}
}
}
void col(vector<int> &v, set<int> &s, int i) {
int c = i % 9;
for(int j = 0; j<9; j++) {
if(v[j*9 + c] !=0) {
s.insert(v[j*9+c]);
}
}
}
void sq(vector<int> &v, set<int> &s, int i) {
int r = ((i / 9)/3)*3;
int c = ((i % 9)/3)*3;
for(int j = 0; j<3; j++) {
for(int k = 0; k<3; k++) {
if(v[(r+j)*9+c+k] !=0) {
s.insert(v[(r+j)*9+c+k]);
}
}
}
}
bool solve(vector<int> &v, int i) {
if(i >= 81) {
return true;
}
if(v[i] != 0) {
return solve(v, i+1);
}
set<int> su;
row(v, su, i);
col(v, su, i);
sq(v, su, i);
vector<int> u;
for(int j = 1; j<10; j++) {
if(su.find(j) == su.end()) {
u.push_back(j);
}
}
// random_shuffle(u.begin(), u.end());
for(int j = 0; j<u.size(); j++) {
v[i] = u[j];
bool r = solve(v, i+1);
if(r) {
return true;
}
}
v[i] = 0;
return false;
}
int main() {
vector<int> v(81, 0);
int sx, sy, x, y, z, a;
cin >> sx >> sy >> z >> a;
while(cin >> x >> y >> a) {
x = x*9.0/(double)sx;
y = y*9.0/(double)sy;
// cout << "[" << y << "," << x <<"] = " << a << "\n";
v[y*9+x] = a;
}
for(int i = 0; i<9; i++) {
for(int j = 0; j<9; j++) {
cerr << v[9*i+j] << " ";
}
cerr << endl;
}
// return 0;
srand (unsigned(time(0)));
solve(v, 0);
cout << "xdotool key ";
for(int i = 0; i<9; i++) {
for(int j = 0; j<9; j++) {
if (i % 2) {
cout << v[i*9+8-j] << " ";
if( j < 8) {
cout << " Left ";
}
}
else {
cout << v[i*9+j] << " ";
if (j < 8)
cout << " Right ";
}
}
cout << " Down ";
}
}
|
#pragma once
#include "../controls/RollupCtrl.h"
#include "../DecalEntity.h"
enum E_TERRAIN_PAINT_TYPE
{
E_TERRAIN_PAINT_NULL_TYPE,
E_TERRAIN_ADD,
E_TERRAIN_MINUS,
E_TERRAIN_PAINT_TYPE_COUNT
};
class CTerrainPaintTool : public CEditTool
{
public:
DECLARE_DYNCREATE(CTerrainPaintTool)
CTerrainPaintTool();
~CTerrainPaintTool();
void BeginTool();
void EndTool();
void Update();
void OnLButtonDown(UINT nFlags, CPoint point);
void OnLButtonUp(UINT nFlags, CPoint point);
void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags);
void OnMouseMove(UINT nFlags, CPoint point);
void SetBrushSize( Real brushSize );
void SetBrushHardness( Real hardness );
void SetBrushType( E_TERRAIN_PAINT_TYPE type );
void SetLayerEdit( uint8 layerId );
protected:
CRollupCtrl* m_pTerrainCtrl;
int m_iCurrentPageId;
E_TERRAIN_PAINT_TYPE mBrushType;
CDecalEntity mEditDecal;
bool mbBeginEdit;
Real mBrushSize;
Real mBrushHardness;
uint8 mLayerEdit;
int mHeightUpdateCountDown;
unsigned long mHeightUpdateRate;
unsigned long mTimeLastFrame;
};
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
**
** Copyright (C) 2000-2008 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** Yngve Pettersen
**
*/
#ifndef __SSLCIPHSPEC_H
#define __SSLCIPHSPEC_H
#ifdef _NATIVE_SSL_SUPPORT_
class SSL_MAC;
class SSL_GeneralCipher;
class SSL_PublicKeyCipher;
class SSL_CipherSpec{
public:
SSL_GeneralCipher *Method;
SSL_MAC *MAC;
SSL_PublicKeyCipher *SignCipherMethod;
SSL_CompressionMethod compression;
uint64 Sequence_number;
public:
SSL_CipherSpec(): Method(NULL),
MAC(NULL),
SignCipherMethod(NULL),
compression(SSL_Null_Compression),
Sequence_number(0){};
~SSL_CipherSpec();
};
#endif
#endif
|
// 0922_16.cpp : 定义控制台应用程序的入口点。
//进制转换
//输入一个十进制数N,将它转换成R进制数输出。
//输入数据包含多个测试实例,每个测试实例包含两个整数N(32位整数)和R(2<=R<=16, R<>10)。
//为每个测试实例输出转换后的数,每个输出占一行。如果R大于10,则对应的数字规则参考16进制(比如,10用A表示,等等)。
#include<iostream>
using namespace std;
int main()
{
char a[50];
char s[17] = "0123456789ABCDEF";
int N, R;
while (cin >> N >> R)
{
int i = 0;
if (N == 0)
cout << '0' << endl;
else
{
if (N < 0)
{
cout << "-";
N *= (-1);
}
while (N)
{
a[i++] = s[N%R];
N = N / R;
}
while (i--)
{
cout << a[i];
}
cout << endl;
}
}
return 0;
}
|
/******************************************************
Main Application
*****************************************************/
#include "Qwerty3D-PC.h"
using namespace Noise3D;
Qwerty::RenderModule::RenderModule():
mTimer(Noise3D::Ut::NOISE_TIMER_TIMEUNIT_MILLISECOND)
{
}
Qwerty::RenderModule::~RenderModule()
{
}
bool Qwerty::RenderModule::Init3D(HINSTANCE hInstance, void(mainLoopFunc()))
{
//get Root interface
m_pRoot = GetRoot();
//create a window (using default window creation function)
HWND windowHWND;
windowHWND = m_pRoot->CreateRenderWindow(1280, 800, L"Hahaha Render Window", hInstance);
//initialize input engine (detection for keyboard and mouse input)
mInputE.Initialize(hInstance, windowHWND);
//register main loop function, call MainLoop to enter
m_pRoot->SetMainLoopFunction(mainLoopFunc);
//---------------------------------------
const UINT bufferWidth = 1280;
const UINT bufferHeight = 800;
//init failed, exit
if (!m_pRoot->Init())return false;
//query pointer to IScene
m_pScene = m_pRoot->GetScenePtr();
//retrieve meshMgr and Create new mesh
m_pMeshMgr = m_pScene->GetMeshMgr();
m_pRenderer = m_pScene->CreateRenderer(bufferWidth, bufferHeight, windowHWND);
m_pRenderer->SwitchToFullScreenMode();
m_pCamera = m_pScene->GetCamera();
m_pLightMgr = m_pScene->GetLightMgr();
m_pMatMgr = m_pScene->GetMaterialMgr();
m_pTexMgr = m_pScene->GetTextureMgr();
m_pAtmos = m_pScene->GetAtmosphere();
m_pGraphicObjMgr = m_pScene->GetGraphicObjMgr();
//diffuse map
m_pTexMgr->CreateTextureFromFile("../../../media/Earth.jpg", "Earth", true, 1024, 1024, false);
m_pTexMgr->CreateTextureFromFile("../../../model/qwerty/arc18_filtered.PNG", "brick", false, 256, 256, false);
m_pTexMgr->CreateTextureFromFile("../../../media/sky.jpg", "Universe", false, 256, 256, false);
m_pTexMgr->CreateTextureFromFile("../../../media/bottom-right-conner-title.jpg", "BottomRightTitle", true, 0, 0, false);
//create font texture
m_pFontMgr = m_pScene->GetFontMgr();
m_pFontMgr->CreateFontFromFile("../../../media/STXINWEI.ttf", "myFont", 24);
m_pMyText_fps = m_pFontMgr->CreateDynamicTextA("myFont", "fpsLabel", "fps:000", 200, 100, NVECTOR4(0, 0, 0, 1.0f), 0, 0);
m_pMyText_fps->SetTextColor(NVECTOR4(0, 0.3f, 1.0f, 0.5f));
m_pMyText_fps->SetDiagonal(NVECTOR2(20, 20), NVECTOR2(170, 60));
m_pMyText_fps->SetFont("myFont");
m_pMyText_fps->SetBlendMode(NOISE_BLENDMODE_ALPHA);
//---------------------INIT QWERTY----------------
m_pScreenDescriptor = m_pMeshMgr->CreateMesh("screen");
m_pModelLoader->LoadFile_OBJ(m_pScreenDescriptor, "../../../model/qwerty/AsusZenbook-Screen-XY.obj");
//meshList.push_back(pScreenDescriptor);
m_pScreenDescriptor->SetPosition(0, 0, 0);
m_pScreenDescriptor->SetCullMode(NOISE_CULLMODE_NONE);
m_pScreenDescriptor->SetShadeMode(NOISE_SHADEMODE_PHONG);
//------------------MESH INITIALIZATION----------------
m_pModelLoader = m_pScene->GetModelLoader();
N_SceneLoadingResult res;
m_pModelLoader->LoadFile_FBX("../../../model/qwerty/testRoom.fbx", res);
for (auto & name : res.meshNameList)
{
IMesh* pMesh = m_pMeshMgr->GetMesh(name);
mMeshList.push_back(pMesh);
pMesh->SetCullMode(NOISE_CULLMODE_BACK);
pMesh->SetShadeMode(NOISE_SHADEMODE_PHONG);
}
m_pGraphicObjBuffer->AddLine3D({ 0,0,0 }, { 50.0f,0,0 }, { 1.0f,0,0,1.0f }, { 1.0f,0,0,1.0f });
m_pGraphicObjBuffer->AddLine3D({ 0,0,0 }, { 0,50.0f,0 }, { 0,1.0f,0,1.0f }, { 0,1.0f,0,1.0f });
m_pGraphicObjBuffer->AddLine3D({ 0,0,0 }, { 0,0,50.0f }, { 0,0,1.0f,1.0f }, { 0,0,1.0f,1.0f });
//----------------------------------------------------------
m_pCamera->SetViewAngle_Radian(MATH_PI *0.4f, float(1.5f));
m_pCamera->SetViewFrustumPlane(1.0f, 3000.f);
m_pCamera->SetPosition(170.0f, 10.0f, -170.0f);
m_pCamera->SetLookAt(0, 0, 0);
m_pModelLoader->LoadSkyDome(m_pAtmos, "Universe", 4.0f, 2.0f);
m_pAtmos->SetFogEnabled(false);
m_pAtmos->SetFogParameter(50.0f, 100.0f, NVECTOR3(0, 0, 1.0f));
m_pPointLight1 = m_pLightMgr->CreateDynamicPointLight("myPointLight1");
N_PointLightDesc pointLightDesc;
pointLightDesc.ambientColor = NVECTOR3(1.0, 1.0, 1.0);
pointLightDesc.diffuseColor = NVECTOR3(0, 0, 0);
pointLightDesc.specularColor = NVECTOR3(0, 0, 0);
pointLightDesc.mAttenuationFactor = 0.0001f;
pointLightDesc.mLightingRange = 1000.0f;
pointLightDesc.mPosition = NVECTOR3(0, 0, -40.0f);
pointLightDesc.specularIntensity = 1.0f;
pointLightDesc.diffuseIntensity = 1.0f;
m_pPointLight1->SetDesc(pointLightDesc);
//bottom right
m_pGraphicObjBuffer->AddRectangle(NVECTOR2(1100.0f, 750.0f), NVECTOR2(1280.0f, 800.0f), NVECTOR4(0.3f, 0.3f, 1.0f, 1.0f), "BottomRightTitle");
m_pGraphicObjBuffer->SetBlendMode(NOISE_BLENDMODE_ALPHA);
mQwertyDesc.pCamera = m_pCamera;
mQwertyDesc.pScreenDescriptor = m_pScreenDescriptor;
return true;
}
void Qwerty::RenderModule::EnterMainLoop()
{
m_pRoot->Mainloop();
}
void Qwerty::RenderModule::Render()
{
mFunction_InputProcess();
m_pRenderer->ClearBackground();
mTimer.NextTick();
//update fps lable
std::stringstream tmpS;
tmpS << "fps :" << mTimer.GetFPS() << std::endl;
m_pMyText_fps->SetTextAscii(tmpS.str());
//add to render list
for (auto& pMesh : mMeshList)m_pRenderer->AddToRenderQueue(pMesh);
m_pRenderer->AddToRenderQueue(m_pGraphicObjBuffer);
m_pRenderer->AddToRenderQueue(m_pMyText_fps);
m_pRenderer->SetActiveAtmosphere(m_pAtmos);
//pRenderer->AddToPostProcessList_QwertyDistortion(qwertyDesc);
//render
m_pRenderer->Render();
//present
m_pRenderer->PresentToScreen();
}
void Qwerty::RenderModule::Cleanup()
{
m_pRoot->ReleaseAll();
}
/************************************************
PRIVATE
************************************************/
void Qwerty::RenderModule::mFunction_InputProcess()
{
mInputE.Update();
if (mInputE.IsKeyPressed(Ut::NOISE_KEY_A))
{
m_pCamera->fps_MoveRight(-0.5f, FALSE);
}
if (mInputE.IsKeyPressed(Ut::NOISE_KEY_D))
{
m_pCamera->fps_MoveRight(0.5f, FALSE);
}
if (mInputE.IsKeyPressed(Ut::NOISE_KEY_W))
{
m_pCamera->fps_MoveForward(0.5f, FALSE);
}
if (mInputE.IsKeyPressed(Ut::NOISE_KEY_S))
{
m_pCamera->fps_MoveForward(-0.5f, FALSE);
}
if (mInputE.IsKeyPressed(Ut::NOISE_KEY_SPACE))
{
m_pCamera->fps_MoveUp(0.5f);
}
if (mInputE.IsKeyPressed(Ut::NOISE_KEY_LCONTROL))
{
m_pCamera->fps_MoveUp(-0.5f);
}
if (mInputE.IsMouseButtonPressed(Ut::NOISE_MOUSEBUTTON_LEFT))
{
m_pCamera->RotateY_Yaw((float)mInputE.GetMouseDiffX() / 200.0f);
m_pCamera->RotateX_Pitch((float)mInputE.GetMouseDiffY() / 200.0f);
}
//quit main loop and terminate program
if (mInputE.IsKeyPressed(Ut::NOISE_KEY_ESCAPE))
{
m_pRoot->SetMainLoopStatus(NOISE_MAINLOOP_STATUS_QUIT_LOOP);
}
}
|
#define BOOST_TEST_MODULE BajkaTestProgram
#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
#include <iostream>
#include <Pointer.h>
#include "Events.h"
//#include "helpers/TestObserver.h"
//#include "helpers/TestObservable.h"
//#include "helpers/TestEvent.h"
BOOST_AUTO_TEST_SUITE (EventTest);
/**
* Testuje w najprostszy sposób strukturę Observer - Observable.
*/
BOOST_AUTO_TEST_CASE (testBasic)
{
// TestObservable mouse;
//
// Ptr <TestObserver> sprite1 (new TestObserver);
// Ptr <TestObserver> sprite2 (new TestObserver);
//
// mouse.addObserver (sprite1);
//
// BOOST_CHECK (sprite1->eventCount == 0);
// BOOST_CHECK (sprite2->eventCount == 0);
//
// mouse.notifyObservers (TestEvent ());
// BOOST_CHECK (sprite1->eventCount == 1);
//
// mouse.notifyObservers (TestEvent ());
// BOOST_CHECK (sprite1->eventCount == 2);
//
// mouse.addObserver (sprite2);
//
// mouse.notifyObservers (TestEvent ());
// BOOST_CHECK (sprite1->eventCount == 3);
// BOOST_CHECK (sprite2->eventCount == 1);
//
// mouse.notifyObservers (TestEvent ());
// BOOST_CHECK (sprite1->eventCount == 4);
// BOOST_CHECK (sprite2->eventCount == 2);
}
BOOST_AUTO_TEST_SUITE_END ();
|
#include <bits/stdc++.h>
using namespace std;
typedef vector<char> VC;
typedef vector<VC> VVC;
VVC MAPA;
int R,C,Npuentes,i,j;
int movs[4][2]= {{0,1},{0,-1},{1,0},{-1,0}};
int busca(short int r, short int c){
int regreso=1;
if(r>=1 && r <=R && c>=1 && c<=C){
if(MAPA[r][c]!='.'){
if(MAPA[r][c] == 'x') regreso = 0;
MAPA[r][c] = '.';
for(short int k=0; k<4; k++){
regreso*= busca(r+movs[k][0],c+movs[k][1]);
}
}
}
return regreso;
}
int main()
{
ios_base::sync_with_stdio(0); cin.tie(0);
cin >> R >> C;
MAPA.resize(R+2,VC (C+2));
for(i=1; i<=R; i++){
for(j=1; j<=C; j++){
cin >> MAPA[i][j];
}
}
for(i=1; i<=R; i++){
for(j=1; j<=C; j++){
if(MAPA[i][j] != '.'){
Npuentes += busca(i,j);
}
}
}
if(Npuentes>0) Npuentes--;
cout << Npuentes << '\n';
return 0;
}
|
#define EPSILON_CLOSE_WITH_FWPDS 1
/*!
* @author Evan Driscoll
*/
#include "wali/Common.hpp"
#include "wali/DefaultWorklist.hpp"
#include "wali/wfa/WFA.hpp"
#include "wali/wfa/State.hpp"
#include "wali/wfa/TransFunctor.hpp"
#include "wali/wfa/Trans.hpp"
#include "wali/wfa/WeightMaker.hpp"
#include "wali/regex/AllRegex.hpp"
#include "wali/wpds/GenKeySource.hpp"
#include "wali/wfa/DeterminizeWeightGen.hpp"
#include "wali/wpds/WPDS.hpp"
#include "wali/KeyPairSource.hpp"
#include "wali/wpds/GenKeySource.hpp"
#include "wali/domains/SemElemSet.hpp"
#include "wali/wpds/fwpds/FWPDS.hpp"
#undef COMBINE // grumble grumble swear swear
#undef EXTEND
#include <algorithm>
#include <iostream>
#include <vector>
#include <stack>
#include <iterator>
using wali::WALI_EPSILON;
using wali::wfa::WFA;
using wali::wfa::ITrans;
using wali::domains::SemElemSet;
namespace
{
int
num_trans(WFA const & wfa)
{
wali::wfa::TransCounter ctr;
wfa.for_each(ctr);
return ctr.getNumTrans();
}
class SemElemSetLifter : public wali::wfa::ConstTransFunctor
{
WFA & target;
wali::domains::SemElemSet::SemElemSubsumptionComputer const & computer;
bool include_zeroes;
public:
SemElemSetLifter(WFA * output_to_here,
wali::domains::SemElemSet::SemElemSubsumptionComputer const & comp,
bool inc_zeroes)
: target(*output_to_here)
, computer(comp)
, include_zeroes(inc_zeroes)
{}
virtual void operator()(wali::wfa::ITrans const * t) {
wali::domains::SemElemSet::ElementSet es;
es.insert(t->weight());
//es.push_back(t->weight());
target.addTrans(t->from(),
t->stack(),
t->to(),
new wali::domains::SemElemSet(computer,
include_zeroes,
t->weight(),
es));
}
};
}
namespace wali
{
namespace wfa
{
//////////////////////////////
// epsilonCloseCached variants
WFA::AccessibleStateMap
WFA::epsilonCloseCached(Key state, WFA::EpsilonCloseCache & cache) const
{
return epsilonCloseCached_FwpdsDemand(state, cache);
}
// On-demand variants
WFA::AccessibleStateMap
epsilonCloseCached_genericDemand(WFA const & wfa,
Key state,
WFA::EpsilonCloseCache & cache,
WFA::AccessibleStateMap (WFA::* accessor)(Key) const)
{
WFA::EpsilonCloseCache::iterator loc = cache.find(state);
if (loc != cache.end()) {
return loc->second;
}
else {
WFA::AccessibleStateMap eclose = (wfa.*accessor)(state);
cache[state] = eclose;
return eclose;
}
}
WFA::AccessibleStateMap
WFA::epsilonCloseCached_MohriDemand(Key state, WFA::EpsilonCloseCache & cache) const
{
return epsilonCloseCached_genericDemand(*this, state, cache,
&wali::wfa::WFA::epsilonClose_Mohri);
}
WFA::AccessibleStateMap
WFA::epsilonCloseCached_FwpdsDemand(Key state, WFA::EpsilonCloseCache & cache) const
{
return epsilonCloseCached_genericDemand(*this, state, cache,
&wali::wfa::WFA::epsilonClose_Fwpds);
}
// "All" variants
/// Populates 'targets' with every state that is a target of a
/// non-epsilon transition. (The reason we do this is because algorithms
/// that require eclose(s) only do so for such states, plus the initial
/// state.
struct TransTargetFinder : ConstTransFunctor
{
std::set<Key> targets;
virtual void operator()( const wali::wfa::ITrans* t ) {
if (t->stack() != wali::WALI_EPSILON) {
targets.insert(t->to());
}
}
};
WFA::AccessibleStateMap
epsilonCloseCached_genericAll(WFA const & wfa,
Key state,
WFA::EpsilonCloseCache & cache,
WFA::AccessibleStateMap (WFA::* accessor)(Key) const)
{
if (cache.size() == 0) {
TransTargetFinder finder;
wfa.for_each(finder);
finder.targets.insert(wfa.getInitialState());
// A source of an eclose is the target of a non-eps transition
for (std::set<Key>::const_iterator source = finder.targets.begin();
source != finder.targets.end(); ++source)
{
cache[*source] = (wfa.*accessor)(*source);
}
}
// Return cache[state]
WFA::EpsilonCloseCache::iterator loc = cache.find(state);
assert(loc != cache.end());
return loc->second;
}
WFA::AccessibleStateMap
WFA::epsilonCloseCached_MohriAll(Key state, WFA::EpsilonCloseCache & cache) const
{
return epsilonCloseCached_genericAll(*this, state, cache,
&wali::wfa::WFA::epsilonClose_Mohri);
}
WFA::AccessibleStateMap
WFA::epsilonCloseCached_FwpdsAllSingles(Key state, WFA::EpsilonCloseCache & cache) const
{
return epsilonCloseCached_genericAll(*this, state, cache,
&wali::wfa::WFA::epsilonClose_Fwpds);
}
WFA::AccessibleStateMap
WFA::epsilonCloseCached_FwpdsAllMulti(Key source, WFA::EpsilonCloseCache & cache) const
{
if (cache.size() == 0) {
TransTargetFinder finder;
this->for_each(finder);
finder.targets.insert(this->getInitialState());
cache = genericFwpdsPoststar(finder.targets, is_epsilon_transition);
}
// Return cache[state]
WFA::EpsilonCloseCache::iterator loc = cache.find(source);
assert(loc != cache.end());
return loc->second;
}
////////////////////////
// epsilonClose variants
WFA::AccessibleStateMap
WFA::epsilonClose(Key state) const
{
return this->epsilonClose_Fwpds(state);
}
WFA::AccessibleStateMap
WFA::epsilonClose_Mohri(Key start) const
{
std::set<Key> worklist;
// Follows Fig 3 from 'Generic epsilon-Removal Algorithm for Weighted
// Automata" by Mohri.
std::map<Key, sem_elem_t> d; // estimates the shortest distance from start to key
std::map<Key, sem_elem_t> r; // weight added to d[q] since last time q was visited
sem_elem_t zero = getSomeWeight()->zero();
// Inialization
for (std::set<Key>::const_iterator p = Q.begin(); p != Q.end(); ++p) {
d[*p] = r[*p] = zero;
}
d[start] = r[start] = getSomeWeight()->one();
worklist.insert(start);
// Worklist loop
while (worklist.size() > 0) {
Key q = *worklist.begin();
worklist.erase(worklist.begin());
sem_elem_t r_q = r[q]; // the change in q's weight since the last time it was visited; just 'r' in the paper
r[q] = zero;
// so we want to look at all outgoing transitions from 'q'.
// kp_map_t maps from (source * stack) -> {trans}. Furthermore,
// this is a hash map so is not in any particular order, which
// means we have to loop over the whole dang thing. (If we had an
// explicit list of symbols we could do (for every symbol) but we
// can't.)
//
// The next three indentation levels are like 'for each e in E[q]' in
// the paper except that 'e' is called 'transition'
for(kp_map_t::const_iterator group = kpmap.begin();
group != kpmap.end(); ++group)
{
if (group->first.first == q
&& group->first.second == WALI_EPSILON)
{
//std::cout << "--- found some epsilon transitions\n";
TransSet const & transitions = group->second;
for (TransSet::const_iterator transition = transitions.begin();
transition != transitions.end(); ++transition)
{
// 'for each transition in E[q]'. Now we have one. The
// following variables aren't explicitly named in the paper,
// but I do here because either my names are too long (for
// 'next') or to reduce caching.
Key next = (*transition)->to(); // 'n[e]'
sem_elem_t w_e = (*transition)->weight(); // 'w[e]'
sem_elem_t delta = r_q->extend(w_e); // 'r*w[e]'
sem_elem_t new_d_n = d[next]->combine(delta); // 'd[n[e]] + (r*w[e])'
if (!new_d_n->equal(d[next])) {
//std::cout << "--- so I updated it's reachability amount and re-enqueued\n";
d[next] = new_d_n;
r[next] = r[next]->combine(delta);
worklist.insert(next);
}
} // for each outgoing transition from q...
} // ..
} // ...for each outgoing transition from q
} // while (!worklist.empty())
AccessibleStateMap out;
for (AccessibleStateMap::const_iterator iter = d.begin();
iter != d.end(); ++iter)
{
if (iter->second != zero) {
assert(!iter->second->equal(zero));
out[iter->first] = iter->second;
}
}
return out;
}
WFA::EpsilonCloseCache
WFA::genericFwpdsPoststar(std::set<Key> const & sources,
boost::function<bool (ITrans const *)> trans_accept) const
{
wali::wpds::fwpds::FWPDS wpds;
wpds.topDownEval(false);
sem_elem_t weight = getSomeWeight();
return genericWpdsPoststar(sources, trans_accept, wpds, weight->one(), weight->zero());
}
WFA::EpsilonCloseCache
WFA::genericWpdsPoststar(std::set<Key> const & sources,
boost::function<bool (ITrans const *)> trans_accept,
wpds::WPDS & wpds,
sem_elem_t query_weight,
sem_elem_t state_weight) const
{
Key p_state = getKey("__p");
Key query_accept = getKey("__accept");
Key dummy = getKey("__dummy");
// Convert this WFA into a WPDS so that we can run poststar
this->toWpds(p_state, &wpds, trans_accept);
// Add an additional dummy node to pull off the multi-source trick
if (sources.size() == 1u) {
wpds.add_rule(p_state, dummy,
p_state, *sources.begin(),
getSomeWeight()->one());
}
else {
for (std::set<Key>::const_iterator source = sources.begin();
source != sources.end(); ++source)
{
wpds.add_rule(p_state, dummy,
p_state, *source, *source,
getSomeWeight()->one());
}
}
// Set up the query automaton:
// dummy
// p_state -----------> ((query_accept))
// query_weight
WFA query;
query.addState(p_state, state_weight);
query.addState(query_accept, state_weight);
query.setInitialState(p_state);
query.addFinalState(query_accept);
query.addTrans(p_state, dummy, query_accept, query_weight);
// Issue poststar. Be careful to not force the output a la what Cindy
// was doing! (Actually I think we look at all the weights anyway so
// that shouldn't matter, but whatever.)
WFA const & result = wpds.poststar(query);
// The 'result' automaton should be something like
//
// dummy
// p_state --------------> ((query_accept))
// \ \ --+
// \ \ S /|
// \ \ /
// \ \ / source
// \| \| /
// --+ -+ /
// (p_state, source)
//
// for each 'source' in 'sources' and lots of symbols 'S' -- which are
// states in 'this' WFA. Each symbol S is in the epsilon close of
// 'source', so add it.
//
// Because of the representation of transitions, we again need to
// iterate over each (start, sym) pair then over the TransSet.
WFA::EpsilonCloseCache closures;
for (kp_map_t::const_iterator kp_iter = result.kpmap.begin();
kp_iter != result.kpmap.end(); ++kp_iter)
{
Key start = kp_iter->first.first;
Key target = kp_iter->first.second; // a state in some epsilon closure, maybe
TransSet const & transitions = kp_iter->second;
if (start != p_state) {
// We are on a (p_state, source) ---source---> ((query_accept))
// transition, which we don't care about
continue;
}
for (TransSet::const_iterator trans = transitions.begin();
trans != transitions.end(); ++trans)
{
Key to_state = (*trans)->to();
if ((*trans)->stack() == dummy) {
// We are on the (p_state) ---dummy---> ((query_accept))
// transition, which we don't care about.
assert (transitions.size() == 1u);
continue;
}
Key source = WALI_BAD_KEY;
if (sources.size() == 1u) {
source = *sources.begin();
}
else {
// to_state better be (p_state, source)_g#; we need to extract
// 'source'.
key_src_t to_state_refptr = getKeySource(to_state);
wpds::GenKeySource const * to_state_gen_source =
dynamic_cast<wpds::GenKeySource const *>(to_state_refptr.get_ptr());
assert(to_state_gen_source);
key_src_t state_pair = getKeySource(to_state_gen_source->getKey());
KeyPairSource const * to_state_pair =
dynamic_cast<KeyPairSource const *>(state_pair.get_ptr());
assert(to_state_pair);
source = to_state_pair->second();
}
assert(this->getState(source) != NULL);
// Now get the weight. That's the net weight from 'source' to
// 'target', where 'target' is actually a state in 'this' WFA.
sem_elem_t weight = (*trans)->weight();
if (!weight->equal(weight->zero())) {
closures[source][target] = (*trans)->weight();
}
}
}
return closures;
}
WFA::AccessibleStateMap
WFA::epsilonClose_Fwpds(Key source) const
{
std::set<Key> sources;
sources.insert(source);
EpsilonCloseCache const & cache = genericFwpdsPoststar(sources, is_epsilon_transition);
EpsilonCloseCache::const_iterator loc = cache.find(source);
assert(loc != cache.end());
return loc->second;
}
WFA::AccessibleStateSetMap
WFA::computeAllReachingWeights() const
{
return computeAllReachingWeights(SemElemSet::KeepAllNonduplicates, false);
}
WFA::AccessibleStateSetMap
WFA::computeAllReachingWeights(SemElemSet::SemElemSubsumptionComputer computer,
bool include_zeroes) const
{
// Lift weights to the sets
WFA lifted;
sem_elem_t lifted_zero = new SemElemSet(computer, include_zeroes, this->getSomeWeight()->zero());
SemElemSetLifter lifter(&lifted, computer, include_zeroes);
for (std::set<Key>::const_iterator q = Q.begin(); q != Q.end(); ++q) {
lifted.addState(*q, lifted_zero);
}
this->for_each(lifter);
lifted.setInitialState(this->getInitialState());
// finals don't matter
assert(num_trans(*this) == num_trans(lifted));
// Issue poststar from the initial state in the lifted automaton.
std::set<Key> sources;
sources.insert(lifted.getInitialState());
EpsilonCloseCache const & poststar_answer = lifted.genericFwpdsPoststar(sources, is_any_transition);
EpsilonCloseCache::const_iterator loc = poststar_answer.find(lifted.getInitialState());
assert(loc != poststar_answer.end());
assert(1u == poststar_answer.size());
AccessibleStateMap const & set_weights = loc->second;
// set_weights is almost what we want, except we don't want to make the
// user downcast everything to get the actual result.
AccessibleStateSetMap result;
for (AccessibleStateMap::const_iterator state_weight_pair = set_weights.begin();
state_weight_pair != set_weights.end(); ++state_weight_pair)
{
SemElemSet * set_weight = dynamic_cast<SemElemSet *>(state_weight_pair->second.get_ptr());
assert(result.find(state_weight_pair->first) == result.end());
result[state_weight_pair->first] = set_weight->getElements();
}
return result;
}
} // namespace wfa
} // namespace wali
// Yo emacs!
// Local Variables:
// c-file-style: "ellemtel"
// c-basic-offset: 2
// indent-tabs-mode: nil
// End:
|
#ifndef CSIDEBARWIDGET_H
#define CSIDEBARWIDGET_H
#include <QFrame>
QT_BEGIN_NAMESPACE
class QVBoxLayout;
class QButtonGroup;
QT_END_NAMESPACE
class CSideBarWidget : public QFrame
{
Q_OBJECT
public:
CSideBarWidget(QWidget *parent);
~CSideBarWidget();
void addTab(const QString& text, const QChar& icon);
void insertTab(int index, QString& text, const QString& icon);
void setCurrentIndex(int index);
Q_SIGNALS:
void currentIndexChanged(int);
private:
QVBoxLayout* m_mainLayout;
QButtonGroup* m_buttonGroup;
};
#endif // CSIDEBARWIDGET_H
|
// we are defining a fake i960Zx series processor, this processor does not exist but will be what I'm calling my simulated design
// It has an SALIGN value of 4 like the i960Kx,i960Sx, and i960MC processors
/// @todo figure out the arcada library to allow for QSPI and SDCard simultaneous interaction and write an example for the Adafruit_SPIFlash library when done
// Adapt this class to the target microcontroller board
// Right now I am targeting a grand central m4
#include <SPI.h>
#include <Adafruit_NeoPixel.h>
#include <Wire.h>
#if 0
#include <SdFat.h>
#include <Adafruit_SPIFlash.h>
#include <ArduinoJson.h>
#endif
#include <array>
#include "CoreTypes.h"
#include "Core.h"
#include "ProcessorMappingConfiguration.h"
#include "ProcessorAddress.h"
constexpr bool doCPUComputation = true;
constexpr auto i960Zx_SALIGN = 4;
Adafruit_NeoPixel onboardNeoPixel(1, PIN_NEOPIXEL, NEO_GRB + NEO_KHZ800);
#if 0
Adafruit_FlashTransport_QSPI flashTransport;
Adafruit_SPIFlash flash(&flashTransport);
FatFileSystem fatfs;
SdFat sdCard; // use SDCARD_SS_PIN for this one
/// the base configuration
const std::string filename = "/config.txt";
i960::MappingConfiguration mapping;
bool
loadConfiguration(const std::string& filename, i960::MappingConfiguration &theMapping) {
/// @todo fix this
// Open file for reading
File file = sdCard.open(filename.c_str());
// Allocate a temporary JsonDocument
// Don't forget to change the capacity to match your requirements.
// Use arduinojson.org/v6/assistant to compute the capacity.
StaticJsonDocument<16384> doc;
// Deserialize the JSON document
DeserializationError error = deserializeJson(doc, file);
if (error)
Serial.println(F("Failed to read file, using default configuration"));
// Copy values from the JsonDocument to the Config
theMapping.setName(doc["name"] | "An i960 Processor");
JsonArray blocks = doc["blocks"];
for (JsonVariant block : blocks) {
JsonObject theObject = block.as<JsonObject>();
auto index = theObject["index"].as<byte>();
auto& targetBlock = theMapping.get(index);
targetBlock.setType(theObject["type"].as<std::string>());
targetBlock.setFilename(theObject["filename"].as<std::string>());
targetBlock.setDescription(theObject["description"].as<std::string>());
targetBlock.setPermissions(theObject["perms"].as<std::string>());
}
// Close the file (Curiously, File's destructor doesn't close the file)
file.close();
return true;
}
#endif
[[noreturn]]
void
somethingBadHappened() {
digitalWrite(LED_BUILTIN, HIGH);
while (true) {
delay(1000);
}
}
constexpr Ordinal simpleProgram[] {
0x8cf03000, 0x00000010, // lda 10 <Li960R1>, g14
0x5c88161e, // mov g14, g1
0x5cf01e00, // mov 0, g14
0x0a000000, // ret
0x00000000, 0x00000000, 0x00000000,
//
0x8ca03000, 0x00ffffff, // lda ffffff, g4
0x58a50090, // and g0, g4, g4
0x8c803000, 0xff000000, // lda ff000000, g0
0x58840394, // or g4, g0, g0
0x86003000, 0x00000000, // callx 0
0x0a000000, // ret
0x00000000, 0x00000000, 0x00000000,
//
0x59840e10, // shlo 16, g0, g0
0x8ca03000, 0x00ff0000, // lda ff0000, g4
0x59840c10, // shro 16, g0, g0
0x58840394, // or g4, g0, g0
0x86003000, 0x00000020, // callx 20
0x0a000000, // ret
//
0x8cf03000, 0x00000094, // lda 94, g14
0x5c88161e, // mov g14, g1
0x5cf01e00, // mov 0, g14
0x5ca01e00, // mov 0, g4
0x3685000c, // cmpoble g0,g4,90
0x59a05014, // addo g4,1,g4
0x08fffff8, // b 84
0x84045000, // bx (g1)
0x0a000000, // ret
0x00000000, 0x00000000,
//
0x8c800104, // lda 0x104, g0
0x86003000, 0x00000050, // callx 50
0x90841000, // ld (g0), g0
0x84003000, 0x00000070, // bx 70
0x0a000000, // ret
0x00000000, // .word 0
//
0x5c201610, // mov g0, r4
0x59210e18, // shlo 24, r4, r4
0x58801988, // setbit 8,0,g0
0x59205404, // shro r4,1,r4
0x86003000, 0x00000050, // callx 50
0x59210901, // subo 1, r4, r4
0x92241000, // st r4, (g0)
0x0a000000, // ret
0x00000000, 0x00000000, 0x00000000,
//
0x5c801e01, // mov 1, g0
0x86003000, 0x000000c0, // callx c0
0x86003000, 0x000000a0, // callx a0
0x5c801e00, // mov 0, g0
0x86003000, 0x000000c0, // callx c0
0x86003000, 0x000000a0, // callx a0
0x08ffffd8, // b f0
0x00000000, // .word 0
// start point
0x84003000, 0x000000f0, // bx f0
0x0a000000, // ret
0x00000000, // .word 0
};
static_assert(simpleProgram[0x8>>2] == 0x5c88161e);
static_assert(simpleProgram[0x20>>2] == 0x8ca03000);
static_assert(simpleProgram[0xa0>>2] == 0x8c800104);
// the i960 has other registers and tables we need to be aware of so onboard sram will most likely _not_ be exposed to the i960 processor
// directly
constexpr Address zxBootBase = 0xFFFF'0000;
constexpr Address codeStartsAt = 0x0000'0120;
constexpr Address ledAddress = 0xFF00'0100;
constexpr Address sleepConstantAddress = 0xFF00'0104;
namespace i960 {
class ZxProcessor : public Core {
public:
using Core::Core;
~ZxProcessor() override = default;
Ordinal
load(Address address) noexcept override {
Serial.print("load: 0x");
Serial.println(address, HEX);
if (address < 0x128) {
return simpleProgram[address >> 2];
}
switch (address) {
case zxBootBase + 16: return codeStartsAt;
case sleepConstantAddress: return 0x100;
default: return 0;
}
}
void
storeByte(Address address, ByteOrdinal value) noexcept override {
}
void
storeShort(Address address, ShortOrdinal value) noexcept override {
}
void
store(Address address, Ordinal value) noexcept override {
switch (address) {
case ledAddress:
digitalWrite(LED_BUILTIN, value != 0 ? HIGH : LOW);
break;
}
}
void
badInstruction(Core::DecodedInstruction inst) noexcept override {
Serial.println("BAD INSTRUCTION!");
std::visit([](auto&& value) {
using K = std::decay_t<decltype(value)>;
Serial.print("Instruction opcode: 0x");
if constexpr (std::is_same_v<K, i960::MEMFormatInstruction>) {
Serial.print(value.upperHalf(), HEX);
}
Serial.println(value.lowerHalf(), HEX);
auto name = value.decodeName();
if (!name.empty()) {
Serial.print("Name: ");
Serial.println(name.c_str());
}
}, inst);
raiseFault();
somethingBadHappened();
}
void
busTestFailed() noexcept override {
somethingBadHappened();
}
};
/// @todo handle unaligned load/store and loads/store which span multiple sections
}
i960::ZxProcessor cpuCore(zxBootBase, i960Zx_SALIGN);
void setupSerial() {
Serial.begin(9600);
while (!Serial) {
delay(100);
}
}
void setupSPI() {
Serial.print("Starting up SPI...");
SPI.begin();
Serial.println("Done");
}
#if 0
void setupSDCard() {
Serial.print("Starting up onboard QSPI Flash...");
flash.begin();
Serial.println("Done");
Serial.println("Onboard Flash information");
Serial.print("JEDEC ID: 0x");
Serial.println(flash.getJEDECID(), HEX);
Serial.print("Flash size: ");
Serial.print(flash.size() / 1024);
Serial.println(" KB");
Serial.print("Initializing fileysstem on external flash...");
if (!fatfs.begin(&flash)) {
Serial.println("Error: filesystem does not exist! Please try SdFat_format example to make one!");
somethingBadHappened();
}
Serial.println("Done");
Serial.print("Starting up SD Card...");
if (!sdCard.begin(SDCARD_SS_PIN)) {
Serial.println("No card found");
} else {
Serial.println("Card found!");
}
}
#endif
void setupNeoPixel() {
Serial.print("Initialzing onboard NeoPixel...");
onboardNeoPixel.begin();
onboardNeoPixel.show();
Serial.println("Done");
}
#if 0
void setupMappingConfiguration() {
Serial.println(F("Loading mapping configuration..."));
if (!loadConfiguration(filename, mapping)) {
Serial.println("Unable to find mapping configuration, stopping!");
somethingBadHappened();
}
}
#endif
/// @todo implement the register frames "in hardware"
void setup() {
setupSerial();
Serial.println("i960 Simulator Starting up");
pinMode(LED_BUILTIN, OUTPUT);
setupSPI();
//setupSDCard();
setupNeoPixel();
//setupMappingConfiguration();
// last thing to do is do the post
if constexpr (doCPUComputation) {
cpuCore.post();
}
}
void loop() {
if constexpr (doCPUComputation) {
digitalWrite(LED_BUILTIN, HIGH);
cpuCore.cycle(); // put a single cycle through
delay(10);
digitalWrite(LED_BUILTIN, LOW);
delay(10);
}
}
|
// Example 6.1 : Buil-in arrays, std::array, simple algorithms
// Created by Oleksiy Grechnyev 2017
// Class Tjej is used here, it logs Ctors and Dtors
#include <iostream>
#include <string>
#include <array>
#include <experimental/array>
#include <algorithm>
#include <memory>
//#include "Tjej.h"
using namespace std;
//=======================================
/// Print a container. Works also with built-in arrays.
/// pair from maps cannot be printed like this
template <typename C>
void print(const C & c){
for (const auto & e : c)
cout << e << " ";
cout << endl;
}
//==============================
/// Print a container. This version uses iterators
template <typename C>
void print2(const C & c){
for (auto it = begin(c); it != end(c); ++it)
cout << *it << " ";
cout << endl;
}
//==============================
// Get array size, template magic !
// Works only with arrays, not pointers !!!
// Uses const ref to array
template <typename T, size_t SIZE>
size_t getArraySize(const T (&) [SIZE]){
return SIZE;
}
//==============================
int main(){
{
cout << "-----------------------------";
cout << "\nBuilt-in arrays : \n\n";
// Array definition
int a[12];
double b[3] = {0.1, 1.2, 2.3};
string weapons[] = {"Sword", "Axe", "Bow"};
constexpr int SIZE = 1024*16; // SIZE must be constexpr
char buffer[SIZE];
// C-string is a char array or char *, terminated with \0
char cString[] = "This is a null-terminated C-string"; // Automatically ended with \0
double matrix[10][10]; // Multidimensional
// Using indices : starts with 0 !!!
for (int i=0; i<12; ++i)
a[i] = i*i;
// Print using our template print
cout << "a = ";
print(a); // Note that print receives a as a ref to array
cout << "\nweapons = ";
print(weapons);
cout << "\nweapons = ";
print2(weapons); // print2 also works !
// Implicitly convert array to pointer
char * message = cString;
cout << "message = " << message << endl;
cout << "\nArrays and sizeof() : \n";
cout << "Size in bytes : sizeof a = " << sizeof a << endl;
cout << "Number of elements = " << sizeof a/sizeof(int) << endl;
// References and pointers to arrays
// This is stupid stuff, but funny
// Size must be always fixed in array refs and pointers !
// This template receives a by reference
cout << "\ngetArraySize(a) = " << getArraySize(a) << endl;
int (& aRef1) [12] = a; // Weird syntax, is't it?
int (* aPtr1) [12] = &a;
// It gets simpler if we create a type alias
using ArrayType = int [12];
ArrayType & aRef2 = a;
ArrayType * aPtr2 = &a;
// Iterator and range for
const string names[] = {"Karen", "Lucia", "Anastasia", "Margaret", "Alice"};
cout << "\nPrinting with range for:\n";
for (const string & s : names) // It actually uses begin(), end()
cout << s << " ";
cout << "\n\nPrinting with pointers :\n";
const string * eit = names + 5; // Position just after the last element
for (const string * it = names; it != eit; ++it)
cout << *it << " ";
cout << "\n\nPrinting with iterators (pointers actually) :\n";
for (const auto *it = begin(names); it != end(names); ++it)
cout << *it << " ";
cout << endl;
// Dynamic memory in heap
// Pointers are not real arrays!
// You cannot use range for, begin(), end() for pointers !
// Absolutely no way to tell the size !
// sizeof(data) returns pointer size (8 bytes) and not array size !
int size = 17; // Not constexpr
int * data = new int[size];
for (int i=0; i<size; ++i)
data[i] = i*i; // We can use operator[] with pointers
cout << "\nDynamic array : data = ";
for (int i=0; i<size; ++i)
cout << data[i]<< " ";
cout << endl;
cout << "sizeof(data) = " << sizeof(data) << endl;
delete [] data; // Array delete
// We can use unique_ptr (But not shared_ptr !)
unique_ptr<int[]> data2(new int[size]);
for (int i=0; i<size; ++i)
data2[i] = i*i;
cout << "\nDynamic array with unique_ptr : data2 = ";
for (int i=0; i<size; ++i)
cout << data2[i]<< " ";
cout << endl;
}
{
cout << "\n-----------------------------";
cout << "\nstd::array basics : \n\n";
// Must always specify size, part of the template !
array<string, 5> aS1{"Karen", "Lucia", "Anastasia", "Margaret", "Alice"};
cout << "aS1 = ";
print(aS1); // Our function print(), see above
constexpr int SIZE = 1024*16;
array<double, SIZE> aD; // Must be constexpr
auto aStr = std::experimental::make_array("Red", "Green", "Blue");
cout << "aStr = "; print(aStr);
// First and last elements
cout << "aS1.front() = " << aS1.front() << endl;
cout << "aS1.back() = " << aS1.back() << endl;
// get: compile-time index
cout << "get<2>(aS1) = " << get<2>(aS1) << endl;
// Declare a type alias to avoid repeated declaration
using SArray = array<string, 5>;
// Arrays can be copied
SArray aS2 = aS1;
// Let us create another array of 5 strings
SArray aS3 = {"One", "Two", "Three", "Four", "Five"};
aS2.swap(aS3); // Swap aS2 and aS3
// swap(aS2, aS3); // The same
cout << "\nAfter swap :\naS2 = "; print(aS2);
cout << "aS3 = "; print(aS3);
// Create an std::array object out of a built-in array
cout << "\nCreating std::array object out of built-in array :\n";
string a[] = {"Maria", "Nel", "Sophia", "Clair", "Mirage"};
auto aS4 = std::experimental::to_array(a);
cout << "aS4 = "; print(aS4);
// Get raw pointer
string * s = aS1.data();
// Fill with repeating value
cout << "\nFill:\n";
array <int, 10> aI;
aI.fill(17);
cout << "aI = "; print(aI);
// std::array of funny types
// Pointers
int i1 = 13, i2 = 17, i3 = 666;
array <int *, 3> aPtr{&i1, &i2, &i3}; // Pointers
array <const int *, 3> aCPtr{&i1, &i2, &i3}; // Pointers to const
// Constants
array<const string, 5> cNames{"Maria", "Nel", "Sophia", "Clair", "Mirage"};
cout << "cNames = "; print(cNames);
// unique_ptr
array<unique_ptr<int>, 2> uAr {
make_unique<int>(17),
make_unique<int>(666)
};
// Built-in array
array<int[17], 3> aa;
}
{
cout << "\n-----------------------------";
cout << "\nstd::array iterators + algorithms: \n\n";
// Access with operator[] or at()
// operator[] does not check boundaries
// at() does and throws std::out_of_range if wrong index
array<int, 12> aI1;
for (int i = 0; i < aI1.size(); ++i)
aI1[i] = i*i;
array<int, 12> aI2;
// This is the proper index type, usually I just use int,
for (array<int, 12>::size_type i = 0; i < aI2.size(); ++i)
aI2.at(i) = i*i;
// Print an array with index
cout << "\nPrint with index : aI1 = ";
for (int i = 0; i < aI2.size(); ++i)
cout << aI2.at(i) << " ";
cout << endl;
// Print an array with iterator
cout << "\nPrint with const iterator : aI1 = ";
for (auto it = aI1.cbegin(); it != aI1.cend(); ++it)
cout << *it << " ";
cout << endl;
cout << "\nPrint with const iterator (no auto) : aI1 = ";
for (array<int, 12>::const_iterator it = aI1.cbegin(); it != aI1.cend(); ++it)
cout << *it << " ";
cout << endl;
cout << "\nPrint with reverse const iterator : aI1 = ";
for (auto it = aI1.crbegin(); it != aI1.crend(); ++it)
cout << *it << " ";
cout << endl;
// Print an array with iterator + index
// This is stupid, demonstrates obtaining index from iterator
cout << "\nPrint with iterator + index : aI1 = ";
for (auto it = aI1.cbegin(); it != aI1.cend(); ++it) {
int index = it - aI1.cbegin(); // Iterator arithmetics !
cout << aI1.at(index) << " ";
}
cout << endl;
// Print with range for, it also uses begin(), end()
cout << "\nPrint with range for : aI1 = ";
for (int i : aI1)
cout << i << " ";
cout << endl;
// Find min and max elements with algorithms:
auto itMax = max_element(aI1.cbegin(), aI1.cend());
cout << "\nMAX = " << *itMax << endl;
cout << "MIN = " << *min_element(aI1.cbegin(), aI1.cend()) << endl;
// Reversing with algorithm reverse(), 2 iterators to algorithm !
reverse(aI1.begin(), aI1.end());
cout << "\nAfter reverse() : aI1 = "; print(aI1);
// Now let us change our array with non-const iterator
cout << "\nChanging aI1 with iterators ( %= 20) :\n";
for (auto it = aI1.begin(); it != aI1.end(); ++it)
*it %= 20;
cout << "aI1 = "; print(aI1);
// Sort with algorithm sort(), 2 iterators to algorithm !
sort(aI1.begin(), aI1.end());
cout << "\nAfter sort() : aI1 = "; print(aI1);
}
{
cout << "\n-----------------------------";
cout << "\nstd::array find + reverse : \n\n";
array<int, 12> aI1; // Same array of squares as before
for (int i = 0; i < aI1.size(); ++i)
aI1[i] = i*i;
cout << "aI1 = "; print(aI1);
// Lets try std::find()
// We use non-const iterators to reverse later
auto found16 = find(aI1.begin(), aI1.end(), 16); // Returns iterator
if (found16 == aI1.end() )
cout << "16 not found !\n";
else
cout << "Found 16 at index " << found16 - aI1.begin() << endl;
auto found17 = find(aI1.begin(), aI1.end(), 17);
if (found17 == aI1.end() )
cout << "17 not found !\n";
else
cout << "Found 17 at index " << found17 - aI1.begin() << endl;
auto found64 = find(aI1.begin(), aI1.end(), 64);
if (found64 == aI1.end() )
cout << "64 not found !\n";
else
cout << "Found 64 at index " << found64 - aI1.begin() << endl;
// Suppose we don't know A Priori that 16 goes before 64.
// What can we do ? For arrays we can compare:
array<int, 12>::iterator it1 = found16, it2 = found64;
if (it1 > it2) // Check the order !
swap(it1, it2);
// Now it1 < it2
// Reverse the part from 16 to 64 inclusive
// We need it2+1 to include 64 in the reverse !
reverse(it1, it2+1);
cout << "\nAfter find reverse:\n";
cout << "aI1 = "; print(aI1);
}
{
cout << "\n-----------------------------";
cout << "\nstd::array fill, copy, generate, for_each : \n\n";
array<int, 12> aI1;
fill(aI1.begin(), aI1.end(), 19); // Fill with the value 19
cout << "aI1 = "; print(aI1);
array<int, 12> aI2 = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37};
array<int, 12> aI3;
copy(aI2.begin(), aI2.end(), aI3.begin()); // Copy aI2 to aI3
cout << "aI3 = "; print(aI3);
array<int, 12> aI4;
// Generate aI4
int n = 0;
generate(aI4.begin(), aI4.end(), [&n](){return n++;});
cout << "aI4 = "; print(aI4);
for_each(aI4.begin(), aI4.end(), [](int &n){n*=3;}); // Multiply each element by 3
cout << "aI4 = "; print(aI4);
}
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2008 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#include "core/pch.h"
#include <stdio.h>
#include <string.h>
#include "platforms/mac/debug/StepSpy.jens.h"
#ifdef _JB_DEBUG
#include "platforms/mac/debug/OnScreen.h"
#endif
StepSpy *gStepSpyListEvenEven = NULL;
StepSpy *gStepSpyList = NULL;
StepSpy *gStepSpyListLong = NULL;
StepSpy::StepSpy(StepSpy **theOwner)
{
next = *theOwner;
*theOwner = this;
owner = theOwner;
if(next)
{
next->prev = this;
}
prev = NULL;
}
StepSpy::~StepSpy()
{
if(this == *owner)
{
*owner = next;
}
if(NULL != prev)
{
prev->next = next;
}
if(NULL != next)
{
next->prev = prev;
}
}
long gStepSpyCounter = 0;
void AddStepSpy(void *start, long length, SpyKind spyKind, char *id)
{
StepSpy *newSpy;
#ifdef _JB_DEBUG
DecOnScreen(0, -16, kOnScreenBlue, kOnScreenWhite, ++gStepSpyCounter);
#endif
if(kStepSpyPointerToVoid == spyKind)
{
newSpy = new StepSpy(&gStepSpyListLong);
newSpy->start = start;
newSpy->value = *((long *) start);
newSpy->length = length | 0x80000000;
newSpy->checksum = *((long *) start);
}
else if((kStepSpyHandle == spyKind) || (length & 1) || (((long) start) & 3))
{
newSpy = new StepSpy(&gStepSpyList);
newSpy->start = start;
newSpy->length = length | ((kStepSpyHandle == spyKind) ? 0x80000000 : 0);
newSpy->checksum = GetCheckSum(newSpy);
}
else if(4 == length)
{
newSpy = new StepSpy(&gStepSpyListLong);
newSpy->start = start;
newSpy->length = length;
newSpy->checksum = *((long *) start);
}
else // length is divisible by 2, start is divisible by 2
{
newSpy = new StepSpy(&gStepSpyListEvenEven);
newSpy->start = start;
newSpy->length = length >> 1;
newSpy->checksum = GetCheckSum2(newSpy);
}
newSpy->id = id;
}
//void AddStepSpy(void *start, long length, short isHandle, char *id)
//{
// AddStepSpy(start, length, kStepSpyHandle, id);
//}
//void AddStepSpy(void *start, long length, SpyKind spyKind)
//{
// AddStepSpy(start, length, spyKind, "");
//}
void RemoveStepSpy(void *start)
{
StepSpy *travel, *theNext;
static bool found;
#ifdef _JB_DEBUG
DecOnScreen(0, -16, kOnScreenBlue, kOnScreenWhite, --gStepSpyCounter);
#endif
found = false;
travel = gStepSpyListEvenEven;
while(NULL != travel)
{
theNext = travel->next;
if(start == travel->start)
{
delete travel;
found = true;
}
travel = theNext;
}
travel = gStepSpyList;
while(NULL != travel)
{
theNext = travel->next;
if(start == travel->start)
{
delete travel;
found = true;
}
travel = theNext;
}
travel = gStepSpyListLong;
while(NULL != travel)
{
theNext = travel->next;
if(start == travel->start)
{
delete travel;
found = true;
}
travel = theNext;
}
if(!found)
{
DebugStr("\pStepSpy not found!");
}
}
bool HasStepSpy(void *start)
{
StepSpy *travel, *theNext;
static bool found;
found = false;
travel = gStepSpyListEvenEven;
while(NULL != travel && !found)
{
theNext = travel->next;
if(start == travel->start)
{
found = true;
}
travel = theNext;
}
travel = gStepSpyList;
while(NULL != travel && !found)
{
theNext = travel->next;
if(start == travel->start)
{
found = true;
}
travel = theNext;
}
travel = gStepSpyListLong;
while(NULL != travel && !found)
{
theNext = travel->next;
if(start == travel->start)
{
found = true;
}
travel = theNext;
}
return found;
}
void EndDebug (void);
void CheckStepSpy(const char *inWhere, long inID)
{
static char dstr[257];
StepSpy *travel;
long address;
long newCheckSum;
// register unsigned char *p;
travel = gStepSpyListEvenEven; // not for handles, not for odd lengths, not for odd addresses
while(NULL != travel)
{
newCheckSum = GetCheckSum2(travel);
if(travel->checksum != newCheckSum)
{
sprintf(dstr, " OperaStepSpyEven: checksum changed at address 0x%p %s routine %ld, SpyKind=\"%s\"", travel->start, inWhere, inID, travel->id);
dstr[0] = strlen(&dstr[1]);
DebugStr((unsigned char *) dstr);
travel->checksum = newCheckSum;
}
travel = travel->next;
}
travel = gStepSpyList;
while(NULL != travel)
{
newCheckSum = GetCheckSum(travel);
if(newCheckSum != travel->checksum)
{
address = (long) travel->start;
if(travel->length < 0)
{
address = * (long*)address;
}
sprintf(dstr, " OperaStepSpy: checksum changed at address 0x%p %s routine %ld, SpyKind=\"%s\"", (void*)address, inWhere, inID, travel->id);
dstr[0] = strlen(&dstr[1]);
DebugStr((unsigned char *) dstr);
travel->checksum = newCheckSum;
}
travel = travel->next;
}
travel = gStepSpyListLong;
while(NULL != travel)
{
if(travel->length & 0x80000000) // PointerToVoid
{
if(travel->value != *((long *) travel->start))
{
sprintf(dstr, " OperaStepSpyPointerToVoid: pointer changed at address 0x%p %s routine %ld, SpyKind=\"%s\"", travel->start, inWhere, inID, travel->id);
dstr[0] = strlen(&dstr[1]);
DebugStr((unsigned char *) dstr);
}
(void) (*((char **) travel->start))[0]; // try pointer
(void) (*((char **) travel->start))[(travel->length & 0x7fffffff) - 1]; // try pointer
}
else if((*(long *) travel->start) != travel->checksum)
{
sprintf(dstr, " OperaStepSpyLong: checksum changed at address 0x%p %s routine %ld, SpyKind=\"%s\"", travel->start, inWhere, inID, travel->id);
dstr[0] = strlen(&dstr[1]);
DebugStr((unsigned char *) dstr);
travel->checksum = (*(long *) travel->start);
}
travel = travel->next;
}
/*
travel = gStepSpyListSmall;
while(NULL != travel)
{
p = (unsigned char *) travel->start;
newCheckSum = (p[0] << 16) | (p[1] << 8) | p[2];
if((*(long *) travel->start) != travel->checksum)
{
sprintf(dstr, " OperaStepSpySmall: checksum changed at address 0x%08X %s routine %d, SpyKind=\"%s\"", travel->start, inWhere, inID, travel->id);
dstr[0] = strlen(&dstr[1]);
DebugStr((unsigned char *) dstr);
travel->checksum = newCheckSum;
}
travel = travel->next;
}
*/
}
// sp = GetStackPointer();
// stackSpace = sp - GetApplLimit();
|
#include "DX11RenderSystem.h"
#include "d3d11.h"
#include "DX11Utils.h"
#include "DX11InputLayout.h"
#include "DX11GpuProgram.h"
#include "DX11DatatypeHelper.h"
#include "DX11RenderTarget.h"
#include "DX11VertexBuffer.h"
#include "DX11IndexBuffer.h"
#include "DX11GpuVertexData.h"
namespace HW{
DX11RenderSystem* g_pDX11RenderSystem = 0;
LRESULT CALLBACK DX11MsgProc::MainWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam){
return g_pDX11RenderSystem->MsgProc(hWnd, msg, wParam, lParam);
}
DX11RenderSystem::DX11RenderSystem()
: m_hMainWnd(0), m_bResizing(false), m_pRenderTargetView(0), m_pGpuProgram(0), m_bIsTerm(false),
m_pDepthStencilView(0), m_pDepthStencilBuffer(0), m_uClientWidth(480), m_uClientHeight(800),
m_bEnable4xMsaa(false), m_Background(0.0f, 0.0f, 0.0f, 0.0f), m_fDepthClear(1.0f), m_StencilClear(0){
g_pDX11RenderSystem = this;
}
DX11RenderSystem::~DX11RenderSystem(){
term_display();
g_pDX11RenderSystem = 0;
}
void DX11RenderSystem::term_display(){
if (!m_bIsTerm){
ReleaseCOM(m_pDevice);
ReleaseCOM(m_pImmediateContext);
ReleaseCOM(m_pSwapChain);
ReleaseCOM(m_pRenderTargetView);
ReleaseCOM(m_pDepthStencilView);
ReleaseCOM(m_pDepthStencilBuffer);
m_bIsTerm = true;
}
}
void DX11RenderSystem::SetWandH(int w, int h){
m_uClientWidth = w;
m_uClientHeight = h;
}
void DX11RenderSystem::GetWandH(int& w, int& h){
w = m_uClientWidth;
h = m_uClientHeight;
}
// Set the default window as render target
void DX11RenderSystem::SetDefaultRenderTarget(){
m_pImmediateContext->OMSetRenderTargets(1, &m_pRenderTargetView, m_pDepthStencilView);
}
// Bind a GpuProgram which has been compiled to this render system
void DX11RenderSystem::BindGpuProgram(GpuProgram* program){
if (!program)
return;
m_pGpuProgram = dynamic_cast<DX11GpuProgram*>(program);
//m_pGpuProgram->NotifyRenderSystem(this);
m_pGpuProgram->UseProgram();
}
// Bind the input layout to the IA stage
void DX11RenderSystem::BindInputLayout(InputLayout* layout){
DX11InputLayout* inputLayout = dynamic_cast<DX11InputLayout*>(layout);
// input the vertex shader to get input signature
if (!inputLayout->CreateInternalRes(this, m_pGpuProgram->GetShader(ShaderType::ST_VERTEX))){
Logger::WriteErrorLog("DX11RenderSystem: BindInputLayout Failed.\n");
return;
}
// Set the input layout
m_pImmediateContext->IASetInputLayout(inputLayout->GetInputLayout());
}
// Set the primitives type of the input data
void DX11RenderSystem::SetPrimType(PrimType geoType){
D3D11_PRIMITIVE_TOPOLOGY primTopology = (D3D11_PRIMITIVE_TOPOLOGY)DX11DatatypeHelper::Get(geoType);
if (primTopology == D3D11_PRIMITIVE_TOPOLOGY_UNDEFINED){
Logger::WriteErrorLog("DX11RenderSystem: SetPrimType Failed. Undefined PrimType.\n");
return;
}
m_pImmediateContext->IASetPrimitiveTopology(primTopology);
}
// Enable/Disable the wireframe mode
void DX11RenderSystem::EnableWireFrame(bool op){
if (op)
m_RasterizerDesc.FillMode = D3D11_FILL_WIREFRAME;
else
m_RasterizerDesc.FillMode = D3D11_FILL_SOLID;
}
// Set the cull mode
void DX11RenderSystem::SetCullMode(CullMode md){
switch (md){
case CullMode::CULL_MODE_NONE:
m_RasterizerDesc.CullMode = D3D11_CULL_NONE; break;
case CullMode::CULL_MODE_BACK:
m_RasterizerDesc.CullMode = D3D11_CULL_BACK; break;
case CullMode::CULL_MODE_FRONT:
m_RasterizerDesc.CullMode = D3D11_CULL_FRONT; break;
default: // CullMode::CULL_MODE_FRONTANDBACK, this is undefined in dx11
Logger::WriteErrorLog("DX11RenderSystem: SetCullMode Failed. Undefined Cull Mode in DX11.\n");
break;
}
}
// Set Whitch side of a face will be
void DX11RenderSystem::SetFaceFront(bool clockwise){
if (clockwise)
m_RasterizerDesc.FrontCounterClockwise = false;
else
m_RasterizerDesc.FrontCounterClockwise = true;
}
// Enable Scissor Test
void DX11RenderSystem::EnableScissorTest(bool teston){
m_RasterizerDesc.ScissorEnable = teston;
}
// Set Scissor Rect
void DX11RenderSystem::SetScissorRect(int tplx, int tply, int btrx, int btry){
D3D11_RECT rect{ tplx, tply, btrx, btry };
m_pImmediateContext->RSSetScissorRects(1, &rect);
}
// Set the rasterizer state to default
void DX11RenderSystem::RasterParamDefault(){
ZeroMemory(&m_RasterizerDesc, sizeof(D3D11_RASTERIZER_DESC));
m_RasterizerDesc.CullMode = D3D11_CULL_BACK;
m_RasterizerDesc.FillMode = D3D11_FILL_SOLID;
m_RasterizerDesc.DepthClipEnable = true;
m_pImmediateContext->RSSetState(0);
}
// Apply the set of raster param
void DX11RenderSystem::ApplyRasterParamSet(){
ID3D11RasterizerState * rs = NULL;
HR(m_pDevice->CreateRasterizerState(&m_RasterizerDesc, &rs));
m_pImmediateContext->RSSetState(rs);
ReleaseCOM(rs);
}
// Set the viewport
void DX11RenderSystem::SetViewport(float tplx, float tply, float width, float height, float minDepth, float maxDepth){
m_ScreenViewport.Width = width;
m_ScreenViewport.Height = height;
m_ScreenViewport.TopLeftX = tplx;
m_ScreenViewport.TopLeftY = tply;
m_ScreenViewport.MinDepth = minDepth;
m_ScreenViewport.MaxDepth = maxDepth;
m_pImmediateContext->RSSetViewports(1, &m_ScreenViewport);
}
// Enable/Disable the alpha to coverage
void DX11RenderSystem::EnableBlendAlphaCoverage(bool bac){
m_BlendDesc.AlphaToCoverageEnable = bac;
}
// Enable/Disable Independent Blend Desc for every render target
void DX11RenderSystem::EnableIndependentBlend(bool ib){
m_BlendDesc.IndependentBlendEnable = ib;
}
// Set the Blend Param for specific render target
void DX11RenderSystem::SetBlendParam(unsigned int target_index, BlendOperand srcBlend,
BlendOperand destBlend, BlendOperation blendOp, BlendOperand srcAlpha,
BlendOperand destAlpha, BlendOperation alphaOp, unsigned char rtMask){
int i = target_index;
m_BlendDesc.RenderTarget[i].SrcBlend = (D3D11_BLEND)DX11DatatypeHelper::Get(srcBlend);
m_BlendDesc.RenderTarget[i].DestBlend = (D3D11_BLEND)DX11DatatypeHelper::Get(destBlend);
m_BlendDesc.RenderTarget[i].BlendOp = (D3D11_BLEND_OP)DX11DatatypeHelper::Get(blendOp);
m_BlendDesc.RenderTarget[i].SrcBlendAlpha = (D3D11_BLEND)DX11DatatypeHelper::Get(srcAlpha);
m_BlendDesc.RenderTarget[i].DestBlendAlpha = (D3D11_BLEND)DX11DatatypeHelper::Get(destAlpha);
m_BlendDesc.RenderTarget[i].BlendOpAlpha = (D3D11_BLEND_OP)DX11DatatypeHelper::Get(alphaOp);
m_BlendDesc.RenderTarget[i].RenderTargetWriteMask = rtMask;
}
// Enable/Disable Blend for specific render target
void DX11RenderSystem::EnableBlend(unsigned int target_index, bool blend){
m_BlendDesc.RenderTarget[target_index].BlendEnable = blend;
}
// Set the Blend Factor
void DX11RenderSystem::SetBlendFactor(float const bf[4], unsigned int sampleMask){
for (int i = 0; i < 4; i++)
m_BlendFactor[i] = bf[i];
m_uSampleMask = sampleMask;
}
// Set Blend Param default
void DX11RenderSystem::BlendParamDefault(){
m_BlendDesc.AlphaToCoverageEnable = false;
m_BlendDesc.IndependentBlendEnable = false;
m_BlendDesc.RenderTarget[0].BlendEnable = false;
m_BlendDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE;
m_BlendDesc.RenderTarget[0].DestBlend = D3D11_BLEND_ZERO;
m_BlendDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
m_BlendDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;
m_BlendDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
m_BlendDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
m_BlendDesc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
for (int i = 1; i < 8; i++)
m_BlendDesc.RenderTarget[i] = m_BlendDesc.RenderTarget[0];
for (int i = 0; i < 4; i++)
m_BlendFactor[i] = 1;
m_uSampleMask = 0xffffffff;
m_pImmediateContext->OMSetBlendState(NULL, NULL, 0xffffffff);
}
// Apply the set of blend param
void DX11RenderSystem::ApplyBlendParamSet(){
ID3D11BlendState* bs = NULL;
HR(m_pDevice->CreateBlendState(&m_BlendDesc, &bs));
m_pImmediateContext->OMSetBlendState(bs, m_BlendFactor, m_uSampleMask);
ReleaseCOM(bs);
}
// Set Depth Param
void DX11RenderSystem::SetDepthParameters(ComparisonFunc func, bool mask){
m_DepthStencilDesc.DepthWriteMask = mask ? D3D11_DEPTH_WRITE_MASK_ALL : D3D11_DEPTH_WRITE_MASK_ZERO;
m_DepthStencilDesc.DepthFunc = (D3D11_COMPARISON_FUNC)DX11DatatypeHelper::Get(func);
}
// Enable/Disable Depth Test
void DX11RenderSystem::EnableDepthTest(bool teston){
m_DepthStencilDesc.DepthEnable = teston;
}
// Set Stencil Params
void DX11RenderSystem::SetStencilParameters(unsigned char readMask, unsigned char writeMask, StencilOperation frontFailOp,
StencilOperation frontDepthFailOp, StencilOperation frontPassOp, ComparisonFunc front,
StencilOperation backFailOp, StencilOperation backDepthFailOp, StencilOperation backPassOp,
ComparisonFunc back, unsigned int refv){
m_DepthStencilDesc.StencilReadMask = readMask;
m_DepthStencilDesc.StencilWriteMask = writeMask;
m_DepthStencilDesc.FrontFace.StencilFailOp = (D3D11_STENCIL_OP)DX11DatatypeHelper::Get(frontFailOp);
m_DepthStencilDesc.FrontFace.StencilDepthFailOp = (D3D11_STENCIL_OP)DX11DatatypeHelper::Get(frontDepthFailOp);
m_DepthStencilDesc.FrontFace.StencilPassOp = (D3D11_STENCIL_OP)DX11DatatypeHelper::Get(frontPassOp);
m_DepthStencilDesc.FrontFace.StencilFunc = (D3D11_COMPARISON_FUNC)DX11DatatypeHelper::Get(front);
m_DepthStencilDesc.BackFace.StencilFailOp = (D3D11_STENCIL_OP)DX11DatatypeHelper::Get(backFailOp);
m_DepthStencilDesc.BackFace.StencilDepthFailOp = (D3D11_STENCIL_OP)DX11DatatypeHelper::Get(backDepthFailOp);
m_DepthStencilDesc.BackFace.StencilPassOp = (D3D11_STENCIL_OP)DX11DatatypeHelper::Get(backPassOp);
m_DepthStencilDesc.BackFace.StencilFunc = (D3D11_COMPARISON_FUNC)DX11DatatypeHelper::Get(back);
m_uStencilRef = refv;
}
// Enable/Disable Stencil
void DX11RenderSystem::EnableStencil(bool teston){
m_DepthStencilDesc.StencilEnable = teston;
}
// Set Depth/Stencil state to default
void DX11RenderSystem::DepthStencilDefault(){
m_DepthStencilDesc.DepthEnable = true;
m_DepthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
m_DepthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;
m_DepthStencilDesc.StencilEnable = false;
m_DepthStencilDesc.StencilReadMask = 0xff;
m_DepthStencilDesc.StencilWriteMask = 0xff;
m_DepthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
m_DepthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_KEEP;
m_DepthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
m_DepthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
m_DepthStencilDesc.BackFace = m_DepthStencilDesc.FrontFace;
m_uStencilRef = 0;
m_pImmediateContext->OMSetDepthStencilState(0, m_uStencilRef);
}
// Apply the set of depth/stencil param
void DX11RenderSystem::ApplyDepthStencilParamSet(){
ID3D11DepthStencilState* dss = NULL;
HR(m_pDevice->CreateDepthStencilState(&m_DepthStencilDesc, &dss));
m_pImmediateContext->OMSetDepthStencilState(dss, m_uStencilRef);
ReleaseCOM(dss);
}
// Set all the parameters within this pipeline to default
void DX11RenderSystem::AllParamDefault(){
RasterParamDefault();
BlendParamDefault();
DepthStencilDefault();
m_Background = Vector4(0.0f, 0.0f, 0.0f, 0.0f);
m_fDepthClear = 1.0f;
m_StencilClear = 0;
}
void DX11RenderSystem::SetBackground(const Vector4& background){
m_Background = background;
}
// Set the clear flag of depth and stencil
void DX11RenderSystem::DepthClearParam(float depth, unsigned char stencil){
m_fDepthClear = depth;
m_StencilClear = stencil;
}
// Swap back buffer to front and present the frame buffer to the monitor
void DX11RenderSystem::BufferSwap(){
if (m_RTStack.empty()){
HR(m_pSwapChain->Present(0, 0));
return;
}
RenderTarget* rt = m_RTStack.top();
if (rt == NULL)
return;
if (rt->getType() == RenderTarget::RTT_WINDOW)
HR(m_pSwapChain->Present(0, 0));
}
// Set Clear Color
void DX11RenderSystem::ClearColor(float r, float g, float b, float a){
m_Background = Vector4(r, g, b, a);
}
// Clear color and depth buffer of the current render target ( Default window if NULL )
void DX11RenderSystem::ClearBuffer(unsigned int buffer){
if (m_RTStack.empty()){
m_pImmediateContext->ClearRenderTargetView(m_pRenderTargetView, m_Background.ptr());
m_pImmediateContext->ClearDepthStencilView(m_pDepthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, m_fDepthClear, m_StencilClear);
}
DX11RenderTarget* rt = dynamic_cast<DX11RenderTarget*>(m_RTStack.top());
if (rt == NULL)
return;
if (rt->getType() == RenderTarget::RTT_WINDOW){
m_pImmediateContext->ClearRenderTargetView(m_pRenderTargetView, m_Background.ptr());
m_pImmediateContext->ClearDepthStencilView(m_pDepthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, m_fDepthClear, m_StencilClear);
}
else if (rt->getType() == RenderTarget::RTT_TEXTURE){
std::vector<ID3D11RenderTargetView*> RTVs = rt->GetRTVs();
for (int i = 0; i < RTVs.size(); i++)
m_pImmediateContext->ClearRenderTargetView(RTVs[i], m_Background.ptr());
m_pImmediateContext->ClearDepthStencilView(rt->GetDepthStencilView(), D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, m_fDepthClear, m_StencilClear);
}
}
void DX11RenderSystem::PushRenderTarget(RenderTarget* rt){
if (rt)
m_RTStack.push(rt);
}
void DX11RenderSystem::PopRenderTarget(){
if (!m_RTStack.empty())
m_RTStack.pop();
}
//Get Current Render Target
RenderTarget* DX11RenderSystem::CurrentRenderTarget() const{
if (!m_RTStack.empty())
return m_RTStack.top();
else
return NULL;
}
// Factory function for creating Vertex Buffer
VertexBuffer* DX11RenderSystem::CreateVertexBuffer(){
return new DX11VertexBuffer();
}
// Factory Function for creating Index Buffer
IndexBuffer* DX11RenderSystem::CreateIndexBuffer(){
return new DX11IndexBuffer();
}
// Set the Clear State, Not used yet
void DX11RenderSystem::setClearState(const ClearState& clearState){
}
// Set the Raster state
void DX11RenderSystem::setRasterState(const RasterState& rasterState){
static RasterState m_last_raster_state;
if (rasterState == m_last_raster_state)
return;
this->SetCullMode(rasterState.mCullMode);
// the input is clockwise
this->SetFaceFront(!rasterState.mFrontCounterClockwise);
this->EnableScissorTest(rasterState.mScissorEnable);
// No write mask in dx11
m_last_raster_state = rasterState;
this->ApplyRasterParamSet();
}
// Set the Blend State
void DX11RenderSystem::setBlendState(const BlendState& blendState){
static BlendState m_last_blend_state;
if (blendState == m_last_blend_state)
return;
this->EnableBlendAlphaCoverage(blendState.mAlphaToConverageEnable);
this->EnableIndependentBlend(blendState.mIndependentBlendEnable);
this->EnableBlend(0, blendState.mBlendEnable);
this->SetBlendParam(0, blendState.mSrcBlend, blendState.mDestBlend, blendState.mBlendFunc,
blendState.mSrcBlendAlpha, blendState.mDestBlendAlpla, blendState.mBlendFuncAlpha, blendState.mWriteMask);
this->SetBlendFactor(blendState.mFactor, blendState.mSampleMask);
this->ApplyBlendParamSet();
m_last_blend_state = blendState;
}
// Set the Depth/Stencil State
void DX11RenderSystem::setDepthStencilState(const DepthStencilState& depthStencilState){
static DepthStencilState m_last_depth_state;
if (depthStencilState == m_last_depth_state)
return;
this->EnableDepthTest(depthStencilState.mDepthEnable);
this->EnableStencil(depthStencilState.mStencilEnable);
this->SetDepthParameters(depthStencilState.mDepthFunc, depthStencilState.mDepthWriteMask);
this->SetStencilParameters(depthStencilState.mStencilReadMask, depthStencilState.mStencilWriteMask, depthStencilState.mFrontStencilFailFunc,
depthStencilState.mFrontStencilDepthFailFunc, depthStencilState.mFrontStencilPassFunc, depthStencilState.mFrontStencilFunc,
depthStencilState.mBackStencilFailFunc, depthStencilState.mBackStencilDepthFailFunc, depthStencilState.mBackStencilPassFunc,
depthStencilState.mBackStencilFunc, depthStencilState.mStencilRef);
this->ApplyDepthStencilParamSet();
m_last_depth_state = depthStencilState;
}
// Set Polygon offset, Didn't find relatives of dx11
void DX11RenderSystem::setPolygonOffset(bool enable, float offset_factor, float offset_unit){
}
// Main Render Interface, iplKey is unuseful here
void DX11RenderSystem::RenderMetadata(GpuVertexData* attrData, IndexBuffer* indexData, const IPLKey& iplKey){
assert(attrData && indexData);
DX11GpuVertexData* dx11AttrData = dynamic_cast<DX11GpuVertexData*>(attrData);
int numBuffers = dx11AttrData->GetCurrentBufferNum();
ID3D11Buffer** vertBuffers = dx11AttrData->GetCurrentBuffers();
DX11IndexBuffer* dx11IndexBuffer = dynamic_cast<DX11IndexBuffer*>(indexData);
UINT* stride = new UINT[numBuffers];
memset(stride, 0, sizeof(UINT)*numBuffers);
UINT* offset = new UINT[numBuffers];
memset(offset, 0, sizeof(UINT)*numBuffers);
m_pImmediateContext->IASetVertexBuffers(0, numBuffers, vertBuffers, stride, offset);
m_pImmediateContext->IASetIndexBuffer(dx11IndexBuffer->GetIndexBuffer(), dx11IndexBuffer->GetIndexFormat(), 0);
m_pImmediateContext->DrawIndexed(dx11IndexBuffer->GetIndexCount(), 0, 0);
delete[] stride;
delete[] offset;
}
bool DX11RenderSystem::Initialize(){
if (!InitMainWindow())
return false;
if (!InitDirect3D())
return false;
RasterParamDefault();
BlendParamDefault();
DepthStencilDefault();
return true;
}
// Create Window
bool DX11RenderSystem::InitMainWindow(){
HINSTANCE hInstance = GetModuleHandle(NULL);
WNDCLASS wc;
//wc.style = CS_HREDRAW | CS_VREDRAW;
wc.style = CS_OWNDC;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.lpfnWndProc = DX11MsgProc::MainWndProc;
wc.hIcon = LoadIcon(0, IDI_APPLICATION);
wc.hCursor = LoadCursor(0, IDC_ARROW);
wc.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
wc.lpszMenuName = NULL;
wc.lpszClassName = "DX11WindowClass";
if (!RegisterClass(&wc)){
MessageBox(0, "RegisterClass Failed.", 0, 0);
return false;
}
DWORD wStyle = WS_VISIBLE | WS_POPUP | WS_BORDER | WS_SYSMENU | WS_CAPTION;
RECT r = { 0, 0, m_uClientWidth, m_uClientHeight };
AdjustWindowRect(&r, wStyle, false);
int width = r.right - r.left;
int height = r.bottom - r.top;
m_hMainWnd = CreateWindow("DX11WindowClass", "DX11Window", wStyle,
0, 0, width, height, 0, 0, hInstance, 0);
if (!m_hMainWnd){
MessageBox(0, "CreateWindow Failed.", 0, 0);
return false;
}
ShowWindow(m_hMainWnd, true);
UpdateWindow(m_hMainWnd);
return true;
}
// Create the device and Context
bool DX11RenderSystem::InitDirect3D(){
UINT createDeviceFlags = 0;
#if defined(DEBUG) | defined(_DEBUG)
createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif
D3D_FEATURE_LEVEL featureLevel;
// Create Device and Context
HRESULT hr = D3D11CreateDevice(
NULL, D3D_DRIVER_TYPE_HARDWARE,
0, createDeviceFlags,
0, 0,
D3D11_SDK_VERSION,
&m_pDevice,
&featureLevel,
&m_pImmediateContext);
// Check if creating succeed
if (FAILED(hr)){
MessageBox(0, "D3D11CreateDevice Failed!", 0, 0);
return false;
}
// Check if the feature level is supported
if (featureLevel != D3D_FEATURE_LEVEL_11_0){
MessageBox(0, "Direct3D Feature Level 11 unsupported.", 0, 0);
return false;
}
// Check if 4x Multi-sample is supported
HR(m_pDevice->CheckMultisampleQualityLevels(DXGI_FORMAT_R8G8B8A8_UNORM, 4, &m_u4xMsaaQuality));
assert(m_u4xMsaaQuality > 0);
// Create Swap Chain
DXGI_SWAP_CHAIN_DESC sd;
sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
sd.BufferDesc.Height = m_uClientHeight;
sd.BufferDesc.Width = m_uClientWidth;
sd.BufferDesc.RefreshRate.Numerator = 60;
sd.BufferDesc.RefreshRate.Denominator = 1;
sd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
sd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
sd.BufferCount = 1;
sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
if (m_bEnable4xMsaa){
sd.SampleDesc.Count = 4;
sd.SampleDesc.Quality = m_u4xMsaaQuality - 1;
}
else{
sd.SampleDesc.Count = 1;
sd.SampleDesc.Quality = 0;
}
sd.Flags = 0;
sd.OutputWindow = m_hMainWnd;
sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
IDXGIDevice *dxgiDevice = NULL;
m_pDevice->QueryInterface(__uuidof(IDXGIDevice), (void**)&dxgiDevice);
IDXGIAdapter* dxgiAdapter = NULL;
dxgiDevice->GetParent(__uuidof(IDXGIAdapter), (void**)&dxgiAdapter);
IDXGIFactory* dxgiFactory = NULL;
dxgiAdapter->GetParent(__uuidof(IDXGIFactory), (void**)&dxgiFactory);
HR(dxgiFactory->CreateSwapChain(m_pDevice, &sd, &m_pSwapChain));
ReleaseCOM(dxgiDevice);
ReleaseCOM(dxgiAdapter);
ReleaseCOM(dxgiFactory);
OnResize();
return true;
}
void DX11RenderSystem::RenderMetadata(VertexBuffer* vertData, IndexBuffer* indexData, const IPLKey & ipkey)
{
}
void DX11RenderSystem::OnResize(){
assert(m_pDevice);
assert(m_pImmediateContext);
assert(m_pSwapChain);
ReleaseCOM(m_pRenderTargetView);
ReleaseCOM(m_pDepthStencilView);
ReleaseCOM(m_pDepthStencilBuffer);
// Create RenderTarget View
HR(m_pSwapChain->ResizeBuffers(1, m_uClientWidth, m_uClientHeight, DXGI_FORMAT_R8G8B8A8_UNORM, 0));
ID3D11Texture2D *backBuffer;
HR(m_pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)&backBuffer));
HR(m_pDevice->CreateRenderTargetView(backBuffer, 0, &m_pRenderTargetView));
// Create Depth/Stencil buffer and view
D3D11_TEXTURE2D_DESC depthStencilDesc;
depthStencilDesc.ArraySize = 1;
depthStencilDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
depthStencilDesc.CPUAccessFlags = 0;
depthStencilDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
depthStencilDesc.Height = m_uClientHeight;
depthStencilDesc.Width = m_uClientWidth;
depthStencilDesc.MipLevels = 1;
depthStencilDesc.MiscFlags = 0;
if (m_bEnable4xMsaa){
depthStencilDesc.SampleDesc.Count = 4;
depthStencilDesc.SampleDesc.Quality = m_u4xMsaaQuality - 1;
}
else{
depthStencilDesc.SampleDesc.Count = 1;
depthStencilDesc.SampleDesc.Quality = 0;
}
depthStencilDesc.Usage = D3D11_USAGE_DEFAULT;
HR(m_pDevice->CreateTexture2D(&depthStencilDesc, 0, &m_pDepthStencilBuffer));
HR(m_pDevice->CreateDepthStencilView(m_pDepthStencilBuffer, 0, &m_pDepthStencilView));
m_pImmediateContext->OMSetRenderTargets(1, &m_pRenderTargetView, m_pDepthStencilView);
// Set Viewport
SetViewport(0.0f, 0.0f, static_cast<float>(m_uClientWidth), static_cast<float>(m_uClientHeight), 0.0f, 1.0f);
}
LRESULT CALLBACK DX11RenderSystem::MsgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam){
switch (msg){
case WM_SIZE:
m_uClientWidth = LOWORD(lParam);
m_uClientHeight = HIWORD(lParam);
if (m_pDevice){
if (wParam == SIZE_MINIMIZED){
}
else if (wParam == SIZE_MAXIMIZED){
OnResize();
}
else if (wParam == SIZE_RESTORED){
if (m_bResizing){
}
else
OnResize();
}
}
return 0;
case WM_ENTERSIZEMOVE:
m_bResizing = true;
return 0;
case WM_EXITSIZEMOVE:
m_bResizing = false;
OnResize();
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hWnd, msg, wParam, lParam);
}
}
|
#include "BrickManager.h"
#include <iostream>
/*
Constructor for brick manager. procRandom is used to set the randomness of
powerups. This constructor initializes the vectors bricks and powerUps.
*/
BrickManager::BrickManager(int procRandom)
{
bricks = std::vector<Brick*>();
powerUps = std::vector<PowerUp*>();
this->procRandom = procRandom;
meshes = NULL;
}
/*
Constructor for brick manager. It is used to set bricks vector with a
custom vector.
*/
BrickManager::BrickManager(std::vector<Brick*> bricks, int procRandom)
{
powerUps = std::vector<PowerUp*>();
this->bricks = bricks;
this->procRandom = procRandom;
meshes = NULL;
}
/*
Destructor for brick manager
*/
BrickManager::~BrickManager()
{
}
/*
Generate radom powerups. Each powerup square has it own color. The number of
powerups is limited to 100000000, but you have to play A LOT to reach this
number.
*/
void BrickManager::GenerateRandomPowerUp(glm::vec2 position)
{
int chance = rand() % procRandom;
if (chance != 0 || meshes == NULL)
return;
char id[20];
// Set the name
do {
memset(id, 0, sizeof(id));
int rnd = rand() % 100000000;
sprintf(id, "pw%d", rnd);
} while ((*meshes)[id] != NULL);
int pwID = rand() % ((int)PowerUpsEnum::Count - 1) + 1;
glm::vec3 color;
// Set powerup square color
switch (pwID)
{
case PowerUpsEnum::WALL:
color = glm::vec3(.5f, .5f, 0);
break;
case PowerUpsEnum::BIG_BALL:
color = glm::vec3(.5f, 0, .5f);
break;
case PowerUpsEnum::STRONG_BALL:
color = glm::vec3(0, .5f, .5f);
break;
default:
break;
}
// Init powerup
PowerUpsEnum pw = static_cast<PowerUpsEnum>(pwID);
float randDuration = (float)(rand() % (maxDuration - minDuration)) +
minDuration;
PowerUp *p = new PowerUp(id, pwSize, pwSize, position.x, position.y, color,
pw, randDuration);
// Put powerup in vector and in meshes map.
powerUps.push_back(p);
(*meshes)[id] = p->CreateMesh();
}
/*
Add brick to manager
*/
void BrickManager::AddBrick(Brick * brick)
{
bricks.push_back(brick);
}
/*
Get all bricks from manager
*/
std::vector<Brick*> BrickManager::GetAllBricks()
{
return this->bricks;
}
/*
Gett all powerup on screen
*/
std::vector<PowerUp*> BrickManager::GetAllPowerUpsOnDisplay()
{
return this->powerUps;
}
/*
Get all collidable squares that have numHits != 0
*/
std::vector<CollidableSquare*> BrickManager::GetAllCollidableSquares()
{
std::vector<CollidableSquare*> vect = std::vector<CollidableSquare*>();
for (Brick* b : bricks) {
if (b->GetNumHits() != 0)
vect.push_back(b);
}
return vect;
}
/*
Setter for meshes
*/
void BrickManager::SetMeshes(std::unordered_map<std::string, Mesh*> &meshes)
{
this->meshes = &meshes;
}
/*
Setter for paddle position
*/
void BrickManager::SetPaddlePos(glm::vec2 paddlePos)
{
this->paddlePos = paddlePos;
}
/*
Setter for paddle size
*/
void BrickManager::SetPaddleSize(glm::vec2 paddleSize)
{
this->paddleSize = paddleSize;
}
/*
Setter for ballRef
*/
void BrickManager::SetBallRef(Ball * ball)
{
this->ballRef = ball;
}
/*
Reset (clear) vectors
*/
void BrickManager::Reset()
{
this->bricks.clear();
this->powerUps.clear();
}
/*
Set the bricks on the board.
*/
void BrickManager::SetBoard(int numHorizontal, int numVertical,
int brickWidth, int brickHeight, int padding, glm::vec2 screenSize,
int weight)
{
for (int i = 0; i < numVertical; i++) {
for (int j = 0; j < numHorizontal; j++) {
// Generate position for the brick
int index = i * numHorizontal + j;
float x = brickWidth / 2.0f +
(screenSize.x - numHorizontal * brickWidth - (numHorizontal - 1)
* padding) / 2.0f + j * (brickWidth + padding);
float y = brickHeight / 2.0f + 275 + i * (brickHeight + padding);
// Generate name for the brick
std::string name = "brick" + std::to_string(index);
// Compute the new color
float r = 1.0f / (float)weight;
float g = r < 0.2f ? 1.0f : 1.0f / (float)weight;
float b = g < 0.2f ? 1.0f : 1.0f - 1.0f / (float)weight;
glm::vec3 color = glm::vec3(r, g, b);
// From level 6, generate random colors
if (r < 0.2f && b > 0.7f && g > 0.9f)
color = glm::vec3((float)rand() / RAND_MAX,
(float)rand() / RAND_MAX, (float)rand() / RAND_MAX);
// Create brick and add it to brick manager
Brick *brick = new Brick(name, brickWidth, brickHeight, x, y,
weight, color);
this->AddBrick(brick);
}
}
}
/*
Update the bricks vector (the brick with numHits == 0 will be destroyed and
removed form the vector) and powerups vector.
*/
void BrickManager::Update(float gameTime)
{
// Update bricks vector
std::vector<Brick*>::iterator it = bricks.begin();
while (it != bricks.end()) {
Brick* b = *it;
if (b->GetNumHits() == 0) {
// The brick is hit. Generate powerup
if (b->GenerateRndPw())
GenerateRandomPowerUp(b->GetPosition());
if (b->GetSize().x <= 0.1f && b->GetSize().y <= 0.1f) {
// The brick is too small. Remove it from vector
it = bricks.erase(it);
}
else {
// Go to next element
it++;
}
}
else {
// Go to next element
it++;
}
}
// Update each brick
for (Brick *b : bricks) {
b->Update(gameTime);
}
// Update powerUps vector
std::vector<PowerUp*>::iterator itP = powerUps.begin();
while (itP != powerUps.end()) {
PowerUp* p = *itP;
// Update each powerUps
p->Update(gameTime);
// Check collision with the paddle
glm::vec2 start = paddlePos + glm::vec2(-paddleSize.x / 2, paddleSize.y / 2);
glm::vec2 end = paddlePos + glm::vec2(paddleSize.x / 2, paddleSize.y / 2);
float radius = 10;
if (CollisionDetection::CollisionWithSegment(start, end, radius,
p->GetPosition(), p->GetPosition(), NULL, NULL))
{
itP = powerUps.erase(itP);
this->ballRef->SetPowerUp(p->GetPowerUp(), p->GetDuration());
}
else {
itP++;
}
}
}
|
#include <bits/stdc++.h>
using namespace std;
#define TESTC ""
#define PROBLEM "12563"
#define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0)
#define MAXN 10000
int main(int argc, char const *argv[])
{
#ifdef DBG
freopen("uva" PROBLEM TESTC ".in", "r", stdin);
freopen("uva" PROBLEM ".out", "w", stdout);
#endif
int kase;
scanf("%d",&kase);
int song,time,sec;
int bag[MAXN+5];
for(int k = 1 ; k <= kase ; k++ ){
scanf("%d %d",&song,&time);
memset(bag,0x8f,sizeof(bag));
bag[0] = 0;
for(int i = 0 ; i < song ; i++ ){
scanf("%d",&sec);
for(int j = time-1 ; j >= sec ; j-- )
bag[j] = max(bag[j], bag[j-sec]+1 );
}
int ans;
for(int i = ans = time-1 ; i >= 0 ; i-- )
if( bag[i] > bag[ans] )
ans = i;
printf("Case %d: %d %d\n", k, bag[ans]+1 , ans+678 );
}
return 0;
}
|
#ifndef MAT_H_INCLUDED
#define MAT_H_INCLUDED
#include <math.h>
#include "GL/gl.h"
template <typename T=GLfloat> union _vec4
{
T m[4];
struct
{
T x, y, z, w;
};
};
template <typename T=GLfloat> union _vec3
{
T m[3];
struct
{
T x, y, z;
};
};
template <typename T=GLfloat> union _vec2
{
T m[2];
struct
{
T x;
T y;
};
};
template <typename T=GLfloat> struct _mat4
{
T m[16];
};
typedef _vec4<GLfloat> vec4;
typedef _vec3<GLfloat> vec3;
typedef _vec2<GLfloat> vec2;
typedef _vec4<GLint> veci4;
typedef _vec3<GLint> veci3;
typedef _vec2<GLint> veci2;
typedef _mat4<GLfloat> mat4;
static const mat4 IDENTITY_MATRIX = {{
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
}};
static const vec4 X_AXIS = {{1.0, 0.0, 0.0, 0.0}};
static const vec4 Y_AXIS = {{0.0, 1.0, 0.0, 0.0}};
static const vec4 Z_AXIS = {{0.0, 0.0, 1.0, 0.0}};
static const vec4 INV_X_AXIS = {{-1.0, 0.0, 0.0, 0.0}};
static const vec4 INV_Y_AXIS = {{0.0, -1.0, 0.0, 0.0}};
static const vec4 INV_Z_AXIS = {{0.0, 0.0, -1.0, 0.0}};
mat4 multymat(mat4* m1, mat4* m2);
vec4 multymatvec(const mat4* m, const vec4* v);
mat4 perspective(float fovy, float aspect_ratio, float near_plane, float far_plane);
void normalizevec4(vec4* v);
vec4 crossvec4(vec4 v1, vec4 v2);
float dotvec4(vec4 v1, vec4 v2);
mat4 lookAt(vec4 pos, vec4 dir);
void scale(const mat4* m, float x, float y, float z);
void translate(const mat4* m, float x, float y, float z);
#endif // MAT_H_INCLUDED
|
#pragma once
#include "utils/ptts.hpp"
#include "proto/config_buff.pb.h"
#include "utils.hpp"
#include <string>
using namespace std;
namespace pc = proto::config;
namespace nora {
namespace config {
using buff_ptts = ptts<pc::buff>;
buff_ptts& buff_ptts_instance();
void buff_ptts_set_funcs();
void check_buff_change_value_type(string arg);
void check_buff_effect_condition_size(const pc::buff& ptt, const pc::buff_effect& bf);
void check_buff_effect_effect_size(const pc::buff& ptt, const pc::buff_effect& bf);
void verify_buff_effect_effect(const pc::buff& ptt, const pc::buff_effect& bf);
void verify_buff_actor_effect_effect(const pc::buff& ptt, const pc::buff_effect& bf);
}
}
|
#include <iostream>
#include <cstring>
#define TempMessageLen 500
static char MsgBuffer[1000];
typedef struct
{
int len;
char logo[5];
char type[5];
char hawq_version[20];
char psql_version[10];
char os_version[40];
char macaddr[20];
char reserverd[10];
} load_req;
#define HQ_VERSION "oushu 4.0.0.0"
#define PSQL_VERSION "8.2.1"
static void GetOsVersion(char *os)
{
FILE *fp = popen("uname -r", "r");
fgets(os, sizeof(os), fp);
pclose(fp);
}
static void PackLoadMsg(char *msg)
{
char connsrc[TempMessageLen];
sprintf(connsrc, "port=%s;dbname=%s;dbuser=%s;",
"1234", "database", "postgres");
int connlen = strlen(connsrc);
load_req header;
strcpy(header.logo, "CSOT");
strcpy(header.type, "LOAD");
memcpy(header.hawq_version, HQ_VERSION, strlen(HQ_VERSION));
memcpy(header.psql_version, PSQL_VERSION, strlen(PSQL_VERSION));
GetOsVersion(header.os_version);
int len = 0XFFFFFFFFFFFFFFFF;
header.len = len;
memcpy(msg, &header, sizeof(header));
memcpy(msg + sizeof(header), connsrc, connlen);
msg[sizeof(header) + connlen] = 0;
}
int main() {
PackLoadMsg(MsgBuffer);
printf("msg len:%d\n", strlen(MsgBuffer));
load_req *head = (load_req *)MsgBuffer;
printf("len:%d,logo:%s,type:%s,hawq:%s,psql:%s,os:%s,mac:%s\n", head->len,
head->logo, head->type, head->hawq_version, head->psql_version,
head->os_version);
char q[200];
strncpy(q, MsgBuffer + sizeof(head), 200);
printf("query:%s\n", q);
}
|
// Based on NVIDIA's OptiX implementation of 2009.
// Code modified by Jeppe Revall Frisvad, 2013.
#define SOLUTION_CODE
#include <cmath>
#include "CGLA/Vec4f.h"
#include "CGLA/Vec3f.h"
#include "CGLA/Vec2f.h"
#include "GLGraphics/GLHeader.h"
#include "skymodel.h"
#include <thread>
#include <QTime>
using namespace std;
using namespace CGLA;
const float SKY_TONEMAPPING = 0.025f;
PreethamSunSky::PreethamSunSky(unsigned int day, float time, float latitude, float turbidity, float overcast) :
_day(day),
_time(time),
_latitude(latitude),
_turbidity(turbidity),
_overcast(overcast),
_dirty(true)
{
Vec2f coord = sun_position(day, time, latitude);
_sun_theta = coord[0];
_sun_phi = coord[1];
_up = Vec3f( 0.0f, 0.0f, 1.0f );
}
DirectionalLight PreethamSunSky::get_directional_light(float scale)
{
init();
DirectionalLight l;
l.direction = _sun_dir;
// Converting radiance to irradiance at the surface of the Earth using the
// solid angle 6.74e-5 subtended by the solar disk as seen from Earth.
// The radiance of a directional source modeling the Sun should be equal
// to the irradiance at the surface of the Earth.
l.diffuse = Vec4f(_sun_color*6.74e-5f*scale,1.0f);
l.specular = Vec4f(0.05f);
l.ambient = Vec4f(0.0f);
return l;
}
// Given a direction vector v sampled on the hemisphere
// over a surface point with the z-axis as its normal,
// this function applies the same rotation to v as is
// needed to rotate the z-axis to the actual normal
// [Frisvad, Journal of Graphics Tools 16, 2012].
inline void rotate_to_normal(const CGLA::Vec3f& normal, CGLA::Vec3f& v)
{
if(normal[2] < -0.999999f)
{
v = CGLA::Vec3f(-v[1], -v[0], -v[2]);
return;
}
const float a = 1.0f/(1.0f + normal[2]);
const float b = -normal[0]*normal[1]*a;
v = CGLA::Vec3f(1.0f - normal[0]*normal[0]*a, b, -normal[0])*v[0]
+ CGLA::Vec3f(b, 1.0f - normal[1]*normal[1]*a, -normal[1])*v[1]
+ normal*v[2];
}
// Given spherical coordinates, where theta is the
// polar angle and phi is the azimuthal angle, this
// function returns the corresponding direction vector
inline CGLA::Vec3f spherical_direction(double sin_theta, double cos_theta, double phi)
{
return CGLA::Vec3f(sin_theta*cos(phi), sin_theta*sin(phi), cos_theta);
}
void PreethamSunSky::init()
{
if( !_dirty ) return;
_dirty = false;
_c0 = Vec3f ( 0.1787f * _turbidity - 1.4630f,
-0.0193f * _turbidity - 0.2592f,
-0.0167f * _turbidity - 0.2608f );
_c1 = Vec3f ( -0.3554f * _turbidity + 0.4275f,
-0.0665f * _turbidity + 0.0008f,
-0.0950f * _turbidity + 0.0092f );
_c2 = Vec3f ( -0.0227f * _turbidity + 5.3251f,
-0.0004f * _turbidity + 0.2125f,
-0.0079f * _turbidity + 0.2102f );
_c3 = Vec3f ( 0.1206f * _turbidity - 2.5771f,
-0.0641f * _turbidity - 0.8989f,
-0.0441f * _turbidity - 1.6537f );
_c4 = Vec3f ( -0.0670f * _turbidity + 0.3703f,
-0.0033f * _turbidity + 0.0452f,
-0.0109f * _turbidity + 0.0529f );
const float sun_theta_2 = _sun_theta * _sun_theta;
const float sun_theta_3 = sun_theta_2 * _sun_theta;
const float xi = ( 4.0f / 9.0f - _turbidity / 120.0f ) *
( static_cast<float>( M_PI ) - 2.0f * _sun_theta );
Vec3f zenith;
// Preetham paper is in kilocandellas -- we want candellas
zenith[0] = ( ( 4.0453f * _turbidity - 4.9710f) * tan(xi) - 0.2155f * _turbidity + 2.4192f ) * 1000.0f;
zenith[1] = _turbidity * _turbidity * ( 0.00166f*sun_theta_3 - 0.00375f*sun_theta_2 + 0.00209f*_sun_theta ) +
_turbidity * (-0.02903f*sun_theta_3 + 0.06377f*sun_theta_2 - 0.03202f*_sun_theta + 0.00394f) +
( 0.11693f*sun_theta_3 - 0.21196f*sun_theta_2 + 0.06052f*_sun_theta + 0.25886f);
zenith[2] = _turbidity * _turbidity * ( 0.00275f*sun_theta_3 - 0.00610f*sun_theta_2 + 0.00317f*_sun_theta ) +
_turbidity * (-0.04214f*sun_theta_3 + 0.08970f*sun_theta_2 - 0.04153f*_sun_theta + 0.00516f) +
( 0.15346f*sun_theta_3 - 0.26756f*sun_theta_2 + 0.06670f*_sun_theta + 0.26688f);
float cos_sun_theta = cos( _sun_theta );
const Vec3f one(1.0f);
const Vec3f c3_s_th = _c3*_sun_theta;
Vec3f divisor_Yxy = ( one + _c0 * Vec3f(exp(_c1[0]), exp(_c1[1]), exp(_c1[2])) ) *
( one + _c2 * Vec3f(exp(c3_s_th[0]), exp(c3_s_th[1]), exp(c3_s_th[2])) + _c4 * (cos_sun_theta * cos_sun_theta) );
_inv_divisor_Yxy = zenith / divisor_Yxy;
//
// Direct sunlight
//
_sun_color = sunColor();
_sun_dir = spherical_direction(sin(_sun_theta), cos_sun_theta, _sun_phi);
rotate_to_normal(_up, _sun_dir);
}
void PreethamSunSky::precomputeTexture(GLuint & cubetex, int size)
{
glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
static const Vec3f CUBEMAP_DIRS[6] = { Vec3f(1,0,0), Vec3f(-1,0,0), Vec3f(0,1,0), Vec3f(0,-1,0), Vec3f(0,0,1), Vec3f(0,0,-1)};
static const Vec3f UPS[6] = { Vec3f(0,-1,0), Vec3f(0,-1,0), Vec3f(0,0,1), Vec3f(0,0,-1), Vec3f(0,-1,0), Vec3f(0,-1,0)};
static const Vec3f BASE[6] = { Vec3f(0,0,-1), Vec3f(0,0,1), Vec3f(1,0,0), Vec3f(1,0,0), Vec3f(1,0,0), Vec3f(-1,0,0)};
glGenTextures(1, &cubetex);
glBindTexture(GL_TEXTURE_CUBE_MAP, cubetex);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_BASE_LEVEL, 0);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAX_LEVEL, 0);
vector<vector<Vec3f> *> cubemap(6);
std::cout << "Generating skymap...";
std::cout.flush();
for(int k = 0; k < 6; k++)
{
cubemap[k] = new vector<Vec3f>(size*size);
vector<Vec3f> * image = cubemap[k];
for(int i = 0; i < size; ++i)
{
for(int j = 0; j < size; ++j)
{
Vec2f real_coord = 2.0f*Vec2f(i, j)/static_cast<float>(size) - Vec2f(1.0f);
Vec3f vec_in_cubemap = normalize(CUBEMAP_DIRS[k] + BASE[k]*real_coord[0] + UPS[k]*real_coord[1]);
float cos_up = dot(vec_in_cubemap, _up);
if(cos_up > -0.05f)
(*image)[j*size + i] = skyColor(vec_in_cubemap, false);
else
{
if(cos_up > -0.15f)
(*image)[j*size + i] = (cos_up + 0.15f)*10.0f*skyColor(vec_in_cubemap, false);
else
(*image)[j*size + i] = Vec3f(0.0f);
}
}
}
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + k, 0, GL_RGB32F, size, size, 0, GL_RGB, GL_FLOAT, &(image->at(0)));
}
std::cout << " Done." << endl << flush;
}
// lambda is wavelength in micro meters
float PreethamSunSky::calculateAbsorption( float , float m, float lambda, float turbidity, float k_o, float k_wa )
{
float alpha = 1.3f; // wavelength exponent
float beta = 0.04608f * turbidity - 0.04586f; // turbidity coefficient
float ell = 0.35f; // ozone at NTP (cm)
float w = 2.0f; // precipitable water vapor (cm)
float rayleigh_air = exp( -0.008735 * m * pow( lambda, -4.08f ) );
float aerosol = exp( -beta * m * pow( lambda, -alpha ) );
float ozone = k_o > 0.0f ? exp( -k_o*ell*m ) : 1.0f;
float water_vapor = k_wa > 0.0f ? exp( -0.2385*k_wa*w*m/pow( 1.0 + 20.07*k_wa*w*m, 0.45 ) ) : 1.0f;
return rayleigh_air*aerosol*ozone*water_vapor;
}
Vec3f PreethamSunSky::sunColor()
{
init();
const float elevation_angle = 93.885f - rad2deg( _sun_theta );
if(elevation_angle < 0.0f)
return Vec3f(0.0f);
// optical mass
const float cos_sun_theta = cos( _sun_theta );
const float m = 1.0f / ( cos_sun_theta + 0.15f * powf( elevation_angle, -1.253f ) );
float results[38];
for( int i = 0; i < 38; ++i ) {
results[i] = data[i].sun_spectral_radiance * 10000.0f // convert from 1/cm^2 to 1/m^2;
/ 1000.0f; // convert from micrometer to nanometer
results[i] *= calculateAbsorption( _sun_theta, m, data[i].wavelength, _turbidity, data[i].k_o, data[i].k_wa );
}
float X = 0.0f, Y = 0.0f, Z = 0.0f;
for( int i = 0; i < 38; ++i ) {
X += results[i]*cie_table[i][1] * 10.0f;
Y += results[i]*cie_table[i][2] * 10.0f;
Z += results[i]*cie_table[i][3] * 10.0f;
}
return XYZ2rgb(Vec3f(X, Y, Z))*SKY_TONEMAPPING; // return result in W/m^2/sr (using a scale of 0.03 to handle dynamic range)
}
Vec3f PreethamSunSky::skyColor( const Vec3f & direction, bool CEL )
{
init();
Vec3f overcast_sky_color = Vec3f( 0.0f );
Vec3f sunlit_sky_color = Vec3f( 0.0f );
// Preetham skylight model
if( _overcast < 1.0f )
{
Vec3f ray_direction = direction;
if(CEL && dot( ray_direction, _sun_dir ) > 0.999 )
sunlit_sky_color = _sun_color;
else
{
float dir_dot_up = dot( direction, _up );
if(abs(dir_dot_up) < 1.0e-16f)
dir_dot_up = 1.0e-16f;
float inv_dir_dot_up = 1.f / dir_dot_up;
if(inv_dir_dot_up < 0.f)
{
ray_direction = 2.0*dot(-ray_direction, _up)*_up + ray_direction;
inv_dir_dot_up = -inv_dir_dot_up;
}
float cos_gamma = dot(_sun_dir, ray_direction);
float gamma = acos(cos_gamma);
Vec3f A = _c1 * inv_dir_dot_up;
Vec3f B = _c3 * gamma;
Vec3f color_Yxy = ( Vec3f(1.0f) + _c0*Vec3f( exp(A[0]), exp(A[1]), exp(A[2]) ) ) *
( Vec3f(1.0f) + _c2*Vec3f( exp(B[0]), exp(B[1]), exp(B[2]) ) + _c4*cos_gamma*cos_gamma );
color_Yxy *= _inv_divisor_Yxy;
Vec3f color_XYZ = Yxy2XYZ( color_Yxy );
sunlit_sky_color = XYZ2rgb( color_XYZ );
sunlit_sky_color *= SKY_TONEMAPPING/683.0f; // return result in W/m^2 (using a scale of 0.03 to handle dynamic range)
}
}
// CIE standard overcast sky model
float Y = 15.0f;
overcast_sky_color = Vec3f( ( 1.0f + 2.0f * fabs( dot(direction,_up) ) ) / 3.0f * Y ) * SKY_TONEMAPPING/683.0f;
// return linear combo of the two
Vec3f color = sunlit_sky_color*(1.0f - _overcast) + overcast_sky_color*_overcast;
color[0] = max(0.0f, color[0]);
color[1] = max(0.0f, color[1]);
color[2] = max(0.0f, color[2]);
return color;
}
// Approximations for Earth-Sun distance correction factor and solar declination [Spencer 1971]
void PreethamSunSky::spencer(unsigned int day, double& earth_sun_dist, double& declination)
{
double day_angle = (day - 1)*2.0*M_PI/365.0;
double cosA = cos(day_angle);
double sinA = sin(day_angle);
double cosA_sqr = cosA*cosA;
double sinA_sqr = sinA*sinA;
double cos2A = cosA_sqr - sinA_sqr;
double sin2A = 2.0*sinA*cosA;
double cos3A = (cosA_sqr - 3.0*sinA_sqr)*cosA;
double sin3A = (3.0*cosA_sqr - sinA_sqr)*sinA;
earth_sun_dist = 1.00011 + 0.034221*cosA + 0.001280*sinA + 0.000719*cos2A + 0.000077*sin2A;
declination = 0.006918 - 0.399912*cosA + 0.070257*sinA - 0.006758*cos2A + 0.000907*sin2A - 0.002697*cos3A + 0.001480*sin3A;
}
// Common equations for computing the sun position [Preetham et al. 1999, Prein and Gayanilo 1992, Milankovitch 1930]
inline Vec2f PreethamSunSky::solar_elevation(double time, double latitude, double declination)
{
double hour_angle = (time - 12.0)*M_PI/12.0;
double cos_hour_angle = cos(hour_angle);
double sin_hour_angle = sign(hour_angle)*sqrt(1.0 - cos_hour_angle*cos_hour_angle);
double cos_latitude = cos(latitude);
double sin_latitude = sin(latitude);
double cos_declination = cos(declination);
double sin_declination = sin(declination);
double cos_zenith = sin_latitude*sin_declination + cos_latitude*cos_declination*cos_hour_angle;
double phi = atan2(cos_declination*sin_hour_angle, cos_latitude*sin_declination + sin_latitude*cos_declination*cos_hour_angle);
return Vec2f(acos(cos_zenith), phi);
}
Vec2f PreethamSunSky::sun_position(unsigned int day, double time, double latitude)
{
double tmp, declination;
spencer(day, tmp, declination);
return solar_elevation(time, latitude*M_PI/180.0, declination);
}
const float PreethamSunSky::cie_table[38][4] =
{
{380.f, 0.0002f, 0.0000f, 0.0007f},
{390.f, 0.0024f, 0.0003f, 0.0105f},
{400.f, 0.0191f, 0.0020f, 0.0860f},
{410.f, 0.0847f, 0.0088f, 0.3894f},
{420.f, 0.2045f, 0.0214f, 0.9725f},
{430.f, 0.3147f, 0.0387f, 1.5535f},
{440.f, 0.3837f, 0.0621f, 1.9673f},
{450.f, 0.3707f, 0.0895f, 1.9948f},
{460.f, 0.3023f, 0.1282f, 1.7454f},
{470.f, 0.1956f, 0.1852f, 1.3176f},
{480.f, 0.0805f, 0.2536f, 0.7721f},
{490.f, 0.0162f, 0.3391f, 0.4153f},
{500.f, 0.0038f, 0.4608f, 0.2185f},
{510.f, 0.0375f, 0.6067f, 0.1120f},
{520.f, 0.1177f, 0.7618f, 0.0607f},
{530.f, 0.2365f, 0.8752f, 0.0305f},
{540.f, 0.3768f, 0.9620f, 0.0137f},
{550.f, 0.5298f, 0.9918f, 0.0040f},
{560.f, 0.7052f, 0.9973f, 0.0000f},
{570.f, 0.8787f, 0.9556f, 0.0000f},
{580.f, 1.0142f, 0.8689f, 0.0000f},
{590.f, 1.1185f, 0.7774f, 0.0000f},
{600.f, 1.1240f, 0.6583f, 0.0000f},
{610.f, 1.0305f, 0.5280f, 0.0000f},
{620.f, 0.8563f, 0.3981f, 0.0000f},
{630.f, 0.6475f, 0.2835f, 0.0000f},
{640.f, 0.4316f, 0.1798f, 0.0000f},
{650.f, 0.2683f, 0.1076f, 0.0000f},
{660.f, 0.1526f, 0.0603f, 0.0000f},
{670.f, 0.0813f, 0.0318f, 0.0000f},
{680.f, 0.0409f, 0.0159f, 0.0000f},
{690.f, 0.0199f, 0.0077f, 0.0000f},
{700.f, 0.0096f, 0.0037f, 0.0000f},
{710.f, 0.0046f, 0.0018f, 0.0000f},
{720.f, 0.0022f, 0.0008f, 0.0000f},
{730.f, 0.0010f, 0.0004f, 0.0000f},
{740.f, 0.0005f, 0.0002f, 0.0000f},
{750.f, 0.0003f, 0.0001f, 0.0000f}
};
const PreethamSunSky::Datum PreethamSunSky::data[] =
{
{0.38f, 1655.9f, -1.f, -1.f},
{0.39f, 1623.37f, -1.f, -1.f},
{0.4f, 2112.75f, -1.f, -1.f},
{0.41f, 2588.82f, -1.f, -1.f},
{0.42f, 2582.91f, -1.f, -1.f},
{0.43f, 2423.23f, -1.f, -1.f},
{0.44f, 2676.05f, -1.f, -1.f},
{0.45f, 2965.83f, 0.003f, -1.f},
{0.46f, 3054.54f, 0.006f, -1.f},
{0.47f, 3005.75f, 0.009f, -1.f},
{0.48f, 3066.37f, 0.014f, -1.f},
{0.49f, 2883.04f, 0.021f, -1.f},
{0.5f, 2871.21f, 0.03f, -1.f},
{0.51f, 2782.5f, 0.04f, -1.f},
{0.52f, 2710.06f, 0.048f, -1.f},
{0.53f, 2723.36f, 0.063f, -1.f},
{0.54f, 2636.13f, 0.075f, -1.f},
{0.55f, 2550.38f, 0.085f, -1.f},
{0.56f, 2506.02f, 0.103f, -1.f},
{0.57f, 2531.16f, 0.12f, -1.f},
{0.58f, 2535.59f, 0.12f, -1.f},
{0.59f, 2513.42f, 0.115f, -1.f},
{0.6f, 2463.15f, 0.125f, -1.f},
{0.61f, 2417.32f, 0.12f, -1.f},
{0.62f, 2368.53f, 0.105f, -1.f},
{0.63f, 2321.21f, 0.09f, -1.f},
{0.64f, 2282.77f, 0.079f, -1.f},
{0.65f, 2233.98f, 0.067f, -1.f},
{0.66f, 2197.02f, 0.057f, -1.f},
{0.67f, 2152.67f, 0.048f, -1.f},
{0.68f, 2109.79f, 0.036f, -1.f},
{0.69f, 2072.83f, 0.028f, 0.028f},
{0.7f, 2024.04f, 0.023f, 0.023f},
{0.71f, 1987.08f, 0.018f, 0.018f},
{0.72f, 1942.72f, 0.014f, 0.014f},
{0.73f, 1907.24f, 0.011f, 0.011f},
{0.74f, 1862.89f, 0.01f, 0.01f},
{0.75f, 1825.92f, 0.009f, 0.009f}
};
|
#ifndef COUNTERS_HPP
#define COUNTERS_HPP
#include "Persistence.hpp"
#include <map>
#include <string>
/**
* @brief Data abstraction for object classification to be persisted
*/
class Counters {
private:
std::map <std::string, int> countMap;
Persistence persistence;
void PersistUpdate(std::string name, int value);
std::string moduleName;
public:
void SetModuleName(std::string);
void Add(std::string name, int value);
void Increment(std::string name);
int Get(std::string name);
};
#endif
|
#include<iostream>
#include<cstdio>
#include<map>
#include<set>
#include<vector>
#include<stack>
#include<queue>
#include<string>
#include<cstring>
#include<sstream>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long LL;
const LL mod = 1000000000;
int n;
LL f[310][310];
bool vis[310][310];
string st;
LL dfs(int l,int r) {
if (l > r) return 0;
if (st[l] != st[r]) return 0;
if (vis[l][r]) return f[l][r];
f[l][r] = 0;
for (int k = l+1;k <= r; k++) {
if (st[k] == st[l]) f[l][r] = (f[l][r] + dfs(l+1,k-1)*dfs(k,r))%mod;
}
vis[l][r] = true;
//printf("%d %d %lld\n",l,r,f[l][r]);
return f[l][r];
}
int main() {
while (cin >> st) {
memset(vis,false,sizeof(vis));
n = st.size();
for (int i = 0;i < n; i++) {vis[i][i] = true;f[i][i] = 1;}
printf("%lld\n",dfs(0,n-1));
}
return 0;
}
|
#pragma once
#include "Analysis.hpp"
#include <cmath>
#include <complex>
#include "Zygelman.hpp"
#include "Helper.hpp"
using namespace std;
typedef std::complex<double> dcomp;
class Bispectrum_NLG {
public:
Bispectrum_NLG(AnalysisInterface *analysis);
~Bispectrum_NLG();
double calc_angular_B(int l1, int l2, int l3, int m1, int m2, int m3,\
double z, int Pk_index, int Tb_index, int q_index);
double D_Growth_interp(double z, int q_index);
double calc_Blll(int l1, int l2, int l3, double z, int Pk_index, int Tb_index, int q_index);
double Wnu(double r, double z_centre, double delta_z);
AnalysisInterface* analysis;
private:
double D_Growth(double z);
double D_Growth(double z, int q_index);
dcomp B_ll(int la, int lb, int lc, double z, int Pk_index, int Tb_index, int q_index);
void update_D_Growth(int q_index);
double z_centre_CLASS;
double delta_z_CLASS;
double f1(double z, int Tb_index);
double theta(int li, int lj, double z, int q, double z_centre, double delta_z,\
int Pk_index, int Tb_index, int q_index);
double alpha(int l, double k, double z_centre, double delta_z,\
int Pk_index, int Tb_index, int q_index);
double sph_bessel_camb(int l, double x);
double power(double k, int Pk_index);
double pi = M_PI;
double Growth_function_norm;
vector<double> Growth_function_norms;
double g1_interp(double z);
spline1dinterpolant Growth_function_interpolator;
vector<spline1dinterpolant> growth_function_interps;
vector<Theta> theta_interpolants;
};
|
#include "global.h"
float interpolate_undefined_arrival(float ***at,const int i,const int j,const int k) {
int ii,lo,up;
ii = i;
while ((ii>0) && (at[ii][j][k]<0)) {
ii--;
}
lo = ii;
ii = i;
while ((ii<nx-1) && (at[ii][j][k]<0)) {
ii++;
}
up = ii;
if ((up>i) && (lo<i)) {
at[i][j][k] = ((up-i)*at[lo][j][k] + (i-lo)*at[up][j][k])/(up-lo);
return at[i][j][k];
}
else if (up>i) {
at[i][j][k] = at[up][j][k];
return at[i][j][k];
}
else if (lo<i) {
at[i][j][k] = at[lo][j][k];
return at[i][j][k];
}
return -2;
}
void save_at_hline(float ***at,int z,int id) {
float *buffer = new float[nx*ny*z];
int *meta = new int[3];
meta[0] = nx;
meta[1] = ny;
meta[2] = z;
for (int i=0;i<nx;i++)
for (int j=0;j<ny;j++)
for (int k=0;k< z;k++) {
if (k<z-2) {
buffer[i*ny*z+j*z+k] = -2;
}
else {
if (at[i][j][k]>0) {
buffer[i*ny*z+j*z+k] = at[i][j][k];
}
else {
buffer[i*ny*z+j*z+k] = interpolate_undefined_arrival(at,i,j,k);
cout<<"ERR"<<i<<","<<j<<","<<k<<" "<<at[i][j][k]<<endl;
cout<<"ERR"<<nx<<","<<ny<<","<<nz<<endl;
}
}
}
char file[256];
filename(file,"at_interface.bin","init",id);
FILE *out = fopen (file, "wb");
fwrite(meta, sizeof(meta[0]), 3, out);
fwrite(buffer, sizeof(buffer[0]), nx*ny*z, out);
fclose(out);
delete buffer;
delete meta;
}
void save_interface(float ***at,int id) {
save_at_hline(at,21,id);
}
void check_init_ats(float ***at) {
FORALL {
if (abs(at[i][j][k])<0.001)
cout<<"init problem "<<i<<","<<j<<","<<k<<" "<<at[i][j][k]<<endl;
if (k>18) {
if (at[i][j][k]<0) {
cout<<"init problem "<<i<<","<<j<<","<<k<<" "<<at[i][j][k]<<endl;
}
}
else {
if (at[i][j][k]>0) {
cout<<"init problem "<<i<<","<<j<<","<<k<<" "<<at[i][j][k]<<endl;
}
}
//edges too fast
if (i==0) if (at[i][j][k]<at[i+1][j][k]) {
at[i][j][k] = at[i+1][j][k];
}
if (i==nx-1) if (at[i][j][k]<at[i-1][j][k]) {
at[i][j][k] = at[i-1][j][k];
}
if (j==0) if (at[i][j][k]<at[i][j+1][k]) {
at[i][j][k] = at[i][j+1][k];
}
if (j==ny-1) if (at[i][j][k]<at[i][j-1][k]) {
at[i][j][k] = at[i][j-1][k];
}
}
}
void init_points(float ***at) {
for(unsigned short i=2;i<nx-2;i++)
for(unsigned short j=2;j<ny-2;j++)
for(unsigned short k=1;k<nz-1;k++) {
if (at[i][j][k]>-1) {
Bod b(-3,i,j,k); //only horizontal interface
b.t = at[i][j][k];
pq.push(b);
}
else if (k==19) {
cout<<"init "<<i<<","<<j<<","<<k<<" "<<at[i][j][k]<<endl;
}
}
//cout<<"initialized "<<pq.size()<<" from "<<(nx-4)*(ny-4)<<endl;
}
void init_interface(float ***at,int id) {
INFO("only horizontal interface");
char file[256];
filename(file,"at_interface.bin","init",id);
FILE *in = fopen (file, "rb");
if (in == NULL) {
INFO("no file ",file,true);
}
int *m = new int[3];
fread (m, sizeof(int), 3, in);
if ((m[0]!=nx) || (m[0]!=nx) || (m[0]!=nx)) {
cerr<<"ERR diferent size of init interface and model:"<<endl;
cerr<<m[0]<<","<<m[1]<<","<<m[2]<<" vs "<<nx<<","<<ny<<","<<nz<<endl;
cin.get();
}
float *buffer = new float[nx*ny*nz];
fread (buffer, sizeof(float), nx*ny*nz, in);
FORALL {
at[i][j][k] = buffer[i*ny*nz+j*nz+k];
}
fclose(in);
delete m;
delete buffer;
check_init_ats(at);
init_points(at);
}
|
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int ret = 0;
vector<int> tasks;
for (int i = 0; i < 3; i++) {
int x; cin >> x;
tasks.push_back(x);
}
sort(tasks.begin(), tasks.end());
for (int i = 1; i < 3; i++) ret += tasks[i] - tasks[i - 1];
cout << ret << endl;
return 0;
}
|
/*
* Copyright (C) 2013 Tom Wong. All rights reserved.
*/
#ifndef __GT_FT_TEMP_H__
#define __GT_FT_TEMP_H__
#include "gtobject.h"
#include <QtCore/QIODevice>
GT_BEGIN_NAMESPACE
class GtFTTempData;
class GtFTTempPrivate;
class GT_SVCE_EXPORT GtFTTemp : public QIODevice, public GtObject
{
Q_OBJECT
public:
explicit GtFTTemp(QObject *parent = 0);
explicit GtFTTemp(const QString &dir,
const QString &fileId,
QObject *parent = 0);
~GtFTTemp();
public:
void setPath(const QString &dir, const QString &fileId);
QString fileId() const;
QString metaPath() const;
QString dataPath() const;
bool open(OpenMode mode);
void close();
bool flush();
qint64 size() const;
bool seek(qint64 pos);
int temps_size() const;
const GtFTTempData& temps(int index) const;
qint64 complete(qint64 begin = 0) const;
bool exists() const;
bool remove();
public:
static qint64 complete(const QList<GtFTTempData*> &list, qint64 begin);
static void append(QList<GtFTTempData*> &list, qint64 begin, qint64 end);
protected:
qint64 readData(char *data, qint64 maxlen);
qint64 writeData(const char *data, qint64 len);
private:
QScopedPointer<GtFTTempPrivate> d_ptr;
private:
Q_DISABLE_COPY(GtFTTemp)
Q_DECLARE_PRIVATE(GtFTTemp)
};
GT_END_NAMESPACE
#endif /* __GT_FT_TEMP_H__ */
|
//
// Created by manout on 17-3-22.
//
#include "common_use.h"
/*
* Find the contiguous sub_array within array(containing at least one number)which has the largest sum
*
* 分析:
* 最大连续子序列的和
* 当我们从头到尾遍历这个数组的时候,对于数组里的一个整数,它只有两种选择
* 1:加入之前的sub_array
* 2:自己另起一个sub_array
* 如果之前的sub_array的和是大于0的,那么认为其对后续是有贡献的,我们选择加入之前的sub_array
* 如果之前的sub_array的和是不大于0的,那么认为其对后续是没有或者负贡献的,我们选择另起一个sub_array
* 设状态f[j],表示以S[j]结尾的最大连续子序列的和,状态转移方程为
* f[j] = max{f[j - 1] + S[j], S[j]},其中1 <= j <= n
* target = max{f[j]}, 其中1 <= j <= n
*/
//时间复杂度O(n), 空间复杂度O(1)
int max_sub_array(vector<int>& nums)
{
int ret = INT32_MIN;
int f = 0;
for (int i = 0; i < nums.size(); ++i)
{
f = max(f + nums[i], nums[s]);
ret = max(ret, f);
}
return ret;
}
|
#include <gtkmm/application.h>
#include "./HelloWorld.h"
int main(int argc, char** argv)
{
auto app = Gtk::Application::create(argc, argv, "org.brianna.love");
HelloWorld hw;
return app->run(hw);
}
|
#include<bits/stdc++.h>
using namespace std;
#define ll long long
ll dp[12][2][2][15],len;
char num[12];
ll digitDP(int pos, int isEqual,int allZeroes, int totZero){
if(pos==len) return totZero;
ll &ret = dp[pos][isEqual][allZeroes][totZero];
if(ret!=-1) return ret;
ret = 0;
int d = num[pos]-'0';
int mx = isEqual?d:9;
for(int i = 0; i<=mx; ++i){
ret+=digitDP(pos+1,isEqual && i==d,allZeroes && (i==0),totZero+(i==0 && !allZeroes));
}
return ret;
}
ll solve(ll a){
sprintf(num,"%lld",a);
len = strlen(num);
memset(dp,-1,sizeof(dp));
return digitDP(0,1,1,0);
}
|
/*
Given a generic tree and an integer x, check if x is present in the given tree or not.
Return true if x is present, return false otherwise.
Input format :
The first line of input contains data of the nodes of the tree in level order form.
The order is: data for root node, number of children to root node, data of each of child nodes
and so on and so forth for each node. The data of the nodes of the tree is separated by space.
The following line contains an integer, that denotes the value of x.
Output format :
The first and only line of output contains true, if x is present and false, otherwise.
Constraints:
Time Limit: 1 sec
Sample Input 1 :
10 3 20 30 40 2 40 50 0 0 0 0
40
Sample Output 1 :
true
Sample Input 2 :
10 3 20 30 40 2 40 50 0 0 0 0
4
Sample Output 2:
false
*/
#include<bits/stdc++.h>
using namespace std;
template<typename T>
class TreeNode{
public:
T data;
vector<TreeNode<T>*> children;
TreeNode(T data){
this -> data = data;
}
};
TreeNode<int>* takeinput(){
queue<TreeNode<int>*> q;
int rootData;
cin >> rootData;
TreeNode<int>* root = new TreeNode<int>(rootData);
q.push(root);
while(!q.empty()){
TreeNode<int>* front = q.front();
q.pop();
int numofchild;
cin >> numofchild;
for(int i=0;i<numofchild;i++){
int childData;
cin >> childData;
TreeNode<int>* child = new TreeNode<int>(childData);
front->children.push_back(child);
q.push(child);
}
}
return root;
}
bool containsX(TreeNode<int>* root,int x){
queue<TreeNode<int>*> q;
q.push(root);
while(!q.empty()){
TreeNode<int>* front = q.front();
q.pop();
if(front -> data == x){
return true;
}
for(int i=0;i<front->children.size();i++){
q.push(front->children[i]);
}
}
return false;
}
int main(){
TreeNode<int>* root = takeinput();
int x;
cin >> x;
bool ans = containsX(root,x);
if(ans){
cout << "true" << endl;
}else{
cout << "false" << endl;
}
return 0;
}
|
class BookInfo {
public:
enum Status {
ONTHEBOOKSHELF,
BORROWED
};
std::string author;
std::string category;
unsigned int pagesno;
Status status;
BookInfo() {
}
BookInfo(std::string author, std::string category, unsigned int pagesno, Status status) {
this->author = author;
this->category = category;
this->pagesno = pagesno;
this->status = status;
}
friend std::ostream& operator<< (std::ostream& stream, const BookInfo& b) {
stream << "Author: " << b.author << std::endl;
stream << "Category: " << b.category << std::endl;
stream << "Number of pages: " << b.pagesno << std::endl;
stream << "Status: " << ((b.status == ONTHEBOOKSHELF) ? ("on the bookshelf") : ("borrowed")) << std::endl;
return stream;
}
};
|
// BHNavigator.h: interface for the CBHNavigator class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_BHNAVIGATOR_H__B6B72310_2259_494E_8CBC_A4124F3CF5DF__INCLUDED_)
#define AFX_BHNAVIGATOR_H__B6B72310_2259_494E_8CBC_A4124F3CF5DF__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#pragma once
#include "guicontrolbar.h"
#include "GuiTabWnd.h"
#include "GuiContainer.h"
#include "GuiMiniTool.h"
class CBHNavigator : public CGuiControlBar
{
public:
CBHNavigator();
virtual ~CBHNavigator();
void FillerControlPanel();
void FillTreeClassView();
int CreatContExplorer();
int CreatContClassView();
DECLARE_MESSAGE_MAP()
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnNcRButtonDown(UINT nHitTest, CPoint point);
afx_msg BOOL OnNotify(WPARAM wParam, LPARAM lParam, LRESULT* pResult);
protected:
CGuiTabWnd m_TabControlPanel;
CTreeCtrl m_TreeControlPanel;
CTreeCtrl m_TreeClassView;
CTreeCtrl m_TreeResourceView;
CImageList m_imgList;
CGuiContainer m_ctControlPanel;
CGuiMiniTool m_miControlPanel;
CGuiContainer m_ctClassView;
CGuiMiniTool m_miClassView;
public:
void Onproperties();
void OnNewFolder();
virtual void StyleDispl(DWORD dwDsp=GUISTYLE_XP)
{
m_StyleDisplay=dwDsp;
m_miControlPanel.StyleDispl(dwDsp);
m_miClassView.StyleDispl(dwDsp);
m_TabControlPanel.StyleDispl(dwDsp);
CGuiControlBar::StyleDispl(dwDsp);
}
};
#endif // !defined(AFX_BHNAVIGATOR_H__B6B72310_2259_494E_8CBC_A4124F3CF5DF__INCLUDED_)
|
//
// Created by cirkul on 27.11.2020.
//
#include "Predator.h"
void Predator::eat() {
for (auto victim : this->home->animals) {
if (!victim->isAlive)
continue;
if (this->satietyInd == this->maxSatisfaction)
return;
if (victim->id == predator || victim->escape() || victim->size > this->size)
continue;
if (victim->hp > this->maxSatisfaction - this->satietyInd)
this->satietyInd = maxSatisfaction;
else
this->satietyInd += victim->hp;
victim->isAlive = false;
}
}
Animal *Predator::spawn(Playground &pg, int i, int j) {
Predator *newAnimal = new Predator(pg, i, j);
++newAnimal->home->creatureCount;
newAnimal->pg->newCreatures[newAnimal] = 1;
newAnimal->pg->allAnimals.push_back(newAnimal);
newAnimal->home->animals.push_back(newAnimal);
return newAnimal;
}
|
#ifndef type_lists_hpp
#define type_lists_hpp
#include "../2/convertability.hpp"
#include "../2/mappings.hpp"
#include "../2/types.hpp"
template<class T, class U>
struct TypeList {
typedef T Head;
typedef U Tail;
};
typedef TypeList<signed char,
TypeList<short int,
TypeList<int,
TypeList<long int, NullType>>>> SignedIntegrals;
namespace TL {
// typelist algorithms
template<typename... Ts>
struct Make;
template<typename T, typename... Ts>
struct Make<T, Ts...> {
using type = TypeList<T, typename Make<Ts...>::type>;
};
template<typename T>
struct Make<T> {
using type = TypeList<T, NullType>;
};
template<>
struct Make<> {
using type = TypeList<NullType, NullType>;
};
template <class TList>
struct Length;
template<>
struct Length<NullType> {
enum { value = 0 };
};
template<class T, class U>
struct Length<TypeList<T, U>> {
enum { value = 1 + Length<U>::value };
};
template<class TList, unsigned int index>
struct TypeAt;
template<class Head, class Tail>
struct TypeAt<TypeList<Head, Tail>, 0> {
typedef Head Result;
};
template<class Head, class Tail, unsigned int index>
struct TypeAt<TypeList<Head, Tail>, index> {
typedef typename TypeAt<Tail, index-1>::Result Result;
};
template<class TList, unsigned int index, class DefaultType>
struct TypeAtNonStrict;
template<unsigned int index, class DefaultType>
struct TypeAtNonStrict<NullType, index, DefaultType> {
typedef DefaultType Result;
};
template<class Head, class Tail, class DefaultType>
struct TypeAtNonStrict<TypeList<Head, Tail>, 0 , DefaultType> {
typedef Head Result;
};
template<class Head, class Tail, unsigned int index, class DefaultType>
struct TypeAtNonStrict<TypeList<Head, Tail>, index, DefaultType> {
typedef typename TypeAtNonStrict<Tail, index-1, DefaultType>::Result Result;
};
template<class TList, class T>
struct IndexOf;
template<class T>
struct IndexOf<NullType, T> {
enum { value = -1 };
};
template<class T, class Tail>
struct IndexOf<TypeList<T, Tail>, T> {
enum { value = 0 };
};
template<class Head, class Tail, class T>
struct IndexOf<TypeList<Head, Tail>, T> {
private:
enum { temp = IndexOf<Tail, T>::value };
public:
enum { value = temp == -1 ? -1 : 1 + temp };
};
template<class TList, class T>
struct Append;
template<>
struct Append<NullType, NullType> {
typedef NullType Result;
};
template<class T>
struct Append<NullType, T> {
typedef typename Make<T>::type Result;
};
template<class Head, class Tail>
struct Append<NullType, TypeList<Head, Tail>> {
typedef TypeList<Head, Tail> Result;
};
template<class Head, class Tail, class T>
struct Append<TypeList<Head, Tail>, T> {
typedef TypeList<Head, typename Append<Tail, T>::Result> Result;
};
template<class TList, class T>
struct Erase;
template<typename T>
struct Erase<NullType, T> {
typedef NullType Result;
};
template<class T, class Tail>
struct Erase<TypeList<T, Tail>, T> {
typedef Tail Result;
};
template<class Head, class Tail, class T>
struct Erase<TypeList<Head, Tail>, T> {
typedef TypeList<Head, typename Erase<Tail, T>::Result> Result;
};
template<class TList, class T>
struct EraseAll;
template<class T>
struct EraseAll<NullType, T> {
typedef NullType Result;
};
template<class T, class Tail>
struct EraseAll<TypeList<T, Tail>, T> {
typedef typename EraseAll<Tail, T>::Result Result;
};
template<class Head, class Tail, class T>
struct EraseAll<TypeList<Head, Tail>, T> {
typedef TypeList<Head, typename EraseAll<Tail, T>::Result> Result;
};
template<class TList>
struct NoDuplicates;
template<>
struct NoDuplicates<NullType> {
typedef NullType Result;
};
template<class Head, class Tail>
struct NoDuplicates<TypeList<Head, Tail>> {
private:
typedef typename NoDuplicates<Tail>::Result L1;
typedef typename Erase<L1, Head>::Result L2;
public:
typedef TypeList<Head, L2> Result;
};
template<class TList, class T, class U>
struct Replace;
template<class T, class U>
struct Replace<NullType, T, U> {
typedef NullType Result;
};
template<class T, class Tail, class U>
struct Replace<TypeList<T, Tail>, T, U> {
typedef TypeList<U, Tail> Result;
};
template<class Head, class Tail, class T, class U>
struct Replace<TypeList<Head, Tail>, T, U> {
typedef TypeList<Head, typename Replace<Tail, T, U>::Result> Result;
};
template<class TList>
struct Head;
template<class Head, Tail>
struct Head<TypeList<Head, Tail>> {
using Result = Head;
}
template<class TList>
struct Last;
template<class T>
struct Last<TypeList<T, NullType>> {
using Result = T;
};
template<class Head, class Tail>
struct Last<TypeList<Head, Tail>> {
using Result = typename Last<Tail>::Result;
};
template<class TList>
struct Strip;
template<class T>
struct Strip<TypeList<T, NullType>> {
using Result = NullType;
};
template<class Head, class Tail>
struct Strip<TypeList<Head, Tail>> {
using Result = TypeList<Head, typename Strip<Tail>::Result>;
};
template<class TList>
struct Reverse;
template<class T>
struct Reverse<TypeList<T, NullType>> {
typedef TypeList<T, NullType> Result;
};
template<class Head, class Tail>
struct Reverse<TypeList<Head, Tail>> {
private:
using LastType = typename Last<Tail>::Result;
using TailStripped = typename Strip<Tail>::Result;
public:
using Result = TypeList<
LastType,
typename Reverse<TypeList<Head,TailStripped>>::Result
>;
};
template<class TList, class T, class U>
struct ReplaceAll;
template<class T, class U>
struct ReplaceAll<NullType, T, U> {
typedef NullType Result;
};
template<class T, class Tail, class U>
struct ReplaceAll<TypeList<T, Tail>, T, U> {
typedef TypeList<U, typename ReplaceAll<Tail, T, U>::Result> Result;
};
template<class Head, class Tail, class T, class U>
struct ReplaceAll<TypeList<Head, Tail>, T, U> {
typedef TypeList<Head, typename ReplaceAll<Tail, T, U>::Result> Result;
};
template<class TList, class T>
struct MostDerived;
template<class T>
struct MostDerived<NullType, T> {
typedef T Result;
};
template<class Head, class Tail, class T>
struct MostDerived<TypeList<Head, Tail>, T> {
private:
typedef typename MostDerived<Tail, T>::Result Candidate;
public:
typedef typename mappings::Select<SUPERSUBCLASS(Candidate, Head), Head, Candidate>::Result Result;
};
template<class TList>
struct DerivedToFront;
template<>
struct DerivedToFront<NullType> {
typedef NullType Result;
};
template<class Head, class Tail>
struct DerivedToFront<TypeList<Head, Tail>> {
private:
typedef typename MostDerived<Tail, Head>::Result TheMostDerived;
typedef typename Replace<Tail, TheMostDerived, Head>::Result L;
public:
typedef TypeList<TheMostDerived, L> Result;
};
}
#define TYPELIST_1(T1) TL::Make<T1>::type
#define TYPELIST_2(T1, T2) TL::Make<T1, T2>::type
#define TYPELIST_3(T1, T2, T3) TL::Make<T1, T2, T3>::type
#define TYPELIST_4(T1, T2, T3, T4) TL::Make<T1, T2, T3, T4>::type
#define TYPELIST_5(T1, T2, T3, T4, T5) TL::Make<T1, T2, T3, T4, T5>::type
#endif // type_lists_hp
|
//: C03:StructArray.cpp
// Kod zrodlowy pochodzacy z ksiazki
// "Thinking in C++. Edycja polska"
// (c) Bruce Eckel 2000
// Informacje o prawie autorskim znajduja sie w pliku Copyright.txt
// Tablica struktur
typedef struct {
int i, j, k;
} ThreeDpoint;
int main() {
ThreeDpoint p[10];
for(int i = 0; i < 10; i++) {
p[i].i = i + 1;
p[i].j = i + 2;
p[i].k = i + 3;
}
} ///:~
|
/*
* Copyright (c) 2001, Swedish Institute of Computer Science.
* 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 Institute 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 INSTITUTE 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 INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
* $Id: sys_arch.c,v 1.3 2002/01/02 17:35:42 adam Exp $
*/
//#include "lwip/debug.h"
#define WIN32_LEAN_AND_MEAN
#include "Const.h"
#include "lwip/stats.h"
#include "lwip/api.h"
#include "VDK.h"
#include "tGeneral.h"
#include "sysarch.h"
struct sys_timeouts timeouts;
sys_sem_t sem_sys_prot;
/*-----------------------------------------------------------------------------------*/
sys_sem_t sys_sem_new(u8_t count)
{
return VDK::CreateSemaphore(count,1,0,0); //0x7ffffff0
}
sys_sem_t sys_sem_new_m(u8_t count, u8_t max)
{
return VDK::CreateSemaphore(count,max,0,0);
}
sys_sem_t new_period_sem(u32_t milliseconds)
{
return VDK::CreateSemaphore(0, 1, milliseconds*TICKPERMS, milliseconds*TICKPERMS);
}
/*-----------------------------------------------------------------------------------*/
void sys_sem_free(sys_sem_t sem)
{
VDK::DestroySemaphore(sem);
}
/*-----------------------------------------------------------------------------------*/
void sys_sem_wait(sys_sem_t sem)
{
VDK::PendSemaphore(sem,0x7ffffff0);
VDK::SystemError Error;
Error=VDK::GetLastThreadError();
if (Error==VDK::kSemaphoreTimeout)
{
VDK::DispatchThreadError((VDK::SystemError)0,0);
}
}
err_t sys_sem_wait_t(sys_sem_t sem, u32_t timeout)
{
DWORD dw;
VDK::DispatchThreadError((VDK::SystemError)0,0);
if (timeout == NOWAIT)
VDK::PendSemaphore(sem, 1);
else
VDK::PendSemaphore(sem, timeout*TICKPERMS);
VDK::SystemError Error;
Error=VDK::GetLastThreadError();
dw = DWORD(Error);
if (Error==VDK::kSemaphoreTimeout)
{
VDK::DispatchThreadError((VDK::SystemError)0,0);
}
if (dw == 0)
{
return SYS_ERR_OK;
}
else
{
return SYS_ERR_TIMEOUT;
}
}
/*-----------------------------------------------------------------------------------*/
void sys_sem_signal(sys_sem_t sem)
{
VDK::PostSemaphore(sem);
}
/*-----------------------------------------------------------------------------------*/
struct sys_timeouts *
sys_arch_timeouts(void)
{
return &timeouts;
}
/*-----------------------------------------------------------------------------------*/
void sys_init(void)
{
timeouts.next = NULL;
timeouts.lasttime = 0;
sem_sys_prot = sys_sem_new(1);
return;
}
/*-----------------------------------------------------------------------------------*/
void sys_thread_new(int (* function)(void *arg), void *arg, DWORD dwStackSize, TPrio prio)
{
TThreadData ThreadData;
ThreadData.function = function;
ThreadData.arg = arg;
VDK::ThreadCreationBlock inOutTCB;
inOutTCB.template_id = ktGeneral; //a ThreadType defined in the vdk.h and vdk.cpp
//inOutTCB.thread_id = 0; //an output only field
inOutTCB.thread_stack_size = dwStackSize;
inOutTCB.thread_priority = prio;
inOutTCB.user_data_ptr = &ThreadData;
//inOutTCB.pTemplate = NULL; //is a member used by VDK internally and does not need to be intilialised
VDK::CreateThreadEx(&inOutTCB); //VDK::ThreadID id =
}
/*-----------------------------------------------------------------------------------*/
sys_mbox_t sys_mbox_new(void)
{
struct sys_mbox *mbox;
mbox = (struct sys_mbox* )mem_malloc(sizeof(struct sys_mbox));
mbox->first = mbox->last = 0;
mbox->mail = (sys_sem )sys_sem_new_m(0, SYS_MBOX_SIZE);
mbox->space = (sys_sem )sys_sem_new_m(SYS_MBOX_SIZE,
SYS_MBOX_SIZE);
mbox->mutex = (sys_sem )sys_sem_new(1);
#ifdef SYS_STATS
stats.sys.mbox.used++;
if(stats.sys.mbox.used > stats.sys.mbox.max)
{
stats.sys.mbox.max = stats.sys.mbox.used;
}
#endif /* SYS_STATS */
return mbox;
}
/*-----------------------------------------------------------------------------------*/
void
sys_mbox_free(struct sys_mbox *mbox)
{
if(mbox != SYS_MBOX_NULL)
{
#ifdef SYS_STATS
stats.sys.mbox.used--;
#endif /* SYS_STATS */
sys_sem_wait(mbox->mutex);
sys_sem_free(mbox->mail);
sys_sem_free(mbox->space);
sys_sem_free(mbox->mutex);
mbox->mail = mbox->mutex = SYS_SEM_NULL;
/* DEBUGF("sys_mbox_free: mbox 0x%lx\r", mbox);*/
mem_free(mbox);
}
}
/*-----------------------------------------------------------------------------------*/
//描述:首先取得对邮箱的占用,然后把消息挂在消息队列,最后释放对邮箱的占用
// 把消息挂在消息队列,使消费者知道有没有新消息并不通过邮箱的信号量,而是递增邮箱的头指针使它
// 不等于尾指针。邮箱的信号量只是保证对邮箱操作的互斥。
// 参见sys_arch_mbox_fetch()
void sys_mbox_post(struct sys_mbox *mbox, void *msg)
{
sys_sem_wait(mbox->space); //先等待邮箱里有空间放邮件
sys_sem_wait(mbox->mutex); //取得对邮箱的占用
DEBUGF(SYS_DEBUG, ("sys_mbox_post: mbox %p msg %p first %d last %d\r",
mbox, msg, mbox->first, mbox->last));
mbox->msgs[mbox->last] = msg; //挂在消息队列的头
//如果msg为NULL,则挂了一条空消息
mbox->last++; //消息队列的头指针++
if(mbox->last == SYS_MBOX_SIZE) //越过循环队列的边界
{
mbox->last = 0;
}
sys_sem_signal(mbox->mail); //加一条新的消息了!
sys_sem_signal(mbox->mutex); //释放对邮箱的占用
}
/*-----------------------------------------------------------------------------------*/
//描述:看邮箱mbox里有没消息,如果有则放到msg,否则把NULL放到msg
// 不消费mbox->mail,这是针对等待函数等到mail信号量(已经先消费)的情况
//参数:@mbox为邮箱,
// @msg用来返回指向取得的消息的指针,这里认为msg不能为空
//返回:无
void sys_mbox_get(sys_mbox_t mbox, void **msg)
{
sys_sem_wait(mbox->mutex); //取得对邮箱的占用
DEBUGF(SYS_DEBUG, ("sys_mbox_get: mbox %p msg %p first %d last %d\r",
mbox, mbox->msgs[mbox->first], mbox->first, mbox->last));
if(msg != NULL)
{
*msg = mbox->msgs[mbox->first]; //返回消息
}
mbox->first++; //尾指针++,即使上面msg==NULL,++表示消费
if(mbox->first == SYS_MBOX_SIZE) //越过循环队列的边界
{
mbox->first = 0;
}
sys_sem_signal(mbox->space); //有新的空间了!
sys_sem_signal(mbox->mutex); //释放对邮箱的占用
}
/*-----------------------------------------------------------------------------------*/
//描述:从邮箱mbox里取一条消息,返回在msg。
// 有新消息的标准是邮箱的头指针不等于尾指针。取得对邮箱的信号量的占用并不代表有新消息,而只是保证
// 对邮箱操作的互斥。
// 参见sys_mbox_post()
//参数:@mbox为邮箱,@msg用来返回指向取得的消息的指针,
// @timeout等待消息的时间,=0无穷等待,!=0等待的时间
//返回:无
void sys_mbox_fetch(sys_mbox_t mbox, void **msg)
{
sys_sem_wait(mbox->mail); //先等待邮箱里有邮件
sys_mbox_get(mbox, msg);
}
err_t sys_mbox_fetch(sys_mbox_t mbox, void **msg, u32_t timeout)
{
err_t err = sys_sem_wait_t(mbox->mail, timeout*TICKPERMS); //先等待邮箱里有邮件
if (err == ERR_OK)
{
sys_mbox_get(mbox, msg);
return ERR_OK;
}
else
{
return err;
}
}
void sys_mbox_drain(sys_mbox_t mbox, u8_t type)
{
void* msg;
/* Drain the recvmbox. */
if(mbox != SYS_MBOX_NULL)
{
sys_sem_wait(mbox->mutex); //取得对邮箱的占用
while(mbox->first != mbox->last) //没有消息
{
msg = mbox->msgs[mbox->first++]; //返回消息,尾指针++
if(mbox->first == SYS_MBOX_SIZE) //越过循环队列的边界
{
mbox->first = 0;
}
if (type == MBOX_DRAINTYPE_NETCONN)
{
netconn_delete((struct netconn *)msg);
}
else if(type == MBOX_DRAINTYPE_PBUF)
{
pbuf_free((struct pbuf *)msg);
}
else //MBOX_DRAINTYPE_NETBUF
{
netbuf_delete((struct netbuf *)msg);
}
}
sys_sem_signal(mbox->mutex); //释放对邮箱的占用,
sys_mbox_free(mbox);
}
}
u16_t sys_mbox_msgnum(sys_mbox_t mbox)
{
u16_t num;
sys_sem_wait(mbox->mutex); //取得对邮箱的占用
num = sys_sem_getval(mbox->mail);
sys_sem_signal(mbox->mutex); //释放对邮箱的占用
return num;
}
u32_t sys_wait_multiple(u8_t nsema, sys_sem sema[], int fwaitall, u32_t timeout)
{
u8_t i;
i=0;
while (1)
{
VDK::PendSemaphore(sema[i],20);
volatile VDK::SystemError Error;
Error = VDK::GetLastThreadError();
if (Error != VDK::kNoError)
VDK::DispatchThreadError((VDK::SystemError)0,0);
else
{
return i;
}
i++;
if (i==nsema) i=0;
}
}
|
#include <iostream>
#include <vector>
using namespace std;
#define max_3base 29527
int main(){
int N;
cin >> N;
int cnt = 0;
for(int i = 1; i <= max_3base; i++)
{
int flag[3] = {0};
int num = i;
vector<int> buf;
int ans;
while((num - 1) / 3 != 0){
buf.push_back((num - 1) % 3);
flag[(num - 1) % 3] = 1;
num -= 1;
num /= 3;
}
buf.push_back((num - 1) % 3);
flag[(num - 1) % 3] = 1;
if (flag[0]*flag[1]*flag[2] == 0) continue;
int tmp = 0;
int amp = 1;
for(int i = 0; i < buf.size(); i++)
{
tmp += (3 + (buf[i] * 2)) * amp;
amp *= 10;
}
if (N < tmp) break;
//cout << tmp << endl;
cnt++;
}
cout << cnt << endl;
}
|
#include "DoggieList.h"
DoggieList::DoggieList()
{
this->current = 0;
}
void DoggieList::add(const Doggie& dog)
{
this->doggies.add(dog);
}
Doggie DoggieList::getCurrentDog()
{
if (this->current == this->doggies.getSize())
this->current = 0;
return this->doggies[this->current];
}
void DoggieList::seeDogs()
{
if (this->doggies.getSize() == 0)
return;
this->current = 0;
Doggie currentDoggie = this->getCurrentDog();
currentDoggie.showPhoto();
}
void DoggieList::next()
{
if (this->doggies.getSize() == 0)
return;
this->current++;
Doggie currentDoggie = this->getCurrentDog();
currentDoggie.showPhoto();
}
bool DoggieList::isEmpty()
{
return this->doggies.getSize() == 0;
}
|
#include <bits/stdc++.h>
using namespace std;
#define MOD 1000000007
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define rep1(i, n) for(int i = 1; i <= (int)(n); i++)
#define show(x) {for(auto i: x){cout << i << " ";} cout<<endl;}
#define showm(m) {for(auto i: m){cout << m.x << " ";} cout<<endl;}
typedef long long ll;
typedef pair<int, int> P;
ll gcd(int x, int y){ return y?gcd(y, x%y):x;}
ll lcm(ll x, ll y){ return (x*y)/gcd(x,y);}
int mod = 3;
typedef struct mint
{
ll x;
mint(ll x = 0) : x(x % mod){} //コンストラクタ
/* 演算子オーバーロード */
mint &operator+=(const mint a)
{
if ((x += a.x) >= mod)
x -= mod;
return *this;
}
mint &operator-=(const mint a)
{
if ((x += mod - a.x) >= mod)
x -= mod;
return *this;
}
mint &operator*=(const mint a)
{
(x *= a.x) %= mod;
return *this;
}
mint operator+(const mint a) const
{
mint res(*this);
return res += a;
}
mint operator-(const mint a) const
{
mint res(*this);
return res -= a;
}
mint operator*(const mint a) const
{
mint res(*this);
return res *= a;
}
mint pow(ll t) const
{
if (!t)
return 1;
mint a = pow(t >> 1);
a *= a;
if (t & 1)
a *= *this;
return a;
}
// for prime mod
mint inv() const
{
return pow(mod - 2);
}
mint &operator/=(const mint a)
{
return (*this) *= a.inv();
}
mint operator/(const mint a) const
{
mint res(*this);
return res /= a;
}
} mint_t;
int main()
{
int n, p;
cin >> n >> p;
vector<int> amaribox(p, 0); //modの数を管理
string s;
cin >> s;
mod = p;
ll ans = 0;
if (p != 2 && p != 5){
mint kurikoshi(0);
mint keta_mod(1);
rep(i, n){
int num = (s[n-1-i] - '0') % p;
kurikoshi += keta_mod * num ;
keta_mod *= 10;
// cout << kurikoshi.x << ":" << num << ":" << keta_mod.x<< endl;
if (kurikoshi.x == 0) ans++;
ans += amaribox[kurikoshi.x];
amaribox[kurikoshi.x] += 1;
}
} else {
// rep(i, n){
// int num = (s[n-1-i] - '0') % p;
// if (num == 0) ans += n-i;
// }
}
cout << ans << endl;
}
/*
aがある数xで割り切れる
0 (mod x)
a = b - c としたとき、b = c (mod x)
xx0000が10に対して互いに素である数pで割り切れるとき、
xxもある数pで割り切れる
*/
|
//Phoenix_RK
/*
https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/
Given a binary tree
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL.
Follow up:
You may only use constant extra space.
Recursive approach is fine, you may assume implicit stack space does not count as extra space for this problem.
Example 1:
Input: root = [1,2,3,4,5,null,7]
Output: [1,#,2,3,#,4,5,7,#]
Explanation: Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.
Constraints:
The number of nodes in the given tree is less than 6000.
-100 <= node.val <= 100
*/
class Solution {
public:
Node* connect(Node* root) {
if(!root)
return NULL;
queue<Node*> q;
q.push(root);
while(!q.empty())
{
int s=q.size();
Node* prev=NULL;
while(s--)
{
Node* temp=q.front();
q.pop();
if(temp->left)
q.push(temp->left);
if(temp->right)
q.push(temp->right);
if(prev!=NULL)
prev->next=temp;
prev=temp;
}
prev->next=NULL;
}
return root;
}
};
|
int Solution::lis(const vector<int> &nums) {
int maxlen = 0;
vector<int> dp(nums.size(), 1);
if(nums.size() <= 1) return nums.size();
int i=0,j=0;
while(i<nums.size()){
if(i==j){
i++;
j=0;
}
else {
if(nums[i]>nums[j]){
dp[i]=max(1+dp[j],dp[i]);
}
j++;
}
}
for(int i = 0; i < dp.size(); i++){
maxlen = max(maxlen, dp[i]);
}
return maxlen;
}
|
#include <unordered_map>
#include <list>
// list 的remove操作是o(n)的,erase才是o(1)
// remove的参数是value,基于该值做遍历比较然后删除
// erase的参数是迭代器,直接删除
class LRUCache {
// 第一个是key,第二个是value
typedef std::list<std::pair<int,int>> LruList;
typedef LruList::iterator list_iterator;
typedef std::unordered_map<int, list_iterator> CacheMap;
public:
LRUCache(int capacity) {
capacity_ = capacity;
}
int get(int key) {
// 如果有的话,需要把该key挪到lru链表的前方
CacheMap::iterator it = cache_.find(key);
if (it != cache_.end())
{
lru_list_.erase(it->second);
lru_list_.push_front(*(it->second));
return it->second->second;
}
return -1;
}
void put(int key, int value) {
// 如果存在的话,直接覆盖,然后更新lru
CacheMap::const_iterator cit = cache_.find(key);
if (cit != cache_.end())
{
lru_list_.erase(cache_[key]);
}
// 否则判断是否容量超过,然后更新lru,覆盖
else if (cache_.size() >= capacity_)
{
std::pair<int,int> remove_key = lru_list_.back();
lru_list_.pop_back();
cache_.erase(remove_key.first);
}
lru_list_.push_front(std::make_pair(key,value));
cache_[key] = lru_list_.begin();
}
private:
CacheMap cache_;
LruList lru_list_;
int capacity_;
};
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache* obj = new LRUCache(capacity);
* int param_1 = obj->get(key);
* obj->put(key,value);
*/
/*
["LRUCache","put","put","get","put","get","put","get","get","get"]
[[2],[1,1],[2,2],[1],[3,3],[2],[4,4],[1],[3],[4]]
*/
int main()
{
LRUCache* obj = new LRUCache(2);
obj->put(1,1);
obj->put(2,2);
obj->get(1);
obj->put(3,3);
obj->get(2);
obj->put(4,4);
obj->get(1);
obj->get(3);
obj->get(4);
return 0;
}
|
// Created on: 1997-04-10
// Created by: Prestataire Mary FABIEN
// Copyright (c) 1997-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// 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, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _TopOpeBRepDS_Check_HeaderFile
#define _TopOpeBRepDS_Check_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <TopOpeBRepDS_DataMapOfCheckStatus.hxx>
#include <Standard_Transient.hxx>
#include <TopOpeBRepDS_ListOfInterference.hxx>
#include <Standard_Integer.hxx>
#include <TopOpeBRepDS_Kind.hxx>
#include <TopTools_ListOfShape.hxx>
#include <Standard_OStream.hxx>
#include <Standard_CString.hxx>
#include <TopOpeBRepDS_CheckStatus.hxx>
#include <TopAbs_ShapeEnum.hxx>
class TopOpeBRepDS_HDataStructure;
class TopOpeBRepDS_Check;
DEFINE_STANDARD_HANDLE(TopOpeBRepDS_Check, Standard_Transient)
//! a tool verifing integrity and structure of DS
class TopOpeBRepDS_Check : public Standard_Transient
{
public:
Standard_EXPORT TopOpeBRepDS_Check();
Standard_EXPORT TopOpeBRepDS_Check(const Handle(TopOpeBRepDS_HDataStructure)& HDS);
//! Check integrition of DS
Standard_EXPORT Standard_Boolean ChkIntg();
//! Check integrition of interferences
//! (les supports et les geometries de LI)
Standard_EXPORT Standard_Boolean ChkIntgInterf (const TopOpeBRepDS_ListOfInterference& LI);
//! Verifie que le ieme element de la DS existe, et
//! pour un K de type topologique, verifie qu'il est du
//! bon type (VERTEX, EDGE, WIRE, FACE, SHELL ou SOLID)
Standard_EXPORT Standard_Boolean CheckDS (const Standard_Integer i, const TopOpeBRepDS_Kind K);
//! Check integrition des champs SameDomain de la DS
Standard_EXPORT Standard_Boolean ChkIntgSamDom();
//! Verifie que les Shapes existent bien dans la DS
//! Utile pour les Shapes SameDomain
//! si la liste est vide, renvoie vrai
Standard_EXPORT Standard_Boolean CheckShapes (const TopTools_ListOfShape& LS) const;
//! Verifie que les Vertex non SameDomain sont bien
//! nonSameDomain, que les vertex sameDomain sont bien
//! SameDomain, que les Points sont non confondus
//! ni entre eux, ni avec des Vertex.
Standard_EXPORT Standard_Boolean OneVertexOnPnt();
Standard_EXPORT const Handle(TopOpeBRepDS_HDataStructure)& HDS() const;
Standard_EXPORT Handle(TopOpeBRepDS_HDataStructure)& ChangeHDS();
Standard_EXPORT Standard_OStream& PrintIntg (Standard_OStream& S);
//! Prints the name of CheckStatus <stat> as a String
Standard_EXPORT Standard_OStream& Print (const TopOpeBRepDS_CheckStatus stat, Standard_OStream& S);
//! Prints the name of CheckStatus <stat> as a String
Standard_EXPORT Standard_OStream& PrintShape (const TopAbs_ShapeEnum SE, Standard_OStream& S);
//! Prints the name of CheckStatus <stat> as a String
Standard_EXPORT Standard_OStream& PrintShape (const Standard_Integer index, Standard_OStream& S);
DEFINE_STANDARD_RTTIEXT(TopOpeBRepDS_Check,Standard_Transient)
protected:
private:
Standard_EXPORT Standard_OStream& PrintMap (TopOpeBRepDS_DataMapOfCheckStatus& MapStat, const Standard_CString eltstr, Standard_OStream& S);
Standard_EXPORT Standard_OStream& PrintElts (TopOpeBRepDS_DataMapOfCheckStatus& MapStat, const TopOpeBRepDS_CheckStatus Stat, Standard_Boolean& b, Standard_OStream& S);
Handle(TopOpeBRepDS_HDataStructure) myHDS;
TopOpeBRepDS_DataMapOfCheckStatus myMapSurfaceStatus;
TopOpeBRepDS_DataMapOfCheckStatus myMapCurveStatus;
TopOpeBRepDS_DataMapOfCheckStatus myMapPointStatus;
TopOpeBRepDS_DataMapOfCheckStatus myMapShapeStatus;
};
#endif // _TopOpeBRepDS_Check_HeaderFile
|
//: C06:DefineInitialize.cpp
// Kod zrodlowy pochodzacy z ksiazki
// "Thinking in C++. Edycja polska"
// (c) Bruce Eckel 2000
// Informacje o prawie autorskim znajduja sie w pliku Copyright.txt
// Definiowanie zmiennych w dowolnych miejscach
#include "../require.h"
#include <iostream>
#include <string>
using namespace std;
class G {
int i;
public:
G(int ii);
};
G::G(int ii) { i = ii; }
int main() {
cout << "wartosc inicjujaca? ";
int retval = 0;
cin >> retval;
require(retval != 0);
int y = retval + 3;
G g(y);
} ///:~
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
//设置输入非明文显示
ui->passlineEdit->setEchoMode(QLineEdit::Password);
//QObject::connect(ui->calButton, SIGNAL(clicked()), this, SLOT(calSlot()));
//QObject::connect(ui->loginButton, SIGNAL(clicked()), this, SLOT(on_loginButton_clicked()));
}
MainWindow::~MainWindow()
{
delete ui;
}
#if 0
void MainWindow::calSlot()
{
//toInt 将文本中的字符串转10进制
int first = ui->firstlineEdit->text().toInt();
int second = ui->secondlineEdit->text().toInt();
int result;
int flag = 1;
/*判断combo Box悬着器中的字符,此处给出两种思路,
1、获取文本中的字符串做对比,效率低此处不讨论
2、使用comboBox的currentIndex下标索引较好
*/
switch (ui->comboBox->currentIndex())
{
case 0: //+
result = first + second;
break;
case 1:
result = first - second;
break;
case 2:
result = first * second;
break;
case 3:
if (0 == second) {
flag = 0;
QMessageBox::information(this, "Result", "The divisor cannot be 0!");
break;
}
result = first / second;
break;
}
//setTex 将结果设置在文本中,调用Qstring域的number方法将十进制转string
if (flag) {
ui->resultlineEdit->setText(QString::number(result));
QMessageBox::information(this, "Result", QString::number(result));
}
}
#endif
void MainWindow::on_loginButton_clicked()
{
if (ui->namelineEdit->text() == "hrk" && ui->passlineEdit->text() == "huruke") {
QMessageBox::information(this, "Message infomation", "Loging Success");
} else {
QMessageBox::information(this, "Message infomation", "name or password error");
}
}
|
#include <Homie.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#define PIN_BUTTON 0
#define PIN_RELAY 12
#define PIN_LED 13
#define DS18B20 14
#define INTERVAL 30
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(DS18B20);
// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);
HomieNode switchNode("switch", "switch");
HomieNode temperatureNode("temperature", "temperature");
#define FW_NAME "sonoff-th-ds18x"
#define FW_VERSION "1.0.1"
/* Magic sequence for Autodetectable Binary Upload */
const char *__FLAGGED_FW_NAME = "\xbf\x84\xe4\x13\x54" FW_NAME "\x93\x44\x6b\xa7\x75";
const char *__FLAGGED_FW_VERSION = "\x6a\x3f\x3e\x0e\xe1" FW_VERSION "\xb0\x30\x48\xd4\x1a";
/* End of magic sequence for Autodetectable Binary Upload */
int relayState = LOW;
int lastButtonState = LOW; // the previous reading from the input pin
unsigned long lastSent = 0;
unsigned long debounceTime = 0; // the last time the output pin was toggled
unsigned long debounceDelay = 50; // the debounce time; increase if the output flickers
bool switchOnHandler(String value) {
if (value == "true") {
digitalWrite(PIN_RELAY, HIGH);
Homie.setNodeProperty(switchNode, "on", "true", true);
relayState = HIGH;
Serial.println("Switch is on");
} else if (value == "false") {
digitalWrite(PIN_RELAY, LOW);
Homie.setNodeProperty(switchNode, "on", "false", true);
relayState = LOW;
Serial.println("Switch is off");
} else {
return false;
}
return true;
}
void setupHandler() {
// publish current relayState when online
Homie.setNodeProperty(switchNode, "on", (relayState == HIGH) ? "true" : "false", true);
// Start up the library
sensors.begin();
}
void loopHandler() {
if (millis() >= (lastSent + (INTERVAL * 1000UL)) || lastSent == 0) {
// call sensors.requestTemperatures() to issue a global temperature
// request to all devices on the bus
sensors.requestTemperatures(); // Send the command to get temperatures
// After we got the temperatures, we can print them here.
// We use the function ByIndex, and as an example get the temperature from the first sensor only.
float temperature = sensors.getTempCByIndex(0);
Serial.print("Temperature: "); Serial.print(temperature); Serial.println(" °C");
if (Homie.setNodeProperty(temperatureNode, "degrees", String(temperature), true)) {
lastSent = millis();
} else {
Serial.println("Temperature sending failed");
}
}
}
void setup() {
pinMode(PIN_RELAY, OUTPUT);
digitalWrite(PIN_RELAY, relayState);
Homie.setFirmware(FW_NAME, FW_VERSION);
Homie.setLedPin(PIN_LED, LOW);
Homie.setResetTrigger(PIN_BUTTON, LOW, 5000);
Homie.registerNode(switchNode);
Homie.registerNode(temperatureNode);
switchNode.subscribe("on", switchOnHandler);
Homie.setSetupFunction(setupHandler);
Homie.setLoopFunction(loopHandler);
Homie.setup();
}
void loop() {
int reading = digitalRead(PIN_BUTTON);
if (reading != lastButtonState) {
// start timer for the first time
if (debounceTime == 0) {
debounceTime = millis();
}
if(reading == LOW) {
Serial.println("Button push");
// restart timer
debounceTime = millis();
} else {
Serial.println("Button release");
// let a unicorn pass
if ((millis() - debounceTime) > debounceDelay) {
// invert relayState
relayState = !relayState;
if (Homie.isReadyToOperate()) {
// normal mode and network connection up
switchOnHandler((relayState == HIGH) ? "true" : "false");
} else {
// not in normal mode or network connection down
digitalWrite(PIN_RELAY, relayState);
}
}
}
}
lastButtonState = reading;
Homie.loop();
}
|
// API_03_WinMenu.cpp : 애플리케이션에 대한 진입점을 정의합니다.
//
#define _CRT_SECURE_NO_WARNINGS
#include "framework.h"
#include "API_03_WinMenu.h"
#include <commdlg.h>
#include <stdio.h>
#define MAX_LOADSTRING 100
// 전역 변수:
HINSTANCE hInst; // 현재 인스턴스입니다.
WCHAR szTitle[MAX_LOADSTRING]; // 제목 표시줄 텍스트입니다.
WCHAR szWindowClass[MAX_LOADSTRING]; // 기본 창 클래스 이름입니다.
// 이 코드 모듈에 포함된 함수의 선언을 전달합니다:
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// TODO: 여기에 코드를 입력합니다.
// 전역 문자열을 초기화합니다.
LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadStringW(hInstance, IDC_API03WINMENU, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
// 애플리케이션 초기화를 수행합니다:
if (!InitInstance (hInstance, nCmdShow))
{
return FALSE;
}
HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDR_ACCELERATOR_MY));
MSG msg;
// 기본 메시지 루프입니다:
while (GetMessage(&msg, nullptr, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int) msg.wParam;
}
//
// 함수: `gisterClass()
//
// 용도: 창 클래스를 등록합니다.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEXW wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_API03WINMENU));
wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = MAKEINTRESOURCEW(IDR_MENU_MYMENU);
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
return RegisterClassExW(&wcex);
}
//
// 함수: InitInstance(HINSTANCE, int)
//
// 용도: 인스턴스 핸들을 저장하고 주 창을 만듭니다.
//
// 주석:
//
// 이 함수를 통해 인스턴스 핸들을 전역 변수에 저장하고
// 주 프로그램 창을 만든 다음 표시합니다.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
hInst = hInstance; // 인스턴스 핸들을 전역 변수에 저장합니다.
HWND hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, nullptr);
if (!hWnd)
{
return FALSE;
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
//
// 함수: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// 용도: 주 창의 메시지를 처리합니다.
//
// WM_COMMAND - 애플리케이션 메뉴를 처리합니다.
// WM_PAINT - 주 창을 그립니다.
// WM_DESTROY - 종료 메시지를 게시하고 반환합니다.
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
OPENFILENAME OFN;
TCHAR filter[] = _T("텍스트파일\0*.txt;*.doc\0모든 형식(*.*)\0*.*\0");
TCHAR str[100] = _T(""), lpstrFile[100] = _T("");
static TCHAR text[1024] = _T("");
static FILE* fout;
switch (message)
{
case WM_CREATE :
fout =NULL;
break;
case WM_COMMAND:
{
int wmId = LOWORD(wParam);
int mbId = 0;
// 메뉴 선택을 구문 분석합니다:
switch (wmId)
{
case IDM_FILELOAD :
memset(&OFN, 0, sizeof(OPENFILENAME)); // OFN의 메모리를 초기화
OFN.lStructSize = sizeof(OPENFILENAME); // OFN의 크기 변수에 크기값을 저장
OFN.hwndOwner = hWnd; // 대화상자를 사용하는 윈도우의 핸들
OFN.lpstrFilter = filter; // 대화상자에 출력할 필터를 저장
OFN.lpstrFile = lpstrFile; // 선택된 파일의 이름이 저장될 변수를 지정
OFN.nMaxFile = 100; // 경로 길이의 최대값 지정
OFN.lpstrInitialDir = _T(".."); // 대화상자가 열렸을때 가장 먼저 띄워질 폴더를 현재폴더 (./) 로 설정
if (GetOpenFileName(&OFN) != 0) {
_stprintf_s(str, _T("%s 파일을 열겠습니까?"), OFN.lpstrFile);
if (MessageBox(hWnd, str, _T("열기"), MB_OKCANCEL) == IDOK) {
#ifdef _UNICODE
_tfopen_s(&fout, OFN.lpstrFile, _T("r, ccs = UNICODE"));
#else
_tfopen_s(&fout, str, _T("r"));
#endif
_fgetts(text, 1024, fout);
fclose(fout);
InvalidateRgn(hWnd, NULL, TRUE);
}
}
break;
case IDM_FILENEW :
mbId = MessageBox(hWnd, _T("저장은 하시고 끄는겁니까? "), _T("알림창"), MB_ICONQUESTION|MB_YESNO );
if (mbId == IDYES) {
}
else if (mbId == IDNO) {
while (
MessageBox(hWnd, _T("왜죠 ? "), _T("장난"), MB_ICONERROR | MB_OKCANCEL) != IDCANCEL);
}
break;
case IDM_FILEEXIT:
DestroyWindow(hWnd);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
}
break;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
// TODO: 여기에 hdc를 사용하는 그리기 코드를 추가합니다...
if (fout != NULL) {
TextOut(hdc, 0, 0, text, _tcslen(text));
}
EndPaint(hWnd, &ps);
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
// 정보 대화 상자의 메시지 처리기입니다.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
|
#pragma once
namespace Hourglass
{
// A wrapper class for hardware vertex and index buffers
class RenderBuffer
{
protected:
ComPtr<ID3D11Buffer> m_VertexBuffer;
ComPtr<ID3D11Buffer> m_IndexBuffer;
ID3D11InputLayout* m_InputLayout;
UINT m_Stride;
UINT m_VertexCount;
UINT m_IndexCount;
uint16_t m_PrimitiveTopology;
public:
RenderBuffer();
// Get vertex count in this render buffer
UINT GetVertexCount() const { return m_VertexCount; }
// Get index count in this render buffer
UINT GetIndexCount() const { return m_IndexCount; }
// Check if vertex buffer has been initialized
bool HasVertexBuffer() const { return m_VertexBuffer != nullptr; }
// Check if index buffer has been initialized
bool HasIndexBuffer() const { return m_IndexBuffer != nullptr; }
void CreateVertexBuffer(void* data, UINT vertexTypeSize, UINT vertexCount, D3D11_PRIMITIVE_TOPOLOGY topology, ID3D11InputLayout* inputLayout, bool dynamic = false, const char* debugResourceName = nullptr);
void CreateIndexBuffer(void* data, UINT indexTypeSize, UINT indexCount, bool dynamic = false, const char* debugResourceName = nullptr);
// Update vertex buffer content
// Note: To update vertex buffer, it must be created as dynamic buffer to avoid performance issue
void UpdateDynamicVertexBuffer(void* data, UINT vertexTypeSize, UINT vertexCount);
void Draw();
void DrawIndexed(UINT IndexCount, UINT StartIndexLocation, INT BaseVertexLocation);
void DrawInstanced(int instanceCount);
// Release both buffers
void Reset();
};
}
|
#pragma once
#include "atlas/tools/Tools.hpp"
#include "atlas/utils/Geometry.hpp"
#include "atlas/gl/VertexArrayObject.hpp"
#include "atlas/gl/Buffer.hpp"
#include <vector>
#include <stack>
namespace assignment3
{
class TurtleValue : public atlas::utils::Geometry
{
using Point = atlas::math::Point;
public:
TurtleValue(Point position, float angle) : _position(position), _angle(angle) {};
// The copy constructor.
TurtleValue(const TurtleValue& v)
{
_position = v._position;
_angle = v._angle;
};
// The move constructor
TurtleValue(TurtleValue&& v)
{
_position = v._position;
_angle = v._angle;
};
// Destroy a vector.
~TurtleValue() {};
// The copy assignment operator.
TurtleValue& operator=(const TurtleValue v)
{
if (this != &v)
{
_position = v._position;
_angle = v._angle;
}
return *this;
};
const Point& position() const { return _position; };
Point& position() { return _position; };
const float& angle() const { return _angle; };
float& angle() { return _angle; };
private:
Point _position;
float _angle;
};
}
|
#include <iostream>
#include <fstream>
#include <cmath>
#include <iomanip>
#include "finite_diffrence_methods/method/regular/explicit/EuroExplicitMethod.hpp"
#include "options/OptionPut.hpp"
#include "finite_diffrence_methods/method/regular/implicit/EuroImplicitMethod.hpp"
#include "finite_diffrence_methods/method/regular/crank_nicolson/EuroCNMethod.hpp"
using namespace std;
template<typename CharT>
class DecimalSeparator : public std::numpunct<CharT>
{
public:
DecimalSeparator(CharT Separator)
: m_Separator(Separator)
{}
protected:
CharT do_decimal_point()const
{
return m_Separator;
}
private:
CharT m_Separator;
};
int main() {
double i_s(50.), i_r(0.1), i_t(0.4167), i_sigma(0.4), i_e(50.);
double xl = 0.0;
double xu = 2 * i_s;
Option<double> *option = new OptionPut<double>(i_t, i_s, i_r, i_sigma, i_e);
ofstream file("tescikcr.txt", ios_base::trunc);
file.imbue(std::locale(std::cout.getloc(), new DecimalSeparator<char>(',')));
file << ";";
for (int m = 20; m <= 40; m++) {
file << m << ";";
}
file << endl;
for (int n = 11; n <= 40; n++) {
file << n << ";";
for (int m = 20; m <= 40; m++) {
auto a = EuroCNMethod<double>(option, xl, xu, n, m);
a.solve();
file << fixed << setprecision(5) << a.average_approximation() << ";";
}
file << endl;
}
file.close();
delete option;
}
|
//
// imcommontests.cpp
// AutoCaller
//
// Created by Micheal Chen on 2017/7/18.
//
//
#include "imcommontests.hpp"
IMCommonTests::IMCommonTests()
{
ADD_TEST_CASE(UserCommonTest);
ADD_TEST_CASE(MessageCommonTest);
ADD_TEST_CASE(VoiceCommonTest);
}
void UserCommonTest::onEnter()
{
TestCase::onEnter();
//TestCore::createTestCoreInstance()->commonTestSuit()->case_user_common();
}
void MessageCommonTest::onEnter()
{
TestCase::onEnter();
//TestCore::createTestCoreInstance()->commonTestSuit()->case_msg_common();
}
void VoiceCommonTest::onEnter()
{
TestCase::onEnter();
//TestCore::createTestCoreInstance()->commonTestSuit()->case_audio_common();
}
|
#include <iostream>
#include <cstring>
#include <vector>
#include <stack>
const int MAX = 10000;
int n, m, ID[MAX * 2 + 1], ID_cnt, group[MAX * 2 + 1];
bool finish[MAX * 2 + 1];
std::vector<int> link[MAX * 2 + 1];
std::stack<int> stk;
std::vector<std::vector<int>> SCC;
void link_push(int xi, int xj)
{
if(xi < 0)
{
xi = -xi + n;
}
if(xj < 0)
{
xj = -xj + n;
}
link[xi].push_back(xj);
}
int Make_SCC(int idx)
{
stk.push(idx);
ID[idx] = ++ID_cnt;
int parent = ID[idx];
for(int next : link[idx])
{
if(ID[next] == 0)
{
parent = std::min(parent, Make_SCC(next));
}
else if(!finish[next])
{
parent = std::min(parent, ID[next]);
}
}
if(parent == ID[idx])
{
std::vector<int> scc;
int grp = SCC.size();
while(!stk.empty())
{
int top = stk.top();
stk.pop();
group[top] = grp;
scc.push_back(top);
finish[top] = 1;
if(top == idx)
{
break;
}
}
SCC.push_back(scc);
}
return parent;
}
bool check()
{
for(int i = 1; i <= n; i++)
{
if(group[i] == group[i + n])
{
return 1;
}
}
return 0;
}
int main()
{
std::cin.sync_with_stdio(false);
std::cin.tie(NULL);
std::cin >> n >> m;
for(int i = 0; i < m; i++)
{
int xi, xj;
std::cin >> xi >> xj;
link_push(-xi, xj);
link_push(-xj, xi);
}
for(int i = 1; i <= MAX * 2; i++)
{
if(ID[i] == 0)
{
Make_SCC(i);
}
}
if(check())
{
std::cout << "0\n";
}
else
{
std::cout << "1\n";
}
return 0;
}
|
//*************************************************************************************************************
//
// レンダラー処理[renderer.cpp]
// Author : Sekine Ikuto
//
//*************************************************************************************************************
//-------------------------------------------------------------------------------------------------------------
// インクルードファイル
//-------------------------------------------------------------------------------------------------------------
#include "renderer.h"
#include "Scene.h"
#include "fade.h"
#include "manager.h"
#include "DebugProc.h"
#include "camera.h"
//-------------------------------------------------------------------------------------------------------------
// 静的メンバ変数の初期化
//-------------------------------------------------------------------------------------------------------------
CFade *CRenderer::m_pFade = nullptr; // フェード
//-------------------------------------------------------------------------------------------------------------
// コンストラクタ
//-------------------------------------------------------------------------------------------------------------
CRenderer::CRenderer()
{
}
//-------------------------------------------------------------------------------------------------------------
// デストラクタ
//-------------------------------------------------------------------------------------------------------------
CRenderer::~CRenderer()
{
}
//-------------------------------------------------------------------------------------------------------------
// 初期化処理
//-------------------------------------------------------------------------------------------------------------
HRESULT CRenderer::Init(HWND hWnd, BOOL bWindow)
{
// 変数宣言
D3DDISPLAYMODE d3ddm; // ディスプレイモード
D3DPRESENT_PARAMETERS d3dpp; // プレゼンテーションパラメータ
// Direct3Dオブジェクトの生成
m_pD3D = Direct3DCreate9(D3D_SDK_VERSION);
if (m_pD3D == NULL) {
return E_FAIL;
}
// 現在のディスプレイモードを取得
if (FAILED(m_pD3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &d3ddm)))
{
return E_FAIL;
}
// デバイスのプレゼンテーションパラメータの設定
ZeroMemory(&d3dpp, sizeof(d3dpp)); // ワークをゼロクリア
d3dpp.BackBufferWidth = SCREEN_WIDTH; // ゲーム画面サイズ(幅)
d3dpp.BackBufferHeight = SCREEN_HEIGHT; // ゲーム画面サイズ(高さ)
d3dpp.BackBufferFormat = d3ddm.Format; // バックバッファの形式
d3dpp.BackBufferCount = 1; // バックバッファの数
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; // ダブルバッファの切り替え(映像信号に同期)
d3dpp.EnableAutoDepthStencil = TRUE; // デプスバッファ(Zバッファ)とステンシルバッファを作成
d3dpp.AutoDepthStencilFormat = D3DFMT_D16; // デプスバッファとして16bitを使う
d3dpp.Windowed = bWindow; // ウィンドウモード
d3dpp.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT; // リフレッシュレート(現在の速度に合わせる)
d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT; // インターバル(VSyncを待って描画)
//d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; // クライアント領域を直ちに更新する
// ステンシル用設定
// 深度バッファの有無
// 深度バッファのフォーマット
d3dpp.AutoDepthStencilFormat = D3DFMT_D24S8;
// Direct3Dデバイスの生成
// [デバイス作成制御]<描画>と<頂点処理>をハードウェアで行なう
if (FAILED(m_pD3D->CreateDevice(D3DADAPTER_DEFAULT, // ディスプレイアダプタ
D3DDEVTYPE_HAL, // デバイスタイプ
hWnd, // フォーカスするウインドウへのハンドル
D3DCREATE_HARDWARE_VERTEXPROCESSING, // デバイス作成制御の組み合わせ
&d3dpp, // デバイスのプレゼンテーションパラメータ
&m_pD3DDevice))) // デバイスインターフェースへのポインタ
{
// 上記の設定が失敗したら
// [デバイス作成制御]<描画>をハードウェアで行い、<頂点処理>はCPUで行なう
if (FAILED(m_pD3D->CreateDevice(D3DADAPTER_DEFAULT,
D3DDEVTYPE_HAL,
hWnd,
D3DCREATE_SOFTWARE_VERTEXPROCESSING,
&d3dpp,
&m_pD3DDevice)))
{
// 上記の設定が失敗したら
// [デバイス作成制御]<描画>と<頂点処理>をCPUで行なう
if (FAILED(m_pD3D->CreateDevice(D3DADAPTER_DEFAULT,
D3DDEVTYPE_REF,
hWnd,
D3DCREATE_SOFTWARE_VERTEXPROCESSING,
&d3dpp,
&m_pD3DDevice)))
{
// 初期化失敗
return E_FAIL;
}
}
}
// レンダーステートパラメータの設定
m_pD3DDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW); // 裏面(左回り)をカリングする
m_pD3DDevice->SetRenderState(D3DRS_ZENABLE, TRUE); // Zバッファを使用
m_pD3DDevice->SetRenderState(D3DRS_LIGHTING, TRUE); // ライティングモード有効
m_pD3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); // αブレンドを行う
m_pD3DDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); // αソースカラーの指定
m_pD3DDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); // αデスティネーションカラーの指定
// サンプラーステートの設定
m_pD3DDevice->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_WRAP);
m_pD3DDevice->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_WRAP);
m_pD3DDevice->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
m_pD3DDevice->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
// テクスチャステージステートの設定
m_pD3DDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE); // アルファブレンディング処理
m_pD3DDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE); // 最初のアルファ引数
m_pD3DDevice->SetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_CURRENT); // 2番目のアルファ引数
// ステンシルバッファの設定
m_pD3DDevice->SetRenderState(D3DRS_ALPHATESTENABLE, TRUE);
m_pD3DDevice->SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_GREATEREQUAL);
m_pD3DDevice->SetRenderState(D3DRS_ALPHAREF, 0x01);
CFade::Load();
m_pFade = CFade::Create();
m_pFade->Init(CManager::MODE_TITLE);
return S_OK;
}
//-------------------------------------------------------------------------------------------------------------
// 終了処理
//-------------------------------------------------------------------------------------------------------------
void CRenderer::Uninit(void)
{
CScene::ReleaseAll();
CFade::Unload();
if (m_pFade != nullptr)
{
m_pFade->Uninit();
delete m_pFade;
m_pFade = nullptr;
}
if (m_pD3DDevice != NULL)
{// Direct3Dデバイスの開放
m_pD3DDevice->Release();
m_pD3DDevice = NULL;
}
if (m_pD3D != NULL)
{
// Direct3Dオブジェクトの開放
m_pD3D->Release();
m_pD3D = NULL;
}
}
//-------------------------------------------------------------------------------------------------------------
// 更新処理
//-------------------------------------------------------------------------------------------------------------
void CRenderer::UpDate(void)
{
#ifdef _DEBUG
CDebugProc::print("FPS:%d\n", m_nCountFPS);
int nNumAll = CScene::GetNumAll();
CDebugProc::print("NumAll:%d\n", nNumAll);
#endif // DEBUG
m_pFade->Update();
CScene::UpdataAll();
}
//-------------------------------------------------------------------------------------------------------------
// 描画処理
//-------------------------------------------------------------------------------------------------------------
void CRenderer::Draw(void)
{
// バックバッファ&Zバッファのクリア
m_pD3DDevice->Clear(0, NULL, (D3DCLEAR_TARGET | D3DCLEAR_STENCIL | D3DCLEAR_ZBUFFER)
, D3DCOLOR_RGBA(0, 0, 0, 0), 1.0f, 0);
// DirectX3Dによる描画開始
if (SUCCEEDED(m_pD3DDevice->BeginScene()))
{
CManager::GetCamera().Set();
CScene::DrawAll();
m_pFade->Draw();
#ifdef _DEBUG
CDebugProc::Draw();
#endif // DEBUG
// Direct3Dによる描画終了
m_pD3DDevice->EndScene();
}
// バッフバッファとフロントバッファの入れ替え
m_pD3DDevice->Present(NULL, NULL, NULL, NULL);
}
//-------------------------------------------------------------------------------------------------------------
// ステンシルマスク用レンダラーステートのセットアップ
//-------------------------------------------------------------------------------------------------------------
void CRenderer::SetStencilMaskRenderState(LPDIRECT3DDEVICE9 pDevice, unsigned char ref, D3DCMPFUNC cmp_func)
{
// ステンシルバッファ設定 => 有効
pDevice->SetRenderState(D3DRS_STENCILENABLE, TRUE);
// ステンシルバッファへ描き込む参照値設定
pDevice->SetRenderState(D3DRS_STENCILREF, ref);
// マスク設定 => 0xff(全て真)
pDevice->SetRenderState(D3DRS_STENCILMASK, 0xff);
// ステンシルテスト比較設定 => 必ず成功する
pDevice->SetRenderState(D3DRS_STENCILFUNC, cmp_func);
// ステンシルテストのテスト設定
pDevice->SetRenderState(D3DRS_STENCILFAIL, D3DSTENCILOP_KEEP);
pDevice->SetRenderState(D3DRS_STENCILZFAIL, D3DSTENCILOP_REPLACE);
pDevice->SetRenderState(D3DRS_STENCILPASS, D3DSTENCILOP_KEEP);
// Zバッファ設定 => 有効
pDevice->SetRenderState(D3DRS_ZENABLE, TRUE);
// ZBUFFER比較設定変更 => 必ず失敗する
pDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_NEVER);
}
//-------------------------------------------------------------------------------------------------------------
// ステンシル用レンダラーステートのセットアップ
//-------------------------------------------------------------------------------------------------------------
void CRenderer::SetStencilRenderState(LPDIRECT3DDEVICE9 pDevice, unsigned char ref, D3DCMPFUNC cmp_func)
{
// Zバッファ設定 => 有効
pDevice->SetRenderState(D3DRS_ZENABLE, TRUE);
// ZBUFFER比較設定変更 => (参照値 <= バッファ値)
pDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_LESSEQUAL);
// ステンシルバッファ => 有効
pDevice->SetRenderState(D3DRS_STENCILENABLE, TRUE);
// ステンシルバッファと比較する参照値設定 => ref
pDevice->SetRenderState(D3DRS_STENCILREF, ref);
// ステンシルバッファの値に対してのマスク設定 => 0xff(全て真)
pDevice->SetRenderState(D3DRS_STENCILMASK, 0xff);
// ステンシルテストの比較方法設定 =>
// この描画での参照値 >= ステンシルバッファの参照値なら合格
pDevice->SetRenderState(D3DRS_STENCILFUNC, cmp_func);
// ステンシルテストの結果に対しての反映設定
pDevice->SetRenderState(D3DRS_STENCILPASS, D3DSTENCILOP_REPLACE);
pDevice->SetRenderState(D3DRS_STENCILFAIL, D3DSTENCILOP_KEEP);
pDevice->SetRenderState(D3DRS_STENCILZFAIL, D3DSTENCILOP_KEEP);
}
//-------------------------------------------------------------------------------------------------------------
// ステンシル用レンダラーステートの設定を外す
//-------------------------------------------------------------------------------------------------------------
void CRenderer::UnsetStencilRenderState(LPDIRECT3DDEVICE9 pDevice)
{
// ステンシルバッファ => 無効
pDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-1999 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#ifndef DOM_LSEVENTS
#define DOM_LSEVENTS
#ifdef DOM3_LOAD
#include "modules/dom/src/domevents/domevent.h"
class DOM_LSParser;
class DOM_Document;
class ES_Object;
class DOM_LSLoadEvent
: public DOM_Event
{
public:
static OP_STATUS Make(DOM_LSLoadEvent *&event, DOM_LSParser *target, DOM_Document *document, ES_Object *input);
virtual ES_GetState GetName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime);
};
class DOM_LSProgressEvent
: public DOM_Event
{
protected:
DOM_LSProgressEvent(unsigned position, unsigned total);
unsigned position, total;
public:
static OP_STATUS Make(DOM_LSProgressEvent *&event, DOM_LSParser *target, ES_Object *input, unsigned position, unsigned total);
virtual ES_GetState GetName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime);
};
#endif // DOM3_LOAD
#endif // DOM_LSEVENTS
|
#pragma once
// Taken largely from Robert Penners easing equations
#define EASE_PI 3.1415926535897932384626433832795f
#define EASE_TWOPI 6.283185307179586476925287f
#define EASE_PI_DIV2 1.570796326794896619231322f
#include <cmath>
#define EASE_MODE_FIRST EASE_LINEAR
#define EASE_MODE_LAST EASE_INOUT_BOUNCE
#define EASE_MODE_AMOUNT ( EASE_MODE_LAST - EASE_MODE_FIRST + 1)
class EasingEquations
{
public:
enum EaseType
{
EASE_LINEAR = 0,
EASE_IN_QUAD,
EASE_OUT_QUAD,
EASE_INOUT_QUAD,
EASE_IN_CUBIC,
EASE_OUT_CUBIC,
EASE_INOUT_CUBIC,
EASE_IN_QUART,
EASE_OUT_QUART,
EASE_INOUT_QUART,
EASE_IN_QUINT,
EASE_OUT_QUINT,
EASE_INOUT_QUINT,
EASE_IN_SINE,
EASE_OUT_SINE,
EASE_INOUT_SINE,
EASE_IN_EXPO,
EASE_OUT_EXPO,
EASE_INOUT_EXPO,
EASE_IN_CIRCULAR,
EASE_OUT_CIRCULAR,
EASE_INOUT_CIRCULAR,
EASE_IN_ELASTIC,
EASE_OUT_ELASTIC,
EASE_INOUT_ELASTIC,
EASE_IN_BACK,
EASE_OUT_BACK,
EASE_INOUT_BACK,
EASE_IN_BOUNCE,
EASE_OUT_BOUNCE,
EASE_INOUT_BOUNCE,
EASE_EQUATION_AMOUNT
};
static float getValueAtFrac( float _startVal, float _targetVal, float _frac );
static float ease( float t, EaseType easeType = EASE_INOUT_QUAD );
static float linearTween( float t, float b = 0.0f, float c = 1.0f, float d = 1.0f );
static float easeInQuad( float t, float b = 0.0f, float c = 1.0f, float d = 1.0f );
static float easeOutQuad( float t, float b = 0.0f, float c = 1.0f, float d = 1.0f );
static float easeInOutQuad( float t, float b = 0.0f, float c = 1.0f, float d = 1.0f );
static float easeInCubic( float t, float b = 0.0f, float c = 1.0f, float d = 1.0f );
static float easeOutCubic( float t, float b = 0.0f, float c = 1.0f, float d = 1.0f );
static float easeInOutCubic( float t, float b = 0.0f, float c = 1.0f, float d = 1.0f );
static float easeInQuart( float t, float b = 0.0f, float c = 1.0f, float d = 1.0f );
static float easeOutQuart( float t, float b = 0.0f, float c = 1.0f, float d = 1.0f );
static float easeInOutQuart( float t, float b = 0.0f, float c = 1.0f, float d = 1.0f );
static float easeInQuint( float t, float b = 0.0f, float c = 1.0f, float d = 1.0f );
static float easeOutQuint( float t, float b = 0.0f, float c = 1.0f, float d = 1.0f );
static float easeInOutQuint( float t, float b = 0.0f, float c = 1.0f, float d = 1.0f );
static float easeInSine( float t, float b = 0.0f, float c = 1.0f, float d = 1.0f );
static float easeOutSine( float t, float b = 0.0f, float c = 1.0f, float d = 1.0f );
static float easeInOutSine( float t, float b = 0.0f, float c = 1.0f, float d = 1.0f );
static float easeInExpo( float t, float b = 0.0f, float c = 1.0f, float d = 1.0f );
static float easeOutExpo( float t, float b = 0.0f, float c = 1.0f, float d = 1.0f );
static float easeInOutExpo( float t, float b = 0.0f, float c = 1.0f, float d = 1.0f );
static float easeInCircular( float t, float b = 0.0f, float c = 1.0f, float d = 1.0f );
static float easeOutCircular( float t, float b = 0.0f, float c = 1.0f, float d = 1.0f );
static float easeInOutCircular( float t, float b = 0.0f, float c = 1.0f, float d = 1.0f );
/////////// ELASTIC EASING: exponentially decaying sine wave //////////////
// t: current time, b: beginning value, c: change in value, d: duration, a: amplitude (optional), p: period (optional)
// t and d can be in frames or seconds/milliseconds
static float easeInElastic( float t, float b, float c, float d = 1.0f, float a = 1.0f, float p = 0.3f );
static float easeOutElastic( float t, float b, float c, float d = 1.0f, float a = 1.0f, float p = 0.3f );
static float easeInOutElastic( float t, float b, float c, float d = 1.0f, float a = 1.0f, float p = 0.45f );
/////////// BACK EASING: overshooting cubic easing: (s+1)*t^3 - s*t^2 //////////////
// back easing in - backtracking slightly, then reversing direction and moving to target
// t: current time, b: beginning value, c: change in value, d: duration, s: overshoot amount (optional)
// t and d can be in frames or seconds/milliseconds
// s controls the amount of overshoot: higher s means greater overshoot
// s has a default value of 1.70158, which produces an overshoot of 10 percent
// s==0 produces cubic easing with no overshoot
static float easeInBack( float t, float b, float c, float d = 1.0f, float s = 1.70158f );
static float easeOutBack( float t, float b, float c, float d = 1.0f, float s = 1.70158f );
static float easeInOutBack( float t, float b, float c, float d = 1.0f, float s = 1.70158f );
/////////// BOUNCE EASING: exponentially decaying parabolic bounce //////////////
// bounce easing in
// t: current time, b: beginning value, c: change in position, d: duration
static float easeInBounce( float t, float b, float c, float d = 1.0f );
static float easeOutBounce( float t, float b, float c, float d = 1.0f );
static float easeInOutBounce( float t, float b, float c, float d = 1.0f );
static EaseType nextEaseType( EaseType _type );
static EaseType prevEaseType( EaseType _type );
};
|
#include "Player.h"
//-------------------------------
//コンストラクタ・デストラクタ
Player::Player( Sounder* sounder ){
_position = VGet( 0, 0, ( float )FIRST_DISTANCE );
_direction = VGet( 0, 0, 1 );
for ( int i = 0; i < PRE_POS_MAX_INDEX; i++ ) {
_prePos[ i ] = VGet( 0, 0, 0 );
}
_prePos[ 0 ] = _position; //最初の座標を_prePos[ 0 ]に代入
_answerCount = 0;
_notAnswerCount = 0;
_movedCount = 0;
_freezedCount = 0;
_sounder = sounder;
_sounder->SetPlayerPosAndDir( _position, _direction );
}
Player::~Player( ){
}
//-------------------------------
//-------------------------------
//---------------------------------------------------
//--ゲッター
VECTOR Player::GetPosition( ) {
return _position;
}
VECTOR* Player::GetPrePos( ) {
return _prePos;
}
int Player::GetAnswerCount( ) {
return _answerCount;
}
int Player::GetNotAnswerCount( ) {
return _notAnswerCount;
}
int Player::GetMovedCount( ) {
return _movedCount;
}
int Player::GetFreezedCount( ) {
return _freezedCount;
}
//---------------------------------------------------
//---------------------------------------------------
//---------------------------------------------------
//--セッター
void Player::SetPrePos( int index, VECTOR position ) {
_prePos[ index ] = position;
}
//---------------------------------------------------
//---------------------------------------------------
//---------------------------------------------------
//--playerが前方(z方向)にpixelピクセル移動する関数
void Player::MoveForwardPixel( int pixel ) {
_position.z += pixel;
_sounder->SetPlayerPosAndDir( _position, _direction );
}
//--playerが左 にpixelピクセル移動する関数
void Player::MoveLeftPixel( int pixel ) {
_position.x -= pixel;
_sounder->SetPlayerPosAndDir( _position, _direction );
}
//--playerが右 にpixelピクセル移動する関数
void Player::MoveRightPixel( int pixel ) {
_position.x += pixel;
_sounder->SetPlayerPosAndDir( _position, _direction );
}
//--playerが前方にescapeCountフレームの間1ピクセル当たりflamePerPixelフレームで移動する関数
void Player::MoveForward( int escapeCount, int flamePerPixel ) {
if ( _movedCount >= escapeCount ) {
StopASIOTOAndLookForward( );
return; //既にescapeCountフレーム動いていたら戻る
}
_movedCount++;
if ( _movedCount == 1 ) {
_direction = VGet( 0, 0, 1 );
SoundASIOTO( );
}
if ( _movedCount % flamePerPixel == 0 ) MoveForwardPixel( 1 );
}
//--playerが左にescapeCountフレームの間1ピクセル当たりflamePerPixelフレームで移動する関数
void Player::MoveLeft( int escapeCount, int flamePerPixel ) {
if ( _movedCount >= escapeCount ) {
StopASIOTOAndLookForward( );
return; //既にescapeCountフレーム動いていたら戻る
}
_movedCount++;
if ( _movedCount == 1 ) {
_direction = VGet( -1, 0, 0 );
SoundASIOTO( );
}
if ( _movedCount % flamePerPixel == 0 ) MoveLeftPixel( 1 );
}
//--playerが右にescapeCountフレームの間1ピクセル当たりflamePerPixelフレームで移動する関数
void Player::MoveRight( int escapeCount, int flamePerPixel ) {
if ( _movedCount >= escapeCount ) {
StopASIOTOAndLookForward( );
return; //既にescapeCountフレーム動いていたら戻る
}
_movedCount++;
if ( _movedCount == 1 ) {
_direction = VGet( 1, 0, 0 );
SoundASIOTO( );
}
if ( _movedCount % flamePerPixel == 0 ) MoveRightPixel( 1 );
}
//--freezeCountフレームの間プレイヤーが硬直する関数
void Player::Freeze( int freezeCount ) {
if ( _freezedCount >= freezeCount ) return; //既にfreezeCountフレーム硬直していたら戻る
_freezedCount++;
}
//--足音を鳴らす関数(ループ再生)
void Player::SoundASIOTO( ) {
int soundHandle = _sounder->GetSoundDataManager( ).GetSoundHandle( SoundData::PLAYER_ASIOTO );
_sounder->ChangeVolumeSoundMem( 100, soundHandle );
_sounder->PlaySoundMem( soundHandle, DX_PLAYTYPE_LOOP, TRUE );
}
//--足音を止める関数
void Player::StopASIOTO( ) {
int soundHandle = _sounder->GetSoundDataManager( ).GetSoundHandle( SoundData::PLAYER_ASIOTO );
if ( _sounder->CheckSoundMem( soundHandle ) ) {
_sounder->StopSoundMem( soundHandle );
}
}
//--足音を止め、正面を向く関数
void Player::StopASIOTOAndLookForward( ) {
StopASIOTO( );
_direction = VGet( 0, 0, 1 );
_sounder->SetPlayerPosAndDir( _position, _direction );
}
//--ドアをガチャガチャする関数
void Player::KnockDoor( ) {
int soundHandle = _sounder->GetSoundDataManager( ).GetSoundHandle( SoundData::DOOR_GATYA );
_sounder->ChangeVolumeSoundMem( 100, soundHandle );
_sounder->PlaySoundMem( soundHandle, DX_PLAYTYPE_NORMAL , TRUE);
}
//--ドアを開ける関数
void Player::OpenDoor( ) {
int soundHandle = _sounder->GetSoundDataManager( ).GetSoundHandle( SoundData::DOOR );
_sounder->ChangeVolumeSoundMem( 100, soundHandle );
_sounder->PlaySoundMem( soundHandle, DX_PLAYTYPE_NORMAL, TRUE );
}
//--_answerCountを一つ増やす関数
void Player::PlusAnswerCount( ) {
_answerCount++;
}
//--_notAnswerCountを一つ増やす関数
void Player::PlusNotAnswerCount( ) {
_notAnswerCount++;
}
//--_answerCountを一つ増やす関数
void Player::ResetMovedCount( ) {
_movedCount = 0;
}
//--_notAnswerCountを一つ増やす関数
void Player::ResetFreezedCount( ) {
_freezedCount = 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.