blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 5
146
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
7
| license_type
stringclasses 2
values | repo_name
stringlengths 6
79
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 4
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.07k
426M
⌀ | star_events_count
int64 0
27
| fork_events_count
int64 0
12
| gha_license_id
stringclasses 3
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 6
values | src_encoding
stringclasses 26
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 1
class | length_bytes
int64 20
6.28M
| extension
stringclasses 20
values | content
stringlengths 20
6.28M
| authors
listlengths 1
16
| author_lines
listlengths 1
16
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
589adfc0c0726428d0c890062ea3a398fd022f6e | 6a1a184ceb7be1f73c490fcbaf8fba7a64cab1ff | /Source/TestFluidic/TestScene.h | 084336f9c634392cf09d11d04e93202f5d73f1e4 | [
"MIT"
]
| permissive | alexsaen/fluidic | c8aa913ce03e8d3d9bc8091a31aa96a7d1e5b4ad | bf7eb0f3e9ca4e15f53623020c7f0313315f4e49 | refs/heads/master | 2020-12-24T15:14:17.261742 | 2010-04-06T13:10:54 | 2010-04-06T13:10:54 | 32,979,664 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,617 | h | /*
Copyright (c) 2010 Steven Leigh
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.
*/
#pragma once
#include <iostream>
#include <fstream>
#include "Fluidic.h"
#include "TestObject.h"
namespace TestFluidic
{
#ifdef _DEBUG
#define CG_PROGRAM_DIR "../../../../Resources/"
#else
// FIXME: Either parametize this, or set up a deployment area so the dir structure isn't crazy
#define CG_PROGRAM_DIR "../Resources/"
#endif
//Mouse Button state
enum MouseButton
{
MB_NONE = 0,
MB_LEFT = 1,
MB_RIGHT = 2,
MB_MIDDLE = 4
};
struct InputState
{
int buttons;
int dx; //change in x
int dy; //change in y
int x;
int y;
int modifiers;
InputState()
{
buttons = MB_NONE;
modifiers = 0;
dx = dy = x = y = 0;
}
};
class TestScene
{
public:
TestScene();
virtual ~TestScene();
void Tick();
virtual void Interact(){}
virtual void Update(float time);
virtual void Display(){};
virtual void HandleMouseMove(int x, int y);
virtual void HandleMouseButton(int button,int state,int x,int y);
virtual void HandleKeyboard(unsigned char key, bool down);
virtual void HandleKeyboardSpecial(int key);
virtual void Resize(int width, int height);
protected:
InputState mouseState;
Fluidic::Fluid *fluid;
Fluidic::FluidOptions options;
void InitFluid();
int fluidTextCallList;
float fluidTextR, fluidTextG, fluidTextB;
void DrawFluidText();
void BuildFluidTextCallList();
int solveCount;
int startTime;
int previousTime;
int currFrame;
};
} | [
"xwipeoutx@6c3c8482-2914-11df-ad47-1d73243ccc9f"
]
| [
[
[
1,
102
]
]
]
|
b18861b5854af56e76896a52ab75dfdede681a0e | b5ad65ebe6a1148716115e1faab31b5f0de1b493 | /src/AranIk/Jacobian.cpp | dff0c2157acdb2320f975c26e841efc808e8f1c0 | []
| no_license | gasbank/aran | 4360e3536185dcc0b364d8de84b34ae3a5f0855c | 01908cd36612379ade220cc09783bc7366c80961 | refs/heads/master | 2021-05-01T01:16:19.815088 | 2011-03-01T05:21:38 | 2011-03-01T05:21:38 | 1,051,010 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,309 | cpp | #include "AranIkPCH.h"
#include "Jacobian.h"
void Arrow(const VectorR3& tail, const VectorR3& head);
///////////////////extern int RestPositionOn;
int RestPositionOn;
///////////////////extern VectorR3 target[];
//VectorR3 target[10];
// Optimal damping values have to be determined in an ad hoc manner (Yuck!)
// const double Jacobian::DefaultDampingLambda = 0.6; // Optimal for the "Y" shape (any lower gives jitter)
const double Jacobian::DefaultDampingLambda = 1.1; // Optimal for the DLS "double Y" shape (any lower gives jitter)
// const double Jacobian::DefaultDampingLambda = 0.7; // Optimal for the DLS "double Y" shape with distance clamping (lower gives jitter)
const double Jacobian::PseudoInverseThresholdFactor = 0.01;
const double Jacobian::MaxAngleJtranspose = 30.0*DegreesToRadians;
const double Jacobian::MaxAnglePseudoinverse = 5.0*DegreesToRadians;
const double Jacobian::MaxAngleDLS = 45.0*DegreesToRadians;
const double Jacobian::MaxAngleSDLS = 45.0*DegreesToRadians;
const double Jacobian::BaseMaxTargetDist = 0.4;
Jacobian::Jacobian(TreePtr tree)
{
Jacobian::m_tree = tree;
m_nEffector = tree->GetNumEffector();
m_nJoint = tree->GetNumJoint();
m_nRow = 3 * m_nEffector;
m_nCol = m_nJoint;
m_Jend.SetSize(m_nRow, m_nCol); // The Jocobian matrix
m_Jend.SetZero();
m_Jtarget.SetSize(m_nRow, m_nCol); // The Jacobian matrix based on target positions
m_Jtarget.SetZero();
SetJendActive();
m_U.SetSize(m_nRow, m_nRow); // The U matrix for SVD calculations
m_w.SetLength(Min(m_nRow, m_nCol));
m_V.SetSize(m_nCol, m_nCol); // The V matrix for SVD calculations
m_dS.SetLength(m_nRow); // (Target positions) - (End effector positions)
m_dTheta.SetLength(m_nCol); // Changes in joint angles
m_dPreTheta.SetLength(m_nCol);
// Used by Jacobian transpose method & DLS & SDLS
m_dT.SetLength(m_nRow); // Linearized change in end effector positions based on dTheta
// Used by the Selectively Damped Least Squares Method
//dT.SetLength(nRow);
m_dSclamp.SetLength(m_nEffector);
m_errorArray.SetLength(m_nEffector);
m_Jnorms.SetSize(m_nEffector, m_nCol); // Holds the norms of the active J matrix
Reset();
}
Jacobian::~Jacobian()
{
}
void Jacobian::Reset()
{
// Used by Damped Least Squares Method
m_DampingLambda = DefaultDampingLambda;
m_DampingLambdaSq = Square(m_DampingLambda);
// DampingLambdaSDLS = 1.5*DefaultDampingLambda;
m_dSclamp.Fill(HUGE_VAL);
}
// Compute the deltaS vector, dS, (the error in end effector positions
// Compute the J and K matrices (the Jacobians)
void Jacobian::ComputeJacobian()
{
// Traverse tree to find all end effectors
VectorR3 temp;
Node* n = m_tree->GetRoot();
while ( n ) {
if ( n->isEndeffector() ) {
int i = n->getEffectorNum();
const VectorR3& targetPos = n->getTarget();
// Compute the delta S value (differences from end effectors to target positions.
temp = targetPos;
temp -= n->getGlobalPosition();
m_dS.SetTriple(i, temp);
// Find all ancestors (they will usually all be joints)
// Set the corresponding entries in the Jacobians J, K.
Node* m = m_tree->GetParent(n);
while ( m ) {
int j = m->getJointNum();
assert ( 0 <=i && i<m_nEffector && 0<=j && j<m_nJoint );
if ( m->isFrozen() ) {
m_Jend.SetTriple(i, j, VectorR3::Zero);
m_Jtarget.SetTriple(i, j, VectorR3::Zero);
}
else {
temp = m->getGlobalPosition(); // joint pos.
temp -= n->getGlobalPosition(); // -(end effector pos. - joint pos.)
temp *= m->getGlobalRotAxis(); // cross product with joint rotation axis
m_Jend.SetTriple(i, j, temp);
temp = m->getGlobalPosition(); // joint pos.
temp -= targetPos; // -(target pos. - joint pos.)
temp *= m->getGlobalRotAxis(); // cross product with joint rotation axis
m_Jtarget.SetTriple(i, j, temp);
}
m = m_tree->GetParent( m );
}
}
n = m_tree->GetSuccessor( n );
}
}
// The delta theta values have been computed in dTheta array
// Apply the delta theta values to the joints
// Nothing is done about joint limits for now.
void Jacobian::UpdateThetas()
{
// Traverse the tree to find all joints
// Update the joint angles
Node* n = m_tree->GetRoot();
while ( n ) {
if ( n->isJoint() ) {
int i = n->getJointNum();
double nextTheta = n->getTheta() + m_dTheta[i];
// Check joint limits
if (n->getMinTheta() < nextTheta && nextTheta < n->getMaxTheta())
{
n->addToTheta( m_dTheta[i] );
}
}
n = m_tree->GetSuccessor( n );
}
// Update the positions and rotation axes of all joints/effectors
m_tree->Compute();
}
void Jacobian::CalcDeltaThetas()
{
switch (m_CurrentUpdateMode) {
case JACOB_Undefined:
ZeroDeltaThetas();
break;
case JACOB_JacobianTranspose:
CalcDeltaThetasTranspose();
break;
case JACOB_PseudoInverse:
CalcDeltaThetasPseudoinverse();
break;
case JACOB_DLS:
CalcDeltaThetasDLS();
break;
case JACOB_SDLS:
CalcDeltaThetasSDLS();
break;
}
}
void Jacobian::ZeroDeltaThetas()
{
m_dTheta.SetZero();
}
// Find the delta theta values using inverse Jacobian method
// Uses a greedy method to decide scaling factor
void Jacobian::CalcDeltaThetasTranspose()
{
const MatrixRmn& J = ActiveJacobian();
J.MultiplyTranspose( m_dS, m_dTheta );
// Scale back the dTheta values greedily
J.Multiply ( m_dTheta, m_dT ); // dT = J * dTheta
double alpha = Dot(m_dS,m_dT) / m_dT.NormSq();
assert ( alpha>0.0 );
// Also scale back to be have max angle change less than MaxAngleJtranspose
double maxChange = m_dTheta.MaxAbs();
double beta = MaxAngleJtranspose/maxChange;
m_dTheta *= Min(alpha, beta);
}
void Jacobian::CalcDeltaThetasPseudoinverse()
{
MatrixRmn& J = const_cast<MatrixRmn&>(ActiveJacobian());
// Compute Singular Value Decomposition
// This an inefficient way to do Pseudoinverse, but it is convenient since we need SVD anyway
J.ComputeSVD( m_U, m_w, m_V );
// Next line for debugging only
assert(J.DebugCheckSVD(m_U, m_w , m_V));
// Calculate response vector dTheta that is the DLS solution.
// Delta target values are the dS values
// We multiply by Moore-Penrose pseudo-inverse of the J matrix
double pseudoInverseThreshold = PseudoInverseThresholdFactor*m_w.MaxAbs();
long diagLength = m_w.GetLength();
double* wPtr = m_w.GetPtr();
m_dTheta.SetZero();
for ( long i=0; i<diagLength; i++ ) {
double dotProdCol = m_U.DotProductColumn( m_dS, i ); // Dot product with i-th column of U
double alpha = *(wPtr++);
if ( fabs(alpha)>pseudoInverseThreshold ) {
alpha = 1.0/alpha;
MatrixRmn::AddArrayScale(m_V.GetNumRows(), m_V.GetColumnPtr(i), 1, m_dTheta.GetPtr(), 1, dotProdCol*alpha );
}
}
// Scale back to not exceed maximum angle changes
double maxChange = m_dTheta.MaxAbs();
if ( maxChange>MaxAnglePseudoinverse ) {
m_dTheta *= MaxAnglePseudoinverse /maxChange;
}
}
void Jacobian::CalcDeltaThetasDLS()
{
const MatrixRmn& J = ActiveJacobian();
MatrixRmn::MultiplyTranspose(J, J, m_U); // U = J * (J^T)
m_U.AddToDiagonal( m_DampingLambdaSq );
// Use the next four lines instead of the succeeding two lines for the DLS method with clamped error vector e.
// CalcdTClampedFromdS();
// VectorRn dTextra(3*nEffector);
// U.Solve( dT, &dTextra );
// J.MultiplyTranspose( dTextra, dTheta );
// Use these two lines for the traditional DLS method
m_U.Solve( m_dS, &m_dT );
J.MultiplyTranspose( m_dT, m_dTheta );
// Scale back to not exceed maximum angle changes
double maxChange = m_dTheta.MaxAbs();
if ( maxChange>MaxAngleDLS ) {
m_dTheta *= MaxAngleDLS/maxChange;
}
}
void Jacobian::CalcDeltaThetasDLSwithSVD()
{
const MatrixRmn& J = ActiveJacobian();
// Compute Singular Value Decomposition
// This an inefficient way to do DLS, but it is convenient since we need SVD anyway
J.ComputeSVD( m_U, m_w, m_V );
// Next line for debugging only
assert(J.DebugCheckSVD(m_U, m_w , m_V));
// Calculate response vector dTheta that is the DLS solution.
// Delta target values are the dS values
// We multiply by DLS inverse of the J matrix
long diagLength = m_w.GetLength();
double* wPtr = m_w.GetPtr();
m_dTheta.SetZero();
for ( long i=0; i<diagLength; i++ ) {
double dotProdCol = m_U.DotProductColumn( m_dS, i ); // Dot product with i-th column of U
double alpha = *(wPtr++);
alpha = alpha/(Square(alpha)+m_DampingLambdaSq);
MatrixRmn::AddArrayScale(m_V.GetNumRows(), m_V.GetColumnPtr(i), 1, m_dTheta.GetPtr(), 1, dotProdCol*alpha );
}
// Scale back to not exceed maximum angle changes
double maxChange = m_dTheta.MaxAbs();
if ( maxChange>MaxAngleDLS ) {
m_dTheta *= MaxAngleDLS/maxChange;
}
}
void Jacobian::CalcDeltaThetasSDLS()
{
const MatrixRmn& J = ActiveJacobian();
// Compute Singular Value Decomposition
J.ComputeSVD( m_U, m_w, m_V );
// Next line for debugging only
assert(J.DebugCheckSVD(m_U, m_w , m_V));
// Calculate response vector dTheta that is the SDLS solution.
// Delta target values are the dS values
int nRows = J.GetNumRows();
int numEndEffectors = m_tree->GetNumEffector(); // Equals the number of rows of J divided by three
int nCols = J.GetNumColumns();
m_dTheta.SetZero();
// Calculate the norms of the 3-vectors in the Jacobian
long i;
const double *jx = J.GetPtr();
double *jnx = m_Jnorms.GetPtr();
for ( i=nCols*numEndEffectors; i>0; i-- ) {
double accumSq = Square(*(jx++));
accumSq += Square(*(jx++));
accumSq += Square(*(jx++));
*(jnx++) = sqrt(accumSq);
}
// Clamp the dS values
CalcdTClampedFromdS();
// Loop over each singular vector
for ( i=0; i<nRows; i++ ) {
double wiInv = m_w[i];
if ( NearZero(wiInv,1.0e-10) ) {
continue;
}
wiInv = 1.0/wiInv;
double N = 0.0; // N is the quasi-1-norm of the i-th column of U
double alpha = 0.0; // alpha is the dot product of dT and the i-th column of U
const double *dTx = m_dT.GetPtr();
const double *ux = m_U.GetColumnPtr(i);
long j;
for ( j=numEndEffectors; j>0; j-- ) {
double tmp;
alpha += (*ux)*(*(dTx++));
tmp = Square( *(ux++) );
alpha += (*ux)*(*(dTx++));
tmp += Square(*(ux++));
alpha += (*ux)*(*(dTx++));
tmp += Square(*(ux++));
N += sqrt(tmp);
}
// M is the quasi-1-norm of the response to angles changing according to the i-th column of V
// Then is multiplied by the wiInv value.
double M = 0.0;
double *vx = m_V.GetColumnPtr(i);
jnx = m_Jnorms.GetPtr();
for ( j=nCols; j>0; j-- ) {
double accum=0.0;
for ( long k=numEndEffectors; k>0; k-- ) {
accum += *(jnx++);
}
M += fabs((*(vx++)))*accum;
}
M *= fabs(wiInv);
double gamma = MaxAngleSDLS;
if ( N<M ) {
gamma *= N/M; // Scale back maximum permissable joint angle
}
// Calculate the dTheta from pure pseudoinverse considerations
double scale = alpha*wiInv; // This times i-th column of V is the psuedoinverse response
m_dPreTheta.LoadScaled( m_V.GetColumnPtr(i), scale );
// Now rescale the dTheta values.
double max = m_dPreTheta.MaxAbs();
double rescale = (gamma)/(gamma+max);
m_dTheta.AddScaled(m_dPreTheta,rescale);
/*if ( gamma<max) {
dTheta.AddScaled( dPreTheta, gamma/max );
}
else {
dTheta += dPreTheta;
}*/
}
// Scale back to not exceed maximum angle changes
double maxChange = m_dTheta.MaxAbs();
if ( maxChange>MaxAngleSDLS ) {
m_dTheta *= MaxAngleSDLS/(MaxAngleSDLS+maxChange);
//dTheta *= MaxAngleSDLS/maxChange;
}
}
void Jacobian::CalcdTClampedFromdS()
{
long len = m_dS.GetLength();
long j = 0;
for ( long i=0; i<len; i+=3, j++ ) {
double normSq = Square(m_dS[i])+Square(m_dS[i+1])+Square(m_dS[i+2]);
if ( normSq>Square(m_dSclamp[j]) ) {
double factor = m_dSclamp[j]/sqrt(normSq);
m_dT[i] = m_dS[i]*factor;
m_dT[i+1] = m_dS[i+1]*factor;
m_dT[i+2] = m_dS[i+2]*factor;
}
else {
m_dT[i] = m_dS[i];
m_dT[i+1] = m_dS[i+1];
m_dT[i+2] = m_dS[i+2];
}
}
}
double Jacobian::UpdateErrorArray()
{
double totalError = 0.0;
// Traverse tree to find all end effectors
VectorR3 temp;
Node* n = m_tree->GetRoot();
while ( n ) {
if ( n->isEndeffector() ) {
int i = n->getEffectorNum();
const VectorR3& targetPos = n->getTarget();
temp = targetPos;
temp -= n->getGlobalPosition();
double err = temp.Norm();
m_errorArray[i] = err;
totalError += err;
}
n = m_tree->GetSuccessor( n );
}
return totalError;
}
void Jacobian::UpdatedSClampValue()
{
// Traverse tree to find all end effectors
VectorR3 temp;
Node* n = m_tree->GetRoot();
while ( n ) {
if ( n->isEndeffector() ) {
int i = n->getEffectorNum();
const VectorR3& targetPos = n->getTarget();
// Compute the delta S value (differences from end effectors to target positions.
// While we are at it, also update the clamping values in dSclamp;
temp = targetPos;
temp -= n->getGlobalPosition();
double normSi = sqrt(Square(m_dS[i])+Square(m_dS[i+1])+Square(m_dS[i+2]));
double changedDist = temp.Norm()-normSi;
if ( changedDist>0.0 ) {
m_dSclamp[i] = BaseMaxTargetDist + changedDist;
}
else {
m_dSclamp[i] = BaseMaxTargetDist;
}
}
n = m_tree->GetSuccessor( n );
}
}
void Jacobian::DrawEigenVectors() const
{
ARN_THROW_SHOULD_NOT_BE_USED_ERROR
/*
int i, j;
VectorR3 tail;
VectorR3 head;
Node *node;
for (i=0; i<w.GetLength(); i++) {
if ( NearZero( w[i], 1.0e-10 ) ) {
continue;
}
for (j=0; j<nEffector; j++) {
node = tree->GetEffector(j);
tail = node->GetS();
U.GetTriple( j, i, &head );
head += tail;
glDisable(GL_LIGHTING);
glColor3f(1.0f, 0.2f, 0.0f);
glLineWidth(2.0);
glBegin(GL_LINES);
glVertex3f(tail.x, tail.y, tail.z);
glVertex3f(head.x, head.y, tail.z);
glEnd();
Arrow(tail, head);
glLineWidth(1.0);
glEnable(GL_LIGHTING);
}
}
*/
}
void Jacobian::CompareErrors( const Jacobian& j1, const Jacobian& j2, double* weightedDist1, double* weightedDist2 )
{
const VectorRn& e1 = j1.m_errorArray;
const VectorRn& e2 = j2.m_errorArray;
double ret1 = 0.0;
double ret2 = 0.0;
int len = e1.GetLength();
for ( long i=0; i<len; i++ ) {
double v1 = e1[i];
double v2 = e2[i];
if ( v1<v2 ) {
ret1 += v1/v2;
ret2 += 1.0;
}
else if ( v1 != 0.0 ) {
ret1 += 1.0;
ret2 += v2/v1;
}
else {
ret1 += 0.0;
ret2 += 0.0;
}
}
*weightedDist1 = ret1;
*weightedDist2 = ret2;
}
void Jacobian::CountErrors( const Jacobian& j1, const Jacobian& j2, int* numBetter1, int* numBetter2, int* numTies )
{
const VectorRn& e1 = j1.m_errorArray;
const VectorRn& e2 = j2.m_errorArray;
int b1=0, b2=0, tie=0;
int len = e1.GetLength();
for ( long i=0; i<len; i++ ) {
double v1 = e1[i];
double v2 = e2[i];
if ( v1<v2 ) {
b1++;
}
else if ( v2<v1 ) {
b2++;
}
else {
tie++;
}
}
*numBetter1 = b1;
*numBetter2 = b2;
*numTies = tie;
}
| [
"[email protected]"
]
| [
[
[
1,
531
]
]
]
|
98a7888783245188b01444ba95285ddf7e9b49a2 | 9426ad6e612863451ad7aac2ad8c8dd100a37a98 | /ULLib/include/ULClassFactory.h | 0a6a7be09a0a5ef05743212cdb80d5b910f416c1 | []
| no_license | piroxiljin/ullib | 61f7bd176c6088d42fd5aa38a4ba5d4825becd35 | 7072af667b6d91a3afd2f64310c6e1f3f6a055b1 | refs/heads/master | 2020-12-28T19:46:57.920199 | 2010-02-17T01:43:44 | 2010-02-17T01:43:44 | 57,068,293 | 0 | 0 | null | 2016-04-25T19:05:41 | 2016-04-25T19:05:41 | null | WINDOWS-1251 | C++ | false | false | 6,950 | h | ///\file ULClassFactory.h
///\brief Заголовочный фаил класса фабрики классов
#pragma once
#ifndef _ULCLASSFACTORY_H__
#define _ULCLASSFACTORY_H__
#include <objbase.h>
#include "ULCOMDllApp.h"
namespace ULCOMs
{
///\namespace ULAgregation
///\brief Пространство имён классов агрегации
namespace ULAgregation
{
;
///\class CAgregateNone
///\brief Класс заглушка при отсутствии агрегации
///\param CComponent_t - Имя класса компонента
template<class CComponent_t>class CULAgregateNone
{
public:
///\brief Конструкор
CULAgregateNone(IUnknown* /*pUnknownOuter*/)
{
}
///\brief Проверяет входные параметры CULClassFactory::CreateInstance
///\ на возможность агрегирования
///\param pUnknownOuter - Запрашиваемый указатель на компонент
///\param iid - идентификатор запрашиваемого интерфейса
///\return S_OK если всё впорядке, иначе CLASS_E_NOAGGREGATION
HRESULT Check(IUnknown* pUnknownOuter,const IID& iid)
{
if(pUnknownOuter!=NULL)
return CLASS_E_NOAGGREGATION;
else
return S_OK;
}
///\brief Создаёт коспонент
///\return указатель на компонент
CComponent_t* GetComponent()
{
return new CComponent_t;
}
};
///\class CULAgregate
///\brief Класс для агрегации
///\param CComponent_t - Имя класса компонента
template<class CComponent_t>class CULAgregate
{
private:
///\brief Указатель на запрашиваемый компонент
IUnknown* m_pUnknownOuter;
public:
///\brief Конструкор
///\param pUnknownOuter - Запрашиваемый указатель на компонент
CULAgregate(IUnknown* pUnknownOuter):
m_pUnknownOuter(pUnknownOuter)
{
}
///\brief Проверяет входные параметры CULClassFactory::CreateInstance
///\ на возможность агрегирования
///\param pUnknownOuter - Запрашиваемый указатель на компонент
///\param iid - идентификатор запрашиваемого интерфейса
///\return S_OK если всё впорядке, иначе CLASS_E_NOAGGREGATION
HRESULT Check(IUnknown* pUnknownOuter,const IID& iid)
{
if ((pUnknownOuter != NULL) && (iid != IID_IUnknown))
return CLASS_E_NOAGGREGATION;
else
return S_OK;
}
///\brief Создаёт коспонент
///\return указатель на компонент
CComponent_t* GetComponent()
{
return new CComponent_t(pUnknownOuter);
}
};
}
template<class CComponent_t,class CAgregate_t=ULAgregation::CULAgregateNone<CComponent_t>>class CULClassFactory:
///\class CULClassFactory
///\brief класс фабрики классов
///\param CComponent_t - тип регистрируемого компонента
public IClassFactory
{
private:
///brief Счётчик ссылок
long m_nRef;
public:
///\brief Конструктор
CULClassFactory():
m_nRef(1)
{
};
///\brief Деструктор
~CULClassFactory()
{
};
//=================Реализация интерфейса IUnknown==========================
///\brief Возвращает указатель на IClassFactory
///\param iid - Идентификатор интерфейса
///\param ppvObject - Указатель на указатель на интерфейс
///\return S_OK в случае создания интерфеса,
///\ E_NOINTERFACE - в слечае отсутствия запрашиваемого интерфейса
virtual HRESULT __stdcall CULClassFactory::QueryInterface(const IID& iid, void** ppvObject)
{
if ((iid == IID_IUnknown) || (iid == IID_IClassFactory))
*ppvObject = static_cast<IClassFactory*>(this);
else
{
*ppvObject = NULL ;
return E_NOINTERFACE ;
}
reinterpret_cast<IUnknown*>(*ppvObject)->AddRef() ;
return S_OK ;
}
///\brief Увеличивает счетчик числа ссылок на интерфейс
///\return текущее число ссылок
virtual ULONG __stdcall CULClassFactory::AddRef()
{
return InterlockedIncrement(&m_nRef) ;
}
///\brief Уменьщает счетчик числа ссылок на интерфейс
///\return текущее число ссылок
virtual ULONG __stdcall CULClassFactory::Release()
{
if (InterlockedDecrement(&m_nRef) == 0)
{
delete this ;
return 0 ;
}
return m_nRef ;
}
// реализация LockServer
///\brief Блокирует сервер при от преждевременной выгрузки необходимости
///\param fLock - TRUE - заблокировать, FALSE - разблокировать
///\return S_OK
virtual HRESULT __stdcall CULClassFactory::LockServer(BOOL fLock)
{
if (fLock)
static_cast<ULApps::CULCOMDllApp*>(ULApps::CULCOMDllApp::GetULDllApp())->ServerLock();
else
static_cast<ULApps::CULCOMDllApp*>(ULApps::CULCOMDllApp::GetULDllApp())->ServerUnlock();
return S_OK ;
}
///\brief Выполняет создание компонента. Вызывается из CoCreateInstance
///\param pUnknownOuter - если поддерживается агрегирование,
/// то к нему присваевается указатель на компонент
///\param iid - Идентификатор интерфейса, поддерживаемого компонентом
///\param ppvObject - Указатель на указатель на интерфейс
///\return COM код возврата
HRESULT __stdcall CreateInstance(IUnknown* pUnknownOuter,
const IID& iid,
void** ppvObject)
{
CAgregate_t Agregation(pUnknownOuter);
HRESULT hr=Agregation.Check(pUnknownOuter,iid);
if(FAILED(hr))
return hr;
//Создание компонента
CComponent_t* pComponent = Agregation.GetComponent();
if (pComponent == NULL)
return E_OUTOFMEMORY;
//Получение запрошенного интерфейса
hr = pComponent->QueryInterface(iid, ppvObject) ;
//Освобожение указателя IUnknown .
// (если QueryInterface выполнилась не верно, то произойдёт удаление компонента.)
pComponent->Release() ;
return hr ;
}
};
}
#endif//_ULCLASSFACTORY_H__
| [
"UncleLab@a8b69a72-a546-0410-9fb4-5106a01aa11f"
]
| [
[
[
1,
175
]
]
]
|
bf518e38133e12b3d9a9ef1d811f6dd3f4696596 | 021e8c48a44a56571c07dd9830d8bf86d68507cb | /build/vtk/vtkMesaPainterDeviceAdapter.h | a386e60d1b2b65bcf1cefa505d0429b3dda5e39e | [
"BSD-3-Clause"
]
| permissive | Electrofire/QdevelopVset | c67ae1b30b0115d5c2045e3ca82199394081b733 | f88344d0d89beeec46f5dc72c20c0fdd9ef4c0b5 | refs/heads/master | 2021-01-18T10:44:01.451029 | 2011-05-01T23:52:15 | 2011-05-01T23:52:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,813 | h | /*=========================================================================
Program: Visualization Toolkit
Module: vtkMesaPainterDeviceAdapter.h
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// .NAME vtkMesaPainterDeviceAdapter - An adapter between a vtkPainter and a
// rendering device.
// .SECTION Description
// An adapter between vtkPainter and the Mesa rendering system. Only a
// handful of attributes with special meaning are supported. The Mesa
// attribute used for each attribute is given below.
//
// \verbatim
// vtkDataSetAttributes::NORMALS glNormal
// vtkDataSetAttributes:::SCALARS glColor
// vtkDataSetAttributes::TCOORDS glTexCoord
// vtkDataSetAttributes::NUM_ATTRIBUTES glVertex
// \endverbatim
//
#ifndef __vtkMesaPainterDeviceAdapter_h
#define __vtkMesaPainterDeviceAdapter_h
#include "vtkPainterDeviceAdapter.h"
class VTK_RENDERING_EXPORT vtkMesaPainterDeviceAdapter :
public vtkPainterDeviceAdapter
{
public:
vtkTypeMacro(vtkMesaPainterDeviceAdapter, vtkPainterDeviceAdapter);
static vtkMesaPainterDeviceAdapter *New();
virtual void PrintSelf(ostream &os, vtkIndent indent);
// Description:
// Converts mode from VTK_* to GL_* and calls glBegin.
virtual void BeginPrimitive(int mode);
// Description:
// Calls glEnd.
virtual void EndPrimitive();
// Description:
// Calls one of glVertex*, glNormal*, glColor*, or glTexCoord*.
virtual void SendAttribute(int index, int components, int type,
const void *attribute, unsigned long offset=0);
// Description:
// Calls one of glVertexPointer, glNormalPointer, glColorPointer, or
// glTexCoordPointer.
virtual void SetAttributePointer(int index, int numcomponents, int type,
int stride, const void *pointer);
// Description:
// Calls glEnableClientState or glDisableClientState.
virtual void EnableAttributeArray(int index);
virtual void DisableAttributeArray(int index);
// Description:
// Calls glDrawArrays. Mode is converted from VTK_* to GL_*.
virtual void DrawArrays(int mode, vtkIdType first, vtkIdType count);
// Description:
// Calls glDrawElements. Mode and type are converted from VTK_* to GL_*.
virtual void DrawElements(int mode, vtkIdType count, int type, void *indices);
// Description:
// Returns true if renderer is a vtkMesaRenderer.
virtual int Compatible(vtkRenderer *renderer);
// Description:
// Turns lighting on and off.
virtual void MakeLighting(int mode);
// Description:
// Returns current lighting setting.
virtual int QueryLighting();
// Description:
// Turns antialiasing on and off.
virtual void MakeMultisampling(int mode);
// Description:
// Returns current antialiasing setting.
virtual int QueryMultisampling();
// Description:
// Turns blending on and off.
virtual void MakeBlending(int mode);
// Description:
// Returns current blending setting.
virtual int QueryBlending();
protected:
vtkMesaPainterDeviceAdapter();
~vtkMesaPainterDeviceAdapter();
private:
vtkMesaPainterDeviceAdapter(const vtkMesaPainterDeviceAdapter &); // Not implemented.
void operator=(const vtkMesaPainterDeviceAdapter &); // Not implemented.
};
#endif //_vtkMesaPainterDeviceAdapter_h
| [
"ganondorf@ganondorf-VirtualBox.(none)"
]
| [
[
[
1,
113
]
]
]
|
47b26359f28646b006173086070851fdf4e62917 | c5534a6df16a89e0ae8f53bcd49a6417e8d44409 | /trunk/nGENE Proj/GUIControlContainer.cpp | 7960d66d1847bcec563af4e4315cd497bf46f7b6 | []
| no_license | svn2github/ngene | b2cddacf7ec035aa681d5b8989feab3383dac012 | 61850134a354816161859fe86c2907c8e73dc113 | refs/heads/master | 2023-09-03T12:34:18.944872 | 2011-07-27T19:26:04 | 2011-07-27T19:26:04 | 78,163,390 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,184 | cpp | /*
---------------------------------------------------------------------------
This source file is part of nGENE Tech.
Copyright (c) 2006- Wojciech Toman
This program is free software.
File: GUIControlContainer.cpp
Version: 0.02
---------------------------------------------------------------------------
*/
#include "PrecompiledHeaders.h"
#include "GUIControlContainer.h"
namespace nGENE
{
class GUIControlTabIndexComparator
{
public:
bool operator()(const GUIControl* _control1, const GUIControl* _control2)
{
return (_control1->getTabIndex() < _control2->getTabIndex());
}
};
GUIControlContainer::GUIControlContainer():
m_pFocusedControl(NULL)
{
}
//----------------------------------------------------------------------
GUIControlContainer::~GUIControlContainer()
{
}
//----------------------------------------------------------------------
void GUIControlContainer::addControl(GUIControl* _control)
{
_control->setParent(this);
_control->setTabIndex(m_vControls.size());
m_vControls.push_back(_control);
if(m_vControls.size() == 1)
setFocusedControl(_control);
// Sort controls based on their tab index
sortByTabIndex();
}
//----------------------------------------------------------------------
void GUIControlContainer::changeResolution(uint _oldWidth, uint _oldHeight,
uint _width, uint _height)
{
GUIControl::changeResolution(_oldWidth, _oldHeight, _width, _height);
for(uint i = 0; i != m_vControls.size(); ++i)
{
m_vControls[i]->changeResolution(_oldWidth, _oldHeight,
_width, _height);
}
}
//----------------------------------------------------------------------
void GUIControlContainer::setFocusedControl(GUIControl* _control)
{
if(m_pFocusedControl == _control)
return;
// Handle events
if(m_pFocusedControl)
m_pFocusedControl->loosingFocus();
m_pFocusedControl = _control;
if(m_pFocusedControl)
m_pFocusedControl->gettingFocus();
}
//----------------------------------------------------------------------
void GUIControlContainer::sortByTabIndex()
{
GUIControlTabIndexComparator comparator;
std::sort(m_vControls.begin(), m_vControls.end(), comparator);
}
//----------------------------------------------------------------------
void GUIControlContainer::render(ScreenOverlay* _overlay, Vector2& _position)
{
// Render all child controls
for(uint i = 0; i < m_vControls.size(); ++i)
{
GUIControl* pControl = m_vControls[i];
if(pControl->isVisible())
{
Vector2 temp = _position + pControl->getPosition();
SRect <uint> rect(temp.x,
temp.y,
temp.x + pControl->getWidth(),
temp.y + pControl->getHeight());
pControl->render(_overlay, temp);
}
}
}
//----------------------------------------------------------------------
void GUIControlContainer::setOpacity(float _opacity)
{
GUIControl::setOpacity(_opacity);
for(uint i = 0; i < m_vControls.size(); ++i)
{
m_vControls[i]->setOpacity(_opacity);
}
}
//----------------------------------------------------------------------
} | [
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
]
| [
[
[
1,
116
]
]
]
|
9797da0cfec93caec7d3ba10ececf3252ab7749f | 1ac3920c854ebd1f591412d0f93b55a5c2b96521 | /GTL Draw/GetNDlg.cpp | 3402c50c30aa2a7251936f1246ebf8945b56ffb1 | []
| no_license | vatai/gtldraw | fe1d9181f033dcda833342c4388f0adb0cdbf871 | 89c288f15cabe4bca348ee93688e995b1a9708bd | refs/heads/master | 2020-05-30T23:14:20.159427 | 2007-05-22T13:39:34 | 2007-05-22T13:39:34 | 32,105,809 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 546 | cpp | // GetNDlg.cpp : implementation file
//
#include "stdafx.h"
#include "GTL Draw.h"
#include "GetNDlg.h"
// GetNDlg dialog
IMPLEMENT_DYNAMIC(GetNDlg, CDialog)
GetNDlg::GetNDlg(CWnd* pParent /*=NULL*/)
: CDialog(GetNDlg::IDD, pParent)
, m_Nval(3)
{
}
GetNDlg::~GetNDlg()
{
}
void GetNDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_N, m_N);
DDX_Text(pDX, IDC_N, m_Nval);
}
BEGIN_MESSAGE_MAP(GetNDlg, CDialog)
END_MESSAGE_MAP()
// GetNDlg message handlers
| [
"emil.vatai@e8fff1a5-fc30-0410-bed7-e1c51b34c90e"
]
| [
[
[
1,
34
]
]
]
|
9a3b6efd25c796b1e592dc0b78e951678ede8c43 | 5f0b8d4a0817a46a9ae18a057a62c2442c0eb17e | /Include/component/ProgressBar.cpp | 3ef98e44a26f94250d656057f675cc7282750633 | [
"BSD-3-Clause"
]
| permissive | gui-works/ui | 3327cfef7b9bbb596f2202b81f3fc9a32d5cbe2b | 023faf07ff7f11aa7d35c7849b669d18f8911cc6 | refs/heads/master | 2020-07-18T00:46:37.172575 | 2009-11-18T22:05:25 | 2009-11-18T22:05:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,842 | cpp | /*
* Copyright (c) 2003-2006, Bram Stein
* 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. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "./ProgressBar.h"
namespace ui
{
ProgressBar::ProgressBar(int min, int max, int orientation)
{
init(min,max,orientation);
}
ProgressBar::ProgressBar(int min, int max)
{
init(min,max,ProgressBar::HORIZONTAL);
}
bool ProgressBar::isStringPainted() const
{
return stringPainted;
}
void ProgressBar::setStringPainted(bool b)
{
stringPainted = b;
}
void ProgressBar::init(int min, int max, int orientation)
{
setThemeName("ProgressBar");
setMinimum(min);
setMaximum(max);
setValue(0);
setOrientation(orientation);
setStringPainted(true);
}
void ProgressBar::setMaximum(int m)
{
max = m;
}
int ProgressBar::getMaximum() const
{
return max;
}
void ProgressBar::setMinimum(int m)
{
min = m;
}
int ProgressBar::getMinimum() const
{
return min;
}
void ProgressBar::setValue(int v)
{
if(v < getMinimum())
{
value = getMinimum();
}
else if(v > getMaximum())
{
value = getMaximum();
}
else
{
value = v;
}
}
int ProgressBar::getValue() const
{
return value;
}
void ProgressBar::setOrientation(int orientation)
{
orient = orientation;
}
int ProgressBar::getOrientation() const
{
return orient;
}
} | [
"bs@bram.(none)"
]
| [
[
[
1,
114
]
]
]
|
b20c5987f8ec92ff1267b511fda15d297adde71a | 00c36cc82b03bbf1af30606706891373d01b8dca | /OpenGUI/OpenGUI_Screen.cpp | 9f4038b356c95c0cd23c19d936cf31e1d72bfbc5 | [
"BSD-3-Clause"
]
| permissive | VB6Hobbyst7/opengui | 8fb84206b419399153e03223e59625757180702f | 640be732a25129a1709873bd528866787476fa1a | refs/heads/master | 2021-12-24T01:29:10.296596 | 2007-01-22T08:00:22 | 2007-01-22T08:00:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 25,954 | cpp | // OpenGUI (http://opengui.sourceforge.net)
// This source code is released under the BSD License
// See LICENSE.TXT for details
#include "OpenGUI_CONFIG.h"
#include "OpenGUI_Screen.h"
#include "OpenGUI_Exception.h"
#include "OpenGUI_System.h"
#include "OpenGUI_Renderer.h"
#include "OpenGUI_Brush.h"
#include "OpenGUI_Control.h"
#include "OpenGUI_TimerManager.h"
#include "OpenGUI_Viewport.h"
#include "OpenGUI_TextureManager.h"
#include "OpenGUI_Macros.h"
namespace OpenGUI {
class ScreenBrush: public Brush {
public:
ScreenBrush( Screen* screenPtr, Viewport* viewport ): mScreen( screenPtr ), mViewport( viewport ) {
if ( !mViewport )
OG_THROW( Exception::ERR_INVALIDPARAMS, "Invalid Viewport", __FUNCTION__ );
}
virtual ~ScreenBrush() {
/**/
}
virtual const FVector2& getDrawSize() const {
return mScreen->getSize();
}
virtual const FVector2& getPPU_Raw() const {
return mScreen->getPPU();
}
virtual const FVector2& getUPI_Raw() const {
return mScreen->getUPI();
}
virtual bool isRTTContext() const {
/* regardless of whether we are or not, we say that we aren't */
return false;
}
protected:
virtual void appendRenderOperation( RenderOperation& renderOp ) {
for ( TriangleList::iterator iter = renderOp.triangleList->begin();
iter != renderOp.triangleList->end(); iter++ ) {
Triangle& t = ( *iter );
for ( int i = 0; i < 3; i++ ) {
t.vertex[i].position.x /= getDrawSize().x;
t.vertex[i].position.y /= getDrawSize().y;
}
}
Renderer::getSingleton().doRenderOperation( renderOp );
}
virtual void onActivate() {
Renderer::getSingleton().selectRenderContext( 0 );
}
virtual void onClear() {
/* we don't try to clear viewports */
}
private:
Screen* mScreen;
Viewport* mViewport;
};
//############################################################################
//############################################################################
SimpleProperty_FVector2( ScreenProp_Size, "Size", Screen, getSize, setSize );
SimpleProperty_Bool( ScreenProp_Active, "Active", Screen, isActive, setActive );
SimpleProperty_Bool( ScreenProp_AUpdate, "AutoUpdate", Screen, isAutoUpdating, setAutoUpdating );
SimpleProperty_Bool( ScreenProp_ATime, "AutoTime", Screen, isAutoTiming, setAutoTiming );
class ScreenProp_Name_CLASS : public ObjectProperty {
public:
virtual ~ScreenProp_Name_CLASS() {}
virtual const char* getAccessorName() {
return "Name";
}
virtual void get( Object& objectRef, Value& valueOut ) {
try {
Screen& s = dynamic_cast<Screen&>( objectRef );
valueOut.setValue( s.getName() );
} catch ( std::bad_cast e ) {
OG_THROW( Exception::ERR_INVALIDPARAMS, "Bad Object Pointer", __FUNCTION__ );
}
}
virtual void set( Object& objectRef, Value& valueIn ) {
/* read-only */
}
virtual Value::ValueType getPropertyType() {
return Value::T_STRING;
}
virtual bool getPermSettable() {
return false;
}
}
ScreenProp_Name;
//############################################################################
class Screen_ObjectAccessorList : public ObjectAccessorList {
public:
Screen_ObjectAccessorList() {
addAccessor( &ScreenProp_Size );
addAccessor( &ScreenProp_Active );
addAccessor( &ScreenProp_AUpdate );
addAccessor( &ScreenProp_ATime );
addAccessor( &ScreenProp_Name );
}
~Screen_ObjectAccessorList() {}
}
gScreen_ObjectAccessorList;
//############################################################################
ObjectAccessorList* Screen::getAccessors() {
return &gScreen_ObjectAccessorList;
}
//############################################################################
//############################################################################
Screen::Screen( const String& screenName, const FVector2& initialSize, Viewport* viewport ) {
if ( gScreen_ObjectAccessorList.getParent() == 0 )
gScreen_ObjectAccessorList.setParent( Object::getAccessors() );
mName = screenName;
mSize = initialSize;
mUPI = FVector2( DEFAULT_SCREEN_UPI_X, DEFAULT_SCREEN_UPI_Y );
_DirtyPPUcache();
Children.setParent( this ); // mark ownership of the WidgetCollection
mCursorPressed = false; // cursor starts not pressed
mCursorPos.x = mSize.x / 2.0f; // cursor starts in the middle of the Screen
mCursorPos.y = mSize.y / 2.0f;
m_CursorEnabled = false; // cursor starts disabled
m_CursorVisible = true; // cursor starts shown
m_CursorFocus = 0; // start with no cursor focused widget
m_KeyFocus = 0; // start with no keyboard focused widget
mStatUpdateTimer = TimerManager::getSingleton().getTimer();
mAutoUpdating = true; // we auto update by default
mAutoTiming = true; // we get time from System by default
mActive = true; // active by default
mViewport = 0; // current viewport
setViewport( viewport ); // we do it this way to ensure proper Screen->Viewport linkage
std::stringstream ss;
ss << "[" << mName << "] Creation -- Size: " << mSize.toStr();
if ( mViewport )
ss << " Viewport: " << mViewport->getSize().toStr();
else
ss << " No Viewport";
LogManager::SlogMsg( "Screen", OGLL_INFO ) << ss.str() << Log::endlog;
}
//############################################################################
Screen::~Screen() {
LogManager::SlogMsg( "Screen", OGLL_INFO ) << "[" << mName << "] Destruction" << Log::endlog;
_setKeyFocus( 0 );
_setCursorFocus( 0 );
setViewport( 0 ); // release from the current viewport, if there is one
/**/
}
//############################################################################
Widget* Screen::getKeyFocusedWidget() {
return m_KeyFocus;
}
//############################################################################
Widget* Screen::getCursorFocusedWidget() {
return m_CursorFocus;
}
//############################################################################
void Screen::_setKeyFocus( Widget* widget ) {
Widget* prev = m_KeyFocus;
Widget* next = widget;
//notify previous of focus lost
if ( prev ) {
prev->_injectKeyFocusLost( next, prev );
}
//set the new focus target
m_KeyFocus = next;
//notify the new of focus acquired
if ( next ) {
next->_injectKeyFocused( next, prev );
}
}
//############################################################################
void Screen::_setCursorFocus( Widget* widget, bool issueMove ) {
Widget* prev = m_CursorFocus;
Widget* next = widget;
if ( prev == next )
return; //skip pointless operations
//notify previous of focus lost
if ( prev ) {
prev->_injectCursorFocusLost( next, prev );
}
//set the new focus target
m_CursorFocus = next;
//notify the new of focus acquired
if ( next ) {
next->_injectCursorFocused( next, prev );
}
//inject a CursorMove to update the new receiver about the cursor's position
if ( issueMove )
_injectCursorPosition( mCursorPos.x, mCursorPos.y );
}
//############################################################################
void Screen::_UpdatePPU() const {
Viewport* v = getViewport();
if ( !v )
OG_THROW( Exception::ERR_INTERNAL_ERROR, "Cannot calculate UPI without a target Viewport", __FUNCTION__ );
const IVector2& targetSize = v->getSize();
mPPUcache.x = (( float )targetSize.x ) / mSize.x;
mPPUcache.y = (( float )targetSize.y ) / mSize.y;
mPPUcache_valid = true;
}
//############################################################################
void Screen::setUPI( const FVector2& newUPI ) {
LogManager::SlogMsg( "Screen", OGLL_INFO ) << "[" << mName << "]"
<< " Changed UnitsPerInch"
<< " From:" << mUPI.toStr() << " To:" << newUPI.toStr()
<< Log::endlog;
mUPI = newUPI;
invalidateAll();
}
//############################################################################
const String& Screen::getName() const {
return mName;
}
//############################################################################
const FVector2& Screen::getSize() const {
return mSize;
}
//############################################################################
void Screen::setSize( const FVector2& newSize ) {
LogManager::SlogMsg( "Screen", OGLL_INFO ) << "[" << mName << "]"
<< " Changed Size"
<< " From:" << mSize.toStr() << " To:" << newSize.toStr()
<< Log::endlog;
mSize = newSize;
_DirtyPPUcache();
invalidateAll();
}
//############################################################################
void Screen::setViewport( Viewport* viewport ) {
if ( viewport != mViewport ) {
if ( mViewport )
mViewport->_screenDetach( this );
mViewport = viewport;
if ( mViewport )
mViewport->_screenAttach( this );
// any previous cache data is no longer useful
// we can't render without a viewport, so why keep it
_DirtyPPUcache();
invalidateAll();
}
}
//############################################################################
Viewport* Screen::getViewport() const {
return mViewport;
}
//############################################################################
void Screen::invalidateAll() {
WidgetCollection::iterator iter = Children.begin();
while ( iter != Children.end() ) {
iter->flush();
iter++;
}
}
//############################################################################
/*! If the Screen is not marked active, or does not have a valid Viewport assigned,
this function will return immediately with no error. */
void Screen::update() {
if ( !_isRenderable() )
return; //abort if we are unsuitable for drawing for any reason
Renderer& renderer = Renderer::getSingleton();
renderer.selectViewport( mViewport ); // inform renderer of new viewport selection
renderer.preRenderSetup(); // begin render sequence
mViewport->preUpdate( this ); // inform the viewport that it is about to be updated
// if pixel alignment changed since last render...
if ( mPrevViewportSize != mViewport->getSize() ) {
_DirtyPPUcache(); // this will need to be recalculated on next use
invalidateAll(); // blow out any widget caches, since they are certainly inaccurate
mPrevViewportSize = mViewport->getSize(); //keep this for next render
}
ScreenBrush b( this, mViewport );
WidgetCollection::reverse_iterator iter, iterend = Children.rend();
for ( iter = Children.rbegin(); iter != iterend; iter++ ) {
iter->_draw( b );
}
if ( m_CursorEnabled && m_CursorVisible ) {
// determine the cursor we're drawing
CursorPtr drawCursor;
Widget* overWidget = getWidgetAt( mCursorPos, true );
if ( overWidget ) {
Control* overControl = dynamic_cast<Control*>( overWidget );
if ( overControl ) {
drawCursor = overControl->_getCurrentCursor();
}
}
if ( !drawCursor )
drawCursor = mDefaultCursor;
// send notifications if necessary
if ( drawCursor != mPrevCursor ) {
if ( mPrevCursor )
mPrevCursor->eventCursorHidden();
mPrevCursor = drawCursor;
if ( mPrevCursor )
mPrevCursor->eventCursorShown( mCursorPos.x, mCursorPos.y );
}
// Draw the cursor
if ( drawCursor )
drawCursor->eventDraw( mCursorPos.x, mCursorPos.y, b );
}
mViewport->postUpdate( this ); // inform the viewport that it is done being updated
renderer.postRenderCleanup(); // end render sequence
//! \todo timing here is broken. #100
float time = (( float )mStatUpdateTimer->getMilliseconds() ) / 1000.0f;
_updateStats_UpdateTime( time );
mStatUpdateTimer->reset();
}
//############################################################################
void Screen::injectTime( unsigned int milliseconds ) {
float seconds;
seconds = (( float )milliseconds ) / 1000.0f;
injectTime( seconds );
}
//############################################################################
void Screen::injectTime( float seconds ) {
WidgetCollection::iterator iter = Children.begin();
while ( iter != Children.end() ) {
iter->_tick( seconds );
iter++;
}
}
//############################################################################
/*!
\note this is a temporary implementation that will be replaced with a more useful system
\todo finish me
*/
bool Screen::injectCharacter( char character ) {
//!\todo fix this to support separate key-up / key-down, typematic repeat, and key->character maps
if ( !m_KeyFocus ) // we only send key events to those that ask for it
return false;
bool retval = false;
Key_EventArgs downargs = Key_EventArgs( character );
m_KeyFocus->_injectKeyDown( downargs );
if ( downargs.Consumed ) retval = true;
Key_EventArgs pressargs = Key_EventArgs( character );
m_KeyFocus->_injectKeyPressed( pressargs );
if ( pressargs.Consumed ) retval = true;
Key_EventArgs upargs = Key_EventArgs( character );
m_KeyFocus->_injectKeyUp( upargs );
if ( upargs.Consumed ) retval = true;
return retval;
}
//############################################################################
/*! Positive values causes right or downward movement depending on axis.
Values of 0.0f on both axis are ignored. If the cursor is disabled, this will always return false. */
bool Screen::injectCursorMovement( float x_rel, float y_rel ) {
x_rel += mCursorPos.x;
y_rel += mCursorPos.y;
return injectCursorPosition( x_rel, y_rel );
}
//############################################################################
/*! 0.0 x 0.0 is the upper left corner of the screen.
If the cursor is disabled, this will always return false.
If the given position is the same as the previous position, this will return false with no event
generated. */
bool Screen::injectCursorPosition( float x_pos, float y_pos ) {
//skip if cursor disabled and if no movement really occurred
if ( !m_CursorEnabled ) return false;
if ( mCursorPos.x == x_pos && mCursorPos.y == y_pos ) return false;
return _injectCursorPosition( x_pos, y_pos );
}
//############################################################################
bool Screen::_injectCursorPosition( float x_pos, float y_pos, bool preConsumed ) {
// before we do anything, abort if the cursor is disabled
if ( !m_CursorEnabled ) return false;
//store the new cursor position for future use
mCursorPos.x = x_pos;
mCursorPos.y = y_pos;
//send to the active cursor, if we have one
if ( mPrevCursor ) {
mPrevCursor->eventCursorMove( mCursorPos.x, mCursorPos.y );
}
//send to just focus holder if present
if ( m_CursorFocus ) {
FVector2 localPos( x_pos, y_pos );
localPos = m_CursorFocus->pointFromScreen( localPos );
Cursor_EventArgs moveEvent( localPos.x, localPos.y );
if ( preConsumed ) moveEvent.eat();
m_CursorFocus->_injectCursorMove( moveEvent );
return true; // see end of function note
}
//send to everyone
Cursor_EventArgs moveEvent( x_pos, y_pos );
if ( preConsumed ) moveEvent.eat();
WidgetCollection::iterator i, ie = Children.end();
for ( i = Children.begin(); i != ie; i++ ) {
i->_injectCursorMove( moveEvent );
}
// we always return true if the move was issued to the widgets, regardless if anyone consumed it
// (merely processing it signifies that it was useful)
return true;
}
//############################################################################
/*! 0.0 x 0.0 is the upper left corner of the screen, 1.0 x 1.0 is the lower right of the screen.
If the cursor is disabled, this will always return false.*/
bool Screen::injectCursorPosition_Percent( float x_perc, float y_perc ) {
x_perc *= mSize.x;
y_perc *= mSize.y;
return injectCursorPosition( x_perc, y_perc );
}
//############################################################################
/*! If the cursor is disabled, this will always return false. */
bool Screen::injectCursorPress() {
if ( !m_CursorEnabled ) return false;
mCursorPressed = true;
//send to the active cursor, if we have one
if ( mPrevCursor ) {
mPrevCursor->eventCursorPress( mCursorPos.x, mCursorPos.y );
}
//send to just focus holder if present
if ( m_CursorFocus ) {
FVector2 localPos = m_CursorFocus->pointFromScreen( mCursorPos );
Cursor_EventArgs pressEvent( localPos.x, localPos.y );
m_CursorFocus->_injectCursorPress( pressEvent );
return pressEvent.Consumed; // return the consumption value
}
//send to everyone else
Cursor_EventArgs pressEvent( mCursorPos.x, mCursorPos.y );
WidgetCollection::iterator i, ie = Children.end();
for ( i = Children.begin(); i != ie; i++ ) {
i->_injectCursorPress( pressEvent );
}
return pressEvent.Consumed; // return the consumption value
}
//############################################################################
/*! If the cursor is disabled, this will always return false. */
bool Screen::injectCursorRelease() {
if ( !m_CursorEnabled ) return false;
mCursorPressed = false;
//send to the active cursor, if we have one
if ( mPrevCursor ) {
mPrevCursor->eventCursorRelease( mCursorPos.x, mCursorPos.y );
}
//send to just focus holder if present
if ( m_CursorFocus ) {
FVector2 localPos = m_CursorFocus->pointFromScreen( mCursorPos );
Cursor_EventArgs releaseEvent( localPos.x, localPos.y );
m_CursorFocus->_injectCursorRelease( releaseEvent );
return releaseEvent.Consumed; // return the consumption value
}
//send to everyone else
Cursor_EventArgs releaseEvent( mCursorPos.x, mCursorPos.y );
WidgetCollection::iterator i, ie = Children.end();
for ( i = Children.begin(); i != ie; i++ ) {
i->_injectCursorRelease( releaseEvent );
}
return releaseEvent.Consumed; // return the consumption value
}
//############################################################################
/*! If the cursor is disabled, this will always return false. */
bool Screen::injectCursorPress_State( bool pressed ) {
if ( pressed != mCursorPressed ) {
if ( pressed )
return injectCursorPress();
else
return injectCursorRelease();
}
return false;
}
//############################################################################
/*! Cursor starts disabled, so you will need to call this to enable it before
you can realistically use it. Multiple calls have no ill effect.
\note You cannot enable a visible cursor until the default cursor for the Screen
has been set. If no default cursor is set when this is called, the cursor will
be immediately hidden via \c hideCursor().*/
void Screen::enableCursor() {
if ( !m_CursorEnabled ) {
m_CursorEnabled = true;
if ( mDefaultCursor.isNull() && cursorVisible() ) {
hideCursor();
}
// send a null move to bring the GUI state into proper planetary alignment
_injectCursorPosition( mCursorPos.x, mCursorPos.y );
}
}
//############################################################################
/*! Multiple calls have no ill effect. */
void Screen::disableCursor() {
if ( m_CursorEnabled ) {
if ( mPrevCursor ) {
mPrevCursor->eventCursorHidden();
mPrevCursor = 0;
}
m_CursorEnabled = false;
// clear any existing cursor focus, but don't issue the state updating move event
_setCursorFocus( 0, false );
// end any existing cursor involvement by issuing a sweeping consumed event
_injectCursorPosition( mCursorPos.x, mCursorPos.y, true );
}
}
//############################################################################
bool Screen::cursorEnabled() {
return m_CursorEnabled;
}
//############################################################################
/*! Cursor starts shown, so you do not need to call this unless you've previously
hidden the cursor. Multiple calls have no ill effect.
\note As stated in enableCursor(), you cannot show the cursor until a default
cursor for the Screen has been set. You can toggle cursor visibility freely
while the cursor is disabled, but attempting to force showing of the cursor
while it is enabled and there is no default will throw an exception. */
void Screen::showCursor() {
if ( cursorEnabled() && mDefaultCursor.isNull() )
OG_THROW( Exception::ERR_INTERNAL_ERROR, "Cannot show enabled cursor on Screen without a default cursor", __FUNCTION__ );
m_CursorVisible = true;
}
//############################################################################
/*! Multiple calls have no ill effect. */
void Screen::hideCursor() {
if ( m_CursorVisible ) {
m_CursorVisible = false;
if ( mPrevCursor ) {
mPrevCursor->eventCursorHidden();
mPrevCursor = 0;
}
}
}
//############################################################################
bool Screen::cursorVisible() {
return m_CursorVisible;
}
//############################################################################
/*! If you assign a null pointer as the new cursor and the cursor is enabled,
this will cause the cursor to become hidden automatically. */
void Screen::setCursor( CursorPtr cursor ) {
if ( cursor.isNull() && cursorEnabled() && cursorVisible() ) {
hideCursor();
}
mDefaultCursor = cursor;
}
//############################################################################
Widget* Screen::getWidgetAt( const FVector2& position, bool recursive ) {
for ( WidgetCollection::iterator iter = Children.begin();iter != Children.end(); iter++ ) {
Widget* child = iter.get();
if ( child->isInside( position ) ) {
Widget* ret = child;
if ( recursive ) {
child = child->getChildAt( position, true );
if ( child )
ret = child;
}
return ret;
}
}
return 0;
}
//############################################################################
void Screen::getWidgetsAt( const FVector2& position, WidgetPtrList& outList, bool recursive ) {
for ( WidgetCollection::iterator iter = Children.begin(); iter != Children.end(); iter++ ) {
Widget* child = iter.get();
if ( child->isInside( position ) ) {
if ( recursive ) {
child->getChildrenAt( position, outList, true );
}
outList.push_back( child );
}
}
}
//############################################################################
/*! */
float Screen::statsGetUpdateTime() {
return mStatUpdate.getAverage();
}
//############################################################################
void Screen::_updateStats_UpdateTime( float newTime ) {
mStatUpdate.addRecord( newTime );
}
//############################################################################
void Screen::statsResetUpdateTime() {
mStatUpdate.reset();
}
//############################################################################
/*! \see Widget::getPath() for a more in-depth explanation of paths */
Widget* Screen::getPath( const String& path ) const {
String tmpPath = path;
StrConv::trim( tmpPath );
StringList pathList;
StrConv::tokenize( tmpPath, pathList, '/' );
if ( pathList.front() == "" ) {
//this was a request for an absolute path
//so just pop off the first entry and continue
pathList.pop_front();
}
return _getPath( pathList );
}
//############################################################################
Widget* Screen::_getPath( StringList& pathList ) const {
if ( pathList.size() == 0 ) {
OG_THROW( Exception::ERR_INVALIDPARAMS, "Paths cannot resolve to Screen objects", __FUNCTION__ );
return 0;
}
const String top = pathList.front();
pathList.pop_front();
if ( !( top.length() > 0 ) ) {
OG_THROW( Exception::ERR_INVALIDPARAMS, "Empty path locations are not allowed", __FUNCTION__ );
return 0;
}
if ( top == "." ) {
return _getPath( pathList );
}
if ( top == ".." ) {
OG_THROW( Exception::OP_FAILED, "Cannot proceed above Screen. There is no higher container.", __FUNCTION__ );
return 0;
}
Widget* child = Children.getWidget( top );
if ( child ) {
return child->_getPath( pathList );
}
return 0;
}
//############################################################################
/*! A Screen cannot be truly active unless it is both set active, and has a valid Viewport assigned.
All Screens are created with the "active" flag set initially to true regardless of if they are
created already attached to a Viewport or not. This flag can be freely toggled regardless of
the presence or lack of a Viewport, but the Screen will never evaluate as "renderable" unless
it is both marked active and has an assigned Viewport.
*/
void Screen::setActive( bool active ) {
mActive = active;
}
//############################################################################
/*! \see setActive() */
bool Screen::isActive() {
return mActive;
}
//############################################################################
bool Screen::_isRenderable() {
return mActive && mViewport;
}
//############################################################################
const FVector2& Screen::getCursorPos() const {
return mCursorPos;
}
//############################################################################
FVector2 Screen::getCursorPos_Percent() const {
FVector2 ret = mCursorPos;
ret = mCursorPos / mSize;
return ret;
}
//############################################################################
unsigned int Screen::getObjectType() const {
return OT_SCREEN;
}
//############################################################################
}//namespace OpenGUI{
| [
"zeroskill@2828181b-9a0d-0410-a8fe-e25cbdd05f59"
]
| [
[
[
1,
702
]
]
]
|
18aa38d538bd14d6811333faabcc5fdeb66c7ef3 | 2514632f2787fd4cba7396f60e49f5968884c688 | /BulletDynamics/ConstraintSolver/shMolecularDynamicsConstraintSolver.cpp | 0156c8b12a4e3aa62cc5f21287b43247c47fba5e | []
| no_license | sabotage3d/pukak | 936555b001ac738f80c69d99e3e99b5ba16c3e11 | f84f5f683de5a454e233002c9c8a9ae7f2faab6c | refs/heads/master | 2021-01-01T15:41:08.973658 | 2010-04-30T16:43:04 | 2010-04-30T16:43:04 | 35,413,544 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 35,205 | cpp | #include "shMolecularDynamicsConstraintSolver.h"
#include "LinearMath/btQuickprof.h"
#include "BulletCollision/NarrowPhaseCollision/btPersistentManifold.h"
#include "BulletDynamics/ConstraintSolver/btContactSolverInfo.h"
#include "BulletDynamics/ConstraintSolver/btTypedConstraint.h"
#include "BulletDynamics/Dynamics/btRigidBody.h"
#include <math.h>
#include <iostream>
using std::cout;
using std::endl;
shMolecularDynamicsConstraintSolver::shMolecularDynamicsConstraintSolver()
{
CollisionHappened = 0.f;
}
shMolecularDynamicsConstraintSolver::~shMolecularDynamicsConstraintSolver()
{
}
// Required by abstract parent class definition
void shMolecularDynamicsConstraintSolver::reset()
{
CollisionHappened = 0.f;
} // reset()
btScalar shMolecularDynamicsConstraintSolver::solveGroup( btCollisionObject** bodies, int numBodies, btPersistentManifold** manifoldPtr, int numManifolds, btTypedConstraint** constraints, int numConstraints, const btContactSolverInfo& infoGlobal, btIDebugDraw* debugDrawer, btStackAlloc* stackAlloc, btDispatcher* /*dispatcher*/)
{
BT_PROFILE("solveGroup");
//we only implement SOLVER_CACHE_FRIENDLY now
//you need to provide at least some bodies
btAssert(bodies);
btAssert(numBodies);
// Iterate through all manifolds in manifoldPtr, computing each manifold's collision impulse for the deepest non-diverging point
// For each manifold, the computed impulse is used to update the velocities of BOTH bodies in the manifold
btScalar doRepeatCollisionsStep = solveCollisionConstraints( manifoldPtr, numManifolds, infoGlobal, debugDrawer, stackAlloc );
// RESET all of the btConstraintSolver and btSolverBody arrays
m_tmpSolverBodyPool.resize(0);
m_tmpSolverContactConstraintPool.resize(0);
m_tmpSolverNonContactConstraintPool.resize(0);
//m_tmpSolverContactFrictionConstraintPool.resize(0);
return doRepeatCollisionsStep; // If doRepeatCollisionsStep == 1.f, then the dynamics world knows to reset the objects' positions based on the new velocities and run collsions again
} // solveGroup()
// solveCollisionConstraints()
// This is the core loop of the nonconvex stacking collision algorithm, to go through each manifold and update the velocities of the respective colliding pairs
btScalar shMolecularDynamicsConstraintSolver::solveCollisionConstraints( btPersistentManifold** manifoldPtr, int numManifolds, const btContactSolverInfo& infoGlobal, btIDebugDraw* debugDrawer, btStackAlloc* stackAlloc )
{
BT_PROFILE("solveCollisionConstraints");
(void)stackAlloc;
(void)debugDrawer;
shSolverBody& fixedBody = m_tmpSolverBodyPool.expand(); // m_tmpSolverBodyPool is type btAlignedObjectArray<btSolverBody>
initSolverBody( &fixedBody, 0 ); // in this case, 0 passed in for btCollisionObject*, so mass,etc. are set to zero instead of an object's mass
if ( !numManifolds )
{
return 0.f;
} // if
//printf( "Num manifolds = %d\n", numManifolds );
CollisionHappened = 0.f;
// For each collision manifold,
// There is a btPersistentManifold object (manifold) for each collision in the current step
// There is a manifold for each pair of colliding objects
int numContacts = 0;
for ( int i = 0; i < numManifolds; i++ )
{
btPersistentManifold* manifold = manifoldPtr[i];
btScalar foundAndComputedCollision = 0.f;
btVector3 rBTot( 0, 0, 0 );
int numContacts = manifold->getNumContacts();
btCollisionObject* colObjB = (btCollisionObject*)manifold->getBody1(); // btPersistentManifold has getBody0() and getBody1(), so this grabs object B
/*for ( int j = 0; j < numContacts; j++ )
{
btManifoldPoint& cp = manifold->getContactPoint( j );
const btVector3& posB = cp.getPositionWorldOnB();
btVector3 rB = posB - colObjB->getWorldTransform().getOrigin();
printf( "rB %d = %f %f %f\n", j, rB.x(), rB.y(), rB.z() );
rBTot = btVector3( rBTot.x() + rB.x(), rBTot.y() + rB.y(), rBTot.z() + rB.z() );
} // for j*/
// compute impulse and resulting deltas for linear and angular velocities
// Compute impulses and UPDATE VELOCITIES for colliding objects based on each collision point in the manifold.
// Each collision point that is diverging is removed from the manifold
computeSoftSphereCollision( manifold, infoGlobal );
} // for i
return CollisionHappened; // If a collision happened, this process will need to be repeated.
} // solveCollisionConstraints()
// computeContactForDeepestNondivergingPointOnManifold()
// Returns 0.0 if there is NO collision
// Returns 1.0 if there IS a collision
btScalar shMolecularDynamicsConstraintSolver::computeSoftSphereCollision( btPersistentManifold* manifold, const btContactSolverInfo& infoGlobal )
{
// Extract the colliding objects from the manifold
btCollisionObject* colObjA = (btCollisionObject*)manifold->getBody0();
btCollisionObject* colObjB = (btCollisionObject*)manifold->getBody1();
btRigidBody* rbA = btRigidBody::upcast(colObjA);
btRigidBody* rbB = btRigidBody::upcast(colObjB);
// Set up a solver body (or retrieve an already existing one) for both colliding bodies.
// The solver bodies are stored in m_tmpSolverBodyPool
int solverBodyIdA = -1;
int solverBodyIdB = -1;
int numContacts = manifold->getNumContacts(); // All we care about is a single contact point
if ( numContacts )
{
solverBodyIdA = getOrInitSolverBody( *colObjA ); // Get the ID for object A's solverBody. If no solverBody exists for object A, create a new one, assign its ID to the object, and return the new ID
solverBodyIdB = getOrInitSolverBody( *colObjB ); // Get the ID for object B's solverBody. If no solverBody exists for object B, create a new one, assign its ID to the object, and return the new ID
} // if
/// avoid collision response between two static objects
if (!solverBodyIdA && !solverBodyIdB)
return btScalar(0.0); // 0.0 means no collision, we may eventually need another return option, such as -1.0 to report a static pair
// Set up the solverConstraint, for passing data around into the various methods called in this method
// A btSolverConstraint keeps track of values that define the constraint (eg. friction, impulse)
// In this implementation, we only need one btSolverConstraint per manifold, since we use only one collision pair in the manifold as the collision constraint
btSolverConstraint& solverConstraint = m_tmpSolverContactConstraintPool.expand();
solverConstraint.m_solverBodyIdA = solverBodyIdA;
solverConstraint.m_solverBodyIdB = solverBodyIdB;
// printf( "num contacts = %d\n", numContacts );
// Grab the deepest collision point (first in the point array) in the manifold
// Since we're dealing with spheres, this is all that matters
btManifoldPoint& cp = manifold->getContactPoint( 0 );
btVector3 contactNormal = -1 * cp.m_normalWorldOnB; // The collision normal is inverted here because we want to go from A to B (A will have the relative velocity).
contactNormal = contactNormal.normalize();
btScalar invMassA = rbA->getInvMass();
btScalar invMassB = rbB->getInvMass();
// Compute relative velocity of colliding objects, and split it into normal and tangential components
btScalar XiContactDepth = cp.getDistance();
btVector3 linVel1 = rbA->getLinearVelocity();
btVector3 linVel2 = rbB->getLinearVelocity();
btVector3 relVel = linVel1 - linVel2; // Relative velocity vector, of sphere1 (as if sphere2 were at rest)
btScalar relVelNMag = relVel.dot( contactNormal ); // Velocity vector magnitude in the normal (Xi) direction
btVector3 relVelN = relVelNMag * contactNormal;
btVector3 relVelT = relVel - relVelN;
btScalar relVelTMag = relVelT.length();
// NORMAL FORCES COMPUTATION
// Set up variables for the normal forces of the collision, which are treated as spring forces
btScalar alpha = 0.0; // determines whether relative position is included into the velocity term of the spring equation
btScalar beta = 1.0; // to control linearity of the force function
// Spring constants
btScalar e_n = 1.0; // Coefficient of normal restitution
btScalar t_c = 1.0; // Contact duration
btScalar log_e_n = log(e_n);
btScalar m_eff = btScalar(1.0) / ( invMassA + invMassB ); // Reduced mass
// Compute damping coefficient, kd, which influences the velocity term of the spring force equation
btScalar k_d = 2 * m_eff * ( -log_e_n / t_c );
// Compute elastic restoration coefficient, kr, which influences the penetration depth (also known as the "spring constant")
btScalar k_r = ( m_eff / t_c*t_c ) * ( log_e_n*log_e_n + (btScalar)PI_SQUARED );
// Compute relative velocity term of the spring equation
btScalar relativeVelocityTerm = k_d * relVelNMag;
if ( alpha != 0.0 ) relativeVelocityTerm = relativeVelocityTerm * pow( XiContactDepth, alpha );
// Compute relative position term of the spring equation
if ( beta != 1.0 ) XiContactDepth = pow( XiContactDepth, beta );
btScalar relativePositionTerm = k_r * XiContactDepth;
// Compute the normal force (with the spring force equation)
btScalar F_n = -1 * ( relativeVelocityTerm + relativePositionTerm ); // NORMAL FORCE
// TANGENTIAL (SHEAR) FORCES COMPUTATION
// Set up variables for the tangential forces of the collision (created by friction)
btScalar mu = 1.0; // Friction coefficient
btScalar k_t = 1.0; // Viscous damping constant
btScalar dampingTerm = -1 * min( (mu * F_n), (k_t*relVelTMag) );
// Compute the tangential force
btVector3 F_t = dampingTerm * (relVelT/relVelTMag);
// Set up the contact constraints
// This loops through each pair of contact points in the manifold
// If this loop finds a converging (colliding) pair of points, it computes the impulse for that pair then returns out of this method (loop over), reporting a collision (returns 1.0)
// Else, all pairs of points are diverging (no collision) and this method returns 0.0 (no converging points)
for ( int j = 0; j < numContacts; j++ )
{
// "manifold," of type btPersistentManifold, is a contact point cache (contains btManifoldPoint objects),
// and it stays persistent as long as objects are overlapping in the broadphase.
// A btManifoldPoint contains (and maintains) the positions of the two points in the contact (one for each object)
// as well as correlated values such as friction and restitution
btManifoldPoint& cp = manifold->getContactPoint( j );
// find or create solverBodys matching the rigidBodys
//int solverBodyIdA = getOrInitSolverBody(rbA); // a btSolverBody is a struct representing the body (object) and solves/computes change in velocities based off impulse,etc.; points back to its corresponding btRigidBody
//int solverBodyIdB = getOrInitSolverBody(rbB);
// Local velocity computation
// Computes local collision point positions relative to the centers of objects A and B respectively
const btVector3& posA = cp.getPositionWorldOnA();
const btVector3& posB = cp.getPositionWorldOnB();
btVector3 rA = posA - colObjA->getWorldTransform().getOrigin(); // rA = the vector from the center of mass (COM) to the collision point on object A
btVector3 rB = posB - colObjB->getWorldTransform().getOrigin(); // rB = the vector from the center of mass (COM) to the collision point on object B
//rB = btVector3( 0.0, rBTot.y(), 0.0 );
solverConstraint.m_relPos1 = rA;
solverConstraint.m_relPos2 = rB;
solverConstraint.m_friction = cp.m_combinedFriction;
solverConstraint.m_contactNormal = cp.m_normalWorldOnB;
// Calculate local velocities of the collision points and their relative velocity (the difference between the two points' velocities)
computeVelocitiesForCollisionPair( rbA, rbB, solverConstraint );
// COMPUTE WHETHER THE COLLIDING POINTS ARE HEADING TOWARD EACH OTHER (CONVERGING) OR NOT (DIVERGING)
// If the relative velocity is headed opposite the collision normal (the normal at point B)
// then the dot product is negative, meaning the two points are colliding (converging);
// otherwise if the dot product is positive, the two points are diverging and thus there is no collision
if ( solverConstraint.m_relVelNormalMagnitude >= 0.0 ) // diverging (if the points are diverging, there is no collision)
{
manifold->removeContactPoint( j );
continue;
} // if
else // converging (the points are colliding, or converging toward the separating plane)
{
// Compute the impulse vector for the current contact point
computeImpulseForCollisionPair( rbA, rbB, solverConstraint ); // Assigns the final impulse to solverConstraint.m_impulse
// Compute the delta velocities of the objects based on solverConstraint.m_impulse
applyImpulseForCollisionPair( rbA, rbB, solverConstraint );
updateVelocitiesForCollisionPair( solverBodyIdA, solverBodyIdB, rbA, rbB, infoGlobal.m_timeStep );
manifold->removeContactPoint( j );
return btScalar(1.f); // Returning 1.0 flags that we resolved a collision and thus will have to iterate through all the manifolds again
} // else
} // for j
// If you got here in the code, all points in the manifold were diverging
return btScalar(0.f);
} // computeContactForDeepestNondivergingPointOnManifold()
// computeVelocitiesForCollisionPair()
// The solverConstraint MUST have the following attributes already set:
// m_relPos1
// m_relPos2
// m_contactNormal
// This method will set the following solverConstraint attributes:
// m_relativeVelocity
// m_relVelNormalMagnitude
void shMolecularDynamicsConstraintSolver::computeVelocitiesForCollisionPair( btRigidBody* rbA, btRigidBody* rbB, btSolverConstraint& solverConstraint )
{
btVector3 rA = solverConstraint.m_relPos1;
btVector3 rB = solverConstraint.m_relPos2;
//btVector3 linvel1 = rbA->getLinearVelocity();
btVector3 linvel2 = rbB->getLinearVelocity();
//btVector3 linvel1 = rbA->getLinearVelocity();
btVector3 angvel2 = rbB->getAngularVelocity();
//printf( "m_linearVelocity A = %f %f %f\n", linvel1[0], linvel1[1], linvel1[2] );
printf( "1.m_linearVelocity B = %f %f %f\n", linvel2[0], linvel2[1], linvel2[2] );
printf( "1.m_angularVelocity B = %f %f %f\n", angvel2[0], angvel2[1], angvel2[2] );
btVector3 velA = rbA ? rbA->getVelocityInLocalPoint( rA ) : btVector3( 0,0,0 ); // Get the velocity at the given position on surface A (adds the linear and angular velocities at that point)
btVector3 velB = rbB ? rbB->getVelocityInLocalPoint( rB ) : btVector3( 0,0,0 ); // Get the velocity at the given position on surface B (adds the linear and angular velocities at that point)
//printf( "rA = %f %f %f\n", rA.x(), rA.y(), rA.z() );
//printf( "rB = %f %f %f\n", rB.x(), rB.y(), rB.z() );
//printf( "VelA = %f %f %f\n", velA.x(), velA.y(), velA.z() );
//printf( "VelB = %f %f %f\n", velB.x(), velB.y(), velB.z() );
// COMPUTE RELATIVE VELOCITY OF THE COLLISION POINT
// Compute the relative velocity of the two collision points
// The variable uRelNormalMagnitude will represent both the magnitude of the point's velocity in the normal direction
// as well as the relative direction of the colliding points (whether they are coming together or moving apart, converging or diverging).
btVector3 uRel = velA - velB; // uRel is the relative velocity
btScalar uRelN = solverConstraint.m_contactNormal.dot( uRel ); // uRel is the relative velocity, and uRelN is uRel's magnitude (scalar) in the normal direction
//printf( "Relative velocity = %f %f %f\n", uRel.x(), uRel.y(), uRel.z() );
// Set the solverConstraint values for passing into computeImpulseForCollisionPair()
solverConstraint.m_relativeVelocity = uRel;
solverConstraint.m_relVelNormalMagnitude = uRelN;
} // computeVelocitiesForCollisionPair()
// computeImpulseForCollisionPair()
// The solverConstraint MUST have the following attributes already set:
// m_relPos1
// m_relPos2
// m_contactNormal
// m_relativeVelocity
// m_relVelNormalMagnitude (currently, since uRelN had to be computed in the parent method, this method does not recompute it even though it could do so)
// m_friction
// Assigns the final impulse to solverConstraint.m_impulse
void shMolecularDynamicsConstraintSolver::computeImpulseForCollisionPair( btRigidBody* rbA, btRigidBody* rbB, btSolverConstraint& solverConstraint )
{
btVector3 rA = solverConstraint.m_relPos1;
btVector3 rB = solverConstraint.m_relPos2;
btVector3 collisionNormal = solverConstraint.m_contactNormal;
//printf( "Contact Normal = %f %f %f\n", collisionNormal.x(), collisionNormal.y(), collisionNormal.z() );
btVector3 uRel = solverConstraint.m_relativeVelocity;
btScalar uRelN = solverConstraint.m_relVelNormalMagnitude;
btScalar friction = solverConstraint.m_friction;
// the restitution (epsilon) equals the lesser restitution of the two objects
btScalar restitution = 0.f;
btScalar restitutionA = rbA->getRestitution();
btScalar restitutionB = rbB->getRestitution();
if ( restitutionA < restitutionB )
restitution = restitutionA;
else
restitution = restitutionB;
// K-matrix calculation.
// We already have rA and rB, now we need to compute rA* and rB*, which are the matrix representations for doing the cross product
btMatrix3x3 rCrossMatrixA( 0.0, -rA[2], rA[1],
rA[2], 0.0, -rA[0],
-rA[1], rA[0], 0.0 );
btMatrix3x3 rCrossMatrixB( 0.0, -rB[2], rB[1],
rB[2], 0.0, -rB[0],
-rB[1], rB[0], 0.0 );
// Linear velocity term (delta/mass), where delta = the identity matrix, and mass = the mass of each object.
// This inverse mass matrix multiplied by impulse = the deltaLinearVelocity
float iMassA = rbA->getInvMass();
float iMassB = rbB->getInvMass();
btMatrix3x3 invMassMatrixA( iMassA, 0.0, 0.0,
0.0, iMassA, 0.0,
0.0, 0.0, iMassA );
btMatrix3x3 invMassMatrixB( iMassB, 0.0, 0.0,
0.0, iMassB, 0.0,
0.0, 0.0, iMassB );
//printf( "Mass B, Inv Mass B = %f %f\n", 1.0/iMassB, iMassB );
// Angular velocity term ((r*)(Iinv)(r*)), where r* is the cross product matrix computed above, and Iinv = inverse of the inertia tensor (the angular momentum of the object).
btMatrix3x3 invMomentOfInertiaA = rbA->getInvInertiaTensorWorld();
btMatrix3x3 invMomentOfInertiaB = rbB->getInvInertiaTensorWorld();
//printf("Moment of Inertia:\n");
//printf(" %f %f %f\n", invMomentOfInertiaB.getRow(0).x(), invMomentOfInertiaB.getRow(0).y(), invMomentOfInertiaB.getRow(0).z() );
//printf(" %f %f %f\n", invMomentOfInertiaB.getRow(1).x(), invMomentOfInertiaB.getRow(1).y(), invMomentOfInertiaB.getRow(1).z() );
//printf(" %f %f %f\n", invMomentOfInertiaB.getRow(2).x(), invMomentOfInertiaB.getRow(2).y(), invMomentOfInertiaB.getRow(2).z() );
btMatrix3x3 KA = invMassMatrixA + ( rCrossMatrixA.transpose() * invMomentOfInertiaA * rCrossMatrixA );
btMatrix3x3 KB = invMassMatrixB + ( rCrossMatrixB.transpose() * invMomentOfInertiaB * rCrossMatrixB );
btMatrix3x3 K = KA + KB;
//printf("KA:\n");
//printf(" %f %f %f\n", KA.getRow(0).x(), KA.getRow(0).y(), KA.getRow(0).z() );
//printf(" %f %f %f\n", KA.getRow(1).x(), KA.getRow(1).y(), KA.getRow(1).z() );
//printf(" %f %f %f\n", KA.getRow(2).x(), KA.getRow(2).y(), KA.getRow(2).z() );
//printf("KB:\n");
//printf(" %f %f %f\n", KB.getRow(0).x(), KB.getRow(0).y(), KB.getRow(0).z() );
//printf(" %f %f %f\n", KB.getRow(1).x(), KB.getRow(1).y(), KB.getRow(1).z() );
//printf(" %f %f %f\n", KB.getRow(2).x(), KB.getRow(2).y(), KB.getRow(2).z() );
// Friction calculation.
// We are using BULLET's method (for friction only).
btVector3 uRelNormal = collisionNormal * uRelN; // normal-component of the collision point's relative velocity, uRel
btVector3 uRelTangent = uRel - uRelNormal; // tangent-component of the collision point's relative velocity, uRel
// Determine if friction should be included in the impulse computation.
// **** NOT COMPLETED ****
bool applyFriction = false; // To be determined in more detail later, for now we are ignoring friction, though some of the math is already implemented in NAdjustedForFriction above
// Impulse calculation.
//btScalar finalURelN = btScalar(-1.0) * restitution * uRelN;
btVector3 NK = collisionNormal * K; // Properly does "row matrix * matrix" => row matrix
btScalar NKN;
if ( applyFriction )
{
btVector3 T = uRelTangent / uRelTangent.length();
btVector3 NAdjustedForFriction = collisionNormal - T * friction;
NKN = NK.dot( NAdjustedForFriction ); // Properly does "row matrix * column matrix" (in other words, vector.vector)
} // if
else
NKN = NK.dot( collisionNormal ); // Properly does "row matrix * column matrix" (in other words, vector.vector)
//printf( "uRelN = %f\n", uRelN );
printf( "restitution = %f\n", restitution );
//printf( "NKN = %f\n", NKN );
btScalar jN = ( btScalar(-1.0) * uRelN * (restitution + btScalar(1.0)) ) / NKN; // jN is the IMPULSE MAGNITUDE
solverConstraint.m_impulse = jN * collisionNormal; // FINAL IMPULSE CALCULATION
//printf( " IMPULSE = %f %f %f\n", solverConstraint.m_impulse[0], solverConstraint.m_impulse[1], solverConstraint.m_impulse[2] );
} // computeImpulseForCollisionPair()
void shMolecularDynamicsConstraintSolver::applyImpulseForCollisionPair( btRigidBody* rbA, btRigidBody* rbB, btSolverConstraint& solverConstraint )
{//printf( "applying impulses\n" );
btScalar iMassA = rbA->getInvMass();
btScalar iMassB = rbB->getInvMass();
// Compute the deltas in both linear and angular velocities for both objects in the collision pair
btVector3 deltaLinearVelocityA = solverConstraint.m_impulse * iMassA; // multiply the impulse times 1/massA (the mass's inverse)
btVector3 deltaLinearVelocityB = btScalar(-1.f)*solverConstraint.m_impulse * iMassB; // multiply the impulse times 1/massB (the mass's inverse)
btVector3 rA = solverConstraint.m_relPos1;
btVector3 rB = solverConstraint.m_relPos2;
btVector3 deltaAngularVelocityA = rbA->getInvInertiaTensorWorld() * ( rA.cross(solverConstraint.m_impulse) ); // matrix * column matrix (rA.cross(impulse) returns a vector that is properly treated as a column matrix)
btVector3 deltaAngularVelocityB = rbB->getInvInertiaTensorWorld() * ( rB.cross(btScalar(-1.f)*solverConstraint.m_impulse) ); // matrix * column matrix (rB.cross(impulse) returns a vector that is properly treated as a column matrix)
//printf( "The delta angular velocity of B = %f %f %f\n", deltaAngularVelocityB[0], deltaAngularVelocityB[1], deltaAngularVelocityB[2] );
// Update the deltas for the linear and angular velocities
// btVector3(0,0,0) );//
m_tmpSolverBodyPool[solverConstraint.m_solverBodyIdA].applyImpulse( deltaLinearVelocityA, deltaAngularVelocityA ); // In updateVelocities(), solverBody.writebackVelocity() will be called to apply these updates
m_tmpSolverBodyPool[solverConstraint.m_solverBodyIdB].applyImpulse( deltaLinearVelocityB, deltaAngularVelocityB ); // In updateVelocities(), solverBody.writebackVelocity() will be called to apply these updates
} // applyImpulseForCollisionPair()
void shMolecularDynamicsConstraintSolver::updateVelocitiesForCollisionPair( int objectIdA, int objectIdB, btRigidBody* rbA, btRigidBody* rbB, btScalar timeStep ) {
// writebackVelocity() adds m_deltaLinearVelocity to this object's linear velocity and m_deltaAngularVelocity to this objects angular velocity
// and updates the corresponding rigid body's linear and angular velocities
m_tmpSolverBodyPool[objectIdA].writebackVelocity();
m_tmpSolverBodyPool[objectIdB].writebackVelocity();
btVector3 linvel2 = rbB->getLinearVelocity();
btVector3 angvel2 = rbB->getAngularVelocity();
printf( "2.m_linearVelocity B = %f %f %f\n", linvel2[0], linvel2[1], linvel2[2] );
printf( "2.m_angularVelocity B = %f %f %f\n", angvel2[0], angvel2[1], angvel2[2] );
/*if ( !rbA->isStaticOrKinematicObject() )
{
btTransform predictedTrans;
rbA->predictIntegratedTransform( timeStep, predictedTrans );
rbA->updateInertiaTensor( predictedTrans );
} // if
if ( !rbB->isStaticOrKinematicObject() )
{
btTransform predictedTrans;
printf("\n");
printf("Before:\n");
printf(" %f %f %f\n", predictedTrans.getBasis().getRow(0).x(), predictedTrans.getBasis().getRow(0).y(), predictedTrans.getBasis().getRow(0).z() );
printf(" %f %f %f\n", predictedTrans.getBasis().getRow(1).x(), predictedTrans.getBasis().getRow(1).y(), predictedTrans.getBasis().getRow(1).z() );
printf(" %f %f %f\n", predictedTrans.getBasis().getRow(2).x(), predictedTrans.getBasis().getRow(2).y(), predictedTrans.getBasis().getRow(2).z() );
printf("\n");
rbB->predictIntegratedTransform( timeStep, predictedTrans );
rbB->updateInertiaTensor( predictedTrans );
printf("After:\n");
printf(" %f %f %f\n", predictedTrans.getBasis().getRow(0).x(), predictedTrans.getBasis().getRow(0).y(), predictedTrans.getBasis().getRow(0).z() );
printf(" %f %f %f\n", predictedTrans.getBasis().getRow(1).x(), predictedTrans.getBasis().getRow(1).y(), predictedTrans.getBasis().getRow(1).z() );
printf(" %f %f %f\n", predictedTrans.getBasis().getRow(2).x(), predictedTrans.getBasis().getRow(2).y(), predictedTrans.getBasis().getRow(2).z() );
printf("\n");
} // if*/
} // updateVelocities()
// solveBodyConstraints()
// Copied over from the body constraints portion of btSequentialImpulseConstraintSolver::solveGroupCacheFriendlySetup()
btScalar shMolecularDynamicsConstraintSolver::solveNonContactConstraints( btTypedConstraint** constraints, int numConstraints, const btContactSolverInfo& infoGlobal, btIDebugDraw* debugDrawer, btStackAlloc* stackAlloc )
{
if ( !numConstraints ) // if no constraints and no collisions
{
return 0.f;
} // if
// Constraints are manually added when the scene is built,
// so for scenes like BasicDemo where no constraints are defined, numConstraints = 0, and this for-loop is not entered
int j;
for ( j=0; j<numConstraints; j++ )
{
btTypedConstraint* constraint = constraints[j];
constraint->buildJacobian();
}
// expand() adds another btSolverBody to the end of m_tmpSolverBodyPool and returns that end btSolverBody, then initSolverBody() inits that btSolverBody's values
shSolverBody& fixedBody = m_tmpSolverBodyPool.expand(); // m_tmpSolverBodyPool is type btAlignedObjectArray<btSolverBody>
initSolverBody( &fixedBody, 0 ); // in this case, 0 passed in for btCollisionObject*, so mass,etc. are set to zero instead of an object's mass
//btRigidBody* rb0=0,*rb1=0;
// set up and solve the constraints (see btTypedConstraint.h for the enumeration of constraint types)
// Again, scenes won't have any constraints (such as BasicDemo) unless they are hard coded into the scene (such as in RagdollDemo)
{
int totalNumRows = 0;
int i;
//calculate the total number of contraint rows
for ( i=0; i<numConstraints; i++ )
{
btTypedConstraint::btConstraintInfo1 info1;
constraints[i]->getInfo1(&info1);
totalNumRows += info1.m_numConstraintRows;
} // for i
m_tmpSolverNonContactConstraintPool.resize(totalNumRows);
btTypedConstraint::btConstraintInfo1 info1;
info1.m_numConstraintRows = 0;
// setup the btSolverConstraints
//
int currentRow = 0;
for ( i=0; i<numConstraints; i++,currentRow+=info1.m_numConstraintRows )
{
constraints[i]->getInfo1(&info1);
if (info1.m_numConstraintRows)
{
btAssert(currentRow<totalNumRows);
btSolverConstraint* currentConstraintRow = &m_tmpSolverNonContactConstraintPool[currentRow];
btTypedConstraint* constraint = constraints[i];
btRigidBody& rbA = constraint->getRigidBodyA(); // a btRigidBody is a class that keeps track of and updates the rigid body object's current attributes
btRigidBody& rbB = constraint->getRigidBodyB();
// find or create solverBodys matching the rigidBodys
int solverBodyIdA = getOrInitSolverBody(rbA); // a btSolverBody is a struct representing the body (object) and solves/computes change in velocities based off impulse,etc.; points back to its corresponding btRigidBody
int solverBodyIdB = getOrInitSolverBody(rbB);
btSolverBody* bodyAPtr = &m_tmpSolverBodyPool[solverBodyIdA];
btSolverBody* bodyBPtr = &m_tmpSolverBodyPool[solverBodyIdB];
// Each typeConstraint (constraint) has multiple corresponding solverConstraints (array currentConstraintRow)
// The number of solverConstraints needed by the current typeConstraint is determined by info1, which was set up by typeConstraint->getInfo1()
int j;
for ( j=0; j<info1.m_numConstraintRows; j++ )
{
memset(¤tConstraintRow[j],0,sizeof(btSolverConstraint));
currentConstraintRow[j].m_lowerLimit = -FLT_MAX;
currentConstraintRow[j].m_upperLimit = FLT_MAX;
currentConstraintRow[j].m_appliedImpulse = 0.f;
currentConstraintRow[j].m_appliedPushImpulse = 0.f;
currentConstraintRow[j].m_solverBodyIdA = solverBodyIdA;
currentConstraintRow[j].m_solverBodyIdB = solverBodyIdB;
}
bodyAPtr->m_deltaLinearVelocity.setValue(0.f,0.f,0.f);
bodyAPtr->m_deltaAngularVelocity.setValue(0.f,0.f,0.f);
bodyBPtr->m_deltaLinearVelocity.setValue(0.f,0.f,0.f);
bodyBPtr->m_deltaAngularVelocity.setValue(0.f,0.f,0.f);
btTypedConstraint::btConstraintInfo2 info2;
info2.fps = 1.f/infoGlobal.m_timeStep;
info2.erp = infoGlobal.m_erp;
info2.m_J1linearAxis = currentConstraintRow->m_contactNormal;
info2.m_J1angularAxis = currentConstraintRow->m_relpos1CrossNormal;
info2.m_J2linearAxis = 0;
info2.m_J2angularAxis = currentConstraintRow->m_relpos2CrossNormal;
info2.rowskip = sizeof(btSolverConstraint)/sizeof(btScalar);//check this
///the size of btSolverConstraint needs be a multiple of btScalar
btAssert(info2.rowskip*sizeof(btScalar)== sizeof(btSolverConstraint));
info2.m_constraintError = ¤tConstraintRow->m_rhs;
info2.cfm = ¤tConstraintRow->m_cfm;
info2.m_lowerLimit = ¤tConstraintRow->m_lowerLimit;
info2.m_upperLimit = ¤tConstraintRow->m_upperLimit;
constraints[i]->getInfo2(&info2);
// Finalize the constraint setup
// All the solverConstraints in currentConstraintRow were recently initialized and assigned a pair of solverBodyIds (see approx. 30 lines up)
// Then compute the angular components, rhs, and applied impulse for each of those solver constraints
// Each constraint has its own row of solverConstraints
for ( j=0; j<info1.m_numConstraintRows; j++ )
{
btSolverConstraint& solverConstraint = currentConstraintRow[j];
{
const btVector3& ftorqueAxis1 = solverConstraint.m_relpos1CrossNormal;
solverConstraint.m_angularComponentA = constraint->getRigidBodyA().getInvInertiaTensorWorld() * ftorqueAxis1 * constraint->getRigidBodyA().getAngularFactor();
}
{
const btVector3& ftorqueAxis2 = solverConstraint.m_relpos2CrossNormal;
solverConstraint.m_angularComponentB = constraint->getRigidBodyB().getInvInertiaTensorWorld()*ftorqueAxis2*constraint->getRigidBodyB().getAngularFactor();
}
{
btVector3 iMJlA = solverConstraint.m_contactNormal * rbA.getInvMass();
btVector3 iMJaA = rbA.getInvInertiaTensorWorld() * solverConstraint.m_relpos1CrossNormal;
btVector3 iMJlB = solverConstraint.m_contactNormal * rbB.getInvMass();//sign of normal?
btVector3 iMJaB = rbB.getInvInertiaTensorWorld() * solverConstraint.m_relpos2CrossNormal;
btScalar sum = iMJlA.dot(solverConstraint.m_contactNormal);
sum += iMJaA.dot(solverConstraint.m_relpos1CrossNormal);
sum += iMJlB.dot(solverConstraint.m_contactNormal);
sum += iMJaB.dot(solverConstraint.m_relpos2CrossNormal);
solverConstraint.m_jacDiagABInv = btScalar(1.)/sum;
}
///fix rhs
///todo: add force/torque accelerators
{
btScalar rel_vel;
btScalar vel1Dotn = solverConstraint.m_contactNormal.dot(rbA.getLinearVelocity()) + solverConstraint.m_relpos1CrossNormal.dot(rbA.getAngularVelocity());
btScalar vel2Dotn = -solverConstraint.m_contactNormal.dot(rbB.getLinearVelocity()) + solverConstraint.m_relpos2CrossNormal.dot(rbB.getAngularVelocity());
rel_vel = vel1Dotn+vel2Dotn;
btScalar restitution = 0.f;
btScalar positionalError = solverConstraint.m_rhs;//already filled in by getConstraintInfo2
btScalar velocityError = restitution - rel_vel;// * damping;
btScalar penetrationImpulse = positionalError*solverConstraint.m_jacDiagABInv;
btScalar velocityImpulse = velocityError *solverConstraint.m_jacDiagABInv;
solverConstraint.m_rhs = penetrationImpulse + velocityImpulse;
solverConstraint.m_appliedImpulse = 0.f;
}
}
}
}
}
// solverConstraints are now done being set up for btTypeConstraints
return 1.f;
} // solveBodyConstraints()
void shMolecularDynamicsConstraintSolver::initSolverBody( shSolverBody* solverBody, btCollisionObject* collisionObject )
{
btRigidBody* rb = collisionObject ? btRigidBody::upcast(collisionObject) : 0;
solverBody->m_deltaLinearVelocity.setValue(0.f,0.f,0.f);
solverBody->m_deltaAngularVelocity.setValue(0.f,0.f,0.f);
if (rb)
{
//solverBody->m_invMass = rb->getInvMass();
solverBody->m_originalBody = rb;
solverBody->m_angularFactor = rb->getAngularFactor();
} // if
else
{
//solverBody->m_invMass = 0.f;
solverBody->m_originalBody = 0;
//solverBody->m_angularFactor = 1.f;
solverBody->m_angularFactor.setValue(1.f, 1.f, 1.f);
} // else
} // initSolverBody()
int shMolecularDynamicsConstraintSolver::getOrInitSolverBody( btCollisionObject& body )
{
int solverBodyIdA = -1;
if ( body.getCompanionId() >= 0 )
{
//body has already been converted
solverBodyIdA = body.getCompanionId();
} // if
else
{
btRigidBody* rb = btRigidBody::upcast( &body );
if ( rb && rb->getInvMass() )
{
solverBodyIdA = m_tmpSolverBodyPool.size();
shSolverBody& solverBody = m_tmpSolverBodyPool.expand();
initSolverBody( &solverBody, &body );
body.setCompanionId( solverBodyIdA );
} // if
else
{
return 0; //assume first one is a fixed solver body
} // else
} // else
return solverBodyIdA;
} // getOrInitSolverBody()
bool shMolecularDynamicsConstraintSolver::thereWasACollision() {
if ( CollisionHappened != 0.f )
return true;
else
return false;
} // didAnythingCollide()
| [
"seth.holladay@b0b181a8-020e-11df-8f7b-bfe16de6f99b"
]
| [
[
[
1,
751
]
]
]
|
a2fcfdf60f8ee02b7de46358b5ce12111df1bb7a | b22c254d7670522ec2caa61c998f8741b1da9388 | /dependencies/OpenSceneGraph/include/osg/Vec2s | d3ab7c673eb30fdd55cd13fcacc59a9ad98b0055 | []
| no_license | ldaehler/lbanet | 341ddc4b62ef2df0a167caff46c2075fdfc85f5c | ecb54fc6fd691f1be3bae03681e355a225f92418 | refs/heads/master | 2021-01-23T13:17:19.963262 | 2011-03-22T21:49:52 | 2011-03-22T21:49:52 | 39,529,945 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,252 | /* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* OpenSceneGraph Public License for more details.
*/
#ifndef OSG_VEC2S
#define OSG_VEC2S 1
namespace osg {
class Vec2s
{
public:
/** Type of Vec class.*/
typedef short value_type;
/** Number of vector components. */
enum { num_components = 2 };
value_type _v[2];
Vec2s() { _v[0]=0; _v[1]=0; }
Vec2s(value_type x, value_type y) { _v[0] = x; _v[1] = y; }
inline bool operator == (const Vec2s& v) const { return _v[0]==v._v[0] && _v[1]==v._v[1]; }
inline bool operator != (const Vec2s& v) const { return _v[0]!=v._v[0] || _v[1]!=v._v[1]; }
inline bool operator < (const Vec2s& v) const
{
if (_v[0]<v._v[0]) return true;
else if (_v[0]>v._v[0]) return false;
else return (_v[1]<v._v[1]);
}
inline value_type* ptr() { return _v; }
inline const value_type* ptr() const { return _v; }
inline void set( value_type x, value_type y)
{
_v[0]=x; _v[1]=y;
}
inline void set( const Vec2s& rhs)
{
_v[0]=rhs._v[0]; _v[1]=rhs._v[1];
}
inline value_type& operator [] (int i) { return _v[i]; }
inline value_type operator [] (int i) const { return _v[i]; }
inline value_type& x() { return _v[0]; }
inline value_type& y() { return _v[1]; }
inline value_type x() const { return _v[0]; }
inline value_type y() const { return _v[1]; }
inline value_type& r() { return _v[0]; }
inline value_type& g() { return _v[1]; }
inline value_type r() const { return _v[0]; }
inline value_type g() const { return _v[1]; }
inline Vec2s operator * (value_type rhs) const
{
return Vec2s(_v[0]*rhs, _v[1]*rhs);
}
inline Vec2s& operator *= (value_type rhs)
{
_v[0]*=rhs;
_v[1]*=rhs;
return *this;
}
inline Vec2s operator / (value_type rhs) const
{
return Vec2s(_v[0]/rhs, _v[1]/rhs);
}
inline Vec2s& operator /= (value_type rhs)
{
_v[0]/=rhs;
_v[1]/=rhs;
return *this;
}
inline Vec2s operator * (const Vec2s& rhs) const
{
return Vec2s(_v[0]*rhs._v[0], _v[1]*rhs._v[1]);
}
inline Vec2s operator + (const Vec2s& rhs) const
{
return Vec2s(_v[0]+rhs._v[0], _v[1]+rhs._v[1]);
}
inline Vec2s& operator += (const Vec2s& rhs)
{
_v[0] += rhs._v[0];
_v[1] += rhs._v[1];
return *this;
}
inline Vec2s operator - (const Vec2s& rhs) const
{
return Vec2s(_v[0]-rhs._v[0], _v[1]-rhs._v[1]);
}
inline Vec2s& operator -= (const Vec2s& rhs)
{
_v[0]-=rhs._v[0];
_v[1]-=rhs._v[1];
return *this;
}
inline Vec2s operator - () const
{
return Vec2s (-_v[0], -_v[1]);
}
}; // end of class Vec2s
/** multiply by vector components. */
inline Vec2s componentMultiply(const Vec2s& lhs, const Vec2s& rhs)
{
return Vec2s(lhs[0]*rhs[0], lhs[1]*rhs[1]);
}
/** divide rhs components by rhs vector components. */
inline Vec2s componentDivide(const Vec2s& lhs, const Vec2s& rhs)
{
return Vec2s(lhs[0]/rhs[0], lhs[1]/rhs[1]);
}
} // end of namespace osg
#endif
| [
"vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13"
]
| [
[
[
1,
148
]
]
]
|
|
e60a1d6e69e32a7d08f3a038beac2fa26190bd2f | 2fdbf2ba994ba3ed64f0e2dc75cd2dfce4936583 | /spectre/dom/domelement.h | 263202a9a58f80bb3f51e0ed9cad2d6e2d60d746 | []
| no_license | TERRANZ/terragraph | 36219a4e512e15a925769512a6b60637d39830bf | ea8c36070f532ad0a4af08e46b19f4ee1b85f279 | refs/heads/master | 2020-05-25T10:31:26.994233 | 2011-01-29T21:23:04 | 2011-01-29T21:23:04 | 1,047,237 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,033 | h | #ifndef DOMELEMENT_H
#define DOMELEMENT_H
#include <QtXml>
#include <string>
#include <list>
#include "domnode.h"
using namespace std;
class DomElement: public DomNode
{
public:
DomElement();
private:
DomElement(const QDomNode &qDomNode);
public:
string tagName() const;
string attribute(const string &name, const string &defaultValue = "") const;
void clearAttributes();
void setTagName(const string &tagName);
void setAttribute(const string &name, const string &value);
void setAttribute(const string &name, int value);
void setAttribute(const string &name, float value);
DomElement elementByTagNameAndIndex(const string &tagName = "", int index = 0) const;
list<DomElement> elementsByTagName(const string &tagName = "") const;
DomElement nextElement(const string &tagName = "");
DomElement previousElement(const string &tagName = "");
private:
friend class DomDocument;
friend class DomNode;
};
#endif // DOMELEMENT_H
| [
"[email protected]"
]
| [
[
[
1,
41
]
]
]
|
eb87a35e3304f31108d9c2abc664560bb849dfaa | 413d5224c2cc2c710e047cdd9cf87e509cfb6a36 | /Zadanie6/Zadanie6MOJE.cpp | e278461dd4855fa485379534cb9c07fe9f8aa4bc | []
| no_license | mzbikows/CodeCPP | 83b6276576f2d9ffbaad0a2f094cdf991d71d990 | be28f185496b811fe79efe2424bfe33a8cf5d1e5 | refs/heads/master | 2020-05-20T13:03:49.802006 | 2010-12-26T19:11:31 | 2010-12-26T19:11:31 | 1,185,141 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,173 | cpp | #include <iostream>
#include <cstdlib>
using namespace std;
/***************************************/
enum Banks {PKO, BGZ, BRE, BPH};
/***************************************/
struct Account
{
Banks bank;
int balance;
};
struct Person
{
char name[20];
Account account;
};
struct Couple
{
Person he;
Person she;
};
/***************************************/
Couple* bestClient(Couple* cpls, int size, Banks bank)
{
int counter_max;
int max_balance;
bool mark;
if (size == 0) return NULL;
else
{
for(int counter = 0; counter < size; ++counter)
{
if( (cpls[counter].he.account.bank == bank) || (cpls[counter].she.account.bank == bank) )
{
if(mark==0)
{
counter_max=counter;
max_balance=cpls[counter].he.account.balance + cpls[counter].she.account.balance;
mark = 1;
}
if((mark == 1) && (max_balance<cpls[counter].he.account.balance + cpls[counter].she.account.balance))
{
counter_max = counter;
max_balance = cpls[counter].he.account.balance + cpls[counter].she.account.balance;
}
}
}
if(mark==0)
{
return NULL;
}
else
{
return (&(cpls[counter_max]));
}
}
}
/***************************************/
void ShowCouple(Couple* p)
{
if (p == NULL)
{
cout << "Zadana osoba z par nie ma konta w podanym banku" << endl;
}
else
{
cout << (p->he).name << " and " << (p->she).name
<< " : " << (p->he).account.balance + (p->she).account.balance
<< endl;
}
}
int main()
{
Couple cpls[4];
Couple *p;
/**************JOHNY********************/
cpls[0].he.name[0] = 'J';
cpls[0].he.name[1] = 'o';
cpls[0].he.name[2] = 'h';
cpls[0].he.name[3] = 'n';
cpls[0].he.name[4] = 'y';
cpls[0].he.name[5] = (char)NULL;
cpls[0].he.account.bank = PKO;
cpls[0].he.account.balance = 1100;
/**************MARY********************/
cpls[0].she.name[0] = 'M';
cpls[0].she.name[1] = 'a';
cpls[0].she.name[2] = 'r';
cpls[0].she.name[3] = 'y';
cpls[0].she.name[4] = (char)NULL;
cpls[0].she.account.bank = BGZ;
cpls[0].she.account.balance = 1500;
/*--------------------------------------------*/
/**************PETER********************/
cpls[1].he.name[0] = 'P';
cpls[1].he.name[1] = 'e';
cpls[1].he.name[2] = 't';
cpls[1].he.name[3] = 'e';
cpls[1].he.name[4] = 'r';
cpls[1].he.name[5] = (char) NULL;
cpls[1].he.account.bank = BGZ;
cpls[1].he.account.balance = 1400;
/**************SUZY********************/
cpls[1].she.name[0] = 'S';
cpls[1].she.name[1] = 'u';
cpls[1].she.name[2] = 'z';
cpls[1].she.name[3] = 'y';
cpls[1].she.name[4] = (char) NULL;
cpls[1].she.account.bank = BRE;
cpls[1].she.account.balance = 1300;
/*--------------------------------------------*/
/**************KEVIN********************/
cpls[2].he.name[0] = 'K';
cpls[2].he.name[1] = 'e';
cpls[2].he.name[2] = 'v';
cpls[2].he.name[3] = 'i';
cpls[2].he.name[4] = 'n';
cpls[2].he.name[5] = (char) NULL;
cpls[2].he.account.bank = PKO;
cpls[2].he.account.balance = 1600;
/**************KATY********************/
cpls[2].she.name[0] = 'K';
cpls[2].she.name[1] = 'a';
cpls[2].she.name[2] = 't';
cpls[2].she.name[3] = 'y';
cpls[2].she.name[4] = (char) NULL;
cpls[2].she.account.bank = BPH;
cpls[2].she.account.balance = 1500;
/*--------------------------------------------*/
/**************KENNY********************/
cpls[3].he.name[0] = 'K';
cpls[3].he.name[1] = 'e';
cpls[3].he.name[2] = 'n';
cpls[3].he.name[3] = 'n';
cpls[3].he.name[4] = 'y';
cpls[3].he.name[5] = (char) NULL;
cpls[3].he.account.bank = BPH;
cpls[3].he.account.balance = 1800;
/**************LUCY********************/
cpls[3].she.name[0] = 'L';
cpls[3].she.name[1] = 'u';
cpls[3].she.name[2] = 'c';
cpls[3].she.name[3] = 'y';
cpls[3].she.name[4] = (char) NULL;
cpls[3].she.account.bank = BRE;
cpls[3].she.account.balance = 1700;
/*--------------------------------------------*/
p = bestClient(cpls, 4, BGZ);
ShowCouple(p);
//system("pause");
return 0;
}
| [
"[email protected]"
]
| [
[
[
1,
168
]
]
]
|
ba372886d632c035cb78aacf956dbc1100df1dd3 | b22c254d7670522ec2caa61c998f8741b1da9388 | /dependencies/OsgAl/include/openalpp/GroupSource | 3e3324b74d21db0c28fb8dd4e9968b10f733eb9f | []
| no_license | ldaehler/lbanet | 341ddc4b62ef2df0a167caff46c2075fdfc85f5c | ecb54fc6fd691f1be3bae03681e355a225f92418 | refs/heads/master | 2021-01-23T13:17:19.963262 | 2011-03-22T21:49:52 | 2011-03-22T21:49:52 | 39,529,945 | 0 | 1 | null | null | null | null | IBM852 | C++ | false | false | 4,817 | /* -*-c++-*- */
/**
* OsgAL - OpenSceneGraph Audio Library
* Copyright (C) 2004 VRlab, Umeň University
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*/
#ifndef GROUPSOURCE_H_INCLUDED_C427B440
#define GROUPSOURCE_H_INCLUDED_C427B440
#include "openalpp/Source"
#include "openalpp/AudioConvert"
#include <vector>
#include <math.h>
#include <stdlib.h>
#include "openalpp/Export"
#include <osg/ref_ptr>
namespace openalpp {
/**
* Class for group sources.
* Used for mixing together several sources _before_ they are played. This can
* be used to play more sounds with less processing power. Of course the
* problem is that the sources cannot be moved separately.
*/
class OPENALPP_API GroupSource : public SourceBase {
/**
* Flag for whether the sources have been mixed yet.
*/
bool mixed_;
/**
* Vector containing the sources in the group.
*/
std::vector<osg::ref_ptr<Source> > sources_;
/**
* OpenAL buffer for the group source.
*/
ALuint buffer_;
enum Speaker {Left,Right};
/**
* Handles distance attenuation and directional sources.
* @param source is the source to filter.
* @return the gain.
*/
ALfloat filterDistance(ALuint source,Speaker speaker);
/**
* Reverb filter.
* @param source is (a pointer to) the source.
* @param buffer is (a pointer to) the buffer (=memory area).
* @param size is the size of the buffer.
* @param frequency is the frequency of the sound.
* @return new pointer to buffer.
*/
ALshort *filterReverb(Source *source,ALshort *buffer,
ALsizei &size,unsigned int frequency);
/**
* Apply filters.
* @param source is (a pointer to) the source.
* @param buffer is the buffer containing the sound.
* @param size is the size of the buffer.
* @param frequency is the frequency of the sound.
* @return (new) pointer to buffer.
*/
ALshort *applyFilters(Source *source,ALshort *buffer,ALsizei &size,
unsigned int frequency);
public:
/**
* Constructor.
* Creates the group source at the specified position.
* @param x x coordinate.
* @param y y coordinate.
* @param z z coordinate.
*/
GroupSource(float x = 0.0, float y = 0.0, float z = 0.0) throw (NameError);
/**
* Same as SourceBase::Play, except that this mixes the sources in the
* group if it haven't been done yet.
*/
void play() throw (InitError,FileError);
/**
* Mix all added sources into one. This function will be called by
* Play(), if sources have been included since the last time MixSamples()
* was called, so if you want the source to start playing as fast as
* possible after the Play()-call, MixSources() should be called
* separately
* @param frequency is the frequency that will be used when mixing.
*/
void mixSources(unsigned int frequency=22050)
throw (InitError,FileError,FatalError,MemoryError,ValueError);
/**
* Includes a source in the group.
* Returns an identifier that can be used as an argument to ExcludeSource().
* This identifier is also the OpenAL name for the included source.
* @param source is (a pointer to) the source to include.
* @return identifier for the source.
*/
ALuint includeSource(Source *source) throw (ValueError);
/**
* Removes a source from the group.
* This will of course require the remaining sources to be mixed again.
* @param source is the source to exclude.
*/
void excludeSource(const Source &source) throw (NameError);
/**
* Removes a source from the group.
* This will of course require the remaining sources to be mixed again.
* @param source is the identifier of the source to exclude.
*/
void excludeSource(ALuint source) throw (NameError);
/**
* Copy constructor.
*/
GroupSource(const GroupSource &groupsource);
/**
* Assignment operator.
*/
GroupSource &operator=(const GroupSource &groupsource);
protected:
/**
* Destructor.
*/
virtual ~GroupSource();
};
}
#endif /* GROUPSOURCE_H_INCLUDED_C427B440 */
| [
"vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13"
]
| [
[
[
1,
157
]
]
]
|
|
d13066a29260962a6098410fe03c4d0d6c3415df | cd0987589d3815de1dea8529a7705caac479e7e9 | /webkit/WebKit/chromium/src/WebDevToolsFrontendImpl.h | e7b5e27299714076a1bd3fc9ada9cb0e445ff31b | [
"BSD-2-Clause"
]
| permissive | azrul2202/WebKit-Smartphone | 0aab1ff641d74f15c0623f00c56806dbc9b59fc1 | 023d6fe819445369134dee793b69de36748e71d7 | refs/heads/master | 2021-01-15T09:24:31.288774 | 2011-07-11T11:12:44 | 2011-07-11T11:12:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,797 | h | /*
* Copyright (C) 2010 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef WebDevToolsFrontendImpl_h
#define WebDevToolsFrontendImpl_h
#include "PlatformString.h"
#include "WebDevToolsFrontend.h"
#include <v8.h>
#include <wtf/Forward.h>
#include <wtf/HashMap.h>
#include <wtf/Noncopyable.h>
#include <wtf/OwnPtr.h>
#include <wtf/RefPtr.h>
#include <wtf/Vector.h>
namespace WebCore {
class ContextMenuItem;
class Node;
class Page;
}
namespace WebKit {
class WebDevToolsClientDelegate;
class WebViewImpl;
struct WebDevToolsMessageData;
using WTF::String;
class WebDevToolsFrontendImpl : public WebKit::WebDevToolsFrontend
, public Noncopyable {
public:
WebDevToolsFrontendImpl(
WebKit::WebViewImpl* webViewImpl,
WebKit::WebDevToolsFrontendClient* client,
const String& applicationLocale);
virtual ~WebDevToolsFrontendImpl();
// WebDevToolsFrontend implementation.
virtual void dispatchOnInspectorFrontend(const WebString& message);
void frontendLoaded();
private:
WebKit::WebViewImpl* m_webViewImpl;
WebKit::WebDevToolsFrontendClient* m_client;
String m_applicationLocale;
bool m_loaded;
};
} // namespace WebKit
#endif
| [
"[email protected]"
]
| [
[
[
1,
81
]
]
]
|
bbc9dc4cddce2056d5f3b2025b63a14b64dddf58 | ff5313a6e6c9f9353f7505a37a57255c367ff6af | /grun/StdAfx.cpp | bc510eb6c1a7f154f38f3ec569293aeec0f5fc79 | []
| no_license | badcodes/vc6 | 467d6d513549ac4d435e947927d619abf93ee399 | 0c11d7a81197793e1106c8dd3e7ec6b097a68248 | refs/heads/master | 2016-08-07T19:14:15.611418 | 2011-07-09T18:05:18 | 2011-07-09T18:05:18 | 1,220,419 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 293 | cpp | // stdafx.cpp : source file that includes just the standard includes
// grun.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"[email protected]"
]
| [
[
[
1,
9
]
]
]
|
748db90c1576204990b672b3fb3da002429066fa | f2b4a9d938244916aa4377d4d15e0e2a6f65a345 | /Game/Ctl_MGuildPage.h | a4134020d8b7d23f2ba393a40fdcfa2969e243cf | [
"Apache-2.0"
]
| permissive | notpushkin/palm-heroes | d4523798c813b6d1f872be2c88282161cb9bee0b | 9313ea9a2948526eaed7a4d0c8ed2292a90a4966 | refs/heads/master | 2021-05-31T19:10:39.270939 | 2010-07-25T12:25:00 | 2010-07-25T12:25:00 | 62,046,865 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,927 | h | /*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
#ifndef _HMM_GAME_CASTLE_VIEW_MAGE_GUILD_PAGE_H_
#define _HMM_GAME_CASTLE_VIEW_MAGE_GUILD_PAGE_H_
class iMGuildTab : public iCtlViewChild, public IViewCmdHandler
{
public:
iMGuildTab(iViewMgr* pViewMgr)
: iCtlViewChild(pViewMgr), m_pCastle(NULL)
{
sint32 cellW = 61;
sint32 cellH = 36;
uint32 xx=0;
for (uint32 lvl = 0; lvl<5; ++lvl){
uint32 scnt = 5-lvl;
iPoint pos(160 - (cellW*scnt+3*(scnt-1))/2, 1 + (5-lvl-1)*cellH);
for (uint32 spid=0; spid<scnt; ++spid) {
AddChild(m_pSpellBtn[xx] = new iSpellBtn(pViewMgr,this,iRect(pos.x,pos.y,cellW,cellH),110 + xx));
++xx;
pos.x += cellW+3;
}
}
}
void OnActivate()
{
SetCastle(m_pCastle);
}
void OnCompose()
{
iCtlViewChild::OnCompose();
}
void SetCastle(iCastle* pCastle)
{
m_pCastle = pCastle;
if (m_pCastle) {
uint32 xx=0;
for (uint32 lvl=0; lvl<5; ++lvl) {
iCtlCnst* pCnst = m_pCastle->FindCnst((CTL_CONSTR)(CTLCNST_MAGEGUILD_L1+lvl));
uint32 tcnt = (5-lvl);
if (pCnst && pCnst->IsBuilt()) {
iMGuildCtlCnst* pMGuild = DynamicCast<iMGuildCtlCnst*>(pCnst);
check(pMGuild);
uint32 spid;
for (spid=0; spid < pMGuild->SpellsCount(); ++spid, ++xx) m_pSpellBtn[xx]->SetSpell(gGame.ItemMgr().m_spellMgr.Spell(pMGuild->Spell(spid)));
for (uint32 fsp=spid; fsp<tcnt; ++fsp, ++xx) m_pSpellBtn[xx]->SetSpell(NULL);
} else {
for (uint32 fsp=0; fsp<tcnt; ++fsp, ++xx) m_pSpellBtn[xx]->SetSpell(NULL);
}
}
} else {
for (uint32 xx=0; xx<15; ++xx) m_pSpellBtn[xx]->SetSpell(NULL);
}
Invalidate();
}
private:
void iCMDH_ControlCommand(iView* pView, CTRL_CMD_ID cmd, sint32 param)
{
uint32 uid = pView->GetUID();
if (uid >= 110 && uid < 125) {
iIconDlg dlg(&gApp.ViewMgr(), gTextMgr[m_pSpellBtn[uid-110]->GetSpell()->NameKey()], gTextMgr[m_pSpellBtn[uid-110]->GetSpell()->DescKey(MSL_NONE)], m_pSpellBtn[uid-110]->GetSpell()->Icon(),m_pCastle->Owner());
dlg.DoModal();
}
}
private:
iCastle* m_pCastle;
iSpellBtn* m_pSpellBtn[15];
};
#endif //_HMM_GAME_CASTLE_VIEW_MAGE_GUILD_PAGE_H_
| [
"palmheroesteam@2c21ad19-eed7-4c86-9350-8a7669309276"
]
| [
[
[
1,
95
]
]
]
|
2622d50a9fa50f1aaeb4e95f1db892e90a72740c | aba49c8e4dd69b96363d7486ec41193ca468150c | /tiwag/wxWidgets/wx_pch.dummy.cpp | a7435ab30b68dbd23619612243c8b100f95f4986 | []
| no_license | BackupTheBerlios/cb-etools-svn | 3622a0b17b3e29b71e06927c7e2f8009040e7712 | 35a220f976d7b3161375fb4ec1cff5df272a5466 | refs/heads/master | 2016-09-06T00:02:38.431720 | 2008-11-11T10:51:08 | 2008-11-11T10:51:08 | 40,663,743 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 31 | cpp | //wx_pch.dummy
int main() {}
| [
"tiwag@ec733b87-680d-0410-a97b-ce2dfefcd09d"
]
| [
[
[
1,
2
]
]
]
|
610bec5503ba2bda03f3fa03ef034e025ec6ed38 | 2139c9f6c7d201e394631dfd54a3e658269e9e68 | /Resources/PPEResourceException.cpp | 33d9820ccbb0eeaaa08f1572f90fc9989e69c932 | []
| no_license | OpenEngineDK/branches-PostProcessing | 294b87604d8d8e73b12ab7a6fd704a83ca33f3c9 | 2497ce3879973c410469618d2cf01b051bd4edbb | refs/heads/master | 2020-12-24T21:10:50.209919 | 2009-04-27T10:12:37 | 2009-04-27T10:12:37 | 58,073,279 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 492 | cpp | #include "PPEResourceException.h"
#include <stdio.h>
namespace OpenEngine {
namespace Resources {
PPEResourceException::PPEResourceException(const char* message) : Exception(message) {
this->message = message;
// the following is temp!
printf("PPEResourceException: %s\n", message);
PPEResourceException* null = NULL;
null->toString();
}
const char* PPEResourceException::toString() {
return message;
}
} // NS Resources
} // NS OpenEngine
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
6
],
[
8,
16
],
[
18,
22
]
],
[
[
7,
7
],
[
17,
17
]
]
]
|
dec1747ffb06a638c13d1dafa977dfb585127f8a | dadae22098e24c412a8d8d4133c8f009a8a529c9 | /tp1/src/fragment_shader.h | 1a510ea0780ed4f79359638f4e544c718533c185 | []
| no_license | maoueh/PHS4700 | 9fe2bdf96576975b0d81e816c242a8f9d9975fbc | 2c2710fcc5dbe4cd496f7329379ac28af33dc44d | refs/heads/master | 2021-01-22T22:44:17.232771 | 2009-10-06T18:49:30 | 2009-10-06T18:49:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 398 | h | #ifndef FRAGMENT_SHADER_H
#define FRAGMENT_SHADER_H
#include "shader.h"
class FragmentShader : public Shader
{
public:
FragmentShader(const STRING& filename);
virtual ~FragmentShader();
virtual void load();
virtual UINT getHandle();
virtual void bindOutputs(UINT programHandle) = 0;
private:
virtual void printLog();
UINT mHandle;
};
#endif | [
"[email protected]"
]
| [
[
[
1,
23
]
]
]
|
c399c9f8d0bc5252c18e53100d05e316afd3313d | 0b23115a0b7d738df12d0dc6c149e76f0c71992e | /Confwiz32/StdAfx.cpp | 4c69b78075caa8bed9c863aa0e9061c1f7a59e63 | []
| no_license | BackupTheBerlios/kinneret | 7bbcaa4d6e00a600c6d504471c0df7d65a843647 | 1a7abb40267e87b4a8b2202de28943ec409e13a8 | refs/heads/master | 2021-01-01T17:56:36.375082 | 2006-02-18T11:12:25 | 2006-02-18T11:12:25 | 40,069,588 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 296 | cpp | // stdafx.cpp : source file that includes just the standard includes
// Confwiz32.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"z9u2k"
]
| [
[
[
1,
8
]
]
]
|
625c81760bd348d1a9add2fe9c11fc68ca6c9942 | 83c9b35f2327528b6805b8e9de147ead75e8e351 | /frames/envelopes/RaisedCosineBellEnvelope.h | 908688dbc51ec1c53565057afeaff62ebbf68e14 | []
| no_license | playmodes/playmodes | ec6ced2e637769353eb66db89aa88ebd1d5185ac | 9a91b192be92c8dedc67cbd126d5a50a4d2b9c54 | refs/heads/master | 2021-01-22T10:14:18.586477 | 2010-01-02T17:55:50 | 2010-01-02T17:55:50 | 456,188 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,854 | h | /*
* AudioFrame.h
*
* Created on: 09-oct-2008
* Author: arturo castro
*/
#ifndef RAISEDCOSINEBELLENVELOPE_H_INCLUDED
#define RAISEDCOSINEBELLENVELOPE_H_INCLUDED
#include "BaseEnvelope.h"
class RaisedCosineBellEnvelope:public BaseEnvelope{
public:
RaisedCosineBellEnvelope(){
attackPct = 0.1;
decayPct = 0.1;
}
AudioFrame * applyEnvelope(AudioFrame * frame){
frame->retain();
int grainSize = frame->getBufferSize();
int attackSamples = grainSize * attackPct;
int releaseSamples = grainSize * decayPct;
float *source = frame->getAudioFrame();
float *dst = new float[grainSize*frame->getChannels()];
for(int i=0;i<attackSamples;i++){
dst[i*2]=(1.0 + cos( PI + ( PI * ( i / attackSamples ) )))*
(source[i*2] / 2.0);
dst[i*2+1]=(1.0 + cos( PI + ( PI * ( i / attackSamples ) )))*
(source[i*2+1] / 2.0);
}
for(int i=attackSamples;i<grainSize-releaseSamples;i++){
dst[i*2]=source[i*2];
dst[i*2+1]=source[i*2+1];
}
for(int i=grainSize-releaseSamples;i<grainSize;i++){
dst[i*2]=(1.0 + cos( PI * ( i / releaseSamples ) ) )*
(source[i*2] / 2.0);
dst[i*2+1]=(1.0 + cos( PI * ( i / releaseSamples ) ) )*
(source[i*2+1] / 2.0);
}
frame->release();
AudioFrame * dstFrame = new AudioFrame(dst,grainSize,frame->getChannels());
return dstFrame;
}
void setAttack(float pct){
attackPct=pct;
}
void setDecay(float pct){
decayPct=pct;
}
float attackPct;
float decayPct;
};
#endif // RAISEDCOSINEBELLENVELOPE_H_INCLUDED
| [
"[email protected]"
]
| [
[
[
1,
60
]
]
]
|
d116044b6754c4470e7439f8b550154970872efb | c95a83e1a741b8c0eb810dd018d91060e5872dd8 | /libs/stdlith/l_allocator.cpp | a94ca6049d5e9f56dd7209fc599799a298df3a4d | []
| no_license | rickyharis39/nolf2 | ba0b56e2abb076e60d97fc7a2a8ee7be4394266c | 0da0603dc961e73ac734ff365bfbfb8abb9b9b04 | refs/heads/master | 2021-01-01T17:21:00.678517 | 2011-07-23T12:11:19 | 2011-07-23T12:11:19 | 38,495,312 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,611 | cpp |
#include "l_allocator.h"
LAlloc g_DefAlloc;
// -------------------------------------------------------------------------------- //
// LAllocCount implementation.
// -------------------------------------------------------------------------------- //
LAllocCount::LAllocCount(LAlloc *pDelegate)
{
m_pDelegate = pDelegate;
ClearCounts();
}
void LAllocCount::ClearCounts()
{
m_nTotalAllocations = 0;
m_nTotalFrees = 0;
m_TotalMemoryAllocated = 0;
m_nCurrentAllocations = 0;
m_nAllocationFailures = 0;
}
void* LAllocCount::Alloc(uint32 size, bool bQuadWordAlign)
{
void *pRet;
if(size == 0)
return NULL;
pRet = m_pDelegate->Alloc(size);
if(pRet)
{
m_nTotalAllocations++;
m_TotalMemoryAllocated += size;
m_nCurrentAllocations++;
}
else
{
m_nAllocationFailures++;
}
return pRet;
}
void LAllocCount::Free(void *ptr)
{
if(!ptr)
return;
m_pDelegate->Free(ptr);
m_nCurrentAllocations--;
m_nTotalFrees++;
}
// -------------------------------------------------------------------------------- //
// LAllocSimpleBlock implementation.
// -------------------------------------------------------------------------------- //
LAllocSimpleBlock::LAllocSimpleBlock()
{
Clear();
}
LAllocSimpleBlock::~LAllocSimpleBlock()
{
Term();
}
LTBOOL LAllocSimpleBlock::Init(LAlloc *pDelegate, uint32 blockSize)
{
Term();
blockSize = (blockSize + 3) & ~3;
if(blockSize > 0)
{
m_pBlock = (uint8*)pDelegate->Alloc(blockSize);
if(!m_pBlock)
return FALSE;
}
m_pDelegate = pDelegate;
m_BlockSize = blockSize;
m_CurBlockPos = 0;
return TRUE;
}
void LAllocSimpleBlock::Term()
{
if(m_pDelegate)
{
m_pDelegate->Free(m_pBlock);
}
Clear();
}
void* LAllocSimpleBlock::Alloc(uint32 size, bool bQuadWordAlign)
{
uint8 *pRet;
if(size == 0)
return NULL;
if (bQuadWordAlign) { // QuadWord Align (We've over alloced a bit to account for this - if we're not QWAligned, force it to be)...
pRet = &m_pBlock[m_CurBlockPos];
m_CurBlockPos += (((uint32)pRet + 0xf) & ~0xf) - (uint32)pRet; }
else { // DWord Align by default...
size = ((size + 3) & ~3); }
if((m_CurBlockPos + size) > m_BlockSize)
return NULL;
pRet = &m_pBlock[m_CurBlockPos];
m_CurBlockPos += size;
assert(!bQuadWordAlign || ((uint32)pRet & 0xf) == 0);
return pRet;
}
void LAllocSimpleBlock::Free(void *ptr)
{
}
void LAllocSimpleBlock::Clear()
{
m_pDelegate = NULL;
m_pBlock = NULL;
m_CurBlockPos = 0;
m_BlockSize = 0;
}
| [
"[email protected]"
]
| [
[
[
1,
150
]
]
]
|
bcbd6caf4f4d8b491027e3c8975b3d101b6ac8ea | f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0 | /Depend/MyGUI/Tools/SkinEditor/ColourPanel.cpp | 76b8d0e00ff87e8adb033216d577c86187829f7d | []
| no_license | lxinhcn/starworld | 79ed06ca49d4064307ae73156574932d6185dbab | 86eb0fb8bd268994454b0cfe6419ffef3fc0fc80 | refs/heads/master | 2021-01-10T07:43:51.858394 | 2010-09-15T02:38:48 | 2010-09-15T02:38:48 | 47,859,019 | 2 | 1 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 11,041 | cpp | /*!
@file
@author Albert Semenov
@date 08/2008
*/
#include "precompiled.h"
#include "ColourPanel.h"
namespace tools
{
ColourPanel::ColourPanel() :
Dialog()
{
initialiseByAttributes(this);
mTextureName = MyGUI::utility::toString((int)this, "_ColourGradient");
mCurrentColour = MyGUI::Colour::Green;
mBaseColour = MyGUI::Colour::Green;
mColourRect->eventMouseButtonPressed += MyGUI::newDelegate(this, &ColourPanel::notifyMouseButtonPressed);
mColourRect->eventMouseDrag += MyGUI::newDelegate(this, &ColourPanel::notifyMouseDrag);
mImageColourPicker->eventMouseDrag += MyGUI::newDelegate(this, &ColourPanel::notifyMouseDrag);
mScrollRange->eventScrollChangePosition += MyGUI::newDelegate(this, &ColourPanel::notifyScrollChangePosition);
mEditRed->eventEditTextChange += MyGUI::newDelegate(this, &ColourPanel::notifyEditTextChange);
mEditGreen->eventEditTextChange += MyGUI::newDelegate(this, &ColourPanel::notifyEditTextChange);
mEditBlue->eventEditTextChange += MyGUI::newDelegate(this, &ColourPanel::notifyEditTextChange);
mOk->eventMouseButtonClick += MyGUI::newDelegate(this, &ColourPanel::notifyMouseButtonClickOk);
mCancel->eventMouseButtonClick += MyGUI::newDelegate(this, &ColourPanel::notifyMouseButtonClickCancel);
MyGUI::Window* window = mMainWidget->castType<MyGUI::Window>(false);
if (window != nullptr)
window->eventWindowButtonPressed += MyGUI::newDelegate(this, &ColourPanel::notifyWindowButtonPressed);
mColourRange.push_back(MyGUI::Colour(1, 0, 0));
mColourRange.push_back(MyGUI::Colour(1, 0, 1));
mColourRange.push_back(MyGUI::Colour(0, 0, 1));
mColourRange.push_back(MyGUI::Colour(0, 1, 1));
mColourRange.push_back(MyGUI::Colour(0, 1, 0));
mColourRange.push_back(MyGUI::Colour(1, 1, 0));
mColourRange.push_back(mColourRange[0]);
mMainWidget->setVisible(false);
createTexture();
updateFirst();
}
ColourPanel::~ColourPanel()
{
destroyTexture();
}
void ColourPanel::updateFirst()
{
notifyScrollChangePosition(nullptr, mScrollRange->getScrollPosition());
notifyMouseDrag(nullptr,
mImageColourPicker->getAbsoluteLeft() + (mColourRect->getWidth() / 2),
mImageColourPicker->getAbsoluteTop() + (mColourRect->getHeight() / 2));
}
void ColourPanel::createTexture()
{
MyGUI::uint size = 32;
mTexture = MyGUI::RenderManager::getInstance().createTexture(mTextureName);
mTexture->createManual(size, size,
MyGUI::TextureUsage::Static | MyGUI::TextureUsage::Write,
MyGUI::PixelFormat::R8G8B8A8);
mColourRect->setImageTexture(mTextureName);
}
void ColourPanel::destroyTexture()
{
MyGUI::RenderManager::getInstance().destroyTexture( mTexture );
mTexture = nullptr;
}
void ColourPanel::updateTexture(const MyGUI::Colour& _colour)
{
size_t size = 32;
MyGUI::uint8* pDest = static_cast<MyGUI::uint8*>(mTexture->lock(MyGUI::TextureUsage::Write));
for (size_t j = 0; j < size; j++)
for (size_t i = 0; i < size; i++)
{
float x = (float)i / size;
float y = (float)j / size;
*pDest++ = MyGUI::uint8((1. - y) * (_colour.blue * x + (1. - x)) * 255); // B
*pDest++ = MyGUI::uint8((1. - y) * (_colour.green * x + (1. - x)) * 255); // G
*pDest++ = MyGUI::uint8((1. - y) * (_colour.red * x + (1. - x)) * 255); // R
*pDest++ = 255; // A
}
// Unlock the pixel buffer
mTexture->unlock();
}
void ColourPanel::notifyMouseDrag(MyGUI::Widget* _sender, int _left, int _top)
{
MyGUI::Widget* parent = mImageColourPicker->getParent();
MyGUI::IntPoint point(_left - parent->getAbsoluteLeft(), _top - parent->getAbsoluteTop());
if (point.left < 0) point.left = 0;
if (point.top < 0) point.top = 0;
if (point.left > mColourRect->getWidth()) point.left = mColourRect->getWidth();
if (point.top > mColourRect->getHeight()) point.top = mColourRect->getHeight();
mImageColourPicker->setPosition(point.left - (mImageColourPicker->getWidth() / 2), point.top - (mImageColourPicker->getHeight() / 2));
updateFromPoint(point);
}
void ColourPanel::notifyMouseButtonPressed(MyGUI::Widget* _sender, int _left, int _top, MyGUI::MouseButton _id)
{
if (_id == MyGUI::MouseButton::Left) notifyMouseDrag(nullptr, _left, _top);
}
void ColourPanel::updateFromPoint(const MyGUI::IntPoint& _point)
{
// вычисляем цвет по положению курсора Altren 09.2008
float x = 1.0f * _point.left / mColourRect->getWidth();
float y = 1.0f * _point.top / mColourRect->getHeight();
if (x > 1) x = 1;
else if (x < 0) x = 0;
if (y > 1) y = 1;
else if (y < 0) y = 0;
mCurrentColour.red = (1 - y) * (mBaseColour.red * x + MyGUI::Colour::White.red * (1 - x));
mCurrentColour.green = (1 - y) * (mBaseColour.green * x + MyGUI::Colour::White.green * (1 - x));
mCurrentColour.blue = (1 - y) * (mBaseColour.blue * x + MyGUI::Colour::White.blue * (1 - x));
mColourView->setColour(mCurrentColour);
mEditRed->setCaption(MyGUI::utility::toString((int)(mCurrentColour.red * 255)));
mEditGreen->setCaption(MyGUI::utility::toString((int)(mCurrentColour.green * 255)));
mEditBlue->setCaption(MyGUI::utility::toString((int)(mCurrentColour.blue * 255)));
}
void ColourPanel::notifyScrollChangePosition(MyGUI::VScroll* _sender, size_t _position)
{
float sector_size = (float)mScrollRange->getScrollRange() / 6.0f;
float sector_current = (float)_position / sector_size;
// текущий сектор
size_t current = (size_t)sector_current;
assert(current < 6);
// смещение до следующего сектора от 0 до 1
float offfset = (sector_current - (float)current);
const MyGUI::Colour& from = mColourRange[current];
const MyGUI::Colour& to = mColourRange[current + 1];
mBaseColour.red = from.red + offfset * (to.red - from.red);
mBaseColour.green = from.green + offfset * (to.green - from.green);
mBaseColour.blue = from.blue + offfset * (to.blue - from.blue);
updateTexture(mBaseColour);
MyGUI::IntPoint point(
mImageColourPicker->getLeft() + (mImageColourPicker->getWidth() / 2),
mImageColourPicker->getTop() + (mImageColourPicker->getHeight() / 2));
updateFromPoint(point);
}
void ColourPanel::notifyEditTextChange(MyGUI::Edit* _sender)
{
MyGUI::Edit* edit = static_cast<MyGUI::Edit*>(_sender);
size_t cursor = edit->getTextCursor();
size_t num = MyGUI::utility::parseSizeT(edit->getOnlyText());
if (num > 255) num = 255;
edit->setCaption(MyGUI::utility::toString(num));
if (cursor < edit->getTextLength()) edit->setTextCursor(cursor);
MyGUI::Colour colour(
MyGUI::utility::parseFloat(mEditRed->getOnlyText()) / 255.0f,
MyGUI::utility::parseFloat(mEditGreen->getOnlyText()) / 255.0f,
MyGUI::utility::parseFloat(mEditBlue->getOnlyText()) / 255.0f);
updateFromColour(colour);
}
void ColourPanel::setColour(const MyGUI::Colour& _colour)
{
MyGUI::Colour colour = getSaturate(_colour);
mEditRed->setCaption(MyGUI::utility::toString((int)(colour.red * 255)));
mEditGreen->setCaption(MyGUI::utility::toString((int)(colour.green * 255)));
mEditBlue->setCaption(MyGUI::utility::toString((int)(colour.blue * 255)));
updateFromColour(colour);
}
void ColourPanel::updateFromColour(const MyGUI::Colour& _colour)
{
mCurrentColour = _colour;
std::vector<float> vec;
vec.push_back(_colour.red);
vec.push_back(_colour.green);
vec.push_back(_colour.blue);
std::sort(vec.begin(), vec.end());
MyGUI::IntPoint point((int)((1 - vec[0] / vec[2]) * mColourRect->getWidth()), (int)((1 - vec[2]) * mColourRect->getHeight()));
mImageColourPicker->setPosition(point.left - (mImageColourPicker->getWidth() / 2), point.top - (mImageColourPicker->getHeight() / 2));
int iMax = (_colour.red == vec[2]) ? 0 : (_colour.green == vec[2]) ? 1 : 2;
int iMin = (_colour.red == vec[0]) ? 0 : (_colour.green == vec[0]) ? 1 : 2;
int iAvg = 3 - iMax - iMin;
if (iMin == iMax) // if gray colour - set base red
{
iMax = 0;
iMin = 1;
iAvg = 2;
byIndex(mBaseColour, iMin) = 0.;
byIndex(mBaseColour, iAvg) = 0.;
byIndex(mBaseColour, iMax) = 1.;
}
else
{
byIndex(mBaseColour, iMin) = 0.;
byIndex(mBaseColour, iAvg) = (vec[1] - vec[0]) / (vec[2] - vec[0]);
byIndex(mBaseColour, iMax) = 1.;
}
int i;
for (i = 0; i < 6; ++i)
{
if ((fabs(byIndex(mColourRange[i], iMin) - byIndex(mBaseColour, iMin)) < 0.001) &&
(fabs(byIndex(mColourRange[i], iMax) - byIndex(mBaseColour, iMax)) < 0.001) &&
(fabs(byIndex(mColourRange[i+1], iMin) - byIndex(mBaseColour, iMin)) < 0.001) &&
(fabs(byIndex(mColourRange[i+1], iMax) - byIndex(mBaseColour, iMax)) < 0.001))
break;
}
float sector_size = (float)mScrollRange->getScrollRange() / 6.0f;
size_t current = i;
float offset = byIndex(mBaseColour, iAvg);
if (byIndex(mColourRange[i+1], iAvg) < byIndex(mColourRange[i], iAvg)) offset = 1 - byIndex(mBaseColour, iAvg);
size_t pos = size_t((current + offset) * sector_size);
mScrollRange->setScrollPosition(pos);
// бонус для обрезки цвета под шкалу
mBaseColour.red = mColourRange[i].red + offset * (mColourRange[i+1].red - mColourRange[i].red);
mBaseColour.green = mColourRange[i].green + offset * (mColourRange[i+1].green - mColourRange[i].green);
mBaseColour.blue = mColourRange[i].blue + offset * (mColourRange[i+1].blue - mColourRange[i].blue);
updateTexture(mBaseColour);
mColourView->setColour(mCurrentColour);
}
MyGUI::Colour ColourPanel::getSaturate(const MyGUI::Colour& _colour)
{
MyGUI::Colour colour = _colour;
if (colour.red < 0)
colour.red = 0;
else if (colour.red > 1)
colour.red = 1;
if (colour.green < 0)
colour.green = 0;
else if (colour.green > 1)
colour.green = 1;
if (colour.blue < 0)
colour.blue = 0;
else if (colour.blue > 1)
colour.blue = 1;
return colour;
}
float& ColourPanel::byIndex(MyGUI::Colour& _colour, size_t _index)
{
if (_index == 0) return _colour.red;
else if (_index == 1) return _colour.green;
else if (_index == 2) return _colour.blue;
else return _colour.alpha;
}
void ColourPanel::onDoModal()
{
MyGUI::IntSize windowSize = mMainWidget->getSize();
MyGUI::IntSize parentSize = mMainWidget->getParentSize();
mMainWidget->setPosition((parentSize.width - windowSize.width) / 2, (parentSize.height - windowSize.height) / 2);
}
void ColourPanel::onEndModal()
{
}
void ColourPanel::notifyMouseButtonClickCancel(MyGUI::Widget* _sender)
{
eventEndDialog(this, false);
}
void ColourPanel::notifyMouseButtonClickOk(MyGUI::Widget* _sender)
{
eventEndDialog(this, true);
}
void ColourPanel::notifyWindowButtonPressed(MyGUI::Window* _sender, const std::string& _name)
{
eventEndDialog(this, false);
}
} // namespace tools
| [
"albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c"
]
| [
[
[
1,
319
]
]
]
|
98b202728c198c36beb6dd7d1910e8ed78e79400 | cf58ec40b7ea828aba01331ee3ab4c7f2195b6ca | /Nestopia/core/NstBase.hpp | 4819ef186cb9d6cc86311e2685086f6a871ad0a9 | []
| no_license | nicoya/OpenEmu | e2fd86254d45d7aa3d7ef6a757192e2f7df0da1e | dd5091414baaaddbb10b9d50000b43ee336ab52b | refs/heads/master | 2021-01-16T19:51:53.556272 | 2011-08-06T18:52:40 | 2011-08-06T18:52:40 | 2,131,312 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,041 | hpp | ////////////////////////////////////////////////////////////////////////////////////////
//
// Nestopia - NES/Famicom emulator written in C++
//
// Copyright (C) 2003-2008 Martin Freij
//
// This file is part of Nestopia.
//
// Nestopia is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// Nestopia is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Nestopia; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
////////////////////////////////////////////////////////////////////////////////////////
#ifndef NST_BASE_H
#define NST_BASE_H
#include <climits>
#include "api/NstApiConfig.hpp"
//--------------------------------------------------------------------------------------
// Microsoft Visual C++
//--------------------------------------------------------------------------------------
#ifdef _MSC_VER
#define NST_MSVC _MSC_VER
#else
#define NST_MSVC 0
#endif
//--------------------------------------------------------------------------------------
// Intel C/C++ Compiler
//--------------------------------------------------------------------------------------
#ifdef __INTEL_COMPILER
#define NST_ICC __INTEL_COMPILER
#else
#define NST_ICC 0
#endif
//--------------------------------------------------------------------------------------
// GNU Compiler Collection
//--------------------------------------------------------------------------------------
#ifdef __GNUC__
#define NST_GCC (__GNUC__ * 100 + __GNUC_MINOR__)
#else
#define NST_GCC 0
#endif
//--------------------------------------------------------------------------------------
// Borland C++
//--------------------------------------------------------------------------------------
#ifdef __BORLANDC__
#define NST_BCB __BORLANDC__
#else
#define NST_BCB 0
#endif
//--------------------------------------------------------------------------------------
// Metrowerks CodeWarrior
//--------------------------------------------------------------------------------------
#ifdef __MWERKS__
#define NST_MWERKS __MWERKS__
#else
#define NST_MWERKS 0
#endif
//--------------------------------------------------------------------------------------
#ifdef NST_PRAGMA_ONCE
#pragma once
#elif NST_MSVC >= 1020 || NST_MWERKS >= 0x3000
#pragma once
#define NST_PRAGMA_ONCE
#endif
//--------------------------------------------------------------------------------------
#ifndef NST_CALL
#define NST_CALL
#endif
namespace Nes
{
typedef signed char schar;
typedef unsigned char uchar;
typedef unsigned short ushort;
typedef unsigned int uint;
typedef unsigned long ulong;
#if UCHAR_MAX >= 0xFF
typedef unsigned char byte;
#else
#error Unsupported plattform!
#endif
#if UCHAR_MAX >= 0xFFFF
typedef unsigned char word;
#elif USHRT_MAX >= 0xFFFF
typedef unsigned short word;
#elif UINT_MAX >= 0xFFFF
typedef unsigned int word;
#else
#error Unsupported plattform!
#endif
#if SCHAR_MAX >= 32767 && SCHAR_MIN <= -32767
typedef signed char iword;
#elif SHRT_MAX >= 32767 && SHRT_MIN <= -32767
typedef signed short iword;
#elif INT_MAX >= 32767 && INT_MIN <= -32767
typedef signed int iword;
#else
#error Unsupported plattform!
#endif
#if UCHAR_MAX >= 0xFFFFFFFF
typedef unsigned char dword;
#elif USHRT_MAX >= 0xFFFFFFFF
typedef unsigned short dword;
#elif UINT_MAX >= 0xFFFFFFFF
typedef unsigned int dword;
#elif ULONG_MAX >= 0xFFFFFFFF
typedef unsigned long dword;
#else
#error Unsupported plattform!
#endif
#if SCHAR_MAX >= 2147483647 && SCHAR_MIN <= -2147483647
typedef signed char idword;
#elif SHRT_MAX >= 2147483647 && SHRT_MIN <= -2147483647
typedef signed short idword;
#elif INT_MAX >= 2147483647 && INT_MIN <= -2147483647
typedef signed int idword;
#elif LONG_MAX >= 2147483647 && LONG_MIN <= -2147483647
typedef signed long idword;
#else
#error Unsupported plattform!
#endif
/**
* General result codes.
*/
enum Result
{
/**
* NTSC/PAL region mismatch.
*/
RESULT_ERR_WRONG_MODE = -13,
/**
* Missing FDS BIOS.
*/
RESULT_ERR_MISSING_BIOS = -12,
/**
* Unsupported or malformed mapper.
*/
RESULT_ERR_UNSUPPORTED_MAPPER = -11,
/**
* Vs DualSystem is unsupported.
*/
RESULT_ERR_UNSUPPORTED_VSSYSTEM = -10,
/**
* File format version is no longer supported.
*/
RESULT_ERR_UNSUPPORTED_FILE_VERSION = -9,
/**
* Unsupported operation.
*/
RESULT_ERR_UNSUPPORTED = -8,
/**
* Invalid CRC checksum.
*/
RESULT_ERR_INVALID_CRC = -7,
/**
* Corrupt file.
*/
RESULT_ERR_CORRUPT_FILE = -6,
/**
* Invalid file.
*/
RESULT_ERR_INVALID_FILE = -5,
/**
* Invalid parameter(s).
*/
RESULT_ERR_INVALID_PARAM = -4,
/**
* System not ready.
*/
RESULT_ERR_NOT_READY = -3,
/**
* Out of memory.
*/
RESULT_ERR_OUT_OF_MEMORY = -2,
/**
* Generic error.
*/
RESULT_ERR_GENERIC = -1,
/**
* Success.
*/
RESULT_OK = 0,
/**
* Success but operation had no effect.
*/
RESULT_NOP = 1,
/**
* Success but image dump may be bad.
*/
RESULT_WARN_BAD_DUMP = 2,
/**
* Success but PRG-ROM may be bad.
*/
RESULT_WARN_BAD_PROM = 3,
/**
* Success but CHR-ROM may be bad.
*/
RESULT_WARN_BAD_CROM = 4,
/**
* Success but file header may have incorrect data.
*/
RESULT_WARN_BAD_FILE_HEADER = 5,
/**
* Success but save data has been lost.
*/
RESULT_WARN_SAVEDATA_LOST = 6,
/**
* Success but data may have been replaced.
*/
RESULT_WARN_DATA_REPLACED = 8
};
namespace Core
{
enum Region
{
REGION_NTSC,
REGION_PAL
};
enum System
{
SYSTEM_NES_NTSC,
SYSTEM_NES_PAL,
SYSTEM_NES_PAL_A,
SYSTEM_NES_PAL_B,
SYSTEM_FAMICOM,
SYSTEM_VS_UNISYSTEM,
SYSTEM_VS_DUALSYSTEM,
SYSTEM_PLAYCHOICE_10
};
enum FavoredSystem
{
FAVORED_NES_NTSC,
FAVORED_NES_PAL,
FAVORED_FAMICOM
};
enum CpuModel
{
CPU_RP2A03,
CPU_RP2A07
};
enum PpuModel
{
PPU_RP2C02,
PPU_RP2C03B,
PPU_RP2C03G,
PPU_RP2C04_0001,
PPU_RP2C04_0002,
PPU_RP2C04_0003,
PPU_RP2C04_0004,
PPU_RC2C03B,
PPU_RC2C03C,
PPU_RC2C05_01,
PPU_RC2C05_02,
PPU_RC2C05_03,
PPU_RC2C05_04,
PPU_RC2C05_05,
PPU_RP2C07
};
enum
{
CLK_M2_MUL = 6,
CLK_NTSC = 39375000UL * CLK_M2_MUL,
CLK_NTSC_DIV = 11,
CLK_NTSC_HVSYNC = 525UL * 455 * CLK_NTSC_DIV * CLK_M2_MUL / 4,
CLK_PAL = 35468950UL * CLK_M2_MUL,
CLK_PAL_DIV = 8,
CLK_PAL_HVSYNC = 625UL * 1418758 / (10000/CLK_PAL_DIV) * CLK_M2_MUL
};
enum
{
CPU_RP2A03_CC = 12,
CPU_RP2A07_CC = 16
};
enum
{
PPU_RP2C02_CC = 4,
PPU_RP2C02_HACTIVE = PPU_RP2C02_CC * 256,
PPU_RP2C02_HBLANK = PPU_RP2C02_CC * 85,
PPU_RP2C02_HSYNC = PPU_RP2C02_HACTIVE + PPU_RP2C02_HBLANK,
PPU_RP2C02_VACTIVE = 240,
PPU_RP2C02_VSLEEP = 1,
PPU_RP2C02_VINT = 20,
PPU_RP2C02_VDUMMY = 1,
PPU_RP2C02_VBLANK = PPU_RP2C02_VSLEEP + PPU_RP2C02_VINT + PPU_RP2C02_VDUMMY,
PPU_RP2C02_VSYNC = PPU_RP2C02_VACTIVE + PPU_RP2C02_VBLANK,
PPU_RP2C02_HVSYNCBOOT = PPU_RP2C02_VACTIVE * PPU_RP2C02_HSYNC + PPU_RP2C02_CC * 312,
PPU_RP2C02_HVREGBOOT = (PPU_RP2C02_VACTIVE + PPU_RP2C02_VINT) * PPU_RP2C02_HSYNC + PPU_RP2C02_CC * 314,
PPU_RP2C02_HVINT = PPU_RP2C02_VINT * ulong(PPU_RP2C02_HSYNC),
PPU_RP2C02_HVSYNC_0 = PPU_RP2C02_VSYNC * ulong(PPU_RP2C02_HSYNC),
PPU_RP2C02_HVSYNC_1 = PPU_RP2C02_VSYNC * ulong(PPU_RP2C02_HSYNC) - PPU_RP2C02_CC,
PPU_RP2C02_HVSYNC = (PPU_RP2C02_HVSYNC_0 + ulong(PPU_RP2C02_HVSYNC_1)) / 2,
PPU_RP2C02_FPS = (CLK_NTSC + CLK_NTSC_DIV * ulong(PPU_RP2C02_HVSYNC) / 2) / (CLK_NTSC_DIV * ulong(PPU_RP2C02_HVSYNC)),
PPU_RP2C07_CC = 5,
PPU_RP2C07_HACTIVE = PPU_RP2C07_CC * 256,
PPU_RP2C07_HBLANK = PPU_RP2C07_CC * 85,
PPU_RP2C07_HSYNC = PPU_RP2C07_HACTIVE + PPU_RP2C07_HBLANK,
PPU_RP2C07_VACTIVE = 240,
PPU_RP2C07_VSLEEP = 1,
PPU_RP2C07_VINT = 70,
PPU_RP2C07_VDUMMY = 1,
PPU_RP2C07_VBLANK = PPU_RP2C07_VSLEEP + PPU_RP2C07_VINT + PPU_RP2C07_VDUMMY,
PPU_RP2C07_VSYNC = PPU_RP2C07_VACTIVE + PPU_RP2C07_VBLANK,
PPU_RP2C07_HVSYNCBOOT = PPU_RP2C07_VACTIVE * PPU_RP2C07_HSYNC + PPU_RP2C07_CC * 312,
PPU_RP2C07_HVREGBOOT = (PPU_RP2C07_VACTIVE + PPU_RP2C07_VINT) * PPU_RP2C07_HSYNC + PPU_RP2C07_CC * 314,
PPU_RP2C07_HVINT = PPU_RP2C07_VINT * ulong(PPU_RP2C07_HSYNC),
PPU_RP2C07_HVSYNC = PPU_RP2C07_VSYNC * ulong(PPU_RP2C07_HSYNC),
PPU_RP2C07_FPS = (CLK_PAL + CLK_PAL_DIV * ulong(PPU_RP2C07_HVSYNC) / 2) / (CLK_PAL_DIV * ulong(PPU_RP2C07_HVSYNC))
};
template<typename T>
class ImplicitBool;
template<>
class ImplicitBool<void>
{
public:
int type;
typedef int ImplicitBool<void>::*Type;
};
template<typename T>
class ImplicitBool
{
template<typename U> void operator == (const ImplicitBool<U>&) const;
template<typename U> void operator != (const ImplicitBool<U>&) const;
public:
operator ImplicitBool<void>::Type () const
{
return !static_cast<const T&>(*this) ? 0 : &ImplicitBool<void>::type;
}
};
}
}
#define NES_FAILED(x_) ((x_) < Nes::RESULT_OK)
#define NES_SUCCEEDED(x_) ((x_) >= Nes::RESULT_OK)
#endif
| [
"[email protected]"
]
| [
[
[
1,
381
]
]
]
|
e21a3395fd0e47abc4b9418d3b5b23f666c326fd | 974a20e0f85d6ac74c6d7e16be463565c637d135 | /trunk/applications/maxPlugin/Import.h | 7db51c4ec29b6c8a765c9dfd56b4893cbd941c49 | []
| no_license | Naddiseo/Newton-Dynamics-fork | cb0b8429943b9faca9a83126280aa4f2e6944f7f | 91ac59c9687258c3e653f592c32a57b61dc62fb6 | refs/heads/master | 2021-01-15T13:45:04.651163 | 2011-11-12T04:02:33 | 2011-11-12T04:02:33 | 2,759,246 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,102 | h |
/* Copyright (c) <2003-2011> <Julio Jerez, Newton Game Dynamics>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source distribution.
*/
#ifndef __NEWTON_MAX_IMPORT_H__
#define __NEWTON_MAX_IMPORT_H__
class Mtl;
class INode;
class dMatrix;
class Interface;
class dMeshInstance;
class ImpInterface;
class GeometryCache;
class MaterialCache;
class MaxNodeChache;
class Import
{
public:
Import(const char* name, Interface* ip, ImpInterface* impip);
~Import(void);
void SetSceneParameters();
void SetSmoothingGroups (Mesh& mesh);
INode* CreateMaxHelperNode ();
INode* CreateMaxMeshNode (dScene& scene, Mtl *mtl, dScene::dTreeNode* meshNode, const GeometryCache& meshCache);
void LoadMaterials (dScene& scene, MaterialCache& materialCache);
void ApplyModifiers (dScene& scene, const MaxNodeChache& maxNodeCache);
void LoadGeometries (dScene& scene, GeometryCache& meshCache, const MaterialCache& materialCache);
void LoadNodes (dScene& scene, const GeometryCache& meshCache, Mtl *mtl, MaxNodeChache& maxNodeCache);
void LoadNode (dScene& scene, INode* maxParent, dScene::dTreeNode* node, const GeometryCache& meshCache, Mtl *mtl, MaxNodeChache& maxNodeCache);
int m_succes;
Interface* m_ip;
ImpInterface* m_impip;
char m_path[256];
};
#endif | [
"[email protected]@b7a2f1d6-d59d-a8fe-1e9e-8d4888b32692"
]
| [
[
[
1,
63
]
]
]
|
27759ce5514a31e84c09ca8443e7d6f355a33b8a | 8fa4334746f35b9103750bb23ec2b8d38e93cbe9 | /coding/qt/forum/forum/jtabwidget.h | 1de3d938dd16f5cc718598c3dc803e92f32c6e86 | []
| no_license | zhzengj/testrepo | 620b22b2cf1e8ff10274a9d0c6491816cecaec3b | daf8bd55fd347220f07bfd7d15b02b01a516479b | refs/heads/master | 2016-09-11T00:50:57.846600 | 2011-10-16T07:59:48 | 2011-10-16T07:59:48 | 2,365,453 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 495 | h | #ifndef _H_JTABWIDGET_H_
#define _H_JTABWIDGET_H_
class QListWidget;
class QStackedWidget;
class QWidget;
class QListWidgetItem;
class QIcon;
class JTabWidget : public QObject
{
Q_OBJECT
private:
QListWidget * m_lw;
QStackedWidget * m_sw;
public:
explicit JTabWidget(QListWidget * lw, QStackedWidget * sw, QObject *parent = 0);
void addTab(QWidget * w, const QString & n, const QIcon & icon);
protected slots:
void itemClicked(QListWidgetItem* item);
};
#endif | [
"[email protected]"
]
| [
[
[
1,
25
]
]
]
|
0b2ef0e1ae14209b65db1e24b80ee5b66390e27e | c2153dcfa8bcf5b6d7f187e5a337b904ad9f91ac | /depends/ClanLib/src/Core/CSS/css_tokenizer.cpp | 671cc8dfcf65ecb1d72571f63af69cb07592b495 | []
| no_license | ptrefall/smn6200fluidmechanics | 841541a26023f72aa53d214fe4787ed7f5db88e1 | 77e5f919982116a6cdee59f58ca929313dfbb3f7 | refs/heads/master | 2020-08-09T17:03:59.726027 | 2011-01-13T22:39:03 | 2011-01-13T22:39:03 | 32,448,422 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,655 | cpp | /*
** ClanLib SDK
** Copyright (c) 1997-2010 The ClanLib Team
**
** This software is provided 'as-is', without any express or implied
** warranty. In no event will the authors be held liable for any damages
** arising from the use of this software.
**
** Permission is granted to anyone to use this software for any purpose,
** including commercial applications, and to alter it and redistribute it
** freely, subject to the following restrictions:
**
** 1. The origin of this software must not be misrepresented; you must not
** claim that you wrote the original software. If you use this software
** in a product, an acknowledgment in the product documentation would be
** appreciated but is not required.
** 2. Altered source versions must be plainly marked as such, and must not be
** misrepresented as being the original software.
** 3. This notice may not be removed or altered from any source distribution.
**
** Note: Some of the libraries ClanLib may link to may have additional
** requirements or restrictions.
**
** File Author(s):
**
** Magnus Norddahl
*/
#include "precomp.h"
#include "API/Core/CSS/css_tokenizer.h"
#include "API/Core/CSS/css_token.h"
#include "css_tokenizer_impl.h"
CL_CSSTokenizer::CL_CSSTokenizer(CL_IODevice &device)
: impl(new CL_CSSTokenizer_Impl(device))
{
}
CL_CSSTokenizer::CL_CSSTokenizer(const CL_String &text)
: impl(new CL_CSSTokenizer_Impl(text))
{
}
void CL_CSSTokenizer::read(CL_CSSToken &token, bool eat_whitespace)
{
do
{
impl->read(token);
} while(eat_whitespace && token.type == CL_CSSToken::type_whitespace);
}
| [
"[email protected]@c628178a-a759-096a-d0f3-7c7507b30227"
]
| [
[
[
1,
50
]
]
]
|
18a0e1f094dc4fe544215ebef66a8dce8e13f857 | ee2e06bda0a5a2c70a0b9bebdd4c45846f440208 | /word/CppUTest/src/CppUTest/TestPlugin.cpp | fe77ebc0c9394f39af497e84c9c4e83a5d0556c9 | []
| no_license | RobinLiu/Test | 0f53a376e6753ece70ba038573450f9c0fb053e5 | 360eca350691edd17744a2ea1b16c79e1a9ad117 | refs/heads/master | 2021-01-01T19:46:55.684640 | 2011-07-06T13:53:07 | 2011-07-06T13:53:07 | 1,617,721 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,358 | cpp | /*
* Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> 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 EARLIER MENTIONED AUTHORS ``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 <copyright holder> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "CppUTest/TestHarness.h"
#include "CppUTest/TestPlugin.h"
TestPlugin::TestPlugin(const SimpleString& name)
: next_(NullTestPlugin::instance()), name_(name), enabled_(true)
{
}
TestPlugin::TestPlugin(TestPlugin* next)
: next_(next), name_("null")
{
}
TestPlugin::~TestPlugin()
{
}
TestPlugin* TestPlugin::addPlugin(TestPlugin* plugin)
{
next_ = plugin;
return this;
}
void TestPlugin::runAllPreTestAction(Utest& test, TestResult& result)
{
if (enabled_) preTestAction(test, result);
next_->runAllPreTestAction(test, result);
}
void TestPlugin::runAllPostTestAction(Utest& test, TestResult& result)
{
if (enabled_) postTestAction(test, result);
next_->runAllPostTestAction(test, result);
}
bool TestPlugin::parseAllArguments(int ac, char** av, int index)
{
if (parseArguments(ac, av, index)) return true;
if (next_) return next_->parseAllArguments(ac, av, index);
return false;
}
const SimpleString& TestPlugin::getName()
{
return name_;
}
TestPlugin* TestPlugin::getPluginByName(const SimpleString& name)
{
if (name == name_) return this;
if (next_) return next_->getPluginByName(name);
return (next_);
}
TestPlugin* TestPlugin::getNext()
{
return next_;
}
TestPlugin* TestPlugin::removePluginByName(const SimpleString& name)
{
TestPlugin* removed;
if (next_ && next_->getName() == name) {
removed = next_;
next_ = next_->next_;
}
return removed;
}
void TestPlugin::disable()
{
enabled_ = false;
}
void TestPlugin::enable ()
{
enabled_ = true;
}
bool TestPlugin::isEnabled()
{
return enabled_;
}
struct cpputest_pair {
void **orig;
void *orig_value;
};
//////// SetPlugin
static int index;
static cpputest_pair setlist[SetPointerPlugin::MAX_SET];
SetPointerPlugin::SetPointerPlugin(const SimpleString& name_)
: TestPlugin(name_)
{
index = 0;
}
SetPointerPlugin::~SetPointerPlugin()
{
}
void CppUTestStore(void**function, void*value)
{
if (index == SetPointerPlugin::MAX_SET) {
FAIL("Maximum number of function pointers installed!");
}
setlist[index].orig_value = value;
setlist[index].orig = function;
index++;
}
void SetPointerPlugin::postTestAction(Utest& test, TestResult& result)
{
for (int i = index-1; i >= 0; i--)
*((void**)setlist[i].orig) = setlist[i].orig_value;
index = 0;
}
//////// NullPlugin
NullTestPlugin::NullTestPlugin()
: TestPlugin(0)
{
}
NullTestPlugin* NullTestPlugin::instance()
{
static NullTestPlugin _instance;
return &_instance;
}
void NullTestPlugin::runAllPreTestAction(Utest&, TestResult&)
{
}
void NullTestPlugin::runAllPostTestAction(Utest&, TestResult&)
{
}
| [
"RobinofChina@43938a50-64aa-11de-9867-89bd1bae666e"
]
| [
[
[
1,
167
]
]
]
|
aa019bf9a87ed1795bd3870de0c61093fee07c86 | 3bce1c769abf091f5ecf6a7f3330e71aba4aae77 | /notelist.cpp | 516fce624e6605610bc10ea611723006417a0747 | []
| no_license | suaannihilant/wikenotes | 3aebffe8f2df534a5a9d234a9e4a8188ede15124 | af512e6fc86855651b1044d568a07cc2ab701be6 | refs/heads/master | 2020-04-21T16:49:13.923925 | 2011-07-06T08:45:18 | 2011-07-06T08:45:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,463 | cpp | #include "notelist.h"
#include "noteitem.h"
#include "mainwindow.h"
const int UNIT_PADDING = 240;
NoteList::NoteList( QWidget* parent ) : QWidget(parent)
{
setStyleSheet(".NoteList { background-color : white;}");
}
QSize NoteList::sizeHint() const
{
int h = m_notes.size()*UNIT_PADDING+m_heightDelta;
if(h == 0)
h = 100;
int w = width();
return QSize(w, h);
}
void NoteList::extend(int num)
{
for(int i=0;i<num;++i)
m_notes.append(0);
}
bool NoteList::createNote(int idx)
{
SQLiteStatement *q = g_mainWindow->getFoundNote(idx);
bool ret = false;
if(q->FetchRow()) {
NoteItem* noteItem;
noteItem = new NoteItem(this,q->GetColumnInt(0),true);
noteItem->autoSize();
m_notes[idx] = noteItem;
int delta = noteItem->height() - UNIT_PADDING;
if(delta) {
m_heightDelta += delta;
adjustSize();
}
ret = true;
}
return ret;
}
void NoteList::fitSize(int w, int h)
{
m_viewPortHeight = h;
int rh = h;
if(m_notes.size() == 1) {
if(m_notes[0] == 0)
createNote(0);
m_notes[0]->resize(w,h);
}
else
rh = size().height();
resize(w, rh);
}
void NoteList::setTextNoteFont(const QFont& font)
{
int i, n = m_notes.size();
for(i=0;i<n;i++) {
if(m_notes[i]) {
m_notes[i]->setFont(font);
}
}
}
void NoteList::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
painter.fillRect(event->rect(), QBrush(Qt::white));
QRect redrawRect = event->rect();
int top = redrawRect.top();
int btm = redrawRect.bottom();
int i, n = m_notes.size();
int h = 0;
int beginRow = -1, endRow = -1;
int beginTop = 0;
int unitHeight;
for(i=0;i<n;++i) {
unitHeight = (m_notes[i] == 0)? UNIT_PADDING : m_notes[i]->height();
h += unitHeight;
if(beginRow == -1 && h >= top) {
beginRow = i;
beginTop = h-unitHeight;
}
if(endRow == -1 && h >= btm) {
endRow = i+1;
break;
}
}
if(endRow == -1 || endRow >= n)
endRow = n-1;
if(beginRow>=0 && endRow-beginRow+1 > 0) {
for (i = beginRow; i <= endRow; ++i) {
if(m_notes[i] == 0)
createNote(i);
if(m_notes[i]) {
m_notes[i]->setGeometry(QRect(16, beginTop, width()-16, m_notes[i]->height()));
beginTop += m_notes[i]->height();
}
}
}
event->accept();
}
void NoteList::addNote(NoteItem* item)
{
m_notes.append(item);
}
NoteItem* NoteList::getNextNote(NoteItem* item, int dir)
{
NoteItem* ret = 0;
int i, n = m_notes.size();
for(i=0;i<n;i++) {
if(m_notes[i] == item) {
break;
}
}
i = i+dir;
if(i >= 0 && i<n)
ret = m_notes[i];
return ret;
}
void NoteList::removeNote(NoteItem* item)
{
m_heightDelta -= item->height()-UNIT_PADDING;
m_notes.removeOne(item);
delete item;
adjustSize();
}
void NoteList::clear()
{
m_heightDelta = 0;
NoteItem::setActiveItem(0);
int i = 0, n = m_notes.size();
NoteItem* item;
n -= m_notes.removeAll(0);
while(i++<n) {
item = m_notes.takeFirst();
delete item;
}
}
| [
"[email protected]"
]
| [
[
[
1,
138
]
]
]
|
ae13d5656c6041fd506042221e9aa113beaaaccc | 772690258e7a85244cc871d744bf54fc4e887840 | /ms22vv/Castle Defence Ogre3d/Castle Defence Ogre3d/Model/Weapon/WeaponFactory.h | fce586677f637be71c9c7f2bd6e107620bd67c11 | []
| no_license | Argos86/dt2370 | f735d21517ab55de19cea933b467f46837bb6401 | 4a393a3c83deb3cb6df90b36a9c59e2e543917ee | refs/heads/master | 2021-01-13T00:53:43.286445 | 2010-02-01T07:43:50 | 2010-02-01T07:43:50 | 36,057,264 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 709 | h | #ifndef Weapon_Factory_H_
#define Weapon_Factory_H_
#include <OgreSceneNode.h>
#include <OgreSceneManager.h>
#include <OgreVector3.h>
#include <OgreString.h>
#include "WeaponBase.h"
#include "..\..\Controller\IEvent.h"
class WeaponFactory
{
private:
IEvent *m_eventToView;
IModel *m_eventToModel;
ISound *m_soundEffects;
public:
enum WeaponType {STANDARD, LASER, Weapon03};
WeaponFactory::WeaponFactory( IEvent *a_eventToView, IModel *a_eventToModel , ISound *a_soundEffects);
WeaponBase* WeaponFactory::CreateWeapon( Ogre::SceneManager *a_scenemgr, Ogre::Vector3 a_relativePosition, int a_weaponType, Ogre::String a_name);
WeaponFactory::~WeaponFactory();
};
#endif
| [
"[email protected]@3422cff2-cdd9-11de-91bf-0503b81643b9"
]
| [
[
[
1,
27
]
]
]
|
0fa42a03650a6ec879237f283bec6fa5b2ed6f5f | 51574a600a87ecfaaec8ea0e46b3809884859680 | /MotionPlan/NavigationRectangle.h | e733f9b72b0bb057c88413f754d00a79da351bfd | []
| no_license | suilevap/motion-plan | b5ad60a8448b118c3742c8c9c42b29fd5e41ef3e | d9f5693938287f2179ca2cb4eb75bda51b97bbb0 | refs/heads/master | 2021-01-10T03:29:50.373970 | 2011-12-20T22:39:55 | 2011-12-20T22:39:55 | 49,495,165 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,212 | h | #pragma once
#ifndef MOTIONPLAN_ASTAR_NAVIGATIONRECTANGLE_H
#define MOTIONPLAN_ASTAR_NAVIGATIONRECTANGLE_H
#include <vector>
#include "FastVector.h"
#include "EdgeInfo.h"
#include "Point.h"
#include "Rectangle.h"
namespace AStar
{
template<
typename CoordType,
typename CellType,
typename CostInfo = float>
class NavigationRectangle : public Rectangle<CoordType>
{
protected:
CellType _value;
std::vector<EdgeInfo<int, CostInfo>> _links;
int _index;
public:
CellType GetValue() { return _value;}
void SetValue(CellType value) { _value = value;}
std::vector<EdgeInfo<int, CostInfo>>* GetNeighboors() { return &(_links); };
int GetId() { return _index;}
void FindNeighbors(std::vector<NavigationRectangle<CoordType, CellType, CostInfo>*> navRects, CoordType step);
void AddEdge(EdgeInfo<int, CostInfo> edge);
NavigationRectangle(Point<CoordType> point1, Point<CoordType> point2, int index, CellType value);
NavigationRectangle(Rectangle<CoordType>& rect, int index, CellType value);
NavigationRectangle(){}
};
#include "NavigationRectangle.inl"
}
#endif //MOTIONPLAN_ASTAR_NAVIGATIONRECTANGLE_H
| [
"suilevap@localhost",
"[email protected]"
]
| [
[
[
1,
34
],
[
36,
49
]
],
[
[
35,
35
]
]
]
|
b46df406210a7e70ca983f3ffb2ee7397feccc25 | 1bbd5854d4a2efff9ee040e3febe3f846ed3ecef | /src/scrview/client.h | c2464f9de94ca6ae41c31edd3e89376dc6c47737 | []
| no_license | amanuelg3/screenviewer | 2b896452a05cb135eb7b9eb919424fe6c1ce8dd7 | 7fc4bb61060e785aa65922551f0e3ff8423eccb6 | refs/heads/master | 2021-01-01T18:54:06.167154 | 2011-12-21T02:19:10 | 2011-12-21T02:19:10 | 37,343,569 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,073 | h | #ifndef CLIENT_H
#define CLIENT_H
#include <QThread>
#include <QMutex>
#include <QObject>
#include <QTcpSocket>
class Viewer;
class Client : public QObject
{
Q_OBJECT
private:
QMutex* scrMutex;
QMutex* mouseMutex;
QTcpSocket *socket;
QString host;
QByteArray *screen;
bool isDone;
quint16 blockSize;
bool canDelete;
Viewer* parrentViewer;
public:
explicit Client(QObject *parent = 0, Viewer* parrentViewer = NULL, QMutex* scrMutex = NULL, QMutex* mouseMutex = NULL);
void sendPacket(QByteArray data);
void setHost(QString host);
QString getHost();
void connectToHost();
void disconnect();
void requestNewFortune();
void send(QByteArray a);
bool isMade() { return isDone; }
void canDel() { canDelete = true; isDone = false; }
QByteArray* fetchScreen() { isDone = true; return screen; }
void send(bool isRight, bool isLeft, quint16 x, quint16 y);
signals:
public slots:
void connected();
void readyRead();
};
#endif // CLIENT_H
| [
"JuliusR@localhost",
"j.salkevicius@localhost"
]
| [
[
[
1,
2
],
[
5,
7
],
[
10,
13
],
[
16,
21
],
[
23,
23
],
[
26,
45
]
],
[
[
3,
4
],
[
8,
9
],
[
14,
15
],
[
22,
22
],
[
24,
25
]
]
]
|
ad4a6da027f2613c551e24bb48a1f9894e197bba | 9ad9345e116ead00be7b3bd147a0f43144a2e402 | /Integration_WAH_&_Extraction/SMDataExtraction/FlexVCBridgeStaticLib/FlexBridge.cpp | 0af6b4677210a1c07a79d495e4dc9e0212723725 | []
| no_license | asankaf/scalable-data-mining-framework | e46999670a2317ee8d7814a4bd21f62d8f9f5c8f | 811fddd97f52a203fdacd14c5753c3923d3a6498 | refs/heads/master | 2020-04-02T08:14:39.589079 | 2010-07-18T16:44:56 | 2010-07-18T16:44:56 | 33,870,353 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,003 | cpp | /*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is the Flex C++ Bridge.
*
* The Initial Developer of the Original Code is
* Anirudh Sasikumar (http://anirudhs.chaosnet.org/).
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
*/
/* TODO: Documentation. (Poor you!) */
#include "FlexBridge.h"
#include "FlexCall.h"
#include <windows.h>
#include "FlexCallQueue.h"
#include "Logger.h"
#include "ctype.h"
#include "ASInstance.h"
#include <sstream>
#include "BridgeManager.h"
#include "BridgeException.h"
using std::string;
using std::map;
using std::stringstream;
using std::istringstream;
const short int CFlexBridge::TYPE_ASINSTANCE = 1;
const short int CFlexBridge::TYPE_ASFUNCTION = 2;
const short int CFlexBridge::TYPE_JSFUNCTION = 3;
const short int CFlexBridge::TYPE_ANONYMOUS = 4;
/* for register local function to be thread safe */
static HANDLE g_hLocalFnMapMutex = CreateMutex(NULL, FALSE, NULL);
CFlexBridge::CFlexBridge(const string& name, int iFlashID)
{
m_sName = name;
m_iFlashID = iFlashID;
}
CFlexBridge::~CFlexBridge(void)
{
std::map<string,CASProxy*>::iterator ii1;
for( ii1=m_RemoteTypeMap.begin(); ii1!=m_RemoteTypeMap.end(); ++ii1)
{
CASProxy* pCache;
pCache = (*ii1).second;
delete pCache;
}
std::map<string,CASProxy*>::iterator ii2;
for( ii2=m_RemoteFunctionMap.begin(); ii2!=m_RemoteFunctionMap.end(); ++ii2)
{
CASProxy* pCache;
pCache = (*ii2).second;
delete pCache;
}
std::map<string,CASInstance*>::iterator ii3;
for( ii3=m_RemoteInstanceMap.begin(); ii3!=m_RemoteInstanceMap.end(); ++ii3)
{
CASInstance* pCache;
pCache = (*ii3).second;
delete pCache;
}
/* for( map<CCPPInstance*,void (*)(CASObject& , CFlexBridge*),cmp_cppinstance>::iterator ii=m_LocalFunctionMap.begin(); ii!=m_LocalFunctionMap.end(); ++ii) */
/* { */
/* CCPPInstance* pCache; */
/* pCache = (*ii).first; */
/* delete pCache; */
/* } */
}
void CFlexBridge::Root(CASObject& oRespObj)
{
CallASFunction(string("getRoot"), NULL, oRespObj);
}
void CFlexBridge::CallASFunction(const string& sFn, const std::vector<CASObject>* vArgs, CASObject& outObj)
{
string res;
if ( vArgs == NULL )
{
CFlexCall::BuildXML(sFn, res);
}
else
{
CFlexCall::BuildXML(sFn, *vArgs, res);
}
string* sendmsg = new string(res);
CASResponse oASResp;
oASResp.m_iFlashID = m_iFlashID;
CFlexCallQueue::RegisterForResponse(oASResp);
SendMessage((HWND)CFlexCall::m_pDlg, WM_FLEXCALLBACK_RETURN, (WPARAM)sendmsg, (LPARAM)&oASResp);
LOGDEBUG("waiting for as response");
CFlexCallQueue::WaitForResponse(oASResp);
LOGDEBUG("got as response");
string fnout;
std::vector<CASObject> objs;
CFlexCallQueue::ParseFlexXML(oASResp.m_sResponse, fnout, objs);
if ( objs.size() > 1 )
LOG("Warning: Unexpected return array size in FlexBridge: " << objs.size());
if ( objs.size () == 1 )
{
//objs[0].Dump();
Deserialize(objs[0], outObj);
}
//LOG("Response from function: " << oASResp.m_sResponse);
}
void CFlexBridge::CallAS(const string& sFn, CASObject& outObj)
{
CallASFunction(sFn, NULL, outObj);
}
void CFlexBridge::CallAS(const string& sFn, const std::vector<CASObject>& vArgs,
CASObject& outObj)
{
CallASFunction(sFn, &vArgs, outObj);
}
/* Look at Ely's FABridge.js. This is a C++ port of that. */
void CFlexBridge::AddTypeDataToCache(CASObject& newTypes)
{
/* it has to be an object of type array */
CASValue newTypesValue;
/* add new functions to cache */
newTypes.GetValue(newTypesValue);
if ( newTypesValue.m_aVal != NULL )
{
for ( unsigned int i = 0; i < newTypesValue.m_aVal->size(); i++ )
{
CASValue oTypeObj;
(*newTypesValue.m_aVal)[i].GetValue(oTypeObj);
CASProxy* oObjProxy = new CASProxy();
string sTypeName;
std::map<string, CASObject>::iterator cur = oTypeObj.m_oVal->find(string("name"));
if ( cur != oTypeObj.m_oVal->end() )
{
LOGDEBUG("This is the name");
CASObject* methodObj;
CASValue methodObjValue;
methodObj = &(cur->second);
methodObj->GetValue(methodObjValue);
if ( methodObjValue.m_sVal )
{
sTypeName = *methodObjValue.m_sVal;
}
}
else
{
LOGDEBUG("No typename");
}
std::map<string, CASProxy*>::iterator dupIt = m_RemoteTypeMap.find(sTypeName);
if ( dupIt != m_RemoteTypeMap.end() )
{
delete oObjProxy;
return;
}
else
m_RemoteTypeMap.insert(std::make_pair(sTypeName, oObjProxy));
cur = oTypeObj.m_oVal->find(string("methods"));
if ( cur != oTypeObj.m_oVal->end() )
{
LOGDEBUG("There are methods");
CASObject* methodObj;
CASValue methodObjValue;
methodObj = &(cur->second);
methodObj->GetValue(methodObjValue);
if ( methodObjValue.m_aVal )
{
LOGDEBUG("Got array of methods");
for ( unsigned int j = 0; j < methodObjValue.m_aVal->size(); j++ )
{
CASValue methodName;
(*methodObjValue.m_aVal)[j].GetValue(methodName);
if ( methodName.m_sVal )
oObjProxy->Add(*methodName.m_sVal, ASPROXY_METHOD);
}
}
//AddTypeDataToCache(*newTypes);
}
else
{
LOGDEBUG("No methods");
}
cur = oTypeObj.m_oVal->find(string("accessors"));
if ( cur != oTypeObj.m_oVal->end() )
{
LOGDEBUG("There are accessors");
CASObject* methodObj;
CASValue methodObjValue;
methodObj = &(cur->second);
methodObj->GetValue(methodObjValue);
if ( methodObjValue.m_aVal )
{
LOGDEBUG("Got array of accessors");
for ( unsigned int j = 0; j < methodObjValue.m_aVal->size(); j++ )
{
CASValue methodName;
(*methodObjValue.m_aVal)[j].GetValue(methodName);
if ( methodName.m_sVal )
{
string oPropStr = *methodName.m_sVal;
string oFinalPropStrGet = "get";
oFinalPropStrGet += oPropStr;
string oFinalPropStrSet = "set";
oFinalPropStrSet += oPropStr;
if ( oPropStr.length() > 1 )
{
/* if ( oPropStr[0] >= 'a' && oPropStr[0] <= 'z' ) */
/* { */
/* oFinalPropStrGet = "get"; */
/* oFinalPropStrGet += toupper(oPropStr[0]); */
/* oFinalPropStrGet += oPropStr.substr(1); */
/* oFinalPropStrSet = "set"; */
/* oFinalPropStrSet += toupper(oPropStr[0]); */
/* oFinalPropStrSet += oPropStr.substr(1); */
/* } */
/* Change to support Devin Garner's FABridge */
if ( ( oPropStr[0] >= 'a' && oPropStr[0] <= 'z' ) || ( oPropStr[0] >= 'A' && oPropStr[0] <= 'Z' ) )
{
oFinalPropStrGet = "get";
oFinalPropStrGet += oPropStr;
oFinalPropStrSet = "set";
oFinalPropStrSet += oPropStr;
}
}
oObjProxy->Add(oFinalPropStrGet, ASPROXY_GETTER);
oObjProxy->Add(oFinalPropStrSet, ASPROXY_SETTER);
}
}
}
//AddTypeDataToCache(*newTypes);
}
else
{
LOGDEBUG("No accessors");
}
/* cur = oTypeObj.m_oVal->find(string("name")); */
/* if ( cur != oTypeObj.m_oVal->end() ) */
/* { */
/* LOGDEBUG("This is the name"); */
/* CASObject* methodObj; */
/* CASValue methodObjValue; */
/* methodObj = &(cur->second); */
/* methodObj->GetValue(methodObjValue); */
/* if ( methodObjValue.m_sVal ) */
/* { */
/* sTypeName = *methodObjValue.m_sVal; */
/* } */
/* } */
/* else */
/* { */
/* LOGDEBUG("No typename"); */
/* } */
/* map<string, CASProxy*>::iterator dupIt = m_RemoteTypeMap.find(sTypeName); */
/* if ( dupIt != m_RemoteTypeMap.end() ) */
/* { */
/* delete oObjProxy; */
/* } */
/* else */
/* m_RemoteTypeMap.insert(std::make_pair(sTypeName, oObjProxy)); */
}
}
else
{
LOGDEBUG("Newtypesvalue is not an array!");
}
}
void CFlexBridge::Deserialize(const CASObject& obj, CASObject& oOutObj)
{
if ( obj.GetType() == ASOBJECT_NUMBER ||
obj.GetType() == ASOBJECT_INT ||
obj.GetType() == ASOBJECT_STRING ||
obj.GetType() == ASOBJECT_BOOLEAN )
{
if ( obj.GetType() == ASOBJECT_STRING )
{
CASValue objStr;
obj.GetValue(objStr);
unsigned int uiErrIndex = (*objStr.m_sVal).find("__FLASHERROR__") ;
if ( uiErrIndex == 0 )
{
string sErr = (*objStr.m_sVal).substr(string("__FLASHERROR__||").length());
LOG("Flash Error occurred: " << sErr);
oOutObj = sErr;
throw CBridgeException(sErr);
return;
}
}
oOutObj = obj;
}
else if ( obj.GetType() == ASOBJECT_ARRAY )
{
CASValue objValue;
obj.GetValue(objValue);
if ( objValue.m_aVal )
{
LOGDEBUG("Deserialize: it is an array");
std::vector<CASObject> vArrObjs;
for ( unsigned int ia = 0; ia < objValue.m_aVal->size(); ia++ )
{
CASObject oArrElem;
Deserialize((*objValue.m_aVal)[ia], oArrElem);
vArrObjs.push_back(oArrElem);
}
oOutObj.SetArray(vArrObjs);
}
}
else if ( obj.GetType() == ASOBJECT_OBJECT ) /* heh heh */
{
/* iterate and add new types to cache */
LOGDEBUG("Deserialize: it is an object");
CASValue objValue;
CASObject* newTypes;
obj.GetValue(objValue);
if ( objValue.m_oVal != NULL )
{
std::map<string, CASObject>::iterator cur = objValue.m_oVal->find(string("newTypes"));
if ( cur != objValue.m_oVal->end() )
{
LOGDEBUG("There are newTypes");
newTypes = &(cur->second);
AddTypeDataToCache(*newTypes);
}
else
{
LOGDEBUG("No newTypes");
}
cur = objValue.m_oVal->find(string("newRefs"));
if ( cur != objValue.m_oVal->end() )
{
LOGDEBUG("There are newRefs");
newTypes = &(cur->second);
CreateProxies(*newTypes);
}
else
{
LOGDEBUG("No newRefs");
}
cur = objValue.m_oVal->find(string("type"));
if ( cur != objValue.m_oVal->end() )
{
newTypes = &(cur->second);
CASValue oASType;
CASObject* oTypeValObj = NULL;
CASValue oASValType;
newTypes->GetValue(oASType);
cur = objValue.m_oVal->find(string("value"));
if ( cur != objValue.m_oVal->end() )
{
oTypeValObj = &(cur->second);
oTypeValObj->GetValue(oASValType);
LOGDEBUG("Got val obj");
//oTypeValObj->Dump();
}
if ( oASType.m_nVal )
{
LOGDEBUG(" AS Type is " << *oASType.m_nVal << " ");
switch ( (int)*oASType.m_nVal )
{
case TYPE_ASINSTANCE:
if ( oTypeValObj )
{
stringstream s;
s << *oASValType.m_nVal;
LOGDEBUG("Type value as string is " << s.str() );
/* look up in cache for this instance */
CASInstance* pAsinst = GetInstance(s.str());
if ( pAsinst )
{
oOutObj.SetASInstance(*pAsinst);
}
}
break;
case TYPE_ASFUNCTION:
/* get function proxy */
LOG("Warning: AS Function not supported yet!");
break;
case TYPE_ANONYMOUS:
if ( oTypeValObj )
{
oOutObj = *oTypeValObj;
}
break;
case TYPE_JSFUNCTION:
if ( oTypeValObj )
{
stringstream s;
s << *oASValType.m_nVal;
CCPPInstance oCPPinst;
oCPPinst.m_sID = s.str();
oCPPinst.m_uiBridgeID = CBridgeManager::GetIDBridgePtr((void*)this);
oOutObj = oCPPinst;
}
break;
}
}
}
else
{
LOG("No type");
}
}
else
{
LOG("Object to be deserialized has map empty!");
}
}
}
void CFlexBridge::CreateProxy(string& sType, CASObject& newTypes)
{
/* TODO: add support of creation of local C++ objects (look at if
* (ut.isUserProto){var instFactory = window[ut.simpleType];var
* instance = new instFactory(this.name,
* objID);instance.fb_instance_id = objID; }
*/
CASInstance* oASInst = new CASInstance();
std::map<string, CASInstance*>::iterator cur = m_RemoteInstanceMap.find(sType);
if ( cur != m_RemoteInstanceMap.end() )
{
delete oASInst;
return;
}
else
m_RemoteInstanceMap.insert(std::make_pair(sType, oASInst));
/* check if the type is there in our cache */
CASValue newTypesValue;
/* add new functions to cache */
newTypes.GetValue(newTypesValue);
oASInst->m_uiBridgeID = CBridgeManager::GetIDBridgePtr((void*)this);
oASInst->m_sID = sType;
if ( newTypesValue.m_sVal )
{
std::map<string, CASProxy*>::iterator cur = m_RemoteTypeMap.find(*newTypesValue.m_sVal);
if ( cur != m_RemoteTypeMap.end() )
{
/* found type */
LOGDEBUG("Type " << *newTypesValue.m_sVal << " is a remote type");
oASInst->m_oTypeProxy = cur->second;
}
}
/* map<string, CASInstance*>::iterator cur = m_RemoteInstanceMap.find(sType); */
/* if ( cur != m_RemoteInstanceMap.end() ) */
/* { */
/* delete oASInst; */
/* } */
/* else */
/* m_RemoteInstanceMap.insert(std::make_pair(sType, oASInst)); */
}
void CFlexBridge::CreateProxies(CASObject& newTypes)
{
/* it has to be an object of type array */
CASValue newTypesValue;
/* add new functions to cache */
newTypes.GetValue(newTypesValue);
if ( newTypesValue.m_oVal != NULL )
{
std::map<string, CASObject>::iterator ii;
for(ii= newTypesValue.m_oVal->begin(); ii!= newTypesValue.m_oVal->end(); ++ii)
{
string sTypeName;
sTypeName = (*ii).first;
LOGDEBUG("Got proxy " << sTypeName );
CreateProxy(sTypeName, (*ii).second);
}
}
else
{
LOG("CreateProxies did not get an object!");
}
}
CASInstance* CFlexBridge::GetInstance(string iID)
{
std::map<string, CASInstance*>::iterator cur = m_RemoteInstanceMap.find(iID);
if ( cur != m_RemoteInstanceMap.end() )
{
return cur->second;
}
return NULL;
}
bool CFlexBridge::Call(const CASObject& oObjIn, const char* sFn, CASObject& oObjOut)
{
return CallInternal(oObjIn, sFn, NULL, oObjOut);
}
bool CFlexBridge::Call(const CASObject& oObjIn, const char* sFn, const std::vector<CASObject>& oArgsIn, CASObject& oObjOut)
{
return CallInternal(oObjIn, sFn, &oArgsIn, oObjOut);
}
bool CFlexBridge::CallInternal(const CASObject& oObjIn, const char* sFn, const std::vector<CASObject>* oArgsIn, CASObject& oObjOut)
{
/* You don't see this */
CASInstance* pInst = oObjIn.GetInstance();
string sFnStr = sFn;
if ( pInst )
{
std::vector<CASObject> vProps;
CASObject objRef;
CASObject propName;
double d = 0;
std::istringstream iss(pInst->m_sID);
iss >> d;
objRef.SetNumber(d);
string propStr = sFnStr;
ASProxyType oPType = pInst->m_oTypeProxy->GetType(sFnStr);
if ( oPType == ASPROXY_NONE )
{
/* not in our type cache */
string errType;
GetProxyName(pInst->m_oTypeProxy, errType);
string errMsg = "Method ";
errMsg += sFnStr;
errMsg += " not found in type cache for type ";
if ( errType.length() == 0 )
errMsg += pInst->m_sID;
else
errMsg += errType;
throw CBridgeException(errMsg);
}
if ( oPType == ASPROXY_GETTER || oPType == ASPROXY_SETTER )
{
/* Change to support Devin Garner's FABridge */
/* if (propStr[0] == 'G' || propStr[0] == 'S' ) */
/* { */
propStr = propStr.substr(3);
/* } */
/* else */
/* { */
/* propStr = propStr.substr(3); */
/* char c = tolower(propStr[0]); */
/* propStr[0] = c; */
/* } */
}
propName.SetString(propStr);
vProps.push_back(objRef);
vProps.push_back(propName);
if ( oPType == ASPROXY_GETTER )
{
if ( oArgsIn )
{
LOG("Warning: Silently ignoring args for getter method");
}
CallASFunction(string("getPropFromAS"), &vProps, oObjOut);
}
else if ( oPType == ASPROXY_SETTER )
{
if ( oArgsIn )
{
if ( oArgsIn->size() > 1 )
{
throw CBridgeException("Setter method passed more than 1 argument");
}
for ( unsigned int i = 0; i < oArgsIn->size(); i++ )
{
vProps.push_back((*oArgsIn)[i]);
}
CallASFunction(string("setPropInAS"), &vProps, oObjOut);
}
else
throw CBridgeException("Setter method called without an argument");
}
else if ( oPType == ASPROXY_METHOD )
{
if ( oArgsIn )
{
CASObject oArgArrObj;
for ( unsigned int i=0; i < oArgsIn->size(); i++ )
{
if ( (*oArgsIn)[i].GetType() == ASOBJECT_LOCALINSTANCE )
{
if ( (*oArgsIn)[i].GetCPPInstance()->m_sID.length() == 0 )
{
CCPPInstance oInst = RegisterLocalFunction((void (*)(CASObject& , CFlexBridge*))((*oArgsIn)[i].GetCPPInstance()->m_pFn));
(*oArgsIn)[i].GetCPPInstance()->m_sID = oInst.m_sID;
(*oArgsIn)[i].GetCPPInstance()->m_uiBridgeID = oInst.m_uiBridgeID;
}
}
}
oArgArrObj.SetArray(*oArgsIn);
vProps.push_back(oArgArrObj);
CallASFunction(string("invokeASMethod"), &vProps, oObjOut);
}
else
{
CASObject oArgArrObj;
std::vector<CASObject> vEmptyArgs;
vProps.push_back(vEmptyArgs);
CallASFunction(string("invokeASMethod"), &vProps, oObjOut);
}
}
}
else
{
throw CBridgeException("ASObject is not an AS instance!");
}
return false;
}
void CFlexBridge::AddInitializationCallback(CASWork* pWork)
{
m_vInitCallbacks.push_back(pWork);
}
void CFlexBridge::Initialized()
{
for ( unsigned int i = 0; i < m_vInitCallbacks.size(); i++ )
{
m_vInitCallbacks[i]->Run();
delete m_vInitCallbacks[i];
}
m_vInitCallbacks.clear();
}
CASObject CFlexBridge::Create(const char* sClassName)
{
CASObject oObjOut;
std::vector<CASObject> vArgs;
vArgs.push_back(CASObject(sClassName));
CallASFunction(string("create"), &vArgs, oObjOut);
return oObjOut;
}
CASObject CFlexBridge::ClassRef(const char* sClassName)
{
CASObject oObjOut;
std::vector<CASObject> vArgs;
vArgs.push_back(CASObject(sClassName));
CallASFunction(string("classRef"), &vArgs, oObjOut);
return oObjOut;
}
CCPPInstance CFlexBridge::RegisterLocalFunction(void (*pFunc)(CASObject& , CFlexBridge*))
{
DWORD dwResult;
dwResult = WaitForSingleObject(g_hLocalFnMapMutex, INFINITE);
CCPPInstance pInst;
if ( dwResult != WAIT_OBJECT_0 )
{
LOG("ERROR: Mutex lock failed!");
return pInst;
}
pInst.m_uiBridgeID = CBridgeManager::GetIDBridgePtr(this);
std::ostringstream s;
s << CCPPInstance::m_uiCounter++;
pInst.m_sID = s.str();
m_LocalFunctionMap.insert(std::make_pair(pInst.m_sID, pFunc));
ReleaseMutex(g_hLocalFnMapMutex);
return pInst;
}
void CFlexBridge::CallLocalFunction(const CASObject& oArgs)
{
CASValue oVal;
oArgs.GetValue(oVal);
if ( oVal.m_aVal && oVal.m_aVal->size() > 0 )
{
CASObject oID = (*oVal.m_aVal)[0];
CASValue oIDVal;
string sID;
oID.GetValue(oIDVal);
std::ostringstream oss;
oss << (int)(*oIDVal.m_nVal);
sID = oss.str();
LOGDEBUG("No Val is " << *oIDVal.m_nVal);
std::map <string, void (*)(CASObject& , CFlexBridge*)>::iterator it = m_LocalFunctionMap.find(sID);
if ( it != m_LocalFunctionMap.end() )
{
if ( oVal.m_aVal->size() > 1 )
{
CASObject oCallArg;
Deserialize((*oVal.m_aVal)[1], oCallArg);
(it->second)(oCallArg, this);
return;
}
}
}
throw CBridgeException("Cannot find registered CPP function");
}
void CFlexBridge::GetProxyName(const CASProxy* pProxy, string& sTypeNameOut)
{
std::map<string,CASProxy*>::iterator ii;
for(ii=m_RemoteTypeMap.begin(); ii!=m_RemoteTypeMap.end(); ++ii)
{
CASProxy* pCache;
pCache = (*ii).second;
if ( pProxy == pCache )
{
sTypeNameOut = ii->first;
return;
}
}
}
| [
"jaadds@c7f6ba40-6498-11de-987a-95e5a5a5d5f1"
]
| [
[
[
1,
812
]
]
]
|
eba0660adef0ba29cc061b940dfc7c36c88b1546 | b2b5c3694476d1631322a340c6ad9e5a9ec43688 | /Baluchon/PoseEstimatedPattern.cpp | 163747c304c2f01589852472283dabb48b1ab5a3 | []
| no_license | jpmn/rough-albatross | 3c456ea23158e749b029b2112b2f82a7a5d1fb2b | eb2951062f6c954814f064a28ad7c7a4e7cc35b0 | refs/heads/master | 2016-09-05T12:18:01.227974 | 2010-12-19T08:03:25 | 2010-12-19T08:03:25 | 32,195,707 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,447 | cpp | #include "PoseEstimatedPattern.h"
namespace baluchon { namespace core { namespace services { namespace poseestimation {
PoseEstimatedPattern::PoseEstimatedPattern(IDetectedPattern *pattern)
{
mPattern = pattern;
mRotationMatrices = new vector<CvMat*>();
mTranslationMatrices = new vector<CvMat*>();
}
PoseEstimatedPattern::~PoseEstimatedPattern(void)
{
}
int PoseEstimatedPattern::getWidth()
{
return mPattern->getWidth();
}
int PoseEstimatedPattern::getPointCount()
{
return mPattern->getPointCount();
}
int PoseEstimatedPattern::getHeight()
{
return mPattern->getHeight();
}
CvPoint2D32f PoseEstimatedPattern::getSourcePointAt(int pos, int orientation)
{
return mPattern->getSourcePointAt(pos, orientation);
}
vector<vector<CvPoint2D32f>>* PoseEstimatedPattern::getImagePoints()
{
return mPattern->getImagePoints();
}
vector<vector<CvPoint2D32f>>* PoseEstimatedPattern::getImageFramePoints()
{
return mPattern->getImageFramePoints();
}
vector<CvMat*>* PoseEstimatedPattern::getRotationMatrices()
{
return mRotationMatrices;
}
vector<CvMat*>* PoseEstimatedPattern::getTranslationMatrices()
{
return mTranslationMatrices;
}
bool PoseEstimatedPattern::decorates(IPattern *pattern)
{
if(mPattern == pattern)
{
return true;
}
else
{
return mPattern->decorates(pattern);
}
}
}}}};
| [
"[email protected]@bd4f47a5-da4e-a94a-6a47-2669d62bc1a5"
]
| [
[
[
1,
70
]
]
]
|
6ad57eda12d91a5eeb8c04b4ff8b854cecac8dd1 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/graph/example/city_visitor.cpp | ea9ad32915e7e5f07e746d2903a694278e3d27e0 | [
"Artistic-2.0",
"LicenseRef-scancode-public-domain",
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | willrebuild/flyffsf | e5911fb412221e00a20a6867fd00c55afca593c7 | d38cc11790480d617b38bb5fc50729d676aef80d | refs/heads/master | 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,563 | cpp | //
//=======================================================================
// Copyright 1997, 1998, 1999, 2000 University of Notre Dame.
// Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
//
#include <boost/config.hpp>
#include <iostream>
#include <vector>
#include <string>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/depth_first_search.hpp>
#include <boost/graph/breadth_first_search.hpp>
#include <boost/property_map.hpp>
#include <boost/graph/graph_utility.hpp> // for boost::make_list
/*
Example of using a visitor with the depth first search
and breadth first search algorithm
Sacramento ---- Reno ---- Salt Lake City
|
San Francisco
|
San Jose ---- Fresno
|
Los Angeles ---- Las Vegas ---- Phoenix
|
San Diego
The visitor has three main functions:
discover_vertex(u,g) is invoked when the algorithm first arrives at the
vertex u. This will happen in the depth first or breadth first
order depending on which algorithm you use.
examine_edge(e,g) is invoked when the algorithm first checks an edge to see
whether it has already been there. Whether using BFS or DFS, all
the edges of vertex u are examined immediately after the call to
visit(u).
finish_vertex(u,g) is called when after all the vertices reachable from vertex
u have already been visited.
*/
using namespace std;
using namespace boost;
struct city_arrival : public base_visitor<city_arrival>
{
city_arrival(string* n) : names(n) { }
typedef on_discover_vertex event_filter;
template <class Vertex, class Graph>
inline void operator()(Vertex u, Graph&) {
cout << endl << "arriving at " << names[u] << endl
<< " neighboring cities are: ";
}
string* names;
};
struct neighbor_cities : public base_visitor<neighbor_cities>
{
neighbor_cities(string* n) : names(n) { }
typedef on_examine_edge event_filter;
template <class Edge, class Graph>
inline void operator()(Edge e, Graph& g) {
cout << names[ target(e, g) ] << ", ";
}
string* names;
};
struct finish_city : public base_visitor<finish_city>
{
finish_city(string* n) : names(n) { }
typedef on_finish_vertex event_filter;
template <class Vertex, class Graph>
inline void operator()(Vertex u, Graph&) {
cout << endl << "finished with " << names[u] << endl;
}
string* names;
};
int main(int, char*[])
{
enum { SanJose, SanFran, LA, SanDiego, Fresno, LasVegas, Reno,
Sacramento, SaltLake, Phoenix, N };
string names[] = { "San Jose", "San Francisco", "Los Angeles", "San Diego",
"Fresno", "Las Vegas", "Reno", "Sacramento",
"Salt Lake City", "Phoenix" };
typedef std::pair<int,int> E;
E edge_array[] = { E(Sacramento, Reno), E(Sacramento, SanFran),
E(Reno, SaltLake),
E(SanFran, SanJose),
E(SanJose, Fresno), E(SanJose, LA),
E(LA, LasVegas), E(LA, SanDiego),
E(LasVegas, Phoenix) };
/* Create the graph type we want. */
typedef adjacency_list<vecS, vecS, undirectedS> Graph;
#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300
// VC++ has trouble with the edge iterator constructor
Graph G(N);
for (std::size_t j = 0; j < sizeof(edge_array)/sizeof(E); ++j)
add_edge(edge_array[j].first, edge_array[j].second, G);
#else
Graph G(edge_array, edge_array + sizeof(edge_array)/sizeof(E), N);
#endif
cout << "*** Depth First ***" << endl;
depth_first_search
(G,
visitor(make_dfs_visitor(boost::make_list(city_arrival(names),
neighbor_cities(names),
finish_city(names)))));
cout << endl;
/* Get the source vertex */
boost::graph_traits<Graph>::vertex_descriptor
s = vertex(SanJose,G);
cout << "*** Breadth First ***" << endl;
breadth_first_search
(G, s, visitor(make_bfs_visitor(boost::make_list(city_arrival(names),
neighbor_cities(names),
finish_city(names)))));
return 0;
}
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
]
| [
[
[
1,
140
]
]
]
|
44ec2a7c8937c720075e659f1f0c35738212dd33 | 58d6063421b9a1fe30d308a8ee12d6c85a1907fb | /bullet/project/jni/bullet.cpp | de527f4679da4c6251f610ae628c81984af0b940 | [
"Zlib",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | zpc930/android-2d-engine | 0b5e202227261e7162c1dd18664b692c0f6d81ec | 9ed36e07df27d9472ea09860d9d41ebfd3ab6af2 | refs/heads/master | 2021-01-18T16:15:50.526940 | 2010-07-15T18:18:28 | 2010-07-15T18:18:28 | 48,933,039 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 30,242 | cpp | /*
Bullet Continuous Collision Detection and Physics Library for Android NDK
Copyright (c) 2006-2009 Noritsuna Imamura http://www.siprop.org/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
Modified copy of the library Jose Manuel Gomez [email protected]
All the file is modified but you can track the changes in http://code.google.com/hosting/p/android-2d-engine
*/
#include "bullet.h"
JNIEXPORT
jint
JNICALL
Java_org_gs_bullet_Bullet_createNonConfigPhysicsWorld(JNIEnv* env,
jobject thiz,
jobject physicsWorld_obj) {
btDefaultCollisionConfiguration* pCollisionConfig = new btDefaultCollisionConfiguration();
LOGV("Load btDefaultCollisionConfiguration.");
btCollisionDispatcher* pCollisionDispatcher = new btCollisionDispatcher(pCollisionConfig);
LOGV("Load btCollisionDispatcher.");
LOGV("Load worldAabb.");
btAxisSweep3* pWorldAabbCache = new btAxisSweep3(get_vec_by_JavaObj(env, physicsWorld_obj, "worldAabbMin"),
get_vec_by_JavaObj(env, physicsWorld_obj, "worldAabbMax"),
get_int_by_JavaObj(env, physicsWorld_obj, "maxProxies"));
LOGV("Load g_pWorldAabbCache.");
btSequentialImpulseConstraintSolver* pSolver = new btSequentialImpulseConstraintSolver();
btDiscreteDynamicsWorld* pDynamicsWorld = new btDiscreteDynamicsWorld(
pCollisionDispatcher,
pWorldAabbCache,
pSolver,
pCollisionConfig );
if(!is_NULL_vec_field_JavaObj(env, physicsWorld_obj, "gravity")) {
btVector3 gravity(get_vec_by_JavaObj(env, physicsWorld_obj, "gravity"));
pDynamicsWorld->setGravity(gravity);
LOGV("Load setGravity.");
}
g_DynamicsWorlds.push_back(pDynamicsWorld);
jint addr_val = (int)pDynamicsWorld;
set_JavaObj_int(env, physicsWorld_obj, "id", addr_val);
return addr_val;
}
JNIEXPORT
jint
JNICALL
Java_org_gs_bullet_Bullet_changePhysicsWorldConfiguration(JNIEnv* env,
jobject thiz,
jobject physicsWorld_obj) {
int id = get_int_by_JavaObj(env, physicsWorld_obj, "id");
LOGV("Load physicsWorld_obj ID.");
btDynamicsWorld* pDynamicsWorld = g_DynamicsWorlds.get((btDynamicsWorld*)id);
if(pDynamicsWorld == NULL) {
LOGV("Don't Load DynamicsWorld.");
return id;
}
jobject method_obj = get_obj_by_JavaObj(env, physicsWorld_obj, "dynamicsWorld", "Lorg/gs/bullet/interfaces/DynamicsWorld;");
int type = get_type_by_JavaObj(env, method_obj);
if(type == BT_DISCRETE_DYNAMICS_WORLD) {
btDiscreteDynamicsWorld* pDiscreteDynamicsWorld = (btDiscreteDynamicsWorld*)pDynamicsWorld;
LOGV("Cast btDiscreteDynamicsWorld.");
pDiscreteDynamicsWorld->setGravity(get_vec_by_JavaObj(env, physicsWorld_obj, "gravity"));
LOGV("Load setGravity.");
} else if(type == BT_CONTINUOUS_DYNAMICS_WORLD) {
btContinuousDynamicsWorld* pContinuousDynamicsWorld = (btContinuousDynamicsWorld*)pDynamicsWorld;
} else if(type == BT_SIMPLE_DYNAMICS_WORLD) {
btSimpleDynamicsWorld* pSimpleDynamicsWorld = (btSimpleDynamicsWorld*)pDynamicsWorld;
} else {
return NULL;
}
return id;
}
JNIEXPORT
jint
JNICALL
Java_org_gs_bullet_Bullet_createGeometry(JNIEnv* env,
jobject thiz,
jobject geometry_obj) {
btCollisionShape* groundShape;
btScalar mass = get_float_by_JavaObj(env, geometry_obj, "mass");
btVector3 localInertia = get_vec_by_JavaObj(env, geometry_obj, "localInertia");
LOGV("in createGeometry.");
jobject shape_obj = get_obj_by_JavaObj(env, geometry_obj, "shape", "Lorg/gs/bullet/interfaces/Shape;");
LOGV("Load shape interface.");
int shapeType = get_type_by_JavaObj(env, shape_obj);
LOGV("Load shape val.");
logi(STATIC_PLANE_PROXYTYPE);
logi(BOX_SHAPE_PROXYTYPE);
logi(CAPSULE_SHAPE_PROXYTYPE);
logi(CONE_SHAPE_PROXYTYPE);
logi(CYLINDER_SHAPE_PROXYTYPE);
logi(SPHERE_SHAPE_PROXYTYPE);
logi(TETRAHEDRAL_SHAPE_PROXYTYPE);
switch(shapeType) {
case STATIC_PLANE_PROXYTYPE:
LOGV("in STATIC_PLANE_PROXYTYPE.");
groundShape = new btStaticPlaneShape(get_vec_by_JavaObj(env, shape_obj, "planeNormal"),
get_float_by_JavaObj(env, shape_obj, "planeConstant"));
break;
case BOX_SHAPE_PROXYTYPE:
LOGV("in BOX_SHAPE_PROXYTYPE.");
groundShape = new btBoxShape(get_vec_by_JavaObj(env, shape_obj, "boxHalfExtents"));
break;
case CAPSULE_SHAPE_PROXYTYPE:
groundShape = new btCapsuleShape(get_float_by_JavaObj(env, shape_obj, "radius"),
get_float_by_JavaObj(env, shape_obj, "height"));
break;
case CONE_SHAPE_PROXYTYPE:
groundShape = new btConeShape(get_float_by_JavaObj(env, shape_obj, "radius"),
get_float_by_JavaObj(env, shape_obj, "height"));
break;
case CYLINDER_SHAPE_PROXYTYPE:
groundShape = new btCylinderShape(get_vec_by_JavaObj(env, shape_obj, "halfExtents"));
break;
case SPHERE_SHAPE_PROXYTYPE:
LOGV("in SPHERE_SHAPE_PROXYTYPE.");
groundShape = new btSphereShape(get_float_by_JavaObj(env, shape_obj, "radius"));
break;
case TETRAHEDRAL_SHAPE_PROXYTYPE:
groundShape = new btBU_Simplex1to4(get_point_by_JavaObj(env, shape_obj, "p0"),
get_point_by_JavaObj(env, shape_obj, "p1"),
get_point_by_JavaObj(env, shape_obj, "p2"),
get_point_by_JavaObj(env, shape_obj, "p3"));
break;
default:
LOGV("create Geometry returning 0");
return 0;
}
bool isDynamic = (mass != 0.f);
if(isDynamic) {
groundShape->calculateLocalInertia( mass, localInertia );
}
g_CollisionShapes.push_back(groundShape);
jint addr_val = (int)groundShape;
set_JavaObj_int(env, geometry_obj, "id", addr_val);
return addr_val;
}
JNIEXPORT
jint
JNICALL
Java_org_gs_bullet_Bullet_createAndAddRigidBody(JNIEnv* env,
jobject thiz,
jint physicsWorldId,
jobject rigidBody_obj) {
LOGV("in createAndAddRigidBody.");
btDynamicsWorld* pDynamicsWorld = g_DynamicsWorlds.get((btDynamicsWorld*)physicsWorldId);
if(pDynamicsWorld == NULL) {
LOGV("Don't Load pDynamicsWorld.");
return 0;
}
jobject geometry_obj = get_obj_by_JavaObj(env, rigidBody_obj, "geometry", "Lorg/gs/bullet/Geometry;");
if(geometry_obj == NULL) {
LOGV("geometry is NULL.");
return 0;
}
LOGV("Load geometry_obj.");
jobject shape_obj = get_obj_by_JavaObj(env, geometry_obj, "shape", "Lorg/gs/bullet/interfaces/Shape;");
if(shape_obj == NULL) {
LOGV("shape is NULL.");
return 0;
}
LOGV("Load shapeID.");
int shapeID = get_id_by_JavaObj(env, shape_obj);
logi(shapeID);
btCollisionShape* colShape = g_CollisionShapes.get((btCollisionShape*)shapeID);
if(colShape == NULL) {
LOGV("shapeID is NULL.");
return 0;
}
jobject motionState_obj = get_obj_by_JavaObj(env, rigidBody_obj, "motionState", "Lorg/gs/bullet/MotionState;");
if(motionState_obj == NULL) {
LOGV("motionState is NULL.");
return 0;
}
LOGV("Load motionState_obj.");
btTransform startTransform;
startTransform.setIdentity();
jobject worldTransform_obj = get_obj_by_JavaObj(env, motionState_obj, "worldTransform", "Lorg/gs/bullet/Transform;");
LOGV("Load worldTransform_obj.");
if(worldTransform_obj != NULL) {
if(!is_NULL_point_field_JavaObj(env, worldTransform_obj, "originPoint")) {
LOGV("Load originPoint.");
startTransform.setOrigin(get_p2v_by_JavaObj(env, worldTransform_obj, "originPoint"));
}
if(!is_NULL_mat3x3_field_JavaObj(env, worldTransform_obj, "basis")) {
LOGV("Load basis.");
startTransform.setBasis(get_mat3x3_by_JavaObj(env, worldTransform_obj, "basis"));
}
if(!is_NULL_quat_field_JavaObj(env, worldTransform_obj, "rotation")) {
LOGV("Load rotation.");
startTransform.setRotation(get_quat_by_JavaObj(env, worldTransform_obj, "rotation"));
}
if(!is_NULL_point_field_JavaObj(env, worldTransform_obj, "invXform")) {
LOGV("Load invXform.");
startTransform.invXform(get_p2v_by_JavaObj(env, worldTransform_obj, "invXform"));
}
}
btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform);
LOGV("Load myMotionState.");
btVector3 localInertia;
if(is_NULL_vec_field_JavaObj(env, geometry_obj, "localInertia")) {
localInertia = btVector3(0.0f, 0.0f, 0.0f);
} else {
localInertia = get_vec_by_JavaObj(env, geometry_obj, "localInertia");
}
LOGV("Load localInertia.");
btRigidBody::btRigidBodyConstructionInfo rbInfo(get_float_by_JavaObj(env, geometry_obj, "mass"),
myMotionState,
colShape,
localInertia);
btRigidBody* body = new btRigidBody(rbInfo);
LOGV("Load localInertia.");
pDynamicsWorld->addRigidBody(body);
jint addr_val = (int)body;
set_JavaObj_int(env, rigidBody_obj, "id", addr_val);
return addr_val;
}
JNIEXPORT
jint
JNICALL
Java_org_gs_bullet_Bullet_applyForce(JNIEnv* env,
jobject thiz,
jint physicsWorldId,
jint rigidBodyId,
jobject force,
jobject applyPoint) {
LOGV("in Java_org_gs_bullet_Bullet_applyForce.");
btDynamicsWorld* pDynamicsWorld = g_DynamicsWorlds.get((btDynamicsWorld*)physicsWorldId);
if(pDynamicsWorld == NULL) {
LOGV("Don't Load pDynamicsWorld.");
return 0;
}
btCollisionObject* obj = pDynamicsWorld->getCollisionObjectArray().get((btRigidBody*)rigidBodyId);
if(obj == NULL) {
LOGV("Don't Load btRigidBody.");
return 0;
}
btRigidBody* body = btRigidBody::upcast(obj);
body->applyForce(get_vec_by_JavaVecObj(env, force),
get_vec_by_JavaVecObj(env, applyPoint));
return 1;
}
JNIEXPORT
jint
JNICALL
Java_org_gs_bullet_Bullet_applyTorque(JNIEnv* env,
jobject thiz,
jint physicsWorldId,
jint rigidBodyId,
jobject torque) {
LOGV("in Java_org_gs_bullet_Bullet_applyTorque.");
btDynamicsWorld* pDynamicsWorld = g_DynamicsWorlds.get((btDynamicsWorld*)physicsWorldId);
if(pDynamicsWorld == NULL) {
LOGV("Don't Load pDynamicsWorld.");
return 0;
}
btCollisionObject* obj = pDynamicsWorld->getCollisionObjectArray().get((btRigidBody*)rigidBodyId);
if(obj == NULL) {
LOGV("Don't Load btRigidBody.");
return 0;
}
btRigidBody* body = btRigidBody::upcast(obj);
body->applyTorque(get_vec_by_JavaVecObj(env, torque));
return 1;
}
JNIEXPORT
jint
JNICALL
Java_org_gs_bullet_Bullet_applyCentralImpulse(JNIEnv* env,
jobject thiz,
jint physicsWorldId,
jint rigidBodyId,
jobject impulse) {
LOGV("in Java_org_gs_bullet_Bullet_applyCentralImpulse.");
btDynamicsWorld* pDynamicsWorld = g_DynamicsWorlds.get((btDynamicsWorld*)physicsWorldId);
if(pDynamicsWorld == NULL) {
LOGV("Don't Load pDynamicsWorld.");
return 0;
}
btCollisionObject* obj = pDynamicsWorld->getCollisionObjectArray().get((btRigidBody*)rigidBodyId);
if(obj == NULL) {
LOGV("Don't Load btRigidBody.");
return 0;
}
btRigidBody* body = btRigidBody::upcast(obj);
body->applyCentralImpulse(get_vec_by_JavaVecObj(env, impulse));
return 1;
}
JNIEXPORT
jint
JNICALL
Java_org_gs_bullet_Bullet_applyTorqueImpulse(JNIEnv* env,
jobject thiz,
jint physicsWorldId,
jint rigidBodyId,
jobject torque) {
LOGV("in Java_org_gs_bullet_Bullet_applyTorqueImpulse.");
btDynamicsWorld* pDynamicsWorld = g_DynamicsWorlds.get((btDynamicsWorld*)physicsWorldId);
if(pDynamicsWorld == NULL) {
LOGV("Don't Load pDynamicsWorld.");
return 0;
}
btCollisionObject* obj = pDynamicsWorld->getCollisionObjectArray().get((btRigidBody*)rigidBodyId);
if(obj == NULL) {
LOGV("Don't Load btRigidBody.");
return 0;
}
btRigidBody* body = btRigidBody::upcast(obj);
body->applyTorqueImpulse(get_vec_by_JavaVecObj(env, torque));
return 1;
}
JNIEXPORT
jint
JNICALL
Java_org_gs_bullet_Bullet_applyImpulse(JNIEnv* env,
jobject thiz,
jint physicsWorldId,
jint rigidBodyId,
jobject impulse,
jobject applyPoint) {
LOGV("in Java_org_gs_bullet_Bullet_applyImpulse.");
btDynamicsWorld* pDynamicsWorld = g_DynamicsWorlds.get((btDynamicsWorld*)physicsWorldId);
if(pDynamicsWorld == NULL) {
LOGV("Don't Load pDynamicsWorld.");
return 0;
}
btCollisionObject* obj = pDynamicsWorld->getCollisionObjectArray().get((btRigidBody*)rigidBodyId);
if(obj == NULL) {
LOGV("Don't Load btRigidBody.");
return 0;
}
btRigidBody* body = btRigidBody::upcast(obj);
body->applyImpulse(get_vec_by_JavaVecObj(env, impulse),
get_vec_by_JavaVecObj(env, applyPoint));
return 1;
}
JNIEXPORT
jint
JNICALL
Java_org_gs_bullet_Bullet_clearForces(JNIEnv* env,
jobject thiz,
jint physicsWorldId,
jint rigidBodyId) {
LOGV("in Java_org_gs_bullet_Bullet_clearForces.");
btDynamicsWorld* pDynamicsWorld = g_DynamicsWorlds.get((btDynamicsWorld*)physicsWorldId);
if(pDynamicsWorld == NULL) {
LOGV("Don't Load pDynamicsWorld.");
return 0;
}
btCollisionObject* obj = pDynamicsWorld->getCollisionObjectArray().get((btRigidBody*)rigidBodyId);
if(obj == NULL) {
LOGV("Don't Load btRigidBody.");
return 0;
}
btRigidBody* body = btRigidBody::upcast(obj);
body->clearForces();
return 1;
}
JNIEXPORT
jint
JNICALL
Java_org_gs_bullet_Bullet_setActivePhysicsWorldAll(JNIEnv* env,
jobject thiz,
jint physicsWorldId,
jboolean isActive) {
btCollisionObject* obj;
btRigidBody* body;
btDynamicsWorld* pDynamicsWorld = g_DynamicsWorlds.get((btDynamicsWorld*)physicsWorldId);
if(pDynamicsWorld == NULL) {
LOGV("Don't Load pDynamicsWorld.");
return 0;
}
signed int coll_obj = pDynamicsWorld->getNumCollisionObjects();
for(signed int i = coll_obj - 1; i >= 0; i--){
LOGV("in for loop.");
obj = pDynamicsWorld->getCollisionObjectArray()[i];
body = btRigidBody::upcast(obj);
body->activate(isActive);
}
return 1;
}
JNIEXPORT
jint
JNICALL
Java_org_gs_bullet_Bullet_setActive(JNIEnv* env,
jobject thiz,
jint physicsWorldId,
jint rigidBodyId,
jboolean isActive) {
LOGV("in Java_org_gs_bullet_Bullet_applyImpulse.");
btDynamicsWorld* pDynamicsWorld = g_DynamicsWorlds.get((btDynamicsWorld*)physicsWorldId);
if(pDynamicsWorld == NULL) {
LOGV("Don't Load pDynamicsWorld.");
return 0;
}
btCollisionObject* obj = pDynamicsWorld->getCollisionObjectArray().get((btRigidBody*)rigidBodyId);
if(obj == NULL) {
LOGV("Don't Load btRigidBody.");
return 0;
}
btRigidBody* body = btRigidBody::upcast(obj);
body->activate(isActive);
return 1;
}
JNIEXPORT
jint
JNICALL
Java_org_gs_bullet_Bullet_setActiveAll(JNIEnv* env,
jobject thiz,
jboolean isActive) {
btDynamicsWorld* pDynamicsWorld;
btCollisionObject* obj;
btRigidBody* body;
signed int coll_obj;
for( signed int i = 0; i < g_DynamicsWorlds.size(); i++ ) {
pDynamicsWorld = g_DynamicsWorlds[i];
coll_obj = pDynamicsWorld->getNumCollisionObjects();
for(signed int j = coll_obj - 1; j >= 0; j--){
LOGV("in for loop.");
obj = pDynamicsWorld->getCollisionObjectArray()[j];
body = btRigidBody::upcast(obj);
body->activate(isActive);
}
}
return 1;
}
JNIEXPORT
jint
JNICALL
Java_org_gs_bullet_Bullet_addConstraint(JNIEnv* env,
jobject thiz,
jobject constraint_obj) {
LOGV("in addConstraint.");
int constraintType = get_type_by_JavaObj(env, constraint_obj);
LOGV("Load constraintType val.");
switch(constraintType) {
case HINGE_CONSTRAINT_TYPE: {
LOGV("in HINGE_CONSTRAINT_TYPE.");
jobject rbA_obj;
jint rbAID;
if(is_NULL_field_JavaObj(env, constraint_obj, "rbA", "Lorg/gs/bullet/RigidBody;")) {
LOGV("Don't Load rbA.");
return 0;
}
rbA_obj = get_obj_by_JavaObj(env, constraint_obj, "rbA", "Lorg/gs/bullet/RigidBody;");
rbAID = get_int_by_JavaObj(env, rbA_obj, "id");
int physicsWorldId = get_int_by_JavaObj(env, rbA_obj, "physicsWorldId");
if(physicsWorldId == 0) {
LOGV("Don't Load physicsWorldId.");
return 0;
}
btDynamicsWorld* pDynamicsWorld = g_DynamicsWorlds.get((btDynamicsWorld*)physicsWorldId);
if(pDynamicsWorld == NULL) {
LOGV("Don't Load pDynamicsWorld.");
return 0;
}
btCollisionObject* objA = pDynamicsWorld->getCollisionObjectArray().get((btRigidBody*)rbAID);
btRigidBody* bodyA = btRigidBody::upcast(objA);
btVector3 pivotInA = get_pivot_by_JavaObj(env, constraint_obj, "pivotInA");
btVector3 axisInA = get_axis_by_JavaObj(env, constraint_obj, "axisInA");
btTypedConstraint* hinge;
if(is_NULL_field_JavaObj(env, constraint_obj, "rbB", "Lorg/gs/bullet/RigidBody;")) {
hinge = new btHingeConstraint(*bodyA,
pivotInA,
axisInA);
} else {
jobject rbB_obj = get_obj_by_JavaObj(env, constraint_obj, "rbB", "Lorg/gs/bullet/RigidBody;");
jint rbBID = get_int_by_JavaObj(env, rbB_obj, "id");
btCollisionObject* objB = pDynamicsWorld->getCollisionObjectArray().get((btRigidBody*)rbBID);
btRigidBody* bodyB = btRigidBody::upcast(objB);
btVector3 pivotInB = get_pivot_by_JavaObj(env, constraint_obj, "pivotInB");
btVector3 axisInB = get_axis_by_JavaObj(env, constraint_obj, "axisInB");
hinge = new btHingeConstraint(*bodyA,
*bodyB,
pivotInA,
pivotInB,
axisInA,
axisInB);
}
pDynamicsWorld->addConstraint(hinge);
break;
}
case POINT2POINT_CONSTRAINT_TYPE: {
LOGV("in POINT2POINT_CONSTRAINT_TYPE.");
jobject rbA_obj;
jint rbAID;
if(is_NULL_field_JavaObj(env, constraint_obj, "rbA", "Lorg/gs/bullet/RigidBody;")) {
LOGV("Don't Load rbA.");
return 0;
}
rbA_obj = get_obj_by_JavaObj(env, constraint_obj, "rbA", "Lorg/gs/bullet/RigidBody;");
rbAID = get_int_by_JavaObj(env, rbA_obj, "id");
int physicsWorldId = get_int_by_JavaObj(env, rbA_obj, "physicsWorldId");
if(physicsWorldId == 0) {
LOGV("Don't Load physicsWorldId.");
return 0;
}
btDynamicsWorld* pDynamicsWorld = g_DynamicsWorlds.get((btDynamicsWorld*)physicsWorldId);
if(pDynamicsWorld == NULL) {
LOGV("Don't Load pDynamicsWorld.");
return 0;
}
btCollisionObject* objA = pDynamicsWorld->getCollisionObjectArray().get((btRigidBody*)rbAID);
btRigidBody* bodyA = btRigidBody::upcast(objA);
btVector3 pivotInA = get_pivot_by_JavaObj(env, constraint_obj, "pivotInA");
btTypedConstraint* p2p;
if(is_NULL_field_JavaObj(env, constraint_obj, "rbB", "Lorg/gs/bullet/RigidBody;")) {
p2p = new btPoint2PointConstraint(*bodyA,
pivotInA);
} else {
jobject rbB_obj = get_obj_by_JavaObj(env, constraint_obj, "rbB", "Lorg/gs/bullet/RigidBody;");
jint rbBID = get_int_by_JavaObj(env, rbB_obj, "id");
btCollisionObject* objB = pDynamicsWorld->getCollisionObjectArray().get((btRigidBody*)rbBID);
btRigidBody* bodyB = btRigidBody::upcast(objB);
btVector3 pivotInB = get_pivot_by_JavaObj(env, constraint_obj, "pivotInB");
p2p = new btPoint2PointConstraint(*bodyA,
*bodyB,
pivotInA,
pivotInB);
}
pDynamicsWorld->addConstraint(p2p);
break;
}
default:
break;
}
return 1;
}
JNIEXPORT
jint
JNICALL
Java_org_gs_bullet_Bullet_doSimulationNative(JNIEnv* env,
jobject thiz,
jint physicsWorldId,
jfloat exec_time,
jint count) {
btCollisionObject* obj;
btRigidBody* body;
btCollisionShape* shape;
btSphereShape* sphere;
btStaticPlaneShape* plane;
btBoxShape* box;
btCylinderShape* cylinder;
btConeShape* cone;
btCapsuleShape* capsule;
btBU_Simplex1to4* tetrahedral;
btTransform trans;
btMatrix3x3 rot;
btVector3 pos;
int shapeType;
jfloat res_rot[9];
jfloat res_pos[3];
jfloat res_opt[9];
jfloatArray j_res_rot = env->NewFloatArray(sizeof(res_rot));
jfloatArray j_res_pos = env->NewFloatArray(sizeof(res_pos));
jfloatArray j_res_opt = env->NewFloatArray(sizeof(res_opt));
LOGV("in doSimulationNative.");
btDynamicsWorld* pDynamicsWorld = g_DynamicsWorlds.get((btDynamicsWorld*)physicsWorldId);
if(pDynamicsWorld == NULL) {
LOGV("Don't Load pDynamicsWorld.");
return 0;
}
pDynamicsWorld->stepSimulation(exec_time, count);
LOGV("collisions detected");
int numManifolds = pDynamicsWorld->getDispatcher()->getNumManifolds();
for (int i=0;i<numManifolds;i++)
{
btPersistentManifold* contactManifold = pDynamicsWorld->getDispatcher()->getManifoldByIndexInternal(i);
btCollisionObject* obA = static_cast<btCollisionObject*>(contactManifold->getBody0());
btCollisionObject* obB = static_cast<btCollisionObject*>(contactManifold->getBody1());
int numContacts = contactManifold->getNumContacts();
for (int j=0;j<numContacts;j++)
{
btManifoldPoint& pt = contactManifold->getContactPoint(j);
if (pt.getDistance()<0.f)
{
jclass bullet_clazz = env->GetObjectClass(thiz);
jmethodID bullet_resultSimulation_mid = env->GetMethodID(bullet_clazz, "collisionDetected", "(II)V");
env->CallVoidMethod(thiz, bullet_resultSimulation_mid, (int)btRigidBody::upcast(obA), (int)btRigidBody::upcast(obB));
}
}
}
signed int coll_obj = pDynamicsWorld->getNumCollisionObjects();
for(signed int i = coll_obj - 1; i >= 0; i--){
LOGV("in getVertex for loop.");
obj = pDynamicsWorld->getCollisionObjectArray()[i];
body = btRigidBody::upcast(obj);
shape = body->getCollisionShape();
shapeType = shape->getShapeType();
trans = body->getWorldTransform();
rot = trans.getBasis();
pos = trans.getOrigin();
res_rot[0] = (jfloat)rot[0].x();
res_rot[1] = (jfloat)rot[0].y();
res_rot[2] = (jfloat)rot[0].z();
res_rot[3] = (jfloat)rot[1].x();
res_rot[4] = (jfloat)rot[1].y();
res_rot[5] = (jfloat)rot[1].z();
res_rot[6] = (jfloat)rot[2].x();
res_rot[7] = (jfloat)rot[2].y();
res_rot[8] = (jfloat)rot[2].z();
res_pos[0] = (jfloat)pos.x();
res_pos[1] = (jfloat)pos.y();
res_pos[2] = (jfloat)pos.z();
LOGV("check shape->getShapeType().");
switch(shapeType) {
case STATIC_PLANE_PROXYTYPE:
LOGV("in STATIC_PLANE_PROXYTYPE.");
break;
case BOX_SHAPE_PROXYTYPE:
LOGV("in BOX_PROXYTYPE.");
box = static_cast<btBoxShape*>(shape);
res_opt[0] = (jfloat)box->getHalfExtentsWithoutMargin().x();
res_opt[1] = (jfloat)box->getHalfExtentsWithoutMargin().y();
res_opt[2] = (jfloat)box->getHalfExtentsWithoutMargin().z();
break;
case CAPSULE_SHAPE_PROXYTYPE:
LOGV("in CAPSULE_SHAPE_PROXYTYPE.");
capsule = static_cast<btCapsuleShape*>(shape);
res_opt[0] = (jfloat)capsule->getRadius();
res_opt[1] = (jfloat)capsule->getHalfHeight();
break;
case CONE_SHAPE_PROXYTYPE:
LOGV("in CONE_SHAPE_PROXYTYPE.");
cone = static_cast<btConeShape*>(shape);
res_opt[0] = (jfloat)cone->getRadius();
res_opt[1] = (jfloat)cone->getHeight();
break;
case CYLINDER_SHAPE_PROXYTYPE:
LOGV("in CYLINDER_SHAPE_PROXYTYPE.");
cylinder = static_cast<btCylinderShape*>(shape);
res_opt[0] = (jfloat)cylinder->getHalfExtentsWithoutMargin().x();
res_opt[1] = (jfloat)cylinder->getHalfExtentsWithoutMargin().y();
res_opt[2] = (jfloat)cylinder->getHalfExtentsWithoutMargin().z();
res_opt[3] = (jfloat)cylinder->getRadius();
break;
// case EMPTY_SHAPE_PROXYTYPE:
// groundShape = new btEmptyShape();
//
// break;
case SPHERE_SHAPE_PROXYTYPE:
LOGV("in SPHERE_SHAPE_PROXYTYPE.");
sphere = static_cast<btSphereShape*>(shape);
res_opt[0] = (jfloat)sphere->getRadius();
break;
case TETRAHEDRAL_SHAPE_PROXYTYPE:
LOGV("in TETRAHEDRAL_SHAPE_PROXYTYPE.");
tetrahedral = static_cast<btBU_Simplex1to4*>(shape);
break;
// case TRIANGLE_SHAPE_PROXYTYPE:
// groundShape = new btTriangleShape(get_p2v_by_JavaObj(env, shape_obj, "p0"),
// get_p2v_by_JavaObj(env, shape_obj, "p1"),
// get_p2v_by_JavaObj(env, shape_obj, "p2"));
//
// break;
default:
return 0;
}
env->SetFloatArrayRegion(j_res_rot, 0, sizeof(res_rot)-1, res_rot);
env->SetFloatArrayRegion(j_res_pos, 0, sizeof(res_pos)-1, res_pos);
env->SetFloatArrayRegion(j_res_opt, 0, sizeof(res_opt)-1, res_opt);
jclass bullet_clazz = env->GetObjectClass(thiz);
jmethodID bullet_resultSimulation_mid = env->GetMethodID(bullet_clazz, "resultSimulation", "(II[F[F[F)V");
env->CallVoidMethod(thiz, bullet_resultSimulation_mid, (int)body, shapeType, j_res_rot, j_res_pos, j_res_opt);
LOGV("CallVoidMethod bullet_resultSimulation_mid.");
}
LOGV("out doSimulationNative.");
return (jint)coll_obj;
}
void destroyPhysicsWorld(btDynamicsWorld* pDynamicsWorld) {
LOGV("in destroyPhysicsWorld.");
// delete MotionStates.
for( signed int i = pDynamicsWorld->getNumCollisionObjects() - 1; i >= 0; i-- ) {
btCollisionObject* obj = pDynamicsWorld->getCollisionObjectArray()[i];
btRigidBody* body = btRigidBody::upcast(obj);
if( (body != NULL) && (body->getMotionState() != NULL) ) {
delete body->getMotionState();
}
pDynamicsWorld->removeCollisionObject( obj );
SAFE_DELETE( obj );
}
// btCollisionConfiguration* cc = pDynamicsWorld->getCollisionConfiguration();
// SAFE_DELETE(cc);
btBroadphaseInterface* bp = pDynamicsWorld->getBroadphase();
SAFE_DELETE(bp);
btOverlappingPairCache* pc = pDynamicsWorld->getPairCache();
SAFE_DELETE(pc);
btDispatcher* dp = pDynamicsWorld->getDispatcher();
SAFE_DELETE(dp);
btIDebugDraw* dd = pDynamicsWorld->getDebugDrawer();
SAFE_DELETE(dd);
btConstraintSolver* cs = pDynamicsWorld->getConstraintSolver();
SAFE_DELETE(cs);
// SAFE_DELETE(pDynamicsWorld->getDispatchInfo());
g_DynamicsWorlds.remove(pDynamicsWorld);
SAFE_DELETE(pDynamicsWorld);
}
JNIEXPORT
jboolean
JNICALL
Java_org_gs_bullet_Bullet_destroyPhysicsWorld(JNIEnv* env,
jobject thiz,
jint physicsWorldId) {
LOGV("in Java_org_gs_bullet_Bullet_destroyPhysicsWorld.");
btDynamicsWorld* pDynamicsWorld = g_DynamicsWorlds.get((btDynamicsWorld*)physicsWorldId);
if(pDynamicsWorld == NULL) {
LOGV("Don't Load pDynamicsWorld.");
return JNI_TRUE;
}
destroyPhysicsWorld(pDynamicsWorld);
return JNI_TRUE;
}
JNIEXPORT
jboolean
JNICALL
Java_org_gs_bullet_Bullet_destroyNative(JNIEnv* env,
jobject thiz) {
LOGV("in Java_org_gs_bullet_Bullet_destroyNative.");
// delete DynamicsWorld.
for( signed int i = 0; i < g_DynamicsWorlds.size(); i++ ) {
btDynamicsWorld* pDynamicsWorld = g_DynamicsWorlds[i];
destroyPhysicsWorld(pDynamicsWorld);
}
// delete Collisions.
for( signed int i = 0; i < g_CollisionShapes.size(); i++ ) {
btCollisionShape* shape = g_CollisionShapes[i];
g_CollisionShapes[i] = 0;
SAFE_DELETE( shape );
}
return JNI_TRUE;
}
| [
"biaggi@b6742504-2898-11df-97f1-b507b49a622a",
"[email protected]"
]
| [
[
[
1,
13
],
[
19,
24
],
[
26,
70
],
[
72,
83
],
[
85,
109
],
[
111,
121
],
[
123,
202
],
[
204,
215
],
[
217,
222
],
[
224,
238
],
[
240,
248
],
[
250,
305
],
[
307,
312
],
[
314,
337
],
[
339,
343
],
[
345,
368
],
[
370,
374
],
[
376,
397
],
[
399,
403
],
[
405,
426
],
[
428,
433
],
[
435,
459
],
[
461,
464
],
[
466,
488
],
[
490,
518
],
[
520,
524
],
[
526,
548
],
[
550,
580
],
[
582,
596
],
[
598,
600
],
[
602,
623
],
[
625,
628
],
[
630,
653
],
[
655,
657
],
[
659,
679
],
[
681,
683
],
[
685,
716
],
[
718,
935
],
[
937,
939
],
[
941,
956
],
[
958,
959
],
[
961,
978
]
],
[
[
14,
18
],
[
25,
25
],
[
71,
71
],
[
84,
84
],
[
110,
110
],
[
122,
122
],
[
203,
203
],
[
216,
216
],
[
223,
223
],
[
239,
239
],
[
249,
249
],
[
306,
306
],
[
313,
313
],
[
338,
338
],
[
344,
344
],
[
369,
369
],
[
375,
375
],
[
398,
398
],
[
404,
404
],
[
427,
427
],
[
434,
434
],
[
460,
460
],
[
465,
465
],
[
489,
489
],
[
519,
519
],
[
525,
525
],
[
549,
549
],
[
581,
581
],
[
597,
597
],
[
601,
601
],
[
624,
624
],
[
629,
629
],
[
654,
654
],
[
658,
658
],
[
680,
680
],
[
684,
684
],
[
717,
717
],
[
936,
936
],
[
940,
940
],
[
957,
957
],
[
960,
960
]
]
]
|
bffcb78fe7ee4b94b8f575461ca74bdb42f7a566 | 442c70da132711866b6b97002db0ebf2d9c3ac53 | /source/iexceptionlocation.cpp | 1e2e477c1234d80df5c9449466c9ee5c1baa4c4a | []
| no_license | fmeyer/openioc | d955ff267896776ca2a3ec8a10f6ac99b9845e74 | 6157ffcae360347c509a079697373355b225f68d | refs/heads/master | 2016-08-03T04:57:26.646359 | 2009-08-20T22:21:59 | 2009-08-20T22:21:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,384 | cpp | #include <iexceptionlocation.hpp>
/*
* Copyright 2005 Fernando Meyer [email protected]
* http://www.fmeyer.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* STL to IBM IOC WRAPPER
*
*/
#include <string>
#include <iostream>
IExceptionLocation::IExceptionLocation( char* fileName, char* functionName,unsigned long lineNumber)
{
set(fileName,functionName,lineNumber);
}
IExceptionLocation::~IExceptionLocation()
{
}
void IExceptionLocation::set( char* fileName, char* functionName, unsigned long lineNumber)
{
strcpy(pClFile, fileName);
strcpy(pClFunction, functionName);
ulClLineNo = lineNumber;
}
char *IExceptionLocation::fileName()
{
return pClFile;
}
char *IExceptionLocation::functionName ()
{
return pClFunction;
}
unsigned long IExceptionLocation::lineNumber()
{
return ulClLineNo;
} | [
"[email protected]"
]
| [
[
[
1,
53
]
]
]
|
db8a54a752e017bb725f88c6bc603bfdb6c34bc1 | 9b3df03cb7e134123cf6c4564590619662389d35 | /FileInputStream.h | 12b8d928cadff92cdcf94a2fbab41925b3da302f | []
| no_license | CauanCabral/Computacao_Grafica | a32aeff2745f40144a263c16483f53db7375c0ba | d8673aed304573415455d6a61ab31b68420b6766 | refs/heads/master | 2016-09-05T16:48:36.944139 | 2010-12-09T19:32:05 | 2010-12-09T19:32:05 | null | 0 | 0 | null | null | null | null | ISO-8859-10 | C++ | false | false | 1,504 | h | #ifndef __FileInputStream_h
#define __FileInputStream_h
//[]------------------------------------------------------------------------[]
//| |
//| GVSG Foundation Classes |
//| Version 1.0 |
//| |
//| CopyrightŪ 2007, Paulo Aristarco Pagliosa |
//| All Rights Reserved. |
//| |
//[]------------------------------------------------------------------------[]
//
// OVERVIEW: FileInputStream.h
// ========
// Class definition for file input stream.
#ifndef __File_h
#include "File.h"
#endif
#ifndef __InputStream_h
#include "InputStream.h"
#endif
namespace System
{ // begin namespace System
//////////////////////////////////////////////////////////
//
// FileInputStream: file input stream
// ===============
class FileInputStream: public InputStream
{
public:
// Constructor
FileInputStream(const char*);
// Destructor
~FileInputStream();
long available() const;
void close();
long read(void*, long);
long skip(long);
private:
File file;
}; // FileInputStream
} // end namespace System
#endif // __FileInputStream_h
| [
"[email protected]"
]
| [
[
[
1,
54
]
]
]
|
984dfae856485528a98ff522f7f230ed14f8ed43 | bc3073755ed70dd63a7c947fec63ccce408e5710 | /src/Game/Graphics/EngineFlameParticleEngine.h | 7f5c9f0284e9f892e662f96abde0d8637ce7119e | []
| no_license | ptrefall/ste6274gamedesign | 9e659f7a8a4801c5eaa060ebe2d7edba9c31e310 | 7d5517aa68910877fe9aa98243f6bb2444d533c7 | refs/heads/master | 2016-09-07T18:42:48.012493 | 2011-10-13T23:41:40 | 2011-10-13T23:41:40 | 32,448,466 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 373 | h | #pragma once
#include "Particle.h"
namespace Graphics
{
class EngineFlameParticleEngine : public QdParticleEngine
{
public:
EngineFlameParticleEngine(float fRed, float fGreen, float fBlue, float fAlpha);
virtual int resetParticles();
virtual int particleDead(int nParticle);
int m_nParticlesDead;
protected:
QdColor m_clrParticleColor;
};
}
| [
"[email protected]@2c5777c1-dd38-1616-73a3-7306c0addc79"
]
| [
[
[
1,
21
]
]
]
|
2daddf20b9a9f258702a8ffed094f029a2774323 | 6bdb3508ed5a220c0d11193df174d8c215eb1fce | /Codes/Halak/UIMouseEventDispatcher.inl | 97ebdea6810e521be84fbeb123f1ac83c8d72002 | []
| no_license | halak/halak-plusplus | d09ba78640c36c42c30343fb10572c37197cfa46 | fea02a5ae52c09ff9da1a491059082a34191cd64 | refs/heads/master | 2020-07-14T09:57:49.519431 | 2011-07-09T14:48:07 | 2011-07-09T14:48:07 | 66,716,624 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 421 | inl | namespace Halak
{
UIDomain* UIMouseEventDispatcher::GetDomain() const
{
return domain;
}
Mouse* UIMouseEventDispatcher::GetDevice() const
{
return device;
}
UIRenderer* UIMouseEventDispatcher::GetRenderer() const
{
return renderer;
}
void UIMouseEventDispatcher::SetRenderer(UIRenderer* value)
{
renderer = value;
}
} | [
"[email protected]"
]
| [
[
[
1,
22
]
]
]
|
3814268961ed345fa2a615e8f62ee0930a620678 | 2d1d1db23023ce078e2553cb088fed3d40e67afc | /TcpServerSocket.h | 337fcd8836e049cf229f357d3de1794193b69bf8 | []
| no_license | liuxw7/ippyproxy | f964c8bfe8d4f710e320bdc5447c0414e3b15b08 | daab0f961c8fb4da239a71d7a106d39a5b682567 | refs/heads/master | 2021-06-15T02:34:44.071400 | 2008-05-13T21:28:30 | 2008-05-13T21:28:30 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 1,228 | h | ////////////////////////////////////////////////////////////////////////////////////////////////////
// IpPyProxy
//
// Copyright ©2008 Liam Kirton <[email protected]>
////////////////////////////////////////////////////////////////////////////////////////////////////
// TcpServerSocket.h
//
// Created: 27/02/2008
////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma once
////////////////////////////////////////////////////////////////////////////////////////////////////
#include "Socket.h"
////////////////////////////////////////////////////////////////////////////////////////////////////
class TcpClientSocket;
class TcpServerSocket : public Socket
{
public:
TcpServerSocket(TcpClientSocket *TcpClientSocket);
public:
~TcpServerSocket();
Socket *OnAccept(SOCKET hSocket);
void OnConnect();
void OnDisconnect();
void OnReceive(unsigned char *buffer, unsigned int length, unsigned int ip = 0, unsigned short port = 0);
void OnSendCompletion(DWORD dwNumberOfBytes);
protected:
TcpClientSocket *tcpClientSocket_;
};
////////////////////////////////////////////////////////////////////////////////////////////////////
| [
"[email protected]"
]
| [
[
[
1,
38
]
]
]
|
a43d001f7f6938c97bb90b29d520e3fbb520a5f2 | 6ea2685ec9aa4be984ea0febb7eefc2f3bc544c9 | /ArcFrameBuilder.cpp | fe911a1ddb2183c44b35ecbddd57ec725d53cb6c | []
| no_license | vpatrinica/pernute | f047445a373f79209f0e32c1bf810d90c3d6289f | e2c0bf4161ccb4e768e7b64ecd2a021e51319383 | refs/heads/master | 2021-01-02T22:31:07.174479 | 2010-05-13T21:13:34 | 2010-05-13T21:13:34 | 39,997,926 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,456 | cpp |
#include "ArcFrameBuilder.h"
ArcFrameBuilder::ArcFrameBuilder()
{
acutPrintf(_T("Constructor of ArcFrameBuilder called ...\n"));
}
ArcFrameBuilder::~ArcFrameBuilder()
{
acutPrintf(_T("Destructor of ArcFrameBuilder called ...\n"));
}
void ArcFrameBuilder::buildFramePoints(AcArray<AcGePoint3d>& arrayPoints, AcDbObjectPointer<AcDbEntity>& ArcObject, int granularity)
{
acutPrintf(_T("Building the points using ArcFrameBuilder ...\n"));
_pArc = AcDbArc::cast(ArcObject);
AcGePoint3d startPoint;
_pArc->getStartPoint(startPoint);
arrayPoints.append(startPoint);
double length, endParam = 0;
_pArc->getEndParam(endParam);
_pArc->getDistAtParam(endParam, length);
acutPrintf(_T("The length and other params: %f, %d, %d ...\n"), length, ((int) length)/granularity, granularity);
for (int i = 0; i< ((int) length)/granularity; i++)
{
AcGePoint3d newPoint;
_pArc->getPointAtDist(i*granularity, newPoint);
arrayPoints.append(newPoint);
}
AcGePoint3d endPoint;
_pArc->getPointAtParam(endParam, endPoint);
arrayPoints.append(endPoint);
acutPrintf(_T("Built the points using ArcFrameBuilder ...\n"));
}
void ArcFrameBuilder::getFramePoints(AcArray<AcGePoint3d> &)
{
acutPrintf(_T("Getting the points using ArcFrameBuilder ...\n"));
}
void ArcFrameBuilder::printFramePoints()
{
acutPrintf(_T("Printing the points using ArcFrameBuilder ...\n"));
} | [
"v.patrinica@4687759a-75b2-d36a-a905-7d4f9b7d90e1"
]
| [
[
[
1,
61
]
]
]
|
3ae696cc185744b15844c6dd8593f3b05ac96b59 | 1d415fdfabd9db522a4c3bca4ba66877ec5b8ef4 | /avstream/ttmpeg2videostream.cpp | c6b1f7a87886fcb4805614d3b96426e787ba86e6 | []
| no_license | panjinan333/ttcut | 61b160c0c38c2ea6c8785ba258c2fa4b6d18ae1a | fc13ec3289ae4dbce6a888d83c25fbc9c3d21c1a | refs/heads/master | 2022-03-23T21:55:36.535233 | 2010-12-23T20:58:13 | 2010-12-23T20:58:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 36,705 | cpp | /*----------------------------------------------------------------------------*/
/* COPYRIGHT: TriTime (c) 2005/2010 / www.tritime.org */
/*----------------------------------------------------------------------------*/
/* PROJEKT : TTCUT 2008 */
/* FILE : ttmpeg2videostream.cpp */
/*----------------------------------------------------------------------------*/
/* AUTHOR : b. altendorf (E-Mail: [email protected]) DATE: 05/12/2005 */
/*----------------------------------------------------------------------------*/
// -----------------------------------------------------------------------------
// TTMPEG2VIDEOSTREAM
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Overview
// -----------------------------------------------------------------------------
//
// +- TTMpegAudioStream
// +- TTAudioStream -|
// | +- TTAC3AudioStream
// TTAVStream -|
// |
// +- TTVideoStream -TTMpeg2VideoStream
//
// -----------------------------------------------------------------------------
/*----------------------------------------------------------------------------*/
/* This program is free software; you can redistribute it and/or modify it */
/* under the terms of the GNU General Public License as published by the Free */
/* Software Foundation; */
/* either version 2 of the License, or (at your option) any later version. */
/* */
/* This program is distributed in the hope that it will be useful, but WITHOUT*/
/* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or */
/* FITNESS FOR A PARTICULAR PURPOSE. */
/* See the GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License along */
/* with this program; if not, write to the Free Software Foundation, */
/* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */
/*----------------------------------------------------------------------------*/
#include "ttmpeg2videostream.h"
#include "../common/ttexception.h"
#include "../common/istatusreporter.h"
#include "../data/ttcutlist.h"
#include "../data/ttcutparameter.h"
#include <QCoreApplication>
#include <stdio.h>
#include <stdlib.h>
#include <QDir>
#include <QStack>
#include <QThread>
/*! ////////////////////////////////////////////////////////////////////////////
* Constructor with QFileInfo
*/
TTMpeg2VideoStream::TTMpeg2VideoStream( const QFileInfo &f_info )
: TTVideoStream( f_info )
{
log = TTMessageLogger::getInstance();
stream_type = TTAVTypes::mpeg2_demuxed_video;
header_list = NULL;
index_list = NULL;
}
/*! ////////////////////////////////////////////////////////////////////////////
* Destructor
*/
TTMpeg2VideoStream::~TTMpeg2VideoStream()
{
}
/*! ////////////////////////////////////////////////////////////////////////////
* Create a shared copy from an existing videostream
*/
void TTMpeg2VideoStream::makeSharedCopy( TTMpeg2VideoStream* v_stream )
{
current_index = 0;
stream_info = v_stream->stream_info;
stream_type = v_stream->stream_type;
header_list = v_stream->header_list;
index_list = v_stream->index_list;
frame_rate = v_stream->frame_rate;
bit_rate = v_stream->bit_rate;
}
/*! ////////////////////////////////////////////////////////////////////////////
* Create the list with mpeg2 header informations
*/
int TTMpeg2VideoStream::createHeaderList()
{
QString iddStreamName;
QFileInfo iddStreamInfo;
openStream();
header_list = new TTVideoHeaderList( 2000 );
// read the header from IDD file
if (TTCut::readVideoIDD)
{
iddStreamName = ttChangeFileExt(stream_info->filePath(), "idd");
iddStreamInfo.setFile(iddStreamName);
if (iddStreamInfo.exists())
{
TTFileBuffer* iddStreamBuffer = new TTFileBuffer(iddStreamName, QIODevice::ReadOnly);
createHeaderListFromIdd(iddStreamBuffer);
if (iddStreamBuffer != NULL) {
delete iddStreamBuffer;
iddStreamBuffer = NULL;
}
}
}
// Read the header from mpeg2 stream
if (header_list->count() == 0)
createHeaderListFromMpeg2();
if (header_list->count() == 0) {
if (header_list != NULL) {
delete header_list;
header_list = NULL;
}
throw TTInvalidOperationException(QString("%1 Could not create header list!").arg(__FILE__));
}
return header_list->count();
}
/*! ////////////////////////////////////////////////////////////////////////////
* Create the mpeg2 video stream picture index list
*/
int TTMpeg2VideoStream::createIndexList()
{
int base_number = 0;
int current_pic_num = 0;
int index = 0;
quint8 start_code = 0xFF;
QTime time;
TTPicturesHeader* current_pic = NULL;
index_list = new TTVideoIndexList();
if (TTCut::logVideoIndexInfo) {
log->infoMsg(__FILE__, __LINE__, "Create index list");
log->infoMsg(__FILE__, __LINE__, "---------------------------------------------");
}
time.start();
while ( index < header_list->count() )
{
if (mAbort) {
mAbort = false;
throw new TTAbortException(tr("Index list creation aborted!"));
}
start_code = header_list->at(index)->headerType();
switch ( start_code )
{
case TTMpeg2VideoHeader::group_start_code:
base_number = current_pic_num;
break;
case TTMpeg2VideoHeader::picture_start_code:
current_pic = (TTPicturesHeader*)header_list->at(index);
if ( current_pic != NULL )
{
TTVideoIndex* video_index = new TTVideoIndex();
video_index->setDisplayOrder(base_number+current_pic->temporal_reference);
video_index->setHeaderListIndex(index);
video_index->setPictureCodingType(current_pic->picture_coding_type);
index_list->add( video_index );
if(TTCut::logVideoIndexInfo) {
log->infoMsg(__FILE__, __LINE__,
QString("stream-order;%1;display-order;%2;frame-type;%3;offset;%4").
arg(current_pic_num).arg(video_index->getDisplayOrder()).
arg(video_index->getPictureCodingType()).arg(current_pic->headerOffset()));
}
current_pic_num++;
}
break;
}
index++;
}
log->debugMsg(__FILE__, __LINE__, QString("time for creating index list %1ms").
arg(time.elapsed()));
return index_list->count();
}
/*! ////////////////////////////////////////////////////////////////////////////
* Return the stream type
*/
TTAVTypes::AVStreamType TTMpeg2VideoStream::streamType() const
{
return TTAVTypes::mpeg2_demuxed_video;
}
/*! ////////////////////////////////////////////////////////////////////////////
* Open the mpeg2 video stream
*/
bool TTMpeg2VideoStream::openStream()
{
stream_buffer->open();
return ttAssigned(stream_buffer);
}
/*! ////////////////////////////////////////////////////////////////////////////
* Close the current mpeg2 video stream
*/
bool TTMpeg2VideoStream::closeStream()
{
stream_buffer->close();
return true;
}
/*! ////////////////////////////////////////////////////////////////////////////
* Create the mpeg2 header-list from Mpeg2Schnitt idd-file
*/
bool TTMpeg2VideoStream::createHeaderListFromIdd(TTFileBuffer* iddStream)
{
quint8 buffer4[4];
iddStream->open();
if (!iddStream->readByte(buffer4, 4))
throw TTIOException(QString(tr("Error reading IDD file in %1 at line %2!")).arg(__FILE__).arg(__LINE__));
if (buffer4[0] != int('i') &&
buffer4[1] != int('d') &&
buffer4[2] != int('d') ) {
throw TTDataFormatException(QString(tr("No IDD file in %1 at line %2!")).arg(__FILE__).arg(__LINE__));
}
readIDDHeader(iddStream, buffer4[3]);
iddStream->close();
return (header_list->count() > 0);
}
/*! ////////////////////////////////////////////////////////////////////////////
* Create the mpeg2 header-list from mpeg2 stream
*/
bool TTMpeg2VideoStream::createHeaderListFromMpeg2()
{
quint8 headerType;
TTVideoHeader* newHeader;
QTime time;
header_list->clear();
try
{
time.start();
emit statusReport(StatusReportArgs::Start, tr("Creating Mpeg2-Header List"), stream_buffer->size());
while(!stream_buffer->atEnd())
{
if (mAbort) {
mAbort = false;
throw new TTAbortException(tr("Headerlist creation aborted by user!"));
}
headerType = 0xFF;
// search next header (start code)
while (headerType != TTMpeg2VideoHeader::picture_start_code &&
headerType != TTMpeg2VideoHeader::sequence_start_code &&
headerType != TTMpeg2VideoHeader::group_start_code &&
headerType != TTMpeg2VideoHeader::sequence_end_code &&
!stream_buffer->atEnd() )
{
stream_buffer->nextStartCodeTS();
stream_buffer->readByte(headerType);
}
newHeader = 0;
// create the appropriate header object
switch ( headerType )
{
case TTMpeg2VideoHeader::sequence_start_code:
newHeader = new TTSequenceHeader();
break;
case TTMpeg2VideoHeader::picture_start_code:
newHeader = new TTPicturesHeader();
break;
case TTMpeg2VideoHeader::group_start_code:
newHeader = new TTGOPHeader();
break;
case TTMpeg2VideoHeader::sequence_end_code:
newHeader = new TTSequenceEndHeader();
break;
}
if ( newHeader != 0 )
{
newHeader->readHeader( stream_buffer );
header_list->add( newHeader );
}
emit statusReport(StatusReportArgs::Step, QString(tr("Found %1 header")).arg(header_list->count()), stream_buffer->position());
}
log->debugMsg(__FILE__, __LINE__, QString("time for creating header list %1ms").
arg(time.elapsed()));
}
catch (TTFileBufferException* ex)
{
qDebug("ttfilebuffer exception...");
}
emit statusReport(StatusReportArgs::Finished, tr("Mpeg2-Header list created"), stream_buffer->size());
// write an idd file with the header information
if (header_list->count() > 0 && TTCut::createVideoIDD )
writeIDDFile();
return (header_list->count() > 0);
}
/*! ////////////////////////////////////////////////////////////////////////////
* Write MPEG2Schnit idd file
*/
void TTMpeg2VideoStream::writeIDDFile( )
{
QString iddStreamName;
QFileInfo iddStreamInfo;
TTPicturesHeader* currentPicture;
int index = 0;
quint8 headerType;
quint64 offset;
quint16 tempRef;
quint8 codingType;
quint8 buffer[8];
// create Mpeg2Schnitt idd-stream name
iddStreamName = ttChangeFileExt(stream_info->filePath(), "idd");
// check for Mpeg2Schnitt idd-stream in current directory
iddStreamInfo.setFile(iddStreamName);
if (iddStreamInfo.exists())
{
QFile idd_file( iddStreamInfo.filePath() );
idd_file.remove();
}
log->debugMsg(__FILE__, __LINE__, QString("create IDD-file %1").arg(iddStreamInfo.filePath()));
emit statusReport(StatusReportArgs::Start, tr("Create Mpeg2Schnitt IDD-file"), header_list->count());
// create new idd-stream
TTFileBuffer* iddStream = new TTFileBuffer(iddStreamName, QIODevice::WriteOnly);
iddStream->open();
// IDD header data and version
buffer[0] = int('i');
buffer[1] = int('d');
buffer[2] = int('d');
buffer[3] = 2;
iddStream->directWrite(buffer, 4);
while (index < header_list->count())
{
if (mAbort) {
mAbort = false;
throw new TTAbortException("Writing IDD file aborted!");
}
headerType = header_list->at(index)->headerType();
iddStream->directWrite(headerType); // 1 Byte
offset = header_list->at(index)->headerOffset();
iddStream->directWriteUInt64( offset ); // 8 Byte
// picture header
if ( headerType == TTMpeg2VideoHeader::picture_start_code )
{
currentPicture = (TTPicturesHeader*)header_list->at(index);
if ( currentPicture != NULL )
{
tempRef = currentPicture->temporal_reference;
iddStream->directWriteUInt16( tempRef ); // 2 Byte
codingType = currentPicture->picture_coding_type;
iddStream->directWrite(codingType); // 1 Byte
}
}
index++;
emit statusReport(StatusReportArgs::Step, tr("Create Mpeg2Schnitt IDD-File"), index);
}
emit statusReport(StatusReportArgs::Finished, tr("IDD-File created"), header_list->count());
// write sequence end header type
buffer[0] = 0xB7;
iddStream->directWrite(buffer, 1); // 1 Byte
// write last file offset
offset = header_list->at(index-1)->headerOffset();
iddStream->directWriteUInt64( offset ); // 8 Byte
iddStream->close();
delete iddStream;
}
/*! ////////////////////////////////////////////////////////////////////////////
* Read MPEG2Schnitt *.idd file (also created by projectX)
*/
void TTMpeg2VideoStream::readIDDHeader(TTFileBuffer* iddStream, quint8 iddFileVersion)
{
quint8 pictureCodingType;
quint16 temporalReference;
quint8 headerType;
quint64 offset;
TTMpeg2VideoHeader* newHeader = NULL;
if (iddFileVersion < 2) {
throw new TTDataFormatException(QString(tr("IDD file version %1 not supported!")).arg(iddFileVersion));
}
emit statusReport(StatusReportArgs::Start, tr("Read Mpeg2Schnitt IDD-file"), iddStream->size());
try
{
while(!iddStream->atEnd())
{
if (mAbort) {
mAbort = false;
throw new TTAbortException(tr("Read IDD header file aborted!"));
}
iddStream->readByte(headerType);
iddStream->readUInt64(offset);
switch (headerType)
{
case TTMpeg2VideoHeader::sequence_start_code:
newHeader = new TTSequenceHeader();
newHeader->readHeader(stream_buffer, offset);
break;
case TTMpeg2VideoHeader::picture_start_code:
newHeader = new TTPicturesHeader();
iddStream->readUInt16(temporalReference);
iddStream->readByte(pictureCodingType);
((TTPicturesHeader*)newHeader)->setHeaderOffset(offset);
((TTPicturesHeader*)newHeader)->temporal_reference = temporalReference;
((TTPicturesHeader*)newHeader)->picture_coding_type = pictureCodingType;
//do we realy need the vbv delay???
newHeader->readHeader(stream_buffer, offset);
break;
case TTMpeg2VideoHeader::group_start_code:
newHeader = new TTGOPHeader();
newHeader->readHeader(stream_buffer, offset);
break;
case TTMpeg2VideoHeader::sequence_end_code:
newHeader = new TTSequenceEndHeader();
newHeader->readHeader(stream_buffer, offset);
break;
}
header_list->add( newHeader );
emit statusReport(StatusReportArgs::Step, tr("Read Mpeg2Schnitt IDD-file"), iddStream->position());
}
emit statusReport(StatusReportArgs::Finished, tr("Finish reading IDD-file"), iddStream->size());
}
catch (...)
{
log->debugMsg(__FILE__, __LINE__, "catch block called!");
}
}
/*! ////////////////////////////////////////////////////////////////////////////
* IsCutInPoint
* Returns true, if the current index position (picture) is a valid cut-in point
* In encoder-mode every picture position is a valid cut-in position, else the
* cut-in is only allowed on I-frames
*/
bool TTMpeg2VideoStream::isCutInPoint(int pos)
{
if (TTCut::encoderMode)
return true;
int index = (pos < 0) ? currentIndex() : pos;
int frame_type = index_list->pictureCodingType(index);
return (frame_type == 1);
}
/*! ////////////////////////////////////////////////////////////////////////////
* IsCutOutPoint
* Returns true, if the current index position (picture) is a valid cut-out
* point.
* In encoder-mode every picture position is a valid cut-out position, else, the
* cut-out is only valid on P- or I-frames
*/
bool TTMpeg2VideoStream::isCutOutPoint(int pos)
{
if (TTCut::encoderMode)
return true;
int index = (pos < 0) ? currentIndex() : pos;
int frame_type = index_list->pictureCodingType(index);
return ((frame_type == 1) || (frame_type == 2));
}
/*! ////////////////////////////////////////////////////////////////////////////
* Cut Method
* TTFileBuffer* targetStream: The mpeg2 video target stream
* int startIndex: Start index of current cut
* int endIndex: End index of current cut
* TTCutParameter: cutParams: Cut parameter
*/
void TTMpeg2VideoStream::cut(int cutInPos, int cutOutPos, TTCutParameter* cutParams)
{
openStream();
log->debugMsg(__FILE__, __LINE__, QString("cut: cutIn %1 / cutOut %2").arg(cutInPos).arg(cutOutPos));
TTVideoHeader* startObject = getCutStartObject(cutInPos, cutParams);
TTVideoHeader* endObject = getCutEndObject(cutOutPos, cutParams);
log->debugMsg(__FILE__, __LINE__, QString("startObject: %1").arg(startObject->headerOffset()));
log->debugMsg(__FILE__, __LINE__, QString("endObject: %1").arg(endObject->headerOffset()));
transferCutObjects(startObject, endObject, cutParams);
if (cutOutPos > cutParams->getCutOutIndex())
encodePart(cutParams->getCutOutIndex()+1, cutOutPos, cutParams);
closeStream();
}
/*! /////////////////////////////////////////////////////////////////////////////
* Return the start object for current cut
*/
TTVideoHeader* TTMpeg2VideoStream::getCutStartObject(int cutInPos, TTCutParameter* cutParams)
{
int iFramePos = cutInPos;
log->debugMsg(__FILE__, __LINE__, QString("getStartObject::cutIn %1").arg(cutInPos));
log->debugMsg(__FILE__, __LINE__, QString("frame-type is %1").arg(index_list->pictureCodingType(iFramePos)));
// if coding type is not I-frame, we must encode
if (index_list->pictureCodingType(iFramePos) != 1)
{
iFramePos = index_list->moveToNextIndexPos(cutInPos, 1);
encodePart(cutInPos, iFramePos-1, cutParams);
}
TTVideoHeader* start_object = checkIFrameSequence(iFramePos, cutParams);
cutParams->setCutInIndex(iFramePos);
return start_object;
}
/*! /////////////////////////////////////////////////////////////////////////////
* Check cut in position and try to insert eventually missing sequence
*/
TTVideoHeader* TTMpeg2VideoStream::checkIFrameSequence(int iFramePos, TTCutParameter* cutParams)
{
int seqHeaderIndex = ((index_list->headerListIndex(iFramePos) - 2) > 0)
? index_list->headerListIndex(iFramePos) - 2
: 0;
TTVideoHeader* currentHeader = (TTVideoHeader*)header_list->headerAt(seqHeaderIndex);
//Check for sequence
if (currentHeader->headerType() == TTMpeg2VideoHeader::sequence_start_code)
return currentHeader;
TTSequenceHeader* seqHeader = (TTSequenceHeader*)header_list->getNextHeader(
seqHeaderIndex, TTMpeg2VideoHeader::sequence_start_code);
if (!ttAssigned(seqHeader))
throw new TTArgumentException(QString(tr("No sequence header for I-Frame at index %1")).arg(iFramePos));
//Check for GOP
int gopHeaderIndex = header_list->headerIndex((TTVideoHeader*)seqHeader) + 1;
TTVideoHeader* gopHeader = header_list->headerAt(gopHeaderIndex);
if (!ttAssigned(gopHeader))
throw new TTArgumentException(QString(tr("No GOP Header found for I-Frame at index %1")).arg(iFramePos));
// inject the sequence header into the target stream
copySegment(cutParams->getTargetStreamBuffer(), seqHeader->headerOffset(), gopHeader->headerOffset()-1);
if (cutParams->getMaxBitrate() < seqHeader->bit_rate_value)
cutParams->setMaxBitrate(seqHeader->bit_rate_value);
log->fatalMsg(__FILE__, __LINE__, QString(tr("Insert missing sequence header in cut target stream!")));
throw new TTMissingMethodException(QString("Sequence copy-constructor not implmented yet!"));
//TODO: here we need a sequence copy constructor!
//TTSequenceHeader* newSequence = new TTSequenceHeader();
//newSequence->setHeaderOffset((quint64)0);
//newSequence->aspect_ratio_information = seqHeader->aspect_ratio_information;
//cutParams->result_header_list->add(newSequence);
return gopHeader;
}
/*! /////////////////////////////////////////////////////////////////////////////
* Returns the end object for current cut
*/
TTVideoHeader* TTMpeg2VideoStream::getCutEndObject(int cutOutPos, TTCutParameter* cutParams)
{
int ipFramePos = cutOutPos;
log->debugMsg(__FILE__, __LINE__, QString("getEndObject::cutIn %1").arg(cutOutPos));
log->debugMsg(__FILE__, __LINE__, QString("frame-type is %1").arg(index_list->pictureCodingType(ipFramePos)));
while (ipFramePos >= 0 && index_list->pictureCodingType(ipFramePos) == 3)
ipFramePos--;
if (index_list->pictureCodingType(ipFramePos) == 3)
throw new TTInvalidOperationException(QString(tr("No I- or P-Frame found at cut out position: %1")).arg(cutOutPos));
int headerListPos = index_list->headerListIndex(ipFramePos);
TTPicturesHeader* endObject = (TTPicturesHeader*)header_list->headerAt(headerListPos);
cutParams->setCutOutIndex(ipFramePos);
if (headerListPos+1 >= header_list->count())
return endObject;
// the following B-Frames belongs to this cut out position
do {
headerListPos++;
TTPicturesHeader* tmpObject = (TTPicturesHeader*)header_list->headerAt(headerListPos);
if (tmpObject->headerType() != TTMpeg2VideoHeader::picture_start_code)
break;
if (tmpObject->picture_coding_type != 3)
break;
endObject = tmpObject;
} while (headerListPos+1 < header_list->count());
return endObject;
}
/*! /////////////////////////////////////////////////////////////////////////////
* Returns the number of bytes between startObject and endObject
*/
quint64 TTMpeg2VideoStream::getByteCount(TTVideoHeader* startObject, TTVideoHeader* endObject)
{
quint64 startOffset = startObject->headerOffset();
int endObjectIndex = header_list->headerIndex(endObject);
quint64 endOffset = (endObjectIndex+1 < header_list->count())
? header_list->headerAt(endObjectIndex+1)->headerOffset()
: stream_buffer->size();
return (endOffset - startOffset);
}
/*! /////////////////////////////////////////////////////////////////////////////
* Transfers the cuts objects to the target stream
* Remark: [startObject, endObject[
*/
void TTMpeg2VideoStream::transferCutObjects(TTVideoHeader* startObject, TTVideoHeader* endObject, TTCutParameter* cr)
{
quint8 buffer[65536];
quint64 bytesToWrite = getByteCount(startObject, endObject);
quint64 bufferStartOffset = startObject->headerOffset();
int numPicsWritten = cr->getNumPicturesWritten();
quint64 process = 0;
bool closeNextGOP = true; // remove B-frames
int tempRefDelta = 0; // delta for temporal reference if closed GOP
const int watermark = 12; // size of header type-code (12 byte)
bool objectProcessed = false;
bool isContinue = false;
log->debugMsg(__FILE__, __LINE__, QString("transferCutObjects::bytesToWrite %1").
arg(bytesToWrite));
TTVideoHeader* currentObject = startObject;
QStack<TTBreakObject*>* break_objects = new QStack<TTBreakObject*>;
stream_buffer->seekAbsolute( startObject->headerOffset() );
//qDebug(qPrintable(QString("transferCutObjects -> emit start in thread %1").arg(QThread::currentThreadId())));
emit statusReport(StatusReportArgs::Start, tr("Transfer objects"), bytesToWrite);
qApp->processEvents();
while( bytesToWrite > 0 )
{
int bytesProcessed = (bytesToWrite < 65536)
? stream_buffer->readByte(buffer, bytesToWrite)
: stream_buffer->readByte(buffer, 65536);
if (bytesProcessed <= 0)
throw TTIOException(QString(tr("%1 bytes from stream buffer read")).arg(bytesProcessed));
do
{
if (mAbort) {
mAbort = false;
throw new TTAbortException(tr("Transfer cut objects aborted!"));
}
isContinue = false;
// is start address not in current buffer
if (currentObject->headerOffset() < bufferStartOffset || currentObject->headerOffset() > (bufferStartOffset+bytesProcessed-1)) {
break;
}
objectProcessed = (currentObject->headerOffset() < bufferStartOffset+bytesProcessed-watermark);
if (!objectProcessed) {
stream_buffer->seekBackward(watermark);
bytesProcessed -= watermark;
break;
}
// removing unwanted objects
if ( break_objects->count() > 0 )
{
TTBreakObject* current_break = (TTBreakObject*)break_objects->top();
if ( current_break->stopObject() != NULL &&
current_break->stopObject()->headerOffset() == currentObject->headerOffset() )
{
quint64 adress_delta = current_break->restartObject()->headerOffset()-currentObject->headerOffset();
bytesProcessed = (int)(currentObject->headerOffset()-bufferStartOffset);
bytesToWrite -= adress_delta;
bufferStartOffset += adress_delta;
currentObject = current_break->restartObject(); // hier gehts weiter
stream_buffer->seekAbsolute(current_break->restartObject()->headerOffset());
current_break->setStopObject((TTVideoHeader*)NULL );
objectProcessed = false;
continue;
}
if (current_break->restartObject()->headerOffset() == currentObject->headerOffset())
{
TTBreakObject* tmpBreak = break_objects->pop();
if (ttAssigned(tmpBreak))
delete tmpBreak;
}
}
switch(currentObject->headerType())
{
case TTMpeg2VideoHeader::sequence_start_code:
// Maximale Bitrate ermitteln
if (cr->getMaxBitrate() < ((TTSequenceHeader*)currentObject)->bit_rate_value)
cr->setMaxBitrate(((TTSequenceHeader*)currentObject)->bit_rate_value);
break;
case TTMpeg2VideoHeader::sequence_end_code: {
//remove sequence end code
TTBreakObject* new_break = new TTBreakObject();
new_break->setStopObject(currentObject);
new_break->setRestartObject(header_list->getNextHeader(currentObject));
break_objects->push( new_break );
isContinue = true;
}
break;
case TTMpeg2VideoHeader::group_start_code:
{
TTPicturesHeader* nextPic = (TTPicturesHeader*)header_list->getNextHeader(
currentObject, TTMpeg2VideoHeader::picture_start_code);
if (closeNextGOP && (ttAssigned(nextPic)) && (nextPic->temporal_reference == 0))
closeNextGOP = false;
rewriteGOP(buffer, bufferStartOffset, (TTGOPHeader*)currentObject, closeNextGOP, cr);
}
break;
case TTMpeg2VideoHeader::picture_start_code: {
TTPicturesHeader* currentPicture = (TTPicturesHeader*)currentObject;
if (closeNextGOP &&
tempRefDelta != 0 &&
currentPicture->picture_coding_type == 3)
{
removeOrphanedBFrames(break_objects, currentObject);
closeNextGOP = false;
isContinue = true;
break;
//continue;
}
numPicsWritten++;
//log->debugMsg(__FILE__, __LINE__, QString("picture %1 transfered %2").
// arg(numPicsWritten).arg(currentPicture->headerOffset()));
cr->setNumPicturesWritten(numPicsWritten);
if (currentPicture->picture_coding_type == 1) {
tempRefDelta = (closeNextGOP)
? currentPicture->temporal_reference
: 0;
}
// M�ssen neue tempor�rere Referenzen geschrieben werden?
if ( tempRefDelta != 0)
{
rewriteTempRefData(buffer, currentPicture, bufferStartOffset, tempRefDelta);
}
}
break;
}
if (isContinue)
continue;
if (currentObject == endObject) {
break;
}
currentObject = header_list->getNextHeader(currentObject);
}while(objectProcessed);
cr->getTargetStreamBuffer()->directWrite(buffer, bytesProcessed);
process += bytesProcessed;
bytesToWrite -= bytesProcessed;
bufferStartOffset += bytesProcessed;
emit statusReport(StatusReportArgs::Step, tr("Transfer objects"), process);
qApp->processEvents();
}
emit statusReport(StatusReportArgs::Finished, tr("Transfer complete"), process);
qApp->processEvents();
// clean-up
for (int i = 0; i < break_objects->size(); i++) {
TTBreakObject* tmpBreak = break_objects->at(i);
if (ttAssigned(tmpBreak))
delete tmpBreak;
}
if (ttAssigned(break_objects)) {
delete break_objects;
break_objects = NULL;
}
}
/*! /////////////////////////////////////////////////////////////////////////////
* Put orphaned B-Frames to break objects stack for removal
*/
void TTMpeg2VideoStream::removeOrphanedBFrames(QStack<TTBreakObject*>* breakObjects, TTVideoHeader* currentObject)
{
TTVideoHeader* nextObject = currentObject;
do
{
log->debugMsg(__FILE__, __LINE__, QString(">>> remove B-Frame at %1").arg(nextObject->headerOffset()));
nextObject = header_list->getNextHeader(nextObject);
}
while (nextObject != NULL &&
nextObject->headerType() == TTMpeg2VideoHeader::picture_start_code &&
((TTPicturesHeader*)nextObject)->picture_coding_type == 3);
TTBreakObject* new_break = new TTBreakObject();
new_break->setStopObject(currentObject);
new_break->setRestartObject(nextObject);
log->debugMsg(__FILE__, __LINE__, QString("stop object %1 / restart object %2").
arg(currentObject->headerOffset()).
arg(nextObject->headerOffset()));
breakObjects->push( new_break );
}
/*! /////////////////////////////////////////////////////////////////////////////
* Rewrites the time codes in GOP header
*/
void TTMpeg2VideoStream::rewriteGOP(quint8* buffer, quint64 abs_pos, TTGOPHeader* gop, bool close_gop, TTCutParameter* cr)
{
if (abs_pos > gop->headerOffset()) {
log->errorMsg(__FILE__, __LINE__, "buffer position is invalid in rewrite GOP!!!");
return;
}
quint8 time_code[4];
TTTimeCode tc = ttFrameToTimeCode(cr->getNumPicturesWritten(), frameRate());
time_code[0]=(quint8)(((tc.drop_frame_flag?1:0)<<7)
+((tc.hours & 0x1f)<<2)
+((tc.minutes & 0x30)>>4));
time_code[1]=(quint8)(((tc.minutes & 0x0f)<<4)
+((tc.marker_bit?1:0)<<3)
+((tc.seconds & 0x38)>>3));
time_code[2]=(quint8)(((tc.seconds & 0x07)<<5)
+ ((tc.pictures & 0x3e)>>1));
time_code[3]=(quint8)((((tc.pictures & 0x01)==1)?0x80:0x00)
| ((close_gop || gop->closed_gop)?0x40:0)
| (gop->broken_link ? 0x20:0x00));
buffer[(int)(gop->headerOffset()-abs_pos)+4] = time_code[0];
buffer[(int)(gop->headerOffset()-abs_pos)+5] = time_code[1];
buffer[(int)(gop->headerOffset()-abs_pos)+6] = time_code[2];
buffer[(int)(gop->headerOffset()-abs_pos)+7] = time_code[3];
}
/* /////////////////////////////////////////////////////////////////////////////
* Rewrite temporal references
*/
void TTMpeg2VideoStream::rewriteTempRefData(quint8* buffer, TTPicturesHeader* currentPicture, quint64 bufferStartOffset, int tempRefDelta)
{
qint16 newTempRef = (qint16)(currentPicture->temporal_reference-tempRefDelta);
int offset = (int)(currentPicture->headerOffset()-bufferStartOffset)+4; // Hier rein damit!
buffer[offset] = (quint8)(newTempRef >> 2); // Bit 10 - 2 von 10 Bit Tempref
buffer[offset+1] = (quint8)(((newTempRef & 0x0003) << 6) + // Bit 1 und 0 von 10 Bit Tempref
((int)currentPicture->picture_coding_type << 3) + // Bildtype auf Bit 5, 4 und 3
(currentPicture->vbv_delay >> 13)); // 3 Bit von VBVDelay
}
/*! ////////////////////////////////////////////////////////////////////////////
* EncodePart
* Decode and encode the part between start and end
* int start: start index (display order)
* int end : end index (display orser)
* TTCutParameter* cr : Cut parameter
*/
void TTMpeg2VideoStream::encodePart(int start, int end, TTCutParameter* cr)
{
// save current cut parameter
bool savIsWriteMaxBitrate = cr->getIsWriteMaxBitrate();
bool savIsWriteSequenceEnd = cr->getIsWriteSequenceEnd();
bool savCreateVideoIDD = TTCut::createVideoIDD;
bool savReadVideoIDD = TTCut::readVideoIDD;
// no sequence end code
cr->setIsWriteSequenceEnd(false);
cr->setIsWriteMaxBitrate(false);
TTCut::createVideoIDD = false;
TTCut::readVideoIDD = false;
log->debugMsg(__FILE__, __LINE__, QString("enocdePart start %1 / end %2").arg(start).arg(end));
// use the sequence header according to current picture for information about
// frame size (width x height) and aspect ratio
TTSequenceHeader* seq_head = getSequenceHeader(current_index);
QDir tempDir( TTCut::tempDirPath );
QString aviOutFile = "encode.avi";
QString mpeg2OutFile = "encode"; // extension is added by transcode (!)
QFileInfo aviFileInfo(tempDir, aviOutFile);
QFileInfo mpeg2FileInfo(tempDir, mpeg2OutFile);
TTEncodeParameter encParams;
encParams.setAVIFileInfo(aviFileInfo);
encParams.setMpeg2FileInfo(mpeg2FileInfo);
encParams.setVideoWidth(seq_head->horizontal_size_value);
encParams.setVideoHeight(seq_head->vertical_size_value);
encParams.setVideoAspectCode(seq_head->aspect_ratio_information);
encParams.setVideoBitrate(seq_head->bitRateKbit());
TTTranscodeProvider* transcode_prov = new TTTranscodeProvider(encParams);
connect(transcode_prov, SIGNAL(statusReport(int, const QString&, quint64)),
this, SIGNAL(statusReport(int, const QString&, quint64)),
Qt::DirectConnection);
qApp->processEvents();
bool success = transcode_prov->encodePart((TTVideoStream*)this, start, end);
if (!success) {
QString msg = QString("Error in encode part!");;
log->fatalMsg(__FILE__, __LINE__, msg);
throw TTInvalidOperationException(msg);
}
mpeg2FileInfo.setFile(tempDir, "encode.m2v");
TTMpeg2VideoStream* new_mpeg_stream = new TTMpeg2VideoStream(mpeg2FileInfo);
new_mpeg_stream->createHeaderList();
new_mpeg_stream->createIndexList();
new_mpeg_stream->indexList()->sortDisplayOrder();
int cutOut = (end-start == 0) ? 0 : end-start;
new_mpeg_stream->cut(0, cutOut, cr);
// remove temporary files
QString rmCmd = QString("rm %1/encode.*").arg(mpeg2FileInfo.absolutePath());
if (system(rmCmd.toAscii().data()) < 0)
log->errorMsg(__FILE__, __LINE__, QString(tr("system call %1 failed!")).arg(rmCmd));
cr->setIsWriteMaxBitrate(savIsWriteMaxBitrate);
cr->setIsWriteSequenceEnd(savIsWriteSequenceEnd);
TTCut::readVideoIDD = savReadVideoIDD;
TTCut::createVideoIDD = savCreateVideoIDD;
disconnect(transcode_prov, SIGNAL(statusReport(int, const QString&, quint64)),
this, SIGNAL(statusReport(int, const QString&, quint64)));
delete transcode_prov;
delete new_mpeg_stream;
}
| [
"[email protected]"
]
| [
[
[
1,
1027
]
]
]
|
7625205021e1770dcf3ee9a3bf0cf3249518b839 | ef25bd96604141839b178a2db2c008c7da20c535 | /src/src/Engine/Objects/Skybox.h | 2c6d3dfc69711520fa48c9196e0bf0991d437af7 | []
| no_license | OtterOrder/crock-rising | fddd471971477c397e783dc6dd1a81efb5dc852c | 543dc542bb313e1f5e34866bd58985775acf375a | refs/heads/master | 2020-12-24T14:57:06.743092 | 2009-07-15T17:15:24 | 2009-07-15T17:15:24 | 32,115,272 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 563 | h | #pragma once
#include "Object.h"
#include "Resources/Shader.h"
class Skybox : public Object
{
public:
Skybox(const std::string& Name);
Skybox();
~Skybox();
HRESULT Init(float _size=10);
HRESULT ResetDevice();
void SetTransform(const D3DXMATRIX* view, const D3DXMATRIX* proj, const D3DXVECTOR3 CamPos);
HRESULT Draw();
HRESULT LostDevice();
void DeleteData();
protected:
std::string m_StrTex;
LPDIRECT3DVERTEXBUFFER9 m_pSkyVB;
IDirect3DCubeTexture9* m_pEnvTex;
Shader* m_pSkyShader;
float m_size;
}; | [
"mathieu.chabanon@7c6770cc-a6a4-11dd-91bf-632da8b6e10b",
"germain.mazac@7c6770cc-a6a4-11dd-91bf-632da8b6e10b"
]
| [
[
[
1,
12
],
[
15,
17
],
[
19,
24
],
[
26,
28
]
],
[
[
13,
14
],
[
18,
18
],
[
25,
25
]
]
]
|
c714464758058fb4c754aa07b9472b896bf61e19 | e580637678397200ed79532cd34ef78983e9aacd | /Grapplon/PlayerObject.h | 6c60bc340294109698a6100bbdf52de403ca7bfe | []
| no_license | TimToxopeus/grapplon2 | 03520bf6b5feb2c6fcb0c5ddb135abe55d3f344b | 60f0564bdeda7d4c6e1b97148b5d060ab84c8bd5 | refs/heads/master | 2021-01-10T21:11:59.438625 | 2008-07-13T06:49:06 | 2008-07-13T06:49:06 | 41,954,527 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,232 | h | #pragma once
#include "BaseObject.h"
#include "WiimoteListener.h"
#include <ode/ode.h>
class CParticleEmitter;
class CHook;
struct CollisionEffect
{
CAnimatedTexture *m_pEffect;
Vector m_vPosition;
CBaseObject *m_pOther;
};
class CPlayerObject : public CBaseObject, public IWiimoteListener
{
private:
float m_fShipVel;
float m_fVelocityForward;
CAnimatedTexture *m_pImageDamage;
CAnimatedTexture *m_pFrozenImage;
CAnimatedTexture *m_pExplosion;
CAnimatedTexture *m_pJellyImage;
CAnimatedTexture *m_pShieldImage;
CAnimatedTexture *m_pRespawnImage;
CAnimatedTexture *m_pPUFrozenImage;
CAnimatedTexture *m_pElectricImage;
CAnimatedTexture *m_pRespawnRing;
Vector explosionPos;
Vector diePosition;
float timeTillDeath;
Vector respawnDisplacement;
bool m_bIsReinitialized;
std::vector<CollisionEffect *> m_vCollisionEffects;
int m_iPlayer;
float m_fExplosionAngle;
CHook *m_pHook;
float timeSinceNoInput;
float m_fRespawnTime;
float m_fPUSpeedTime;
float m_fPUShieldTime;
float m_fPUHealthTime;
float m_fPUFreezeTime;
bool m_bHandleWiiMoteEvents;
CParticleEmitter *m_pThrusterLeft, *m_pThrusterRight;
void Respawn();
bool HasSpark( CBaseObject *pOther );
bool m_bElectroChangedThisFrame;
float m_fTimeForEMP;
float m_fElectroTime;
float m_fEMPTime;
int m_iJellyFrame;
public:
CPlayerObject( int iPlayer );
virtual ~CPlayerObject();
CAnimatedTexture *m_pRadius;
float m_fPUJellyTime;
int m_iScore;
float m_fFreezeTime;
virtual bool HandleWiimoteEvent( wiimote_t* pWiimoteEvent );
virtual void Update( float fTime );
virtual void Render();
virtual void SetPosition( float fX, float fY );
virtual void SetPosition( Vector pos );
virtual void CollideWith( CBaseObject *pOther, Vector &pos);
virtual void OnDie( CBaseObject *m_pKiller );
virtual inline void ApplyForceFront();
void TookHealthPowerUp();
void TookSpeedPowerUp();
void TookJellyPowerUp();
void TookShieldPowerUp();
void ResetStatus();
void AffectedByFreezePU();
int GetPlayerNr() { return m_iPlayer; }
void IncreaseElectro(float timePassed);
int GetPlayerID() { return m_iPlayer; }
};
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
24
],
[
27,
29
],
[
33,
33
],
[
42,
53
],
[
55,
61
],
[
69,
72
],
[
78,
94
],
[
98,
98
],
[
100,
103
]
],
[
[
25,
26
],
[
30,
32
],
[
34,
41
],
[
54,
54
],
[
62,
68
],
[
73,
77
],
[
95,
97
],
[
99,
99
]
]
]
|
2aa9c339f4049ec1d487b14e0fb7b64843250907 | c6f4fe2766815616b37beccf07db82c0da27e6c1 | /Barrier.h | 1de8b4560edb655166f79f3e1647724869740545 | []
| no_license | fragoulis/gpm-sem1-spacegame | c600f300046c054f7ab3cbf7193ccaad1503ca09 | 85bdfb5b62e2964588f41d03a295b2431ff9689f | refs/heads/master | 2023-06-09T03:43:53.175249 | 2007-12-13T03:03:30 | 2007-12-13T03:03:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 272 | h | #pragma once
#include "TileObject.h"
using tlib::Vector3f;
class Barrier : public TileObject
{
public:
/**
* Constructor
*/
Barrier();
Barrier( const Vector3f& vBBox );
/**
* Destructor
*/
virtual ~Barrier() {}
}; | [
"john.fragkoulis@201bd241-053d-0410-948a-418211174e54"
]
| [
[
[
1,
18
]
]
]
|
152552499f414c536eb2113e0b0bee7a139a9f42 | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.0/bctestlist/src/bctestlistpopupcase.cpp | bb77d6b28f8b5f8da90144caa9768e22157d6d3e | []
| no_license | SymbianSource/oss.FCL.sftools.ana.compatanamdw | a6a8abf9ef7ad71021d43b7f2b2076b504d4445e | 1169475bbf82ebb763de36686d144336fcf9d93b | refs/heads/master | 2020-12-24T12:29:44.646072 | 2010-11-11T14:03:20 | 2010-11-11T14:03:20 | 72,994,432 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,474 | cpp | /*
* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description: test case for popup list box classes
*
*/
#include <eikenv.h>
#include <eikapp.h>
#include "bctestlistpopupcase.h"
#include "bctestlistcontainer.h"
#include "bctestlist.hrh"
#include <bctestlist.rsg>
#include <bctestlist.mbg>
_LIT( KPopupCreate1, "Create CAknSinglePopupMenuStyleListBox" );
_LIT( KPopupCreate2, "Create CAknSingleGraphicPopupMenuStyleListBox" );
_LIT( KPopupCreate3, "Create CAknSingleGraphicBtPopupMenuStyleListBox" );
_LIT( KPopupCreate4, "Create CAknSingleHeadingPopupMenuStyleListBox" );
_LIT( KPopupCreate5, "Create CAknSingleGraphicHeadingPopupMenuStyleListBox" );
_LIT( KPopupCreate6, "Create CAknDoublePopupMenuStyleListBox" );
_LIT( KPopupCreate7, "Create CAknSinglePopupSubmenuStyleListBox" );
_LIT( KPopupCreate8, "Create CAknDoubleLargeGraphicPopupMenuStyleListBox" );
_LIT( KPopupCreate9, "Create CAknDouble2PopupMenuStyleListBox" );
_LIT( KPopupCreate10, "Create CAknSingle2GraphicPopupMenuStyleListBox" );
_LIT( KPopupCreate11, "Create CAknDoubleGraphicPopupMenuStyleListBox" );
_LIT( KPopupCreate12, "Create CAknSetStyleListBox" );
_LIT( KSetConstructWithWindow, "CAknSetStyleListBox::ConstructWithWindowL" );
_LIT( KPopupCreate13, "Create CAknFormGraphicStyleListBox" );
_LIT( KFormGraphicConstructWithWindow, "CAknFormGraphicStyleListBox::ConstructWithWindowL" );
_LIT( KPopupCreate14, "Create CAknFormGraphicWideStyleListBox" );
_LIT( KSinglePopupMenuTest1, "CAknSinglePopupMenuStyleListBox::SizeChanged" );
_LIT( KSinglePopupMenuTest2, "CAknSinglePopupMenuStyleListBox::MinimumSize" );
_LIT( KSinglePopupMenuTest3, "CAknSinglePopupMenuStyleListBox::HandlePointerEventL" );
_LIT( KSingleGraphicPopupMenuTest1, "CAknSingleGraphicPopupMenuStyleListBox::SizeChanged" );
_LIT( KSingleGraphicPopupMenuTest2, "CAknSingleGraphicPopupMenuStyleListBox::MinimumSize" );
_LIT( KSingleGraphicPopupMenuTest3, "CAknSingleGraphicPopupMenuStyleListBox::HandlePointerEventL" );
_LIT( KSingleGraphicBtPopupMenuTest1, "CAknSingleGraphicBtPopupMenuStyleListBox::SizeChanged" );
_LIT( KSingleGraphicBtPopupMenuTest2, "CAknSingleGraphicBtPopupMenuStyleListBox::HandlePointerEventL" );
_LIT( KSingleHeadingPopupMenuTest1, "CAknSingleHeadingPopupMenuStyleListBox::SizeChanged" );
_LIT( KSingleHeadingPopupMenuTest2, "CAknSingleHeadingPopupMenuStyleListBox::MinimumSize" );
_LIT( KSingleHeadingPopupMenuTest3, "CAknSingleHeadingPopupMenuStyleListBox::HandlePointerEventL" );
_LIT( KSingleGraphicHeadingPopupMenuTest1, "CAknSingleGraphicHeadingPopupMenuStyleListBox::SizeChanged" );
_LIT( KSingleGraphicHeadingPopupMenuTest2, "CAknSingleGraphicHeadingPopupMenuStyleListBox::MinimumSize" );
_LIT( KSingleGraphicHeadingPopupMenuTest3, "CAknSingleGraphicHeadingPopupMenuStyleListBox::HandlePointerEventL" );
_LIT( KDoublePopupMenuTest1, "CAknDoublePopupMenuStyleListBox::SizeChanged" );
_LIT( KDoublePopupMenuTest2, "CAknDoublePopupMenuStyleListBox::MinimumSize" );
_LIT( KDoublePopupMenuTest3, "CAknDoublePopupMenuStyleListBox::HandlePointerEventL" );
_LIT( KSinglePopupSubMenuTest1, "CAknSinglePopupSubmenuStyleListBox::SizeChanged" );
_LIT( KSinglePopupSubMenuTest2, "CAknSinglePopupSubmenuStyleListBox::MinimumSize" );
_LIT( KSinglePopupSubMenuTest3, "CAknSinglePopupSubmenuStyleListBox::HandlePointerEventL" );
_LIT( KDoubleLargeGraphicPopupMenuTest1, "CAknDoubleLargeGraphicPopupMenuStyleListBox::SizeChanged" );
_LIT( KDoubleLargeGraphicPopupMenuTest2, "CAknDoubleLargeGraphicPopupMenuStyleListBox::MinimumSize" );
_LIT( KDoubleLargeGraphicPopupMenuTest3, "CAknDoubleLargeGraphicPopupMenuStyleListBox::HandlePointerEventL" );
_LIT( KDouble2PopupMenuTest1, "CAknDouble2PopupMenuStyleListBox::SizeChanged" );
_LIT( KDouble2PopupMenuTest2, "CAknDouble2PopupMenuStyleListBox::MinimumSize" );
_LIT( KDouble2PopupMenuTest3, "CAknDouble2PopupMenuStyleListBox::HandlePointerEventL" );
_LIT( KSingle2GraphicPopupMenuTest1, "CAknSingle2GraphicPopupMenuStyleListBox::SizeChanged" );
_LIT( KSingle2GraphicPopupMenuTest2, "CAknSingle2GraphicPopupMenuStyleListBox::MinimumSize" );
_LIT( KSingle2GraphicPopupMenuTest3, "CAknSingle2GraphicPopupMenuStyleListBox::HandlePointerEventL" );
_LIT( KDoubleGraphicPopupMenuTest1, "CAknDoubleGraphicPopupMenuStyleListBox::SizeChanged" );
_LIT( KDoubleGraphicPopupMenuTest2, "CAknDoubleGraphicPopupMenuStyleListBox::MinimumSize" );
_LIT( KDoubleGraphicPopupMenuTest3, "CAknDoubleGraphicPopupMenuStyleListBox::HandlePointerEventL" );
_LIT( KSetTest1, "CAknSetStyleListBox::SizeChanged" );
_LIT( KSetTest2, "CAknSetStyleListBox::MinimumSize" );
_LIT( KSetTest3, "CAknSetStyleListBox::HandlePointerEventL" );
_LIT( KSetTest4, "CAknSetStyleListBox::MopSupplyObject" );
_LIT( KSetTest5, "CAknSetStyleListBox::Draw with empty list" );
_LIT( KSetTest6, "CAknSetStyleListBox::Draw with item" );
_LIT( KFormGraphicTest1, "CAknFormGraphicStyleListBox::SizeChanged" );
_LIT( KFormGraphicTest2, "CAknFormGraphicStyleListBox::MinimumSize" );
_LIT( KFormGraphicTest3, "CAknFormGraphicStyleListBox::AdjustRectHeightToWholeNumberOfItems" );
_LIT( KFormGraphicTest4, "CAknFormGraphicStyleListBox::HandlePointerEventL" );
_LIT( KFormGraphicWideTest1, "CAknFormGraphicWideStyleListBox::SizeChanged" );
_LIT( KFormGraphicWideTest2, "CAknFormGraphicWideStyleListBox::MinimumSize" );
_LIT( KFormGraphicWideTest3, "CAknFormGraphicWideStyleListBox::HandlePointerEventL" );
// ======== MEMBER FUNCTIONS ========
// ---------------------------------------------------------------------------
// Symbian 2nd static Constructor
// ---------------------------------------------------------------------------
//
CBCTestListPopupCase* CBCTestListPopupCase::NewL(
CBCTestListContainer* aContainer, CEikonEnv* aEikEnv )
{
CBCTestListPopupCase* self = new( ELeave ) CBCTestListPopupCase(
aContainer, aEikEnv );
CleanupStack::PushL( self );
self->ConstructL();
CleanupStack::Pop( self );
return self;
}
// ---------------------------------------------------------------------------
// C++ default constructor
// ---------------------------------------------------------------------------
//
CBCTestListPopupCase::CBCTestListPopupCase( CBCTestListContainer* aContainer,
CEikonEnv* aEikEnv )
: CBCTestListBaseCase( aContainer, aEikEnv )
{
}
// ---------------------------------------------------------------------------
// Destructor
// ---------------------------------------------------------------------------
//
CBCTestListPopupCase::~CBCTestListPopupCase()
{
}
// ---------------------------------------------------------------------------
// Symbian 2nd Constructor
// ---------------------------------------------------------------------------
//
void CBCTestListPopupCase::ConstructL()
{
BuildScriptL();
}
// ---------------------------------------------------------------------------
// CBCTestListPopupCase::BuildScriptL
// ---------------------------------------------------------------------------
//
void CBCTestListPopupCase::BuildScriptL()
{
for ( TInt i=0; i <= EBCTestCmdOutline39 - EBCTestCmdOutline26; i++ )
{
AddTestL( LeftCBA, REP( Down, 3 ), KeyOK, TEND );
AddTestL( REP( Down, i ), KeyOK, TEND );
}
}
// ---------------------------------------------------------------------------
// CBCTestListPopupCase::RunL
// ---------------------------------------------------------------------------
//
void CBCTestListPopupCase::RunL( TInt aCmd )
{
if ( aCmd < EBCTestCmdOutline26 ||
aCmd > EBCTestCmdOutline39 )
{
return;
}
iOutlineId = aCmd;
ReleaseCase();
PrepareCaseL( aCmd );
TestPopupListL( aCmd );
}
// ---------------------------------------------------------------------------
// CBCTestListPopupCase::PrepareCaseL
// ---------------------------------------------------------------------------
//
void CBCTestListPopupCase::PrepareCaseL( TInt aCmd )
{
TInt flags = EAknListBoxSelectionList | EAknListBoxViewerFlags;
TBool useGraphics( EFalse );
switch ( aCmd )
{
case EBCTestCmdOutline26:
{
iListBox = new( ELeave ) CBCTestSinglePopupMenuStyleListBox();
AssertNotNullL( iListBox, KPopupCreate1 );
}
break;
case EBCTestCmdOutline27:
{
iListBox = new( ELeave ) CBCTestSingleGraphicPopupMenuStyleListBox();
AssertNotNullL( iListBox, KPopupCreate2 );
}
break;
case EBCTestCmdOutline28:
{
iListBox = new( ELeave ) CAknSingleGraphicBtPopupMenuStyleListBox();
AssertNotNullL( iListBox, KPopupCreate3 );
}
break;
case EBCTestCmdOutline29:
{
iListBox = new( ELeave ) CAknSingleHeadingPopupMenuStyleListBox();
AssertNotNullL( iListBox, KPopupCreate4 );
}
break;
case EBCTestCmdOutline30:
{
iListBox = new( ELeave ) CAknSingleGraphicHeadingPopupMenuStyleListBox();
AssertNotNullL( iListBox, KPopupCreate5 );
}
break;
case EBCTestCmdOutline31:
{
iListBox = new( ELeave ) CAknDoublePopupMenuStyleListBox();
AssertNotNullL( iListBox, KPopupCreate6 );
}
break;
case EBCTestCmdOutline32:
{
iListBox = new( ELeave ) CAknSinglePopupSubmenuStyleListBox();
AssertNotNullL( iListBox, KPopupCreate7 );
}
break;
case EBCTestCmdOutline33:
{
iListBox = new( ELeave ) CAknDoubleLargeGraphicPopupMenuStyleListBox();
AssertNotNullL( iListBox, KPopupCreate8 );
}
break;
case EBCTestCmdOutline34:
{
iListBox = new( ELeave ) CAknDouble2PopupMenuStyleListBox();
AssertNotNullL( iListBox, KPopupCreate9 );
}
break;
case EBCTestCmdOutline35:
{
iListBox = new( ELeave ) CBCTestSingle2GraphicPopupMenuStyleListBox();
AssertNotNullL( iListBox, KPopupCreate10 );
}
break;
case EBCTestCmdOutline36:
{
iListBox = new( ELeave ) CBCTestDoubleGraphicPopupMenuStyleListBox();
AssertNotNullL( iListBox, KPopupCreate11 );
}
break;
case EBCTestCmdOutline37:
{
useGraphics = ETrue;
iListBox = new( ELeave ) CAknSetStyleListBox();
AssertNotNullL( iListBox, KPopupCreate12 );
CAknSetStyleListBox* listbox =
static_cast<CAknSetStyleListBox*>( iListBox );
listbox->ConstructWithWindowL( iContainer, flags );
AssertTrueL( ETrue, KSetConstructWithWindow );
}
break;
case EBCTestCmdOutline38:
{
useGraphics = ETrue;
iListBox = new( ELeave ) CAknFormGraphicStyleListBox();
AssertNotNullL( iListBox, KPopupCreate13 );
CAknFormGraphicStyleListBox* listbox =
static_cast<CAknFormGraphicStyleListBox*>( iListBox );
listbox->ConstructWithWindowL( iContainer, flags );
AssertTrueL( ETrue, KFormGraphicConstructWithWindow );
}
break;
case EBCTestCmdOutline39:
{
useGraphics = ETrue;
iListBox = new( ELeave ) CAknFormGraphicWideStyleListBox();
AssertNotNullL( iListBox, KPopupCreate14 );
CAknFormGraphicWideStyleListBox* listbox =
static_cast<CAknFormGraphicWideStyleListBox*>( iListBox );
listbox->ConstructWithWindowL( iContainer, flags );
}
break;
default:
break;
}
if ( iListBox )
{
if ( aCmd < EBCTestCmdOutline37 )
{
SetListBoxFromInnerDescriptionL( iListBox );
}
if ( useGraphics )
{
SetGraphicIconL( iListBox );
}
iContainer->SetControl( iListBox );
}
}
// ---------------------------------------------------------------------------
// CBCTestListPopupCase::ReleaseCase
// ---------------------------------------------------------------------------
//
void CBCTestListPopupCase::ReleaseCase()
{
iContainer->ResetControl();
iListBox = NULL;
}
// ---------------------------------------------------------------------------
// CBCTestListPopupCase::TestPopupListL
// ---------------------------------------------------------------------------
//
void CBCTestListPopupCase::TestPopupListL( TInt aCmd )
{
if ( !iListBox )
{
return;
}
TPointerEvent event;
event.iType = TPointerEvent::EButton1Down;
event.iModifiers = 0;
TPoint eventPos(0, 30);
event.iPosition = eventPos;
event.iParentPosition = eventPos;
TSize size;
switch ( aCmd )
{
case EBCTestCmdOutline26:
{
CBCTestSinglePopupMenuStyleListBox* listbox =
static_cast<CBCTestSinglePopupMenuStyleListBox*>( iListBox );
listbox->SizeChanged();
AssertTrueL( ETrue, KSinglePopupMenuTest1 );
size = listbox->MinimumSize();
AssertTrueL( ETrue, KSinglePopupMenuTest2 );
listbox->TestHandlePointerEventL( event );
AssertTrueL( ETrue, KSinglePopupMenuTest3 );
}
break;
case EBCTestCmdOutline27:
{
CBCTestSingleGraphicPopupMenuStyleListBox* listbox =
static_cast<CBCTestSingleGraphicPopupMenuStyleListBox*>( iListBox );
listbox->SizeChanged();
AssertTrueL( ETrue, KSingleGraphicPopupMenuTest1 );
size = listbox->MinimumSize();
AssertTrueL( ETrue, KSingleGraphicPopupMenuTest2 );
listbox->TestHandlePointerEventL( event );
AssertTrueL( ETrue, KSingleGraphicPopupMenuTest3 );
}
break;
case EBCTestCmdOutline28:
{
CAknSingleGraphicBtPopupMenuStyleListBox* listbox =
static_cast<CAknSingleGraphicBtPopupMenuStyleListBox*>( iListBox );
listbox->SizeChanged();
AssertTrueL( ETrue, KSingleGraphicBtPopupMenuTest1 );
listbox->HandlePointerEventL( event );
AssertTrueL( ETrue, KSingleGraphicBtPopupMenuTest2 );
}
break;
case EBCTestCmdOutline29:
{
CAknSingleHeadingPopupMenuStyleListBox* listbox =
static_cast<CAknSingleHeadingPopupMenuStyleListBox*>( iListBox );
listbox->SizeChanged();
AssertTrueL( ETrue, KSingleHeadingPopupMenuTest1 );
size = listbox->MinimumSize();
AssertTrueL( ETrue, KSingleHeadingPopupMenuTest2 );
listbox->HandlePointerEventL( event );
AssertTrueL( ETrue, KSingleHeadingPopupMenuTest3 );
}
break;
case EBCTestCmdOutline30:
{
CAknSingleGraphicHeadingPopupMenuStyleListBox* listbox =
static_cast<CAknSingleGraphicHeadingPopupMenuStyleListBox*>( iListBox );
listbox->SizeChanged();
AssertTrueL( ETrue, KSingleGraphicHeadingPopupMenuTest1 );
size = listbox->MinimumSize();
AssertTrueL( ETrue, KSingleGraphicHeadingPopupMenuTest2 );
listbox->HandlePointerEventL( event );
AssertTrueL( ETrue, KSingleGraphicHeadingPopupMenuTest3 );
}
break;
case EBCTestCmdOutline31:
{
CAknDoublePopupMenuStyleListBox* listbox =
static_cast<CAknDoublePopupMenuStyleListBox*>( iListBox );
listbox->SizeChanged();
AssertTrueL( ETrue, KDoublePopupMenuTest1 );
size = listbox->MinimumSize();
AssertTrueL( ETrue, KDoublePopupMenuTest2 );
listbox->HandlePointerEventL( event );
AssertTrueL( ETrue, KDoublePopupMenuTest3 );
}
break;
case EBCTestCmdOutline32:
{
CAknSinglePopupSubmenuStyleListBox* listbox =
static_cast<CAknSinglePopupSubmenuStyleListBox*>( iListBox );
listbox->SizeChanged();
AssertTrueL( ETrue, KSinglePopupSubMenuTest1 );
size = listbox->MinimumSize();
AssertTrueL( ETrue, KSinglePopupSubMenuTest2 );
listbox->HandlePointerEventL( event );
AssertTrueL( ETrue, KSinglePopupSubMenuTest3 );
}
break;
case EBCTestCmdOutline33:
{
CAknDoubleLargeGraphicPopupMenuStyleListBox* listbox =
static_cast<CAknDoubleLargeGraphicPopupMenuStyleListBox*>( iListBox );
listbox->SizeChanged();
AssertTrueL( ETrue, KDoubleLargeGraphicPopupMenuTest1 );
size = listbox->MinimumSize();
AssertTrueL( ETrue, KDoubleLargeGraphicPopupMenuTest2 );
listbox->HandlePointerEventL( event );
AssertTrueL( ETrue, KDoubleLargeGraphicPopupMenuTest3 );
}
break;
case EBCTestCmdOutline34:
{
CAknDouble2PopupMenuStyleListBox* listbox =
static_cast<CAknDouble2PopupMenuStyleListBox*>( iListBox );
listbox->SizeChanged();
AssertTrueL( ETrue, KDouble2PopupMenuTest1 );
size = listbox->MinimumSize();
AssertTrueL( ETrue, KDouble2PopupMenuTest2 );
listbox->HandlePointerEventL( event );
AssertTrueL( ETrue, KDouble2PopupMenuTest3 );
}
break;
case EBCTestCmdOutline35:
{
CBCTestSingle2GraphicPopupMenuStyleListBox* listbox =
static_cast<CBCTestSingle2GraphicPopupMenuStyleListBox*>( iListBox );
listbox->SizeChanged();
AssertTrueL( ETrue, KSingle2GraphicPopupMenuTest1 );
size = listbox->MinimumSize();
AssertTrueL( ETrue, KSingle2GraphicPopupMenuTest2 );
listbox->TestHandlePointerEventL( event );
AssertTrueL( ETrue, KSingle2GraphicPopupMenuTest3 );
}
break;
case EBCTestCmdOutline36:
{
CBCTestDoubleGraphicPopupMenuStyleListBox* listbox =
static_cast<CBCTestDoubleGraphicPopupMenuStyleListBox*>( iListBox );
AssertTrueL( ETrue, KDoubleGraphicPopupMenuTest1 );
size = listbox->MinimumSize();
AssertTrueL( ETrue, KDoubleGraphicPopupMenuTest2 );
listbox->TestHandlePointerEventL( event );
AssertTrueL( ETrue, KDoubleGraphicPopupMenuTest3 );
}
break;
case EBCTestCmdOutline37:
{
CAknSetStyleListBox* listbox =
static_cast<CAknSetStyleListBox*>( iListBox );
listbox->EnableExtendedDrawingL();
listbox->SetRect( iContainer->Rect() );
listbox->SizeChanged();
AssertTrueL( ETrue, KSetTest1 );
size = listbox->MinimumSize();
AssertTrueL( ETrue, KSetTest2 );
listbox->HandlePointerEventL( event );
AssertTrueL( ETrue, KSetTest3 );
TTypeUid typeId( iEikEnv->EikAppUi()->Application()->AppDllUid().iUid );
TTypeUid::Ptr uidPtr = listbox->MopSupplyObject( typeId );
AssertTrueL( ETrue, KSetTest4 );
listbox->EnableExtendedDrawingL();
listbox->Draw( iContainer->Rect() );
AssertTrueL( ETrue, KSetTest5 );
CDesCArray* textArray = iEikEnv->ReadDesCArrayResourceL(
R_BCTESTLIST_ITEM_SINGLE_NUMBER );
if ( textArray )
{
listbox->Model()->SetItemTextArray( textArray );
listbox->Model()->SetOwnershipType( ELbmOwnsItemArray );
}
listbox->Draw( iContainer->Rect() );
AssertTrueL( ETrue, KSetTest6 );
}
break;
case EBCTestCmdOutline38:
{
CAknFormGraphicStyleListBox* listbox =
static_cast<CAknFormGraphicStyleListBox*>( iListBox );
listbox->SizeChanged();
AssertTrueL( ETrue, KFormGraphicTest1 );
size = listbox->MinimumSize();
AssertTrueL( ETrue, KFormGraphicTest2 );
TRect rect = iContainer->Rect();
TInt height = listbox->AdjustRectHeightToWholeNumberOfItems( rect );
AssertTrueL( ETrue, KFormGraphicTest3 );
listbox->HandlePointerEventL( event );
AssertTrueL( ETrue, KFormGraphicTest4 );
}
break;
case EBCTestCmdOutline39:
{
CAknFormGraphicWideStyleListBox* listbox =
static_cast<CAknFormGraphicWideStyleListBox*>( iListBox );
listbox->SizeChanged();
AssertTrueL( ETrue, KFormGraphicWideTest1 );
size = listbox->MinimumSize();
AssertTrueL( ETrue, KFormGraphicWideTest2 );
listbox->HandlePointerEventL( event );
AssertTrueL( ETrue, KFormGraphicWideTest3 );
}
break;
default:
break;
}
}
// ---------------------------------------------------------------------------
// CBCTestListPopupCase::GraphicIconL
// ---------------------------------------------------------------------------
//
void CBCTestListPopupCase::GraphicIconL( CArrayPtr<CGulIcon>* aIcons )
{
if ( aIcons )
{
// Appends icon according to iOutlineId.
switch ( iOutlineId )
{
case EBCTestCmdOutline37:
case EBCTestCmdOutline38:
case EBCTestCmdOutline39:
for ( TInt i = 0; i< 10; i++ )
{
CreateIconAndAddToArrayL(
aIcons, KBCTestListMbmFileName,
EMbmBctestlistGolgo2,
EMbmBctestlistGolgo2_mask );
}
break;
default:
break;
}
}
}
// ======== MEMBER FUNCTIONS ========
// ---------------------------------------------------------------------------
// CBCTestSinglePopupMenuStyleListBox::TestCreateItemDrawerL
// ---------------------------------------------------------------------------
//
void CBCTestSinglePopupMenuStyleListBox::
TestHandlePointerEventL(const TPointerEvent& aPointerEvent)
{
HandlePointerEventL( aPointerEvent );
}
// ======== MEMBER FUNCTIONS ========
// ---------------------------------------------------------------------------
// CBCTestSingleGraphicPopupMenuStyleListBox::TestCreateItemDrawerL
// ---------------------------------------------------------------------------
//
void CBCTestSingleGraphicPopupMenuStyleListBox::
TestHandlePointerEventL(const TPointerEvent& aPointerEvent)
{
HandlePointerEventL( aPointerEvent );
}
// ======== MEMBER FUNCTIONS ========
// ---------------------------------------------------------------------------
// CBCTestSingle2GraphicPopupMenuStyleListBox::TestHandlePointerEventL
// ---------------------------------------------------------------------------
//
void CBCTestSingle2GraphicPopupMenuStyleListBox::
TestHandlePointerEventL( const TPointerEvent& aPointerEvent )
{
HandlePointerEventL( aPointerEvent );
}
// ======== MEMBER FUNCTIONS ========
// ---------------------------------------------------------------------------
// CBCTestDoubleGraphicPopupMenuStyleListBox::TestHandlePointerEventL
// ---------------------------------------------------------------------------
//
void CBCTestDoubleGraphicPopupMenuStyleListBox::
TestHandlePointerEventL( const TPointerEvent& aPointerEvent )
{
HandlePointerEventL( aPointerEvent );
}
| [
"none@none"
]
| [
[
[
1,
608
]
]
]
|
2204145afe23fa0616fea99709ccb8e23a1c3704 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/mpl/test/remove.cpp | 9ea4985d71310e66478ffd8a6f5b1621223761c6 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | willrebuild/flyffsf | e5911fb412221e00a20a6867fd00c55afca593c7 | d38cc11790480d617b38bb5fc50729d676aef80d | refs/heads/master | 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 809 | cpp |
// Copyright Aleksey Gurtovoy 2000-2004
// Copyright David Abrahams 2003-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Source: /cvsroot/boost/boost/libs/mpl/test/remove.cpp,v $
// $Date: 2004/09/02 15:41:35 $
// $Revision: 1.2 $
#include <boost/mpl/remove.hpp>
#include <boost/mpl/vector/vector10.hpp>
#include <boost/mpl/equal.hpp>
#include <boost/mpl/aux_/test.hpp>
MPL_TEST_CASE()
{
typedef vector6<int,float,char,float,float,double> types;
typedef mpl::remove< types,float >::type result;
typedef vector3<int,char,double> answer;
MPL_ASSERT(( equal< result,answer > ));
}
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
]
| [
[
[
1,
28
]
]
]
|
b8d30efbfe0e0d4367bcc0609cc83601250b9037 | 826479e30cfe9f7b9a1b7262211423d8208ffb68 | /RayTracer/CSphere.h | 1d6e1088414dd26d31fe1738befe109b50159ca7 | []
| no_license | whztt07/real-time-raytracer | 5d1961c545e4703a3811fd7eabdff96017030abd | f54a75aed811b8ab6a509c70f879739896428fff | refs/heads/master | 2021-01-17T05:33:13.305151 | 2008-12-19T20:17:30 | 2008-12-19T20:17:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,827 | h | // Author : Jean-Rene Bedard ([email protected])
#pragma once
#include "CObjectRT.h"
#define PI 3.1415926535897932384626433833f
#define TWOPI 6.283185307179586476925286766559f
#define PID2 1.5707963267948966192313216916398f
class CSphere : public CObjectRT
{
public:
CSphere();
CVector centre;
CVector direction;
float radius;
virtual void frameCalc(CCamera *c);
virtual float inline IntersectGeneral(CRay *r);
virtual float inline intersectFixed(CRay *r);
virtual inline bool intersects(CRay *r);
virtual inline bool intersects(CPlaneIntersection *p);
virtual CVector inline Normal(CVector *poi);
virtual void RenderGL( char unique );
private:
float rSquared, invRadius, cTerm;
CVector origin;
};
float inline CSphere::IntersectGeneral(CRay *r)
{
float b = r->d.x * (r->o.x - centre.x) + r->d.y * (r->o.y - centre.y) + r->d.z * (r->o.z - centre.z);
float c = (r->o.x - centre.x) * (r->o.x - centre.x) + (r->o.y - centre.y) * (r->o.y - centre.y) + (r->o.z - centre.z) * (r->o.z - centre.z) - rSquared;
float d = b * b - c;
if (d < 0.0f) return -1.0f;
return -b - sqrtf(d);
}
float inline CSphere::intersectFixed(CRay *r)
{
float b = r->d.x * origin.x + r->d.y * origin.y + r->d.z * origin.z;
float d = b * b - cTerm;
if (d < 0.0f) return -1.0f;
return -b - sqrtf(d);
}
bool inline CSphere::intersects(CRay *r)
{
float b = r->d * (r->o - centre);
float c = (r->o - centre) * (r->o - centre) - rSquared;
float d = b * b - c;
if (d < 0.0f) return false;
return true;
}
bool inline CSphere::intersects(CPlaneIntersection *p)
{
if (fabsf(p->n * centre - p->d) > radius) return false;
return true;
}
CVector inline CSphere::Normal(CVector *poi)
{
return (*poi - centre) * invRadius;
}
| [
"[email protected]"
]
| [
[
[
1,
80
]
]
]
|
9fdbdda602e34b329bff6a0f16cbefd370673f31 | 81215fde203e75b157f2a3e3507d99897c6d2020 | /src/scoreview.h | 0b9a3d48aae70b088773b5d0758cfbfd61091d58 | []
| no_license | fuyasing/RankView | fb8e039843088a54da2ad10979726234ea467712 | b4d99cdfa03699ec41f8581db9262a367306b5a4 | refs/heads/master | 2020-05-17T10:58:47.709718 | 2011-06-25T14:05:05 | 2011-06-25T14:05:05 | 1,738,411 | 0 | 1 | null | 2012-08-04T14:49:30 | 2011-05-12T13:31:00 | C++ | UTF-8 | C++ | false | false | 1,158 | h | #ifndef SCOREVIEW_H
#define SCOREVIEW_H
#include <QWidget>
#include "global.h"
class QSqlTableModel;
class QSqlRelationalTableModel;
class QTableView;
class QHBoxLayout;
class ScoreView : public QWidget
{
Q_OBJECT
public:
explicit ScoreView(QSqlTableModel* student_list, QSqlTableModel* exam_list, QSqlRelationalTableModel* score_list, QWidget *parent = 0);
~ScoreView();
QSqlTableModel* studentListModel() const;
void setStudentListModel(QSqlTableModel* student_list);
QSqlTableModel* examListModel() const;
void setExamListModel(QSqlTableModel* exam_list);
QSqlRelationalTableModel* scoreListModel() const;
void setScoreListModel(QSqlRelationalTableModel* score_list);
void setCurrentStudent(int row = 0);
private slots:
void updateScoreListView();
private:
void createStudentListView(QSqlTableModel* student_list);
void createExamListView(QSqlTableModel* exam_list);
void createScoreListView(QSqlRelationalTableModel* score_list);
QHBoxLayout* m_mainLayout;
QTableView* m_studentListView;
QTableView* m_examListView;
QTableView* m_scoreListView;
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
47
]
]
]
|
cba0e08be4065575014d91654618e985f93fa91c | af9524b76162da55a8d44fb50ffbb8f1dc8fa98c | /examples/cloud-setup2/sources/common/Matrix2Dlc.cc | c808e3e586fef1a8d181068508ba1a80b6a89649 | [
"GPL-1.0-or-later",
"MIT"
]
| permissive | GaretJax/pop-utils | e72c5b387541d05cd35d599294184d1ca6673330 | 2cdfaf24c2f8678edfab1f430c07611d488247d5 | refs/heads/master | 2022-07-22T17:48:15.798181 | 2011-05-19T21:46:19 | 2011-05-19T21:46:19 | 1,735,213 | 0 | 0 | MIT | 2022-07-06T19:17:17 | 2011-05-11T20:34:07 | C++ | UTF-8 | C++ | false | false | 2,895 | cc | #include <stdlib.h>
#include <stdio.h>
#include "Matrix2Dlc.h"
Matrix2Dlc::Matrix2Dlc()
{
}
Matrix2Dlc::Matrix2Dlc(int line, int col): Matrix2D(line,col)
{
}
inline ValueType Matrix2Dlc::get(int line, int col)
{
return value[line*nbCol+col];
}
inline void Matrix2Dlc::set(int line, int col, ValueType v)
{
value[line*nbCol+col]=v;
}
Matrix2Dlc Matrix2Dlc::getLinesBloc(int noLine, int nbLines)
{
if ( (value!=NULL) || (nbLine>=(noLine+nbLines)) )
{
Matrix2Dlc tmp;
tmp.nbCol = nbCol;
tmp.nbLine = nbLines;
tmp.dataSize = dataSize;
tmp.value = &(value[noLine*nbCol]);
if(shared==NULL) tmp.shared = value; else tmp.shared=shared;
if (tmp.shared!=NULL) (tmp.shared[dataSize])= (tmp.shared[dataSize])+(ValueType)1;
//tmp.showState("Getting lines DONE:", true);
return tmp;
}
else
{
Matrix2Dlc tmp;
showState("ERROR Getting lines:", false);
return tmp;
}
}
void Matrix2Dlc::setBloc(int noLine, int noCol, Matrix2Dlc v)
{
if ((nbCol>=noCol+v.nbCol) && (nbLine>=(noLine+v.nbLine)) )
{
if (value==NULL)
{
dataSize = nbLine*nbCol;
value = (ValueType*)malloc((dataSize+1)*ValueTypeSize);
if (value==NULL) {printf("\nMEMORY OVERFLOW !!!!\n"); exit(0);}
value[dataSize]=0;
shared = NULL;
}
for (int i=0; i<v.nbLine; i++)
memcpy(&(value[(noLine+i)*nbCol+noCol]),&(v.value[i*v.nbCol]), v.nbCol*sizeof(ValueType));
// memcpy replaces the following for loop
//for (int j=0; j<v.nbCol; j++)
// value[(noLine+i)*nbCol+noCol+j]=v.value[i*v.nbCol+j];
}
else printf("Matrix ERROR: Non coherent bloc setting !!!\n");
}
void Matrix2Dlc::setLinesBloc(int noLine, Matrix2Dlc v)
{
if ((nbCol==v.nbCol) && (nbLine>=(noLine+v.nbLine)) )
{
if (value==NULL)
{
dataSize = nbLine*nbCol;
value = (ValueType*)malloc((dataSize+1)*ValueTypeSize);
if (value==NULL) {printf("\nMEMORY OVERFLOW !!!!\n"); exit(0);}
value[dataSize]=0;
shared = NULL;
}
memcpy(&(value[noLine*nbCol]), v.value, v.nbCol*v.nbLine*sizeof(ValueType));
// memcpy replaces the following for loop
//for (int i=0; i<v.nbCol*v.nbLine; i++)
// value[noLine*nbCol+i]=v.value[i];
}
else printf("Matrix ERROR: Non coherent line setting !!!\n");
}
void Matrix2Dlc::display()
{
if (value!=NULL)
for (int i=0; i<nbLine; i++)
{
for (int j=0; j<nbCol; j++)
printf("%8.1lf ",(double)value[i*nbCol+j]);
printf("\n");
}
printf("....................\n");
}
void Matrix2Dlc::display(int n)
{
if (n>nbLine) n=nbLine; if (n>nbCol) n=nbCol;
for (int i=0; i<n; i++)
{
for (int j=0; j<n; j++)
printf("%6.1f ",(float)value[i*nbCol+j]);
printf("..\n");
}
printf("....................\n");
}
| [
"[email protected]"
]
| [
[
[
1,
109
]
]
]
|
4c466564c5a833ba54f9eb5ea3bd79455031265b | 9c62af23e0a1faea5aaa8dd328ba1d82688823a5 | /rl/tags/techdemo2/engine/uicomponents/src/ListboxWrappedTextItem.cpp | b235bb8bca3b03a7f179ee883790c9c24e727134 | [
"ClArtistic",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | jacmoe/dsa-hl-svn | 55b05b6f28b0b8b216eac7b0f9eedf650d116f85 | 97798e1f54df9d5785fb206c7165cd011c611560 | refs/heads/master | 2021-04-22T12:07:43.389214 | 2009-11-27T22:01:03 | 2009-11-27T22:01:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,557 | cpp | /************************************************************************
filename: ListboxWrappedTextItem.cpp
created: 01/8/2006
author: Paul D Turner, Philipp Walser
purpose: Implementation of List box text items with WordWrapping
*************************************************************************/
/*************************************************************************
Crazy Eddie's GUI System (http://www.cegui.org.uk)
Copyright (C)2004 - 2005 Paul D Turner ([email protected])
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*************************************************************************/
#include "ListboxWrappedTextItem.h"
#include "CEGUIFontManager.h"
#include "CEGUIFont.h"
#include "CEGUIWindow.h"
#include "CEGUIImage.h"
// Start of CEGUI namespace section
namespace CEGUI
{
/*************************************************************************
Constants
*************************************************************************/
const colour ListboxWrappedTextItem::DefaultTextColour = 0xFFFFFFFF;
const String ListboxWrappedTextItem::ds_bullet = " - ";
/*************************************************************************
Constructor
*************************************************************************/
ListboxWrappedTextItem::ListboxWrappedTextItem(const String& text, int padding,
bool draw_bullet, uint item_id,
void* item_data, bool disabled, bool auto_delete) :
ListboxItem(text, item_id, item_data, disabled, auto_delete),
d_textCols(DefaultTextColour, DefaultTextColour, DefaultTextColour, DefaultTextColour),
d_padding(padding), d_draw_bullet(draw_bullet),
d_font(0), d_textFormatting(WordWrapLeftAligned)
{
}
/*************************************************************************
Destructor
*************************************************************************/
ListboxWrappedTextItem::~ListboxWrappedTextItem()
{
}
/*************************************************************************
Return a pointer to the font being used by this ListboxWrappedTextItem
*************************************************************************/
const Font* ListboxWrappedTextItem::getFont(void) const
{
// prefer out own font
if (d_font)
{
return d_font;
}
// try our owner window's font setting (may be null if owner uses no existant default font)
else if (d_owner)
{
return d_owner->getFont();
}
// no owner, just use the default (which may be NULL anyway)
else
{
return System::getSingleton().getDefaultFont();
}
}
/*************************************************************************
Set the font to be used by this ListboxWrappedTextItem
*************************************************************************/
void ListboxWrappedTextItem::setFont(const String& font_name)
{
setFont(FontManager::getSingleton().getFont(font_name));
}
/*************************************************************************
Return the rendered pixel size of this list box item.
*************************************************************************/
Size ListboxWrappedTextItem::getPixelSize(void) const
{
Size size(0,0);
if (d_owner != NULL)
{
size.d_width = d_owner->getAbsoluteSize().d_width - 25;
}
const Font* font = getFont();
if (font != NULL)
{
size.d_height = PixelAligned(font->getLineSpacing());
if(size.d_width == 0)
{
size.d_width = PixelAligned(font->getTextExtent(d_itemText));
}
Rect formatRect;
formatRect.setPosition(CEGUI::Point(0,0));
if (d_draw_bullet)
{
formatRect.d_left = font->getTextExtent(ds_bullet);
}
formatRect.setSize(size);
uint lines = font->getFormattedLineCount(d_itemText, formatRect, d_textFormatting);
size.d_height *= lines;
size.d_height += d_padding;
}
return size;
}
/*************************************************************************
Draw the list box item in its current state.
*************************************************************************/
void ListboxWrappedTextItem::draw(const Vector3& position, float alpha, const Rect& clipper) const
{
if (d_selected && (d_selectBrush != 0))
{
d_selectBrush->draw(clipper, position.d_z, clipper,
getModulateAlphaColourRect(d_selectCols, alpha));
}
const Font* font = getFont();
if (font)
{
float left_offset = 0;
if (d_draw_bullet)
{
left_offset = font->getTextExtent(ds_bullet);
}
Vector3 finalPos = position;
finalPos.d_y -= PixelAligned((font->getLineSpacing() - font->getBaseline()) * 0.5f);
Rect draw_area = Rect(finalPos.d_x, finalPos.d_y,
clipper.d_right, finalPos.d_y);
font->drawText(ds_bullet, draw_area, finalPos.d_z, clipper, d_textFormatting,
getModulateAlphaColourRect(d_textCols, alpha));
draw_area.d_left += left_offset;
font->drawText(d_itemText, draw_area, finalPos.d_z, clipper, d_textFormatting,
getModulateAlphaColourRect(d_textCols, alpha));
}
}
void ListboxWrappedTextItem::draw(RenderCache& cache,const Rect& targetRect,
float zBase, float alpha, const Rect* clipper) const
{
if (d_selected && d_selectBrush != 0)
{
cache.cacheImage(*d_selectBrush, targetRect, zBase,
getModulateAlphaColourRect(d_selectCols, alpha), clipper);
}
const Font* font = getFont();
if (font)
{
float left_offset = 0;
if (d_draw_bullet)
{
left_offset = font->getTextExtent(ds_bullet);
}
Rect finalPos = targetRect;
finalPos.d_top -= (font->getLineSpacing() - font->getBaseline()) * 0.5f;
cache.cacheText(ds_bullet, font, d_textFormatting, finalPos, zBase,
getModulateAlphaColourRect(d_textCols, alpha), clipper);
finalPos.d_left += left_offset;
cache.cacheText(d_itemText, font, d_textFormatting, finalPos, zBase,
getModulateAlphaColourRect(d_textCols, alpha), clipper);
}
}
/*************************************************************************
Set the colours used for text rendering.
*************************************************************************/
void ListboxWrappedTextItem::setTextColours(colour top_left_colour,
colour top_right_colour,
colour bottom_left_colour,
colour bottom_right_colour)
{
d_textCols.d_top_left = top_left_colour;
d_textCols.d_top_right = top_right_colour;
d_textCols.d_bottom_left = bottom_left_colour;
d_textCols.d_bottom_right = bottom_right_colour;
}
void ListboxWrappedTextItem::setTextFormatting(TextFormatting fmt)
{
d_textFormatting = fmt;
}
const TextFormatting& ListboxWrappedTextItem::getTextFormatting() const
{
return d_textFormatting;
}
} // End of CEGUI namespace section
| [
"tanis@4c79e8ff-cfd4-0310-af45-a38c79f83013"
]
| [
[
[
1,
223
]
]
]
|
cb241c675a135c0251fa9e7d923add0395f485a2 | 2e6bb5ab6f8ad09f30785c386ce5ac66258df252 | /project/HappyHunter/Core/StaticMesh.h | a20f5ff4fb1d711a2e1ea5299cb6c1031b00a227 | []
| no_license | linfuqing/happyhunter | 961061f84947a91256980708357b583c6ad2c492 | df38d8a0872b3fd2ea0e1545de3ed98434c12c5e | refs/heads/master | 2016-09-06T04:00:30.779303 | 2010-08-26T15:41:09 | 2010-08-26T15:41:09 | 34,051,578 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,904 | h | #pragma once
#include "debug.h"
#include "BasicString.h"
#include "Sprite.h"
#include "RenderMethod.h"
#include "Mesh.h"
#include "ShadowVolume.h"
namespace zerO
{
class CStaticMesh : public CSprite
{
public:
CStaticMesh(void);
~CStaticMesh(void);
public:
CMesh& GetMesh();
void SetShadowVisible(bool bValue);
bool Create(const PBASICCHAR meshFile);
bool Destroy();
void Clone(CStaticMesh& StaticMesh)const;
virtual bool ApplyForRender();
virtual void Update();
virtual void Render(CRenderQueue::LPRENDERENTRY pEntry, UINT32 uFlag);
void SetEffectFile(const BASICSTRING& file);
const BASICSTRING& GetEffectFile() const;
const CRenderMethod& GetRenderMethod() const;
private:
CRenderMethod m_RenderMethod; // 渲染方法
BASICSTRING m_strEffectFile; // 效果文件
CMesh* m_pMesh;
CShadowVolume* m_pShadow;
bool m_bIsCreated;
bool m_bIsVisibleShadow;
bool m_bIsCulled;
};
//---------------------------------------------------------------------------
// 设置函数
//---------------------------------------------------------------------------
inline void CStaticMesh::SetEffectFile(const BASICSTRING& file)
{
m_strEffectFile = file;
}
inline const BASICSTRING& CStaticMesh::GetEffectFile() const
{
return m_strEffectFile;
}
//---------------------------------------------------------------------------
// 获取函数
//---------------------------------------------------------------------------
inline CMesh& CStaticMesh::GetMesh()
{
return *m_pMesh;
}
inline const CRenderMethod& CStaticMesh::GetRenderMethod() const
{
return m_RenderMethod;
}
inline void CStaticMesh::SetShadowVisible(bool bValue)
{
m_bIsVisibleShadow = bValue;
}
}
| [
"linfuqing0@c6a4b443-94a6-74e8-d042-0855a5ab0aac"
]
| [
[
[
1,
80
]
]
]
|
76a7da0ac2e911e585bb0a32d0ef0d0f191a38d2 | b2d46af9c6152323ce240374afc998c1574db71f | /cursovideojuegos/flostiproyect/quakegame/QuakeGameProcess.h | 33db96adea449567b7b70d6adf2aa092d7ac7d72 | []
| no_license | bugbit/cipsaoscar | 601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4 | 52aa8b4b67d48f59e46cb43527480f8b3552e96d | refs/heads/master | 2021-01-10T21:31:18.653163 | 2011-09-28T16:39:12 | 2011-09-28T16:39:12 | 33,032,640 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,897 | h | //----------------------------------------------------------------------------------
// CQuakeGameProcess class
// Author: Enric Vergara
//
// Description:
// Test para probar el funcionamiento del reproductor de videos AVI.
//----------------------------------------------------------------------------------
#pragma once
#ifndef INC_QUAKE_GAME_PROCESS_H_
#define INC_QUAKE_GAME_PROCESS_H_
//---Engine Includes----
#include "Core/Core.h"
#include "Core/Process.h"
#include "Math/Matrix44.h"
#include "Graphics/ASEObject/ASEObject.h"
#include "PhysX/PhysicTriggerReport.h"
//---Game Includes-------
#include "Arena.h"
//-----------------------
//--Forward Declaration--
class CRenderManager;
class CObject3D;
class CThPSCamera;
class CInputManager;
class CAviPlayer;
class CTexture;
class CPhysicActor;
class CPhysicController;
class CQuakePhysicsData;
class CPhysicSphericalJoint;
class CQuakePlayerInput;
//-----------------------
//struct SPRUEBAITEM
//{
// Vect3f Position;
// Mat44f Mat;
// float Angle;
//};
struct SPRUEBASHUT
{
std::string msg;
Vect3f pos;
};
class CQuakeGameProcess: public CProcess, public CPhysicTriggerReport
{
public:
//---Init and End protocols
CQuakeGameProcess(const std::string& processName): CProcess(processName),
m_IsCameraView(false),
m_pCameraView(NULL),
m_CameraViewObj3D(NULL),
m_PelotaData(NULL),
m_EnemyData(NULL),
m_SpeedPlayer(15.f),
m_Pelota(NULL),
m_Enemy(NULL),
m_Trigger(NULL),
m_TriggerData(NULL),
m_ActorPruebaShut(NULL),
m_ActorPruebaShutData(NULL),
m_ActorPruebaJoint(NULL),
m_ActorPruebaJointData(NULL),
m_PruebaJoint(NULL),
mPCX(0),
mPCDiff(1)
{
}
virtual ~CQuakeGameProcess(void) {Done();}
//----CScriptRegister Interface---------------------------------------
virtual void RegisterFunctions (CScriptManager* scriptManager);
//----CProcess Interface---------------------------------------
virtual bool Init ();
virtual bool Start () {m_bStart = true; return true;}
//---Update and Render function
virtual void Update (float elapsedTime);
virtual void RenderScene (CRenderManager* renderManager);
virtual uint32 RenderDebugInfo (CRenderManager* renderManager, float fps);
//--------------------------------------------------------------
virtual CCamera* GetCamera () const;
//----CPhysicTriggerReport Interface------------------------------------------------------
virtual void OnEnter (CPhysicUserData* trigger1, CPhysicUserData* other_shape);
virtual void OnLeave (CPhysicUserData* trigger1, CPhysicUserData* other_shape);
private:
//----CProcess Interface---------------------------------------
virtual void Release ();
//--------------------------------------------------------------
//void UpdatePruebaItems (float elapsedTime);
private:
bool m_IsCameraView;
CThPSCamera * m_pCameraView;
CObject3D * m_CameraViewObj3D;
CArena m_Arena;
CASEObject m_PruebaItemASE;
//std::vector <SPRUEBAITEM *> m_PruebaItems;
std::vector <SPRUEBASHUT *> m_PruebaShut;
float m_SpeedPlayer;
std::vector<CQuakePlayerInput *> m_PlayerInputs;
void RenderQuake (CRenderManager* renderManager);
// Prueba PhysX
CQuakePhysicsData *m_PelotaData;
CQuakePhysicsData *m_EnemyData;
CPhysicActor *m_Pelota;
CPhysicController *m_Enemy;
CPhysicActor *m_Trigger;
CQuakePhysicsData *m_TriggerData;
CPhysicActor *m_ActorPruebaShut;
CQuakePhysicsData *m_ActorPruebaShutData;
CPhysicActor *m_ActorPruebaJoint;
CQuakePhysicsData *m_ActorPruebaJointData;
CPhysicSphericalJoint *m_PruebaJoint;
int mPCX;
int mPCDiff;
std::string mStrTrigger;
void ReleasePlayerInputs();
void UpdatePlayerInputs(float elapsedTime);
void UpdateCameraView (float elapsedTime);
};
static CQuakeGameProcess* GetQuakeGame() {return static_cast<CQuakeGameProcess*>(CCore::GetSingletonPtr()->GetProcess());}
#endif //INC_AVI_TEST_PROCESS_H_ | [
"ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a"
]
| [
[
[
1,
139
]
]
]
|
d971a1dabfb0396361e0747af312867ab1624773 | 1c80a726376d6134744d82eec3129456b0ab0cbf | /Project/C++/POJ/1808/1808.cpp | 3eb7147d68f01973573cb381cf0076dfcd725747 | []
| no_license | dabaopku/project_pku | 338a8971586b6c4cdc52bf82cdd301d398ad909f | b97f3f15cdc3f85a9407e6bf35587116b5129334 | refs/heads/master | 2021-01-19T11:35:53.500533 | 2010-09-01T03:42:40 | 2010-09-01T03:42:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,116 | cpp | #include "stdio.h"
#include "iostream"
#include "string.h"
#include "math.h"
#include "string"
#include "vector"
#include "set"
#include "map"
#include "queue"
#include "list"
using namespace std;
bool isprime(int n)
{
if(n==1) return false;
if(n==2 || n==3) return true;
int i;
if(n%2==0) return false;
int t=sqrt(1.0*n);
while(t*t<n) t++;
for(i=3;i<=t;i+=2){
if(n%i==0) return false;
}
return true;
}
int solve(int a,int p)
{
if(a>p) return solve(a%p,p);
if(a==1) return 1;
if(a==-1){
int t=(p-1)/2;
if(t%2) return -1;
else return 1;
}
if(a==2){
int t=(p*p-1)/8;
if(t%2) return -1;
else return 1;
}
if(a<0) return solve(-1,p)*solve(-a,p);
if(a*2>p) return solve(a-p,p);
if(isprime(a)){
int t=(a-1)*(p-1)/4;
int s=solve(p,a);
if(t%2) return -s;
else return s;
}
int i;
for(i=2;i<a;i++){
if(a%i==0){
return solve(i,p)*solve(a/i,p);
}
}
}
int main()
{
int cs;
int ii;
cin>>cs;
int a,b;
for(ii=1;ii<=cs;ii++){
cin>>a>>b;
cout<<"Scenario #"<<ii<<":\n";
cout<<solve(a,b)<<endl<<endl;
}
} | [
"[email protected]@592586dc-1302-11df-8689-7786f20063ad"
]
| [
[
[
1,
68
]
]
]
|
ec52d8e1f55d1831db826ed2d28ff8e665c585dc | b0252ba622183d115d160eb28953189930ebf9c0 | /Source/CLoadGameState.cpp | 27631d178654394b4da13ab16607a060b2d771b9 | []
| no_license | slewicki/khanquest | 6c0ced33bffd3c9ee8a60c1ef936139a594fe2fc | f2d68072a1d207f683c099372454add951da903a | refs/heads/master | 2020-04-06T03:40:18.180208 | 2008-08-28T03:43:26 | 2008-08-28T03:43:26 | 34,305,386 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,701 | cpp | //////////////////////////////////////////////////////////
// File: "CLoadGameState.cpp"
//
// Author: Sean Hamstra (SH)
//
// Purpose: To contain functionality of the unit creation state
//////////////////////////////////////////////////////////
#include "CLoadGameState.h"
#include "CWorldMapState.h"
#include "UpgradeMenuState.h"
#include "MainMenuState.h"
#include "CGame.h"
#include "CFactory.h"
CLoadGameState::CLoadGameState(void)
{
PROFILE("CLoadGameState::CLoadGameState()");
m_nButtonID = -1;
m_nChosenSlot = 0;
m_nBackgroundID = -1;
m_bIsNewGame = false;
}
CLoadGameState::~CLoadGameState(void)
{
}
void CLoadGameState::Enter(void)
{
PROFILE("CLoadGameState::Enter()");
m_pCG = CGame::GetInstance();
m_pTM = CSGD_TextureManager::GetInstance();
m_pWM = CSGD_WaveManager::GetInstance();
m_pDI = CSGD_DirectInput::GetInstance();
m_pPE = CParticleEngine::GetInstance();
m_nLucidiaWhiteID = m_pTM->LoadTexture("Resource/KQ_FontLucidiaWhite.png");
m_nBackgroundID = m_pTM->LoadTexture("Resource/KQ_PageBkg3.png");
m_nButtonID = m_pTM->LoadTexture("Resource/KQ_Slot.png");
m_nScrollButtonID = m_pTM->LoadTexture("Resource/KQ_ScrollButton.png");
// torch
m_nTorchPicID = m_pTM->LoadTexture("Resource/KQ_Torch1.png");
m_nTorchID = m_pPE->LoadBineryEmitter("Resource/Emitters/KQ_Torch2.dat", 100, 300);
m_nSmokeID1 = m_pPE->LoadBineryEmitter("Resource/Emitters/KQ_Smoke.dat", 100, 300);
m_nTorchID2 = m_pPE->LoadBineryEmitter("Resource/Emitters/KQ_Torch2.dat", 670, 300);
m_nSmokeID2 = m_pPE->LoadBineryEmitter("Resource/Emitters/KQ_Smoke.dat", 670, 300);
// fire sound
m_nTorchSound = m_pWM->LoadWave("Resource/KQ_FireBurn.wav");
m_nClickID = m_pWM->LoadWave("Resource/KQ_Click.wav");
m_nTickID = m_pWM->LoadWave("Resource/KQ_ButtonTick.wav");
m_pWM->SetVolume(m_nClickID, m_pCG->GetSFXVolume());
m_cFont.InitBitmapFont(m_nLucidiaWhiteID, ' ', 16, 128, 128);
for (int i = 0; i < 3; i++)
{
m_rClickRect[i].left = 291;
m_rClickRect[i].top = 80 + (i*150);
m_rClickRect[i].right = m_rClickRect[i].left + 219;
m_rClickRect[i].bottom = m_rClickRect[i].top + 30;
}
m_rAccept.left = 415;
m_rAccept.top = 515;
m_rAccept.right = 545;
m_rAccept.bottom = 575;
m_rBack.left = 615;
m_rBack.top = 515;
m_rBack.right = 745;
m_rBack.bottom = 575;
m_fJoyTimer += 0;
m_pCG->SetSongPlay(CITYSELECT);
//m_pPE->SetPostion(100, 100, m_nTorchID);
m_pPE->SetIsRunning(m_nTorchID, true);
m_pPE->SetIsRunning(m_nSmokeID1, true);
m_pPE->SetIsRunning(m_nSmokeID2, true);
m_pPE->SetIsRunning(m_nTorchID2, true);
if(m_pCG->GetTutorialMode())
{
m_bTutorial = true;
m_rTutorial.top = 400;
m_rTutorial.left = 350;
m_rTutorial.bottom = m_rTutorial.top + 64;
m_rTutorial.right = m_rTutorial.left + 128;
}
else
m_bTutorial = false;
// torch sound
m_nTorchSound = m_pWM->LoadWave("Resource/KQ_FireBurn2.wav");
m_pWM->Play(m_nTorchSound, DSBPLAY_LOOPING );
m_pWM->SetVolume(m_nTorchSound, m_pCG->GetSFXVolume());
}
void CLoadGameState::Exit(void)
{
PROFILE("CLoadGameState::Exit()");
if(m_pWM->IsWavePlaying(m_nClickID))
m_pWM->Stop(m_nClickID);
if(m_pWM->IsWavePlaying(m_nTickID))
m_pWM->Stop(m_nTickID);
// torch sound
if(m_pWM->IsWavePlaying(m_nTorchSound))
m_pWM->Stop(m_nTorchSound);
m_pWM->UnloadWave(m_nTorchSound);
m_pWM->UnloadWave(m_nClickID);
m_pWM->UnloadWave(m_nTickID);
m_pTM->ReleaseTexture(m_nButtonID);
m_pTM->ReleaseTexture(m_nLucidiaWhiteID);
m_pTM->ReleaseTexture(m_nBackgroundID);
m_pTM->ReleaseTexture(m_nTorchPicID);
m_pPE->SetIsRunning(m_nTorchID, false);
m_pPE->SetIsRunning(m_nSmokeID1, false);
m_pPE->SetIsRunning(m_nTorchID2, false);
m_pPE->SetIsRunning(m_nSmokeID2, false);
m_pPE->UnLoadEmitter(m_nTorchID);
m_pPE->UnLoadEmitter(m_nTorchID2);
}
bool CLoadGameState::Input(float fElapsedTime)
{
PROFILE("CLoadGameState::Input(float)");
if(!m_bTutorial)
{
m_fJoyTimer = fElapsedTime;
#pragma region Controller to Mouse
if(m_pDI->GetJoystickDir(JOYSTICK_UP) && m_pDI->GetJoystickDir(JOYSTICK_LEFT))
{
if(m_fJoyTimer > .002f)
{
GetCursorPos(&m_ptMousePos);
SetCursorPos(m_ptMousePos.x-3,m_ptMousePos.y-3);
m_fJoyTimer = 0;
}
}
else if(m_pDI->GetJoystickDir(JOYSTICK_UP) && m_pDI->GetJoystickDir(JOYSTICK_RIGHT))
{
if(m_fJoyTimer > .002f)
{
GetCursorPos(&m_ptMousePos);
SetCursorPos(m_ptMousePos.x+3,m_ptMousePos.y-3);
m_fJoyTimer = 0;
}
}
else if(m_pDI->GetJoystickDir(JOYSTICK_DOWN) && m_pDI->GetJoystickDir(JOYSTICK_LEFT))
{
if(m_fJoyTimer > .002f)
{
GetCursorPos(&m_ptMousePos);
SetCursorPos(m_ptMousePos.x-3,m_ptMousePos.y+3);
m_fJoyTimer = 0;
}
}
else if(m_pDI->GetJoystickDir(JOYSTICK_DOWN) && m_pDI->GetJoystickDir(JOYSTICK_RIGHT))
{
if(m_fJoyTimer > .002f)
{
GetCursorPos(&m_ptMousePos);
SetCursorPos(m_ptMousePos.x+3,m_ptMousePos.y+3);
m_fJoyTimer = 0;
}
}
else if(m_pDI->GetJoystickDir(JOYSTICK_UP))
{
if(m_fJoyTimer > .002f)
{
GetCursorPos(&m_ptMousePos);
SetCursorPos(m_ptMousePos.x,m_ptMousePos.y-3);
m_fJoyTimer = 0;
}
}
else if(m_pDI->GetJoystickDir(JOYSTICK_DOWN))
{
if(m_fJoyTimer > .002f)
{
GetCursorPos(&m_ptMousePos);
SetCursorPos(m_ptMousePos.x,m_ptMousePos.y+3);
m_fJoyTimer = 0;
}
}
else if(m_pDI->GetJoystickDir(JOYSTICK_LEFT))
{
if(m_fJoyTimer > .002f)
{
GetCursorPos(&m_ptMousePos);
SetCursorPos(m_ptMousePos.x-3,m_ptMousePos.y);
m_fJoyTimer = 0;
}
}
else if(m_pDI->GetJoystickDir(JOYSTICK_RIGHT))
{
if(m_fJoyTimer > .002f)
{
GetCursorPos(&m_ptMousePos);
SetCursorPos(m_ptMousePos.x+3,m_ptMousePos.y);
m_fJoyTimer = 0;
}
}
#pragma endregion
for (int i = 0; i < 3; i++)
{
if(m_pCG->GetSaveName(i, true) == "EMPTY")
m_bIsEmpty[i] = true;
else
m_bIsEmpty[i] = false;
if(m_nChosenSlot != i &&m_pCG->IsMouseInRect(m_rClickRect[i]))
{
// Change cursor to click icon
m_pCG->SetCursorClick();
if(m_pDI->GetBufferedMouseButton(M_BUTTON_LEFT) || m_pDI->GetBufferedJoyButton(JOYSTICK_X))
{
m_pWM->Play(m_nTickID);
m_nChosenSlot = i;
}
}
}
if(m_pCG->IsMouseInRect(m_rAccept))
{
if(!m_bIsNewGame && m_bIsEmpty[m_nChosenSlot])
return true;
m_pCG->SetCursorClick();
if(m_pDI->GetBufferedMouseButton(M_BUTTON_LEFT) || m_pDI->GetBufferedJoyButton(JOYSTICK_X))
{
m_pWM->Play(m_nClickID);
if(m_bIsNewGame)
{
if(m_bIsEmpty[m_nChosenSlot])
{
m_pCG->NewGame(m_nChosenSlot);
m_pCG->Save(false);
m_pCG->ChangeState(CWorldMapState::GetInstance());
}
else
{
m_pCG->NewGame(m_nChosenSlot);
m_pCG->Save(true);
m_pCG->PopCurrentState();
m_pCG->PushState(this);
}
}
else
if(m_pCG->LoadSlot(m_nChosenSlot))
m_pCG->ChangeState(CWorldMapState::GetInstance());
}
}
if(m_pCG->IsMouseInRect(m_rBack) )
{
m_pCG->SetCursorClick();
if(m_pDI->GetBufferedMouseButton(M_BUTTON_LEFT)|| m_pDI->GetBufferedJoyButton(JOYSTICK_X))
{
m_pWM->Play(m_nClickID);
// Go back to the map
CMainMenuState::GetInstance()->SetPause(false);
m_pCG->PopCurrentState();
}
}
}
else
{
if(m_pCG->IsMouseInRect(m_rTutorial))
{
m_pCG->SetCursorClick();
if(m_pDI->GetBufferedMouseButton(M_BUTTON_LEFT)|| m_pDI->GetBufferedJoyButton(JOYSTICK_X))
{
m_pWM->Play(m_nClickID);
m_bTutorial = false;
}
}
}
return true;
}
void CLoadGameState::Update(float fElapsedTime)
{
m_pPE->Update(fElapsedTime);
}
void CLoadGameState::Render(float fElapsedTime)
{
m_pTM->Draw(m_nBackgroundID, -20, -10, 1.f, 1.f, 0, 0.f, 0.f, 0.f, D3DCOLOR_ARGB(255, 0, 0, 0));
// draw torch and flame
m_pTM->Draw(m_nTorchPicID, 80, 300, 0.4f, 0.5f, 0);
m_pTM->Draw(m_nTorchPicID, 650, 300, 0.4f, 0.5f, 0);
m_pPE->Render(fElapsedTime);
if(!m_bTutorial)
{
for (int i = 0; i < 3; i++)
{
m_pTM->Draw(m_nButtonID, m_rClickRect[i].left, m_rClickRect[i].top, 1.f, 1.f);
if(i == m_nChosenSlot)
{
string szInfo =m_pCG->GetSaveName(i, false);
m_cFont.DrawTextA(m_pCG->GetSaveName(i, true), m_rClickRect[i].left+50, m_rClickRect[i].top, .25f, .25f, D3DCOLOR_ARGB(255, 255, 255, 0));
if(!m_bIsEmpty[i])
m_cFont.DrawTextA(szInfo, (int)(((800-(15*szInfo.length()))*.5f)), m_rClickRect[i].top+20, .25f, .25f, D3DCOLOR_ARGB(255, 255, 255, 0));
}
else
m_cFont.DrawTextA(m_pCG->GetSaveName(i, true), m_rClickRect[i].left+50, m_rClickRect[i].top, .25f, .25f, D3DCOLOR_ARGB(255, 0, 0, 0));
}
if(m_bIsNewGame)
{
m_cFont.DrawTextA("New Game", 320, 10, .3f, .3f, D3DCOLOR_ARGB(255, 255, 0, 0));
}
else
m_cFont.DrawTextA("Load Game", 310, 10, .3f, .3f, D3DCOLOR_ARGB(255, 255, 0, 0));
m_pTM->Draw(m_nScrollButtonID, m_rAccept.left, m_rAccept.top, .4f, .3f);
if(m_bIsNewGame)
{
if(m_bIsEmpty[m_nChosenSlot])
m_cFont.DrawTextA("Accept", m_rAccept.left+24, m_rAccept.top+24, .2f, .2f, D3DCOLOR_ARGB(255, 0, 155, 0));
else
m_cFont.DrawTextA("Erase", m_rAccept.left+30, m_rAccept.top+24, .2f, .2f, D3DCOLOR_ARGB(255, 255, 0, 0));
}
else
{
m_cFont.DrawTextA("Accept", m_rAccept.left+24, m_rAccept.top+24, .2f, .2f, D3DCOLOR_ARGB(255, 255, 0, 0));
if(m_bIsEmpty[m_nChosenSlot])
m_pTM->Draw(m_nScrollButtonID, m_rAccept.left, m_rAccept.top, .4f, .3f, 0, 0.f, 0.f, 0.f, D3DCOLOR_ARGB(150, 50, 50, 50));
}
m_pTM->Draw(m_nScrollButtonID, m_rBack.left, m_rBack.top, .4f, .3f);
m_cFont.DrawTextA("Back", m_rBack.left+40, m_rBack.top+24, .2f, .2f, D3DCOLOR_ARGB(255, 255, 0, 0));
}
else if(m_pCG->GetTutorialMode() && m_bTutorial)
{
RECT toDraw; toDraw.top = 0; toDraw.left = 0; toDraw.right = 578; toDraw.bottom = 495;
int nImage = m_pTM->LoadTexture("Resource/KQ_TutorialBox.png");
m_pTM->Draw(nImage,0,2,1.4f,1.2f,&toDraw);
m_pTM->Draw(m_nScrollButtonID,325,400,.4f,.3f);
m_cFont.DrawTextA("Accept",350,425,.2f,.2f,D3DCOLOR_ARGB(255,255,0,0));
m_cFont.DrawTextA("Tutorial",315,15,.4f,.4f,D3DCOLOR_ARGB(255,255,0,0));
m_cFont.DrawTextA("This next screen is the new game screen./The current file will be selected and is /highlighted in yellow. Feel free to pick /a different file if you like.//Click accept to continue.",100,100,.25f,.25f,D3DCOLOR_ARGB(255,0,0,0));
}
}
| [
"[email protected]@631b4192-2952-0410-9426-c5ed74a7d3ec",
"[email protected]@631b4192-2952-0410-9426-c5ed74a7d3ec",
"[email protected]@631b4192-2952-0410-9426-c5ed74a7d3ec",
"[email protected]@631b4192-2952-0410-9426-c5ed74a7d3ec"
]
| [
[
[
1,
18
],
[
20,
30
],
[
32,
36
],
[
39,
41
],
[
45,
49
],
[
62,
63
],
[
65,
74
],
[
76,
79
],
[
81,
85
],
[
88,
88
],
[
111,
114
],
[
116,
119
],
[
127,
132
],
[
134,
134
],
[
145,
148
],
[
232,
232
],
[
238,
238
],
[
243,
245
],
[
248,
249
],
[
251,
251
],
[
257,
257
],
[
259,
262
],
[
266,
268
],
[
273,
275
],
[
287,
287
],
[
291,
292
],
[
294,
294
],
[
296,
296
],
[
303,
309
],
[
311,
319
],
[
321,
321
],
[
323,
323
],
[
331,
332
],
[
342,
342
],
[
345,
345
],
[
351,
351
],
[
355,
355
],
[
358,
358
],
[
362,
362
],
[
365,
366
],
[
376,
376
],
[
378,
381
]
],
[
[
19,
19
],
[
37,
37
],
[
115,
115
]
],
[
[
31,
31
],
[
58,
60
],
[
75,
75
],
[
80,
80
],
[
86,
86
],
[
93,
93
],
[
96,
104
],
[
149,
231
],
[
234,
236
],
[
239,
239
],
[
241,
242
],
[
246,
247
],
[
252,
253
],
[
255,
256
],
[
258,
258
],
[
278,
279
],
[
281,
281
],
[
283,
286
],
[
288,
288
],
[
290,
290
],
[
293,
293
],
[
298,
302
],
[
320,
320
],
[
322,
322
],
[
324,
328
],
[
333,
335
],
[
337,
341
],
[
343,
344
],
[
346,
350
],
[
352,
354
],
[
356,
357
],
[
359,
361
],
[
363,
364
],
[
367,
367
],
[
369,
375
],
[
377,
377
]
],
[
[
38,
38
],
[
42,
44
],
[
50,
57
],
[
61,
61
],
[
64,
64
],
[
87,
87
],
[
89,
92
],
[
94,
95
],
[
105,
110
],
[
120,
126
],
[
133,
133
],
[
135,
144
],
[
233,
233
],
[
237,
237
],
[
240,
240
],
[
250,
250
],
[
254,
254
],
[
263,
265
],
[
269,
272
],
[
276,
277
],
[
280,
280
],
[
282,
282
],
[
289,
289
],
[
295,
295
],
[
297,
297
],
[
310,
310
],
[
329,
330
],
[
336,
336
],
[
368,
368
]
]
]
|
c88ddaea336e0989a84c9aafbe6abf89fdf776f9 | c1a2953285f2a6ac7d903059b7ea6480a7e2228e | /deitel/ch08/Ex08_29/ex08_29.cpp | 3b7c1aece44ef51d72bf3f13ab936a7d69688099 | []
| no_license | tecmilenio/computacion2 | 728ac47299c1a4066b6140cebc9668bf1121053a | a1387e0f7f11c767574fcba608d94e5d61b7f36c | refs/heads/master | 2016-09-06T19:17:29.842053 | 2008-09-28T04:27:56 | 2008-09-28T04:27:56 | 50,540 | 4 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,769 | cpp | // Ex. 8.29: ex08_29.cpp
// What does this program do?
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
bool mystery3( const char *, const char * ); // prototype
int main()
{
char string1[ 80 ], string2[ 80 ];
cout << "Enter two strings: ";
cin >> string1 >> string2;
cout << "The result is " << mystery3( string1, string2 ) << endl;
return 0; // indicates successful termination
} // end main
// What does this function do?
bool mystery3( const char *s1, const char *s2 )
{
for ( ; *s1 != '\0' && *s2 != '\0'; s1++, s2++ )
if ( *s1 != *s2 )
return false;
return true;
} // end function mystery3
/**************************************************************************
* (C) Copyright 1992-2008 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/
| [
"[email protected]"
]
| [
[
[
1,
44
]
]
]
|
1717206fd26ce7a8e29a6346553a832c32cf1f20 | c5534a6df16a89e0ae8f53bcd49a6417e8d44409 | /trunk/Dependencies/Xerces/include/xercesc/util/Compilers/MVSCPPDefs.hpp | 5f4c2b40bcd2fbc78c17dfef06935b6337b1d792 | []
| no_license | svn2github/ngene | b2cddacf7ec035aa681d5b8989feab3383dac012 | 61850134a354816161859fe86c2907c8e73dc113 | refs/heads/master | 2023-09-03T12:34:18.944872 | 2011-07-27T19:26:04 | 2011-07-27T19:26:04 | 78,163,390 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,966 | hpp | /*
* Copyright 1999-2002,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id: MVSCPPDefs.hpp 191054 2005-06-17 02:56:35Z jberry $
*/
#if !defined(MVSCPPDEFS_HPP)
#define MVSCPPDEFS_HPP
// ---------------------------------------------------------------------------
// Include some runtime files that will be needed product wide
// ---------------------------------------------------------------------------
#include <sys/types.h> // for size_t and ssize_t
#include <limits.h> // for MAX of size_t and ssize_t
// ---------------------------------------------------------------------------
// A define in the build for each project is also used to control whether
// the export keyword is from the project's viewpoint or the client's.
// These defines provide the platform specific keywords that they need
// to do this.
// ---------------------------------------------------------------------------
#define PLATFORM_EXPORT _Export
#define PLATFORM_IMPORT
// ---------------------------------------------------------------------------
// Indicate that we do not support native bools
// If the compiler can handle boolean itself, do not define it
// ---------------------------------------------------------------------------
//#define NO_NATIVE_BOOL
// ---------------------------------------------------------------------------
// Each compiler might support L"" prefixed constants. There are places
// where it is advantageous to use the L"" where it supported, to avoid
// unnecessary transcoding.
// If your compiler does not support it, don't define this.
// ---------------------------------------------------------------------------
#define XML_LSTRSUPPORT
// ---------------------------------------------------------------------------
// Indicate that we support C++ namespace
// Do not define it if the compile cannot handle C++ namespace
// ---------------------------------------------------------------------------
#define XERCES_HAS_CPP_NAMESPACE
// ---------------------------------------------------------------------------
// Define our version of the XML character
// ---------------------------------------------------------------------------
typedef unsigned short XMLCh;
// typedef wchar_t XMLCh;
// ---------------------------------------------------------------------------
// Define unsigned 16 and 32 bits integers
// ---------------------------------------------------------------------------
typedef unsigned short XMLUInt16;
typedef unsigned int XMLUInt32;
// ---------------------------------------------------------------------------
// Define signed 32 bits integers
// ---------------------------------------------------------------------------
typedef int XMLInt32;
// ---------------------------------------------------------------------------
// XMLSize_t is the unsigned integral type.
// ---------------------------------------------------------------------------
#if defined(_SIZE_T) && defined(SIZE_MAX) && defined(_SSIZE_T) && defined(SSIZE_MAX)
typedef size_t XMLSize_t;
#define XML_SIZE_MAX SIZE_MAX
typedef ssize_t XMLSSize_t;
#define XML_SSIZE_MAX SSIZE_MAX
#else
typedef unsigned long XMLSize_t;
#define XML_SIZE_MAX ULONG_MAX
typedef long XMLSSize_t;
#define XML_SSIZE_MAX LONG_MAX
#endif
// ---------------------------------------------------------------------------
// Force on the Xerces debug token if it was on in the build environment
// ---------------------------------------------------------------------------
#if defined(_DEBUG)
#define XERCES_DEBUG
#endif
// ---------------------------------------------------------------------------
// Provide some common string ops that are different/notavail on MVSCPP
// ---------------------------------------------------------------------------
//
// This is a upper casing function. Note that this will not cover
// all NLS cases such as European accents etc. but there aren't
// any of these in the current uses of this function in Xerces.
// If this changes in the future, than we can re-address the issue
// at that time.
//
inline char mytoupper(const char toUpper)
{
if ((toUpper >= 0x61) && (toUpper <= 0x7A))
return char(toUpper - 0x20);
return toUpper;
}
inline char mytolower(const char toLower)
{
if ((toLower >= 0x41) && (toLower <= 0x5A))
return char(toLower + 0x20);
return toLower;
}
inline XMLCh mytowupper(const XMLCh toUpper)
{
if ((toUpper >= 0x61) && (toUpper <= 0x7A))
return XMLCh(toUpper - 0x20);
return toUpper;
}
inline XMLCh mytowlower(const XMLCh toLower)
{
if ((toLower >= 0x41) && (toLower <= 0x5A))
return XMLCh(toLower + 0x20);
return toLower;
}
int stricmp(const char* const str1, const char* const str2);
int strnicmp(const char* const str1, const char* const str2, const unsigned int count);
// ---------------------------------------------------------------------------
// The name of the DLL that is built by the MVSCPP version of the system.
// ---------------------------------------------------------------------------
const char* const Xerces_DLLName = "libxerces-c";
#endif // MVSCPPDEFS_HPP
| [
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
]
| [
[
[
1,
148
]
]
]
|
b6fd90d708afd35f3f553c4bea0e14e50ff2d37e | 36d0ddb69764f39c440089ecebd10d7df14f75f3 | /プログラム/Ngllib/include/Ngl/Plane.h | 0074689ca878d13b60e0093c50bd9ee93543363f | []
| no_license | weimingtom/tanuki-mo-issyo | 3f57518b4e59f684db642bf064a30fc5cc4715b3 | ab57362f3228354179927f58b14fa76b3d334472 | refs/heads/master | 2021-01-10T01:36:32.162752 | 2009-04-19T10:37:37 | 2009-04-19T10:37:37 | 48,733,344 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 7,395 | h | /*******************************************************************************/
/**
* @file Plane.h.
*
* @brief 平面構造体ヘッダファイル.
*
* @date 2008/07/16.
*
* @version 1.00.
*
* @author Kentarou Nishimura.
*/
/******************************************************************************/
#ifndef _NGL_PLANE_H_
#define _NGL_PLANE_H_
#include "Vector3.h"
namespace Ngl{
/**
* @struct Plane.
* @brief 平面構造体.
*/
struct Plane
{
/** 面法線x成分 */
float x;
/** 面法線y成分 */
float y;
/** 面法線z成分 */
float z;
/** 原点からの距離 */
float d;
/**
* @enum PlanePositionFlags.
* @brief 位置関係列挙型.
*/
enum PlanePositionFlags
{
FRONT_PLANE = 0, /**< 平面の前 */
BEHIND_PLANE, /**< 平面の後ろ */
ON_PLANE, /**< 平面上 */
INTERSECTS_PLANE /**< 平面と交差 */
};
/*=========================================================================*/
/**
* @brief コンストラクタ
*
* @param[in] なし.
*/
Plane();
/*=========================================================================*/
/**
* @brief コンストラクタ
*
* @param[in] other 配列の先頭ポインタ.
*/
Plane ( float* other );
/*=========================================================================*/
/**
* @brief コンストラクタ
*
* @param[in] X 面法線x成分.
* @param[in] Y 面法線y成分.
* @param[in] Z 面法線z成分.
* @param[in] D 原点からの距離.
*/
Plane( float X, float Y, float Z, float D );
/*=========================================================================*/
/**
* @brief コンストラクタ
*
* @param[in] N 法線ベクトル.
* @param[in] D 原点からの距離.
*/
Plane( const Ngl::Vector3& N, float D );
/*=========================================================================*/
/**
* @brief コンストラクタ
*
* @param[in] P 平面上の座標.
* @param[in] N 法線ベクトル.
*/
Plane( const Ngl::Vector3& P, const Ngl::Vector3 N );
/*=========================================================================*/
/**
* @brief コンストラクタ
*
* @param[in] v1 座標1.
* @param[in] v2 座標2.
* @param[in] v3 座標3.
*/
Plane( const Ngl::Vector3& v1, const Ngl::Vector3& v2, const Ngl::Vector3& v3 );
/*=========================================================================*/
/**
* @brief 平面を正規化する
*
* @param[in] なし.
* @return 正規化した平面.
*/
Plane& normalize();
/*=========================================================================*/
/**
* @brief 平面上の位置を取得する
*
* @param[in] なし.
* @return 位置座標.
*/
Ngl::Vector3 getPoint() const;
/*=========================================================================*/
/**
* @brief 平面とベクトルの内積を求める
*
* @param[in] v 内積を求めるベクトル .
* @return 内積.
*/
float dot( const Ngl::Vector3& v ) const;
/*=========================================================================*/
/**
* @brief 平面と座標との距離を求める
*
* @param[in] v 距離を求めるベクトル .
* @return 距離.
*/
float distance( const Ngl::Vector3& v ) const;
/*=========================================================================*/
/**
* @brief 平面と座標の位置関係を返す
*
* @param[in] pos 調べる座標.
* @return 位置関係.
*/
PlanePositionFlags getClassifyPoint( const Ngl::Vector3& pos );
/*=========================================================================*/
/**
* @brief 平面と球体の位置関係を返す
*
* @param[in] center 球体の中心座標.
* @param[in] radius 球体の半径.
* @return 位置関係.
*/
PlanePositionFlags getClassifySphere( const Ngl::Vector3& center, float radius );
/*=========================================================================*/
/**
* @brief 平面と線分が交差するか調べる
*
* @param[in] line0 線分の始点.
* @param[in] line1 線分の終点.
* @return true 交差している, false 交差していない.
*/
bool intersectLine( const Ngl::Vector3& line0, const Ngl::Vector3& line1 );
/*=========================================================================*/
/**
* @brief 平面と線分が交差する座標を求める
*
* @param[in] line0 線分の始点.
* @param[in] line1 線分の終点.
* @param[in] retVec 交差していなかった時に戻るベクトル.
* @return 交点座標.
*/
Ngl::Vector3 intersectLinePosition
(
const Ngl::Vector3& line0,
const Ngl::Vector3& line1,
const Ngl::Vector3& retVec
);
/*=========================================================================*/
/**
* @brief 平面とレイが交差するか調べる
*
* @param[in] rayPos レイの始点.
* @param[in] rayDir レイの方向.
* @return true 交差している, false 交差していない.
*/
bool intersectRay( const Ngl::Vector3& rayPos, const Ngl::Vector3& rayDir );
/*=========================================================================*/
/**
* @brief 平面とレイの交点座標を求める
*
* @param[in] rayPos レイの始点.
* @param[in] rayDir レイの方向.
* @param[in] retVec 交差していなかった時に戻るベクトル.
* @return 交点座標.
*/
Ngl::Vector3 intersectRayPositon
(
const Ngl::Vector3& rayPos,
const Ngl::Vector3& rayDir,
const Ngl::Vector3& retVec
);
/*=========================================================================*/
/**
* @brief 平面上の座標と平面の法線ベクトルから平面を作成する
*
* @param[in] point 平面状の座標.
* @param[in] normal 平面の法線ベクトル.
* @return 作成した平面.
*/
Plane& createFromPointNormal( const Ngl::Vector3& point, const Ngl::Vector3& normal );
/*=========================================================================*/
/**
* @brief 平面上の3つの座標から平面を作成する
*
* @param[in] v1 座標1.
* @param[in] v2 座標2.
* @param[in] v3 座標3.
* @return 作成した平面.
*/
Plane& createFromPoints( const Ngl::Vector3& v1, const Ngl::Vector3& v2, const Ngl::Vector3& v3 );
/*=========================================================================*/
/**
* @brief == 演算子オーバーロード
*
* @param[in] other 演算する平面.
* @retval true 一致している.
* @retval false 一致していない.
*/
bool operator == ( const Ngl::Plane& other );
/*=========================================================================*/
/**
* @brief != 演算子オーバーロード
*
* @param[in] other 演算する平面.
* @retval true 一致していない.
* @retval false 一致している.
*/
bool operator != ( const Ngl::Plane& other );
};
} // namespace Ngl
#endif
/*===== EOF ==================================================================*/ | [
"rs.drip@aa49b5b2-a402-11dd-98aa-2b35b7097d33"
]
| [
[
[
1,
280
]
]
]
|
063e9e228c0b6b31235144e5ea9893baaa0fb3c6 | 6630a81baef8700f48314901e2d39141334a10b7 | /1.4/Testing/Cxx/swWxGuiTesting/swModalDialogTimer.cpp | 49b8534c75420a4da4161712eab6ecafcc41ac0a | []
| no_license | jralls/wxGuiTesting | a1c0bed0b0f5f541cc600a3821def561386e461e | 6b6e59e42cfe5b1ac9bca02fbc996148053c5699 | refs/heads/master | 2021-01-10T19:50:36.388929 | 2009-03-24T20:22:11 | 2009-03-26T18:51:24 | 623,722 | 1 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 2,333 | cpp | ///////////////////////////////////////////////////////////////////////////////
// Name: swWxGuiTesting/CppGuiTest/swModalDialogTimer.cpp
// Author: Reinhold Füreder
// Created: 2006
// Copyright: (c) 2006 Reinhold Füreder
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
#ifdef __GNUG__
#pragma implementation "swModalDialogTimer.h"
#endif
#include "swModalDialogTimer.h"
#include <wx/dialog.h>
#include "swModalDialogInteractionInterface.h"
#include "swWxLogicErrorException.h"
namespace swTst {
ModalDialogTimer::ModalDialogTimer (int retCode) :
m_retCode (retCode)
{
m_interactor = NULL;
}
ModalDialogTimer::~ModalDialogTimer ()
{
if (m_interactor) {
delete m_interactor;
}
}
void ModalDialogTimer::SetModalDialog (wxDialog *dialog)
{
m_dialog = dialog;
}
void ModalDialogTimer::SetModalDialogInteractor (ModalDialogInteractionInterface *interactor)
{
m_interactor = interactor;
}
bool ModalDialogTimer::Start (int milliseconds, bool oneShot)
{
if (oneShot == false) {
throw sw::WxLogicErrorException ("Only one-shot timer is allowed");
}
return wxTimer::Start (milliseconds, oneShot);
}
void ModalDialogTimer::Notify ()
{
// GUI interaction is only allowed if the timer is actually fired in the
// main thread:
if (!wxThread::IsMain()) {
throw sw::WxLogicErrorException ("not main thread");
}
if (m_interactor) {
m_interactor->Execute ();
}
wxCommandEvent event;
if (m_retCode == wxID_CANCEL) {
// Cannot access protected in wxWidgets 2.8:
//m_dialog->EndDialog (m_retCode);
this->EndDialog ();
} else if (m_retCode == wxID_OK) {
// Cannot access protected in wxWidgets 2.8:
//m_dialog->AcceptAndClose ();
if (m_dialog->Validate () && m_dialog->TransferDataFromWindow ()) {
this->EndDialog ();
}
} else {
wxFAIL_MSG ("Invalid return code");
}
}
void ModalDialogTimer::EndDialog ()
{
if (m_dialog->IsModal ())
m_dialog->EndModal (m_retCode);
else
m_dialog->Hide ();
}
} // End namespace swTst
| [
"john@64288482-8357-404e-ad65-de92a562ee98"
]
| [
[
[
1,
107
]
]
]
|
6f0bdc36df6fa9b2b2c9b75773eb0dec0640bed3 | 35c06332e5cbdf18538ecf22dc2de43910508e42 | /smartalbum/MainFrm.cpp | 4cf25668ed06f8d029139169294f0db755e095f1 | []
| no_license | Dandelion0124/smartalbum | dd24400359c5302b1489caf603efb3cb9803c993 | dbeca19ecbf302c1d03d7ad39c1c3045c4bfd69a | refs/heads/master | 2021-01-11T05:52:58.285637 | 2009-01-05T05:59:45 | 2009-01-05T05:59:45 | 49,498,431 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,890 | cpp | // MainFrm.cpp : CMainFrame 类的实现
//
#include "stdafx.h"
#include "Smart Album.h"
#include "MainFrm.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CMainFrame
IMPLEMENT_DYNCREATE(CMainFrame, CFrameWnd)
BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
ON_WM_CREATE()
END_MESSAGE_MAP()
static UINT indicators[] =
{
ID_SEPARATOR, // 状态行指示器
ID_INDICATOR_CAPS,
ID_INDICATOR_NUM,
ID_INDICATOR_SCRL,
};
// CMainFrame 构造/析构
CMainFrame::CMainFrame()
{
// TODO: 在此添加成员初始化代码
}
CMainFrame::~CMainFrame()
{
}
int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CFrameWnd::OnCreate(lpCreateStruct) == -1)
return -1;
if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP
| CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) ||
!m_wndToolBar.LoadToolBar(IDR_MAINFRAME))
{
TRACE0("未能创建工具栏\n");
return -1; // 未能创建
}
if (!m_wndStatusBar.Create(this) ||
!m_wndStatusBar.SetIndicators(indicators,
sizeof(indicators)/sizeof(UINT)))
{
TRACE0("未能创建状态栏\n");
return -1; // 未能创建
}
// TODO: 如果不需要工具栏可停靠,则删除这三行
m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY);
EnableDocking(CBRS_ALIGN_ANY);
DockControlBar(&m_wndToolBar);
return 0;
}
BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
if( !CFrameWnd::PreCreateWindow(cs) )
return FALSE;
// TODO: 在此处通过修改
// CREATESTRUCT cs 来修改窗口类或样式
return TRUE;
}
// CMainFrame 诊断
#ifdef _DEBUG
void CMainFrame::AssertValid() const
{
CFrameWnd::AssertValid();
}
void CMainFrame::Dump(CDumpContext& dc) const
{
CFrameWnd::Dump(dc);
}
#endif //_DEBUG
// CMainFrame 消息处理程序
| [
"wanglpqpq@d3b2af04-d0e3-11dd-bfda-f1b6ccb9c726"
]
| [
[
[
1,
102
]
]
]
|
1b7840a1a2643986e1aca24b572e0aba63900c95 | f0c08b3ddefc91f1fa342f637b0e947a9a892556 | /branches/develop/cppreflect/SmokeTest/ObjectShared.cpp | 86fd908f4c9c5e1c8bfa335311dea1012a5ba689 | []
| no_license | BackupTheBerlios/coffeestore-svn | 1db0f60ddb85ccbbdfeb9b3271a687b23e29fc8f | ddee83284fe9875bf0d04e6b7da7a2113e85a040 | refs/heads/master | 2021-01-01T05:30:22.345767 | 2009-10-11T08:55:35 | 2009-10-11T08:55:35 | 40,725,038 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,834 | cpp | #include "Field.hpp"
#include "TypeOf.hpp"
#include "TypeRegistry.hpp"
using namespace reflect;
#include <string>
#include <iostream>
using namespace std;
#include "macro.hpp"
class MyClass
{
REFLECT_ALLOW(MyClass)
public:
MyClass(double myDouble, int myInt, char myChar)
: _myDouble(myDouble), _myInt(myInt), _myChar(myChar)
{
}
~MyClass()
{
std::cout << "DTOR" << std::endl;
}
private:
double _myDouble;
int _myInt;
char _myChar;
std::string _myStr;
};
REFLECT_BEGIN(MyClass)
REFLECT_FIELD(_myDouble)
REFLECT_FIELD(_myInt)
REFLECT_FIELD(_myChar)
REFLECT_FIELD(_myStr)
REFLECT_END()
class MyComposition
{
REFLECT_ALLOW(MyComposition)
public:
MyComposition(const MyClass& myClass)
: _myClass(myClass)
{
}
const MyClass& getMyClass() { return _myClass; }
private:
MyClass _myClass;
};
REFLECT_BEGIN(MyComposition)
REFLECT_FIELD(_myClass)
REFLECT_END()
void printObject(const Object& obj)
{
const Type& t = obj.concreteType();
if (!t.isClassType())
return;
const ClassType& type = t.asClassType();
for (ClassType::FieldsIterator it = type.fieldsBegin(); it != type.fieldsEnd(); ++it)
{
const Field& field = *it;
std::cout << it->name() << " : " << (*it).type().name() << std::endl;
if (field.isBuiltinField())
{
std::cout << "\tbuiltin ";
const BuiltinField& builtin = field.asBuiltinField();
if (builtin.isBool())
std::cout << builtin.getBool(obj);
if (builtin.isChar())
std::cout << builtin.getChar(obj);
if (builtin.isInt())
std::cout << builtin.getInt(obj);
if (builtin.isFloat())
std::cout << builtin.getFloat(obj);
if (builtin.isDouble())
std::cout << builtin.getDouble(obj);
std::cout << std::endl;
}
else if (field.isStringField())
{
const StringField& str = field.asStringField();
std::cout << "\tstring " << str.getString(obj) << std::endl;
}
else if (field.isCompositeField())
{
std::cout << "\tcomposite" << std::endl;
const CompositeField& composite = field.asCompositeField();
printObject(composite.get(obj));
}
else
{
std::cout << "INTERNAL ERROR" << std::endl;
}
}
}
int main()
{
MyClass myObj(12.23f, 11, 'a');
Object object(myObj, false);
const BuiltinField& field_myDouble = TypeOf<MyClass>::get().findField("_myDouble").asBuiltinField();
const BuiltinField& field_myInt = TypeOf<MyClass>::get().findField("_myInt").asBuiltinField();
const BuiltinField& field_myChar = TypeOf<MyClass>::get().findField("_myChar").asBuiltinField();
const StringField& field_myStr = TypeOf<MyClass>::get().findField("_myStr").asStringField();
std::cout << field_myDouble.getDouble(object) << std::endl;
std::cout << field_myInt.getInt(object) << std::endl;
std::cout << field_myChar.getChar(object) << std::endl;
try
{
std::cout << field_myDouble.getInt(object) << std::endl;
}
catch (const BadCastException& e)
{
cout << e.what() << endl;
}
try
{
std::cout << field_myInt.getDouble(object) << std::endl;
}
catch (const BadCastException& e)
{
cout << e.what() << endl;
}
try
{
std::cout << field_myChar.getInt(object) << std::endl;
}
catch (const BadCastException& e)
{
cout << e.what() << endl;
}
try
{
field_myDouble.setDouble(object, 21.32f);
field_myInt.setInt(object, 123);
field_myChar.setChar(object, 'b');
std::cout << field_myDouble.getDouble(object) << std::endl;
std::cout << field_myInt.getInt(object) << std::endl;
std::cout << field_myChar.getChar(object) << std::endl;
field_myStr.setString(myObj, "mickey");
std::cout << field_myStr.getString(object) << std::endl;
Object obj = field_myStr.get(object);
std::cout << obj.get<std::string>() << std::endl;
std::string newStr = "mouse";
Object valueStr(newStr, false);
field_myStr.set(object, valueStr);
std::cout << field_myStr.getString(object) << std::endl;
field_myStr.setString(object, "mickey");
std::cout << field_myStr.getString(object) << std::endl;
}
catch (Exception& e)
{
cout << "Unexpected " << e.what() << endl;
}
const MyClass myConstObj(11.2, 12, '2');
Object constObject(myConstObj);
cout << constObject.abstractType().name() << endl;
cout << constObject.concreteType().name() << endl;
cout << TypeRegistry::getInstance().find(typeid(bool))->name() << endl;
MyComposition myComp(myConstObj);
cout << TypeRegistry::getInstance().find(typeid(MyComposition))->name() << endl;
printObject(myComp);
try
{
const MyClass myObj(12.23f, 11, 'a');
Object object(myObj, false);
field_myStr.setString(object, "pippo");
}
catch (Exception& e)
{
cout << e.what() << endl;
}
system("pause");
return 0;
}
| [
"fabioppp@e591b805-c13a-0410-8b2d-a75de64125fb"
]
| [
[
[
1,
212
]
]
]
|
05856cb85ad4d77e064c0e64a8664d16302adf5e | bdb1e38df8bf74ac0df4209a77ddea841045349e | /CapsuleSortor/Version 1.0 -2.0/CapsuleSortor-10-11-12/CapsuleSortor-10-11-12/Remain/ArcTemple.h | d53f7e5c2e875d1c6ed654389e72e22dbb886e30 | []
| no_license | Strongc/my001project | e0754f23c7818df964289dc07890e29144393432 | 07d6e31b9d4708d2ef691d9bedccbb818ea6b121 | refs/heads/master | 2021-01-19T07:02:29.673281 | 2010-12-17T03:10:52 | 2010-12-17T03:10:52 | 49,062,858 | 0 | 1 | null | 2016-01-05T11:53:07 | 2016-01-05T11:53:07 | null | UTF-8 | C++ | false | false | 1,494 | h | #ifndef ARCTEMPLE_H
#define ARCTEMPLE_H
#include <vector>
using namespace std;
#include "TAllocTmpl.h"
#include "TRect2D.h"
#include "TPoint2D.h"
#include "TImageTmpl.h"
#include "TBmpBoard.h"
#include "TImgPainter.h"
typedef TAlloc<IPoint> CoorArray;
class ArcTemple
{
public:
typedef enum {eUpArc, eDownArc } EArcPos;
private:
friend class ArcCreator;
EArcPos m_eArcPos;
IRect m_range;
CoorArray m_coorArray;
public:
EArcPos GetArcPos () const;
IRect GetArcRange () const;
CoorArray GetCoorArray() const;
};
class ArcCreator
{
public:
static ArcTemple CreateArc(size_t radius, ArcTemple::EArcPos ePos);
};
class ArcMatchor
{
public:
void SetImage (const TImage<PelGray8>& image);
bool GetMaxMatchPos(const ArcTemple& arcTmpl, const IRect& range, IPoint& pos);
IPoint GetMaxMatchPos(const vector< POINT >& coorArray, const IRect& range, int step);
bool GetMaxMatchPos(const vector< POINT >& arcTmpl, const IRect& range, IPoint& pos);
private:
IPoint GetMaxMatchPos (const CoorArray& coorArray, const IRect& range, int step);
int GetMatchValue (const CoorArray& coorArray, const IPoint& center);
int GetMatchValue(const vector<POINT>& coorArray, const IPoint& center);
IRect GetCenRange (const ArcTemple& arc, const IRect& ROI);
IRect GetCenRange (const vector<POINT>& arc, const IRect& ROI);
private:
TImage<PelGray8> m_image;
std::vector<int> m_matchVect;
};
#endif //ARCTEMPLE_H
| [
"vincen.cn@66f52ff4-a261-11de-b161-9f508301ba8e"
]
| [
[
[
1,
62
]
]
]
|
27e69b7cf39f8229a7c0863542feeb0d32393bb6 | 4a99fa98abd0285bc3b5671f237b932114123340 | /physics/RunBox2D/Box2dDemo.h | 2303951142f12276b2498ac8d53bc69e685f1f70 | []
| no_license | automenta/crittergod1.5 | 937cd925a4ba57b3e8cfa4899a81ba24fe3e4138 | 4786fe9d621c0e61cdd43ca3a363bfce6510e3c0 | refs/heads/master | 2020-12-24T16:58:32.854270 | 2010-04-12T03:25:39 | 2010-04-12T03:25:39 | 520,917 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,389 | h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BOX2D_DEMO_H
#define BOX2D_DEMO_H
#include "../OpenGL/AbstractSpace.h"
#include "../LinearMath/btAlignedObjectArray.h"
class btBroadphaseInterface;
class btCollisionShape;
class btOverlappingPairCache;
class btCollisionDispatcher;
class btConstraintSolver;
struct btCollisionAlgorithmCreateFunc;
class btDefaultCollisionConfiguration;
class GL_DialogDynamicsWorld;
///Box2dDemo is good starting point for learning the code base and porting.
class Box2dDemo : public AbstractSpace
{
//keep the collision shapes, for deletion/cleanup
btAlignedObjectArray<btCollisionShape*> m_collisionShapes;
btBroadphaseInterface* m_broadphase;
btCollisionDispatcher* m_dispatcher;
btConstraintSolver* m_solver;
btDefaultCollisionConfiguration* m_collisionConfiguration;
GL_DialogDynamicsWorld* m_dialogDynamicsWorld;
public:
Box2dDemo() : m_dialogDynamicsWorld(0)
{
}
virtual ~Box2dDemo() {
exitPhysics();
}
virtual void reshape(int w, int h);
void initPhysics();
void exitPhysics();
virtual void clientMoveAndDisplay();
virtual void draw();
static SpaceProcess* Create()
{
Box2dDemo* demo = new Box2dDemo;
demo->preDraw();
demo->initPhysics();
return demo;
}
virtual void onMouseButton(int button, int state, int x, int y);
virtual void onMouseMove(int x,int y);
};
void runBox2D();
#endif //BOX2D_DEMO_H
| [
"[email protected]"
]
| [
[
[
1,
84
]
]
]
|
3ffab4395aa2bfccd521cb8d8898f3f1179d972a | 7d349e6342c084a4d11234a0aa0846db41c50303 | /themeagent/ModuleManager.h | 139cbb77cf57098caec47d5380d41e79efc0df8a | []
| no_license | Tobbe/themeagent | 8f72641228a9cbb4c57e3bcd7475aee5f755eb3d | cbdbf93859ee7ef5d43330da7dd270f7b966f0b2 | refs/heads/master | 2020-12-24T17:44:42.819782 | 2009-04-18T22:38:58 | 2009-04-18T22:38:58 | 97,412 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,491 | h | #ifndef MODULE_MANAGER_H_
#define MODULE_MANAGER_H_
#include "ModuleList.h"
#include "Module.h"
#include "FileDownloader.h"
#include <string>
#include <vector>
#include <windows.h>
class ModuleManager
{
private:
std::string modulesDir;
std::string nlmIni;
std::vector<std::string> downloadSites;
ModuleList modules;
FileDownloader fileDownloader;
void findModulesInModulesDir();
bool isDll(const WIN32_FIND_DATA &wfd) const;
bool isDir(const WIN32_FIND_DATA &wfd) const;
bool fileExists(const std::string &path) const;
bool downloadModule(const std::string &moduleName);
bool unzipModule(const std::string &moduleName) const;
void fillUnzipVectors(const std::string &moduleName,
const std::string &path,
std::vector<std::pair<int, std::string>> &dllFiles,
std::vector<std::pair<int, std::string>> &docsFiles) const;
bool extractDlls(const std::string &moduleName, const std::string &path,
const std::vector<std::pair<int, std::string>> &dllFiles) const;
void extractDocs(const std::string &moduleName, const std::string &path,
const std::vector<std::pair<int, std::string>> &docsFiles) const;
bool updateNLMList(const std::string &moduleName) const;
public:
ModuleManager(const std::string &modulesDir, const std::string &nlmIni,
const std::vector<std::string> &downloadSites);
ModuleList getModuleList() const;
bool installModule(const std::string &moduleName);
bool installModule(const Module &module);
};
#endif | [
"[email protected]"
]
| [
[
[
1,
43
]
]
]
|
59c98c4e889690518499bf118f26f7534974535e | b2155efef00dbb04ae7a23e749955f5ec47afb5a | /tools/ModelConverter/ConverterMgr.h | 004e6532141929702ac9745cb4cb24e3f5de09d8 | []
| no_license | zjhlogo/originengine | 00c0bd3c38a634b4c96394e3f8eece86f2fe8351 | a35a83ed3f49f6aeeab5c3651ce12b5c5a43058f | refs/heads/master | 2021-01-20T13:48:48.015940 | 2011-04-21T04:10:54 | 2011-04-21T04:10:54 | 32,371,356 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 575 | h | /*!
* \file ConverterMgr.h
* \date 1-3-2010 21:18:28
*
*
* \author zjhlogo ([email protected])
*/
#ifndef __CONVERTERMGR_H__
#define __CONVERTERMGR_H__
#include "IConverter.h"
#include <vector>
class CConverterMgr
{
public:
typedef std::vector<IConverter*> TV_CONVERTER;
public:
CConverterMgr();
~CConverterMgr();
static CConverterMgr& Get();
bool DoConvert(const tstring& strFileIn, const tstring& strFileOut);
private:
void Init();
void Destroy();
private:
TV_CONVERTER m_vConverter;
};
#endif // __CONVERTERMGR_H__
| [
"zjhlogo@fdcc8808-487c-11de-a4f5-9d9bc3506571"
]
| [
[
[
1,
35
]
]
]
|
eaf4177e35fd2ea6f115bb35f04a0a522d5a871f | 3276915b349aec4d26b466d48d9c8022a909ec16 | /c++小作品/sony/inch43.cpp | ad454173bba180ae6e4b547e46f6530c0063348b | []
| no_license | flyskyosg/3dvc | c10720b1a7abf9cf4fa1a66ef9fc583d23e54b82 | 0279b1a7ae097b9028cc7e4aa2dcb67025f096b9 | refs/heads/master | 2021-01-10T11:39:45.352471 | 2009-07-31T13:13:50 | 2009-07-31T13:13:50 | 48,670,844 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 90 | cpp | #ifndef INCH43_HEADER
#define INCH43_HEADER
class inch43:public sony
{
};
#endif | [
"[email protected]"
]
| [
[
[
1,
8
]
]
]
|
4a319db435d242dc8983914ca3db40f9202be617 | 0b039565382fe5cf8a9abe90a2999396d79ca37f | /GrpInformative/dumpIdentifyData_r10b.h | bf049096b08dfb13c027aed9a19bf44fe8fc4016 | [
"Apache-2.0"
]
| permissive | cornsea/tnvme | 989cf26233e05f816b7d64d4bb402124efd7d4e6 | 9e6100b771cd3d0ee7c497e27db391fca626d245 | refs/heads/master | 2021-01-16T18:14:35.269183 | 2011-12-23T20:56:25 | 2011-12-23T20:56:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,058 | h | /*
* Copyright (c) 2011, Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _DUMPIDENTIFYDATA_r10b_H_
#define _DUMPIDENTIFYDATA_r10b_H_
#include "test.h"
#include "../Queues/asq.h"
#include "../Queues/acq.h"
/** \verbatim
* -----------------------------------------------------------------------------
* ----------------Mandatory rules for children to follow-----------------------
* -----------------------------------------------------------------------------
* 1) See notes in the header file of the Test base class
* \endverbatim
*/
class DumpIdentifyData_r10b : public Test
{
public:
DumpIdentifyData_r10b(int fd, string grpName, string testName);
virtual ~DumpIdentifyData_r10b();
/**
* IMPORTANT: Read Test::Clone() header comment.
*/
virtual DumpIdentifyData_r10b *Clone() const
{ return new DumpIdentifyData_r10b(*this); }
DumpIdentifyData_r10b &operator=(const DumpIdentifyData_r10b &other);
DumpIdentifyData_r10b(const DumpIdentifyData_r10b &other);
protected:
virtual bool RunCoreTest();
private:
///////////////////////////////////////////////////////////////////////////
// Adding a member variable? Then edit the copy constructor and operator().
///////////////////////////////////////////////////////////////////////////
void SendIdentifyCtrlrStruct(SharedASQPtr asq, SharedACQPtr acq);
void SendIdentifyNamespaceStruct(SharedASQPtr asq, SharedACQPtr acq);
};
#endif
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
16
]
],
[
[
17,
60
]
]
]
|
78a8ca0de448e9de3e066134a5be0f7517482762 | 343ec16e9616f4890988a25d4928a0b67261fcdc | /engine/trunk/src/introstate.cpp | 6678c71cbce594f12307a61909b1d13ae2b8954a | []
| no_license | kfdm/murasaki | 02ab3192bad71bab7cc566e0d19dc147b48980af | ac9cc2e58db7716dba3caa266a0eb409243afea2 | refs/heads/master | 2021-01-23T13:28:48.560747 | 2008-12-08T07:11:32 | 2008-12-08T07:11:32 | 2,116,902 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,904 | cpp |
#include <stdio.h>
#include <SDL.h>
#include "gameengine.h"
#include "gamestate.h"
#include "introstate.h"
#include "playstate.h"
CIntroState CIntroState::m_IntroState;
void CIntroState::Init()
{
SDL_Surface* temp = SDL_LoadBMP("intro.bmp");
bg = SDL_DisplayFormat(temp);
SDL_FreeSurface(temp);
// create the fader surface like the background with alpha
fader = SDL_CreateRGBSurface( SDL_SRCALPHA, bg->w, bg->h,
bg->format->BitsPerPixel,
bg->format->Rmask, bg->format->Gmask,
bg->format->Bmask, bg->format->Amask );
// fill the fader surface with black
SDL_FillRect (fader, NULL, SDL_MapRGB (bg->format, 0, 0, 0)) ;
// start off opaque
alpha = 255;
SDL_SetAlpha(fader, SDL_SRCALPHA, alpha);
printf("CIntroState Init\n");
}
void CIntroState::Cleanup()
{
SDL_FreeSurface(bg);
SDL_FreeSurface(fader);
printf("CIntroState Cleanup\n");
}
void CIntroState::Pause()
{
printf("CIntroState Pause\n");
}
void CIntroState::Resume()
{
printf("CIntroState Resume\n");
}
void CIntroState::HandleEvents(CGameEngine* game)
{
SDL_Event event;
if (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_QUIT:
game->Quit();
break;
case SDL_KEYDOWN:
switch (event.key.keysym.sym) {
case SDLK_SPACE:
game->ChangeState( CPlayState::Instance() );
break;
case SDLK_ESCAPE:
game->Quit();
break;
}
break;
}
}
}
void CIntroState::Update(CGameEngine* game)
{
alpha--;
if (alpha < 0)
alpha = 0;
SDL_SetAlpha(fader, SDL_SRCALPHA, alpha);
}
void CIntroState::Draw(CGameEngine* game)
{
SDL_BlitSurface(bg, NULL, game->screen, NULL);
// no need to blit if it's transparent
if ( alpha != 0 )
SDL_BlitSurface(fader, NULL, game->screen, NULL);
SDL_UpdateRect(game->screen, 0, 0, 0, 0);
}
| [
"[email protected]"
]
| [
[
[
1,
98
]
]
]
|
f03ebc98aeebaf7091d72a509c81373530b94f12 | 59066f5944bffb953431bdae0482a2abfb75f49a | /trunk/ogreopcode/src/OgreOpcodeRay.cpp | f0dea40bf55b1581592c14f12a0b7e4640e7c65e | []
| no_license | BackupTheBerlios/conglomerate-svn | 5b1afdea5fbcdd8b3cdcc189770b1ad0f8027c58 | bbecac90353dca2ae2114d40f5a6697b18c435e5 | refs/heads/master | 2021-01-01T18:37:56.730293 | 2006-05-21T03:12:39 | 2006-05-21T03:12:39 | 40,668,508 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,691 | cpp | ///////////////////////////////////////////////////////////////////////////////
/// @file OgreOpcodeRay.cpp
/// @brief <TODO: insert file description here>
///
/// @author The OgreOpcode Team @date 28-05-2005
///
///////////////////////////////////////////////////////////////////////////////
///
/// This file is part of OgreOpcode.
///
/// A lot of the code is based on the Nebula Opcode Collision module, see docs/Nebula_license.txt
///
/// OgreOpcode is free software; you can redistribute it and/or
/// modify it under the terms of the GNU Lesser General Public
/// License as published by the Free Software Foundation; either
/// version 2.1 of the License, or (at your option) any later version.
///
/// OgreOpcode is distributed in the hope that it will be useful,
/// but WITHOUT ANY WARRANTY; without even the implied warranty of
/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
/// Lesser General Public License for more details.
///
/// You should have received a copy of the GNU Lesser General Public
/// License along with OgreOpcode; if not, write to the Free Software
/// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
///
///////////////////////////////////////////////////////////////////////////////
#include "OgreOpcodeRay.h"
namespace OgreOpcode
{
namespace Details
{
//------------------------------------------------------------------------
// This class is implemented together with Line in 'OgreOpcodeLine.cpp'
// because they share internal, supporting C functions.
//------------------------------------------------------------------------
}
}
| [
"gilvanmaia@4fa2dde5-35f3-0310-a95e-e112236e8438"
]
| [
[
[
1,
40
]
]
]
|
dc308a722f7c6ddaab2bb4e5feb9465ae65a6bbe | 41371839eaa16ada179d580f7b2c1878600b718e | /UVa/Volume I/00117.cpp | 16b6e6c5a4b3311721fb773bf5b76a768f367e63 | []
| no_license | marinvhs/SMAS | 5481aecaaea859d123077417c9ee9f90e36cc721 | 2241dc612a653a885cf9c1565d3ca2010a6201b0 | refs/heads/master | 2021-01-22T16:31:03.431389 | 2009-10-01T02:33:01 | 2009-10-01T02:33:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,710 | cpp | /////////////////////////////////
// 00117 - The Postal Worker Rings Once
/////////////////////////////////
#include<cstring>
#include<cstdio>
#define MM 200
#define INF (1<<28)
const char *de = "deadend";
char road[50000];
int node_num[200];
int adj[200][200];
int deg[200];
int n;
int dijkstra(int s, int t) {
int in[MM], d[MM];
int i, u;
for(i = 0; i < n; i++)
d[i] = adj[s][i], in[i] = 0;
while(!in[t]) {
int best = INF;
for(i = 0; i < n; i++)
if(!in[i] && best > d[i])
best = d[u = i];
if(best == INF) break;
in[u] = 1;
for(i = 0; i < n; i++)
if(!in[i] && adj[u][i] != -1 && d[i] > d[u] + adj[u][i])
d[i] = d[u] + adj[u][i];
}
return d[t];
}
int main(void){
int answer, i, j, len;
while(gets(road)){
/* clear everything */
memset(node_num,-1,sizeof(node_num));
for(i = 0; i < 200; i++)
for(j = 0; j < 200; j++)
adj[i][j] = INF;
memset(deg,0,sizeof(deg));
n = answer = 0;
/* INPUT */
while(strcmp(road,de)){
len = strlen(road);
if(node_num[road[0]] != -1) i = node_num[road[0]];
else i = node_num[road[0]] = n++;//, printf("%c mapped to %d\n",road[0],i);
if(node_num[road[len-1]] != -1) j = node_num[road[len-1]];
else j = node_num[road[len-1]] = n++;//, printf("%c mapped to %d\n",road[len-1],j);
adj[i][j] = adj[j][i] = len;
deg[i]++; deg[j]++;
answer += len;
gets(road);
}
/* Check if graph has odd degree nodes (SOURCE) */
int s , t;
for(s = t = i = 0; i < n; i++)
if(s == 0 && deg[i]&1) s = i;
else if(deg[i]&1) { t = i; break; }
/* OUTPUT */
if(s) printf("%d\n",answer + dijkstra(s,t));
else printf("%d\n",answer);
}
return 0;
}
| [
"[email protected]"
]
| [
[
[
1,
65
]
]
]
|
4a6f1d98534e4ab42d30c272164c4d373ba4e7fc | bda7b365b5952dc48827a8e8d33d11abd458c5eb | /LeaderBoardDefinition.h | 4d750bd6a1dfbc5cca44d50e8e5293b20f0f77f9 | []
| no_license | MrColdbird/gameservice | 3bc4dc3906d16713050612c1890aa8820d90272e | 009d28334bdd8f808914086e8367b1eb9497c56a | refs/heads/master | 2021-01-25T09:59:24.143855 | 2011-01-31T07:12:24 | 2011-01-31T07:12:24 | 35,889,912 | 3 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,778 | h | // ======================================================================================
// File : LeaderBoardDefinition.h
// Author : Li Chen
// Last Change : 07/29/2010 | 15:47:37 PM | Thursday,July
// Description :
// ======================================================================================
#ifndef GAMESERVICE_LEADERBOARDDEFINITION_H
#define GAMESERVICE_LEADERBOARDDEFINITION_H
namespace GameService
{
#if defined(_XBOX) || defined(_XENON)
#define LB_COLUMN_MAX XUSER_STATS_ATTRS_IN_SPEC
#else
#define LB_COLUMN_MAX 100 // temp
#endif
class LeaderBoardDef
{
public:
LeaderBoardDef() : m_iBoardID(-1)
#if defined(_XBOX) || defined(_XENON)
, m_iColumnNum(0)
#endif
{}
#if defined(_XBOX) || defined(_XENON)
void Set(GS_DWORD bid, GS_INT num, GS_INT* values)
#elif defined(_PS3)
void Set(GS_DWORD bid, GS_INT score)
#endif
{
m_iBoardID = bid;
#if defined(_XBOX) || defined(_XENON)
m_Spec.dwViewId = bid;
m_iColumnNum = num;
m_Spec.dwNumColumnIds = num;
for (GS_UINT i=0;i<m_Spec.dwNumColumnIds;i++)
{
m_Spec.rgwColumnIds[i] = values[i];
}
#elif defined(_PS3)
m_iScore = score;
#endif
}
#if defined(_XBOX) || defined(_XENON)
PXUSER_STATS_SPEC GetDefinition() { return &m_Spec; }
#elif defined(_PS3)
GS_INT GetScore() { return m_iScore; }
#endif
GS_DWORD GetBoardID() { return m_iBoardID; }
private:
GS_DWORD m_iBoardID;
#if defined(_XBOX) || defined(_XENON)
GS_INT m_iColumnNum;
GS_INT m_piColumnIDs[LB_COLUMN_MAX];
XUSER_STATS_SPEC m_Spec; // Stats specification
#elif defined(_PS3)
GS_INT m_iScore;
#endif
};
} // namespace GameService
#endif // GAMESERVICE_LEADERBOARDDEFINITION_H
| [
"leavesmaple@383b229b-c81f-2bc2-fa3f-61d2d0c0fe69"
]
| [
[
[
1,
70
]
]
]
|
bb1326f38419f095e91a41c8edbb5b7b6d0dc92f | b8c3d2d67e983bd996b76825f174bae1ba5741f2 | /RTMP/utils/gil_2/boost/gil/extension/io_new/jpeg_tags.hpp | 028a24c10d91782b15cbbcd1061446615e9519db | []
| no_license | wangscript007/rtmp-cpp | 02172f7a209790afec4c00b8855d7a66b7834f23 | 3ec35590675560ac4fa9557ca7a5917c617d9999 | refs/heads/master | 2021-05-30T04:43:19.321113 | 2008-12-24T20:16:15 | 2008-12-24T20:16:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,850 | hpp | /*
Copyright 2007-2008 Christian Henning, Andreas Pokorny, Lubomir Bourdev
Use, modification and distribution are subject to the Boost Software License,
Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt).
*/
/*************************************************************************************************/
#ifndef BOOST_GIL_EXTENSION_IO_JPEG_TAGS_HPP_INCLUDED
#define BOOST_GIL_EXTENSION_IO_JPEG_TAGS_HPP_INCLUDED
////////////////////////////////////////////////////////////////////////////////////////
/// \file
/// \brief All supported jpeg tags by the gil io extension.
/// \author Christian Henning, Andreas Pokorny, Lubomir Bourdev \n
///
/// \date 2007-2008 \n
///
////////////////////////////////////////////////////////////////////////////////////////
extern "C" {
#include <jpeglib.h>
}
#include "detail/base.hpp"
namespace boost { namespace gil {
struct jpeg_tag : format_tag {};
struct jpeg_image_width
{
typedef JDIMENSION type;
};
struct jpeg_image_height
{
typedef JDIMENSION type;
};
struct jpeg_num_components
{
typedef int type;
};
struct jpeg_color_space
{
typedef J_COLOR_SPACE type;
};
struct jpeg_quality
{
typedef int type;
};
struct jpeg_data_precision
{
typedef int type;
};
template<>
struct image_read_info<jpeg_tag>
{
jpeg_image_width::type _width;
jpeg_image_height::type _height;
jpeg_num_components::type _num_components;
jpeg_color_space::type _color_space;
jpeg_data_precision::type _data_precision;
};
template<>
struct image_write_info<jpeg_tag>
{
jpeg_quality::type _quality;
};
} // namespace gil
} // namespace boost
#endif // BOOST_GIL_EXTENSION_IO_JPEG_TAGS_HPP_INCLUDED
| [
"fpelliccioni@71ea4c15-5055-0410-b3ce-cda77bae7b57"
]
| [
[
[
1,
84
]
]
]
|
92ded85c2030920e4b1585d21c590f1b3b8dd94d | 3e69b159d352a57a48bc483cb8ca802b49679d65 | /tags/release-2005-10-27/pcbnew/class_text_mod.h | 9cdf022a1ab5a39c8c04cff073625b95ae085372 | []
| no_license | BackupTheBerlios/kicad-svn | 4b79bc0af39d6e5cb0f07556eb781a83e8a464b9 | 4c97bbde4b1b12ec5616a57c17298c77a9790398 | refs/heads/master | 2021-01-01T19:38:40.000652 | 2006-06-19T20:01:24 | 2006-06-19T20:01:24 | 40,799,911 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 1,917 | h | /***************************************************/
/* class_text_module.h : texts module description */
/***************************************************/
/* Description des Textes sur Modules : */
#define TEXT_is_REFERENCE 0
#define TEXT_is_VALUE 1
#define TEXT_is_DIVERS 2
class TEXTE_MODULE: public EDA_BaseStruct
{
public:
int m_Layer; // layer number
int m_Width;
wxPoint m_Pos; // Real coord
wxPoint m_Pos0; // coord du debut du texte /ancre, orient 0
char m_Unused; // unused (reserved for future extensions)
char m_Miroir ; // vue normale / miroir
char m_NoShow; // 0: visible 1: invisible (bool)
char m_Type; // 0: ref,1: val, autre = 2..255
int m_Orient; // orientation en 1/10 degre
wxSize m_Size; // dimensions (en X et Y) du texte
wxString m_Text;
public:
TEXTE_MODULE::TEXTE_MODULE(MODULE * parent, int text_type = TEXT_is_DIVERS );
TEXTE_MODULE::~TEXTE_MODULE(void);
/* supprime du chainage la structure Struct */
void UnLink( void );
void Copy(TEXTE_MODULE * source); // copy structure
/* Gestion du texte */
void SetWidth(int new_width);
const char * GetText(void);
int GetLength(void); /* text length */
int Pitch(void); /* retourne le pas entre 2 caracteres */
int GetDrawRotation(void); // Return text rotation for drawings and plotting
void SetDrawCoord(void); // mise a jour des coordonnées absolues de tracé
// a partir des coord relatives
void SetLocalCoord(void); // mise a jour des coordonnées relatives
// a partir des coord absolues de tracé
/* Reading and writing data on files */
int WriteDescr( FILE * File );
int ReadDescr( FILE * File, int * LineNum = NULL);
/* drawing functions */
void Draw(WinEDA_DrawPanel * panel, wxDC * DC, wxPoint offset, int draw_mode);
/* locate functions */
int Locate(const wxPoint & posref);
};
| [
"bokeoa@244deca0-f506-0410-ab94-f4f3571dea26"
]
| [
[
[
1,
57
]
]
]
|
ce4ad37606e2096c55ef9130b2f512b67f354b01 | a1e5c0a674084927ef5b050ebe61a89cd0731bc6 | /OpenGL_SceneGraph_Stussman/Code/Aufgabe1/main.cpp | 870a4897eaf94356edc0d6d3a45a91d184623efb | []
| no_license | danielkummer/scenegraph | 55d516dc512e1b707b6d75ec2741f48809d8797f | 6c67c41a38946ac413333a84c76340c91b87dc96 | refs/heads/master | 2016-09-01T17:36:02.995636 | 2008-06-05T09:45:24 | 2008-06-05T09:45:24 | 32,327,185 | 0 | 0 | null | null | null | null | ISO-8859-3 | C++ | false | false | 6,040 | cpp | /**************************************************/
/* */
/* Main Sorucecode Aufgabe 1 */
/* */
/**************************************************/
/* Authors: Reto Bollinger */
/* [email protected] */
/* */
/* Hanspeter Brühlmann */
/* [email protected] */
/* */
/**************************************************/
/* Date: 15. October 2004 */
/**************************************************/
#include "main.h"
#include "draw.h"
/**************************************************/
/* Variable definition */
/**************************************************/
int width = 1024; // Dimensions of our window
int height = 768;
bool fullscreen = false; // Fullscreen or windowed mode
/**************************************************/
/* Exit */
/**************************************************/
void quit_program( int code )
{
SDL_Quit( ); // Quit SDL and restore previous video stettings
exit( code ); // Exit program
}
/**************************************************/
/* Poll keyevents */
/**************************************************/
void process_events( )
{
SDL_Event event; // SDL event placeholder
while( SDL_PollEvent( &event ) ) { // Grab all the events off the queue
switch( event.type ) {
case SDL_QUIT: // Handle quit requests (like Ctrl-c)
quit_program( 0 );
break;
case SDL_VIDEORESIZE:
width = event.resize.w;
height = event.resize.h;
glViewport(0, 0, width, height);
break;
case SDL_KEYDOWN:
{ // Handle each Keydown
switch( event.key.keysym.sym ) { // Switch keyvalue
case SDLK_ESCAPE:
quit_program( 0 ); // Quit program
break;
case SDLK_F1:
quit_program( 0 ); // Quit program
break;
case SDLK_F2:
fullscreen = (true==fullscreen) ? false : true;
init_SDL();
init_OpenGL();
glViewport(0, 0, width, height);
break;
default:
break;
}
}
default:
break;
}
}
}
/**************************************************/
/* Init OpenGL */
/* Returnvalue: true if init was successful */
/**************************************************/
bool init_OpenGL( )
{
float ratio = (float) width / (float) height; // Calculate and store the aspect ratio of the display
glMatrixMode( GL_PROJECTION ); // Change to the projection matrix
gluPerspective( 60.0, ratio, 0.1, 1024.0 ); // Set view perspective
glMatrixMode( GL_MODELVIEW ); // Change to the modelview matrix
glEnable(GL_DEPTH_TEST); // Enable hidden surface elimination
return true;
}
/**************************************************/
/* Init SDL */
/* Returnvalue: true if init was successful */
/**************************************************/
bool init_SDL()
{
const SDL_VideoInfo* info = NULL; // Information about the current video settings
int bpp = 0; // Color depth in bits of our window
int flags = 0; // Flags we will pass into SDL_SetVideoMode
if( SDL_Init( SDL_INIT_VIDEO ) < 0 ) // First, initialize SDL's video subsystem (video only)
{
fprintf( stderr, "Video initialization failed: %s\n",
SDL_GetError( ) );
quit_program( 1 ); // Failed, exit
}
info = SDL_GetVideoInfo( ); // Get some video information
if( !info ) // This should probably never happen
{
fprintf( stderr, "Video query failed: %s\n", SDL_GetError( ) );
return false;
}
bpp = info->vfmt->BitsPerPixel; // Get color depth
SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 8 ); // Sets the color-depth of the red, green and blue color-part
SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 8 ); // to 8bit (standard today)
SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 8 );
SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 ); // Set depth buffer
SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); // Sets wether to enable or disable doublebuffering
flags = SDL_OPENGL | SDL_RESIZABLE; // Set flags for SDL OpenGL
if (fullscreen){
flags = flags | SDL_FULLSCREEN; // Set flag for fullscreen or windowed mode
}
if( SDL_SetVideoMode( width, height, bpp, flags ) == 0 ) // Set the video mode
{ // If failed, print error message
fprintf( stderr, "Video mode set failed: %s\n", SDL_GetError( ) );
return false;
}
return true;
}
/**************************************************/
/* Main */
/* Returnvalue: 0 if main was successful */
/**************************************************/
int main( int argc, char* argv[] )
{
if(!init_SDL( )) // If intialising of SDL fails -> quit the program with error code 1
{
quit_program( 1 );
}
if(!init_OpenGL()) // If intialising of OpenGL fails -> quit the program with error code 1
{
quit_program( 1 );
}
while(true) // Repeat forever
{
draw_screen(); // Draw your graphics
process_events( ); // Process any ocuring events
}
quit_program(0); // You shouldn't get here. Only if someone changes the while condition...
}
| [
"dr0iddr0id@fe886383-234b-0410-a1ab-e127868e2f45"
]
| [
[
[
1,
179
]
]
]
|
68d91c36ae6cb3c2d0e9cc2451566d1a6829151b | 1c80a726376d6134744d82eec3129456b0ab0cbf | /Project/C++/POJ/最小生成树/最小生成树.cpp | 7efea6135fd4a6864a354286e2782e4c3d04632b | []
| no_license | dabaopku/project_pku | 338a8971586b6c4cdc52bf82cdd301d398ad909f | b97f3f15cdc3f85a9407e6bf35587116b5129334 | refs/heads/master | 2021-01-19T11:35:53.500533 | 2010-09-01T03:42:40 | 2010-09-01T03:42:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,069 | cpp | #include "stdio.h"
#include "iostream"
#include "string"
using namespace std;
# define MaxSize 2005
# define MaxPath 10005
struct node
{
node * parent;
};
struct path
{
int a,b;
int len;
};
int cmp(const void *a,const void *b)
{
path * pa, *pb;
pa=(path*)a;
pb=(path*)b;
return pa->len - pb->len ;
}
int main()
{
int n,m;
int i,j;
int max=0;
node pt[MaxSize];
path pa[MaxPath];
node *root1,*root2;
cin>>n>>m;
for(i=0;i<m;i++){
cin>>pa[i].a>>pa[i].b>>pa[i].len;
}
qsort(pa,m,sizeof(path),cmp);
for(i=1;i<=n;i++)
pt[i].parent=NULL;
for(i=0;i<m;i++){
node * na, *nb;
na=&pt[pa[i].a];
nb=&pt[pa[i].b];
while(na->parent) na=na->parent;
while(nb->parent) nb=nb->parent;
if(na==nb) continue;
root1=na;
nb->parent=na;
na=&pt[pa[i].a];
while(na->parent) {
root2=na->parent;
na->parent=root1;
na=root2;
}
na=&pt[pa[i].b];
while(na->parent) {
root2=na->parent;
na->parent=root1;
na=root2;
}
if(pa[i].len>max) max=pa[i].len;
}
cout<<max<<endl;
} | [
"[email protected]@592586dc-1302-11df-8689-7786f20063ad"
]
| [
[
[
1,
63
]
]
]
|
504328e3a7ea3b8bc517a4936025fc6410b89d6c | 74c8da5b29163992a08a376c7819785998afb588 | /NetAnimal/Game/wheel/MyWheelDirector/src/TableComponentKey.cpp | 644f2a1c5bd02704326872f036bb634d8c65cb13 | []
| no_license | dbabox/aomi | dbfb46c1c9417a8078ec9a516cc9c90fe3773b78 | 4cffc8e59368e82aed997fe0f4dcbd7df626d1d0 | refs/heads/master | 2021-01-13T14:05:10.813348 | 2011-06-07T09:36:41 | 2011-06-07T09:36:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 911 | cpp | #include "MyWheelDirectorStableHeaders.h"
#include "TableComponentKey.h"
#include "F5TableInterface.h"
#include "F5Table.h"
#include "F6Table.h"
using namespace Orz;
TableComponentKey::~TableComponentKey(void)
{
Orz::IInputManager::getSingleton().removeKeyListener(this);
}
bool TableComponentKey::onKeyPressed(const KeyEvent & evt)
{
//switch(evt.getKey())
//{
//case Orz::KC_P:
// F5Table::getInstancePtr()->pushCoin(F5TableInterface::_1,1);
// break;
//case Orz::KC_L:
// F5Table::getInstancePtr()->popCoin(F5TableInterface::_1,1);
// break;
//}
return false;
}
bool TableComponentKey::onKeyReleased(const KeyEvent & evt)
{
return false;
}
TableComponentKey::TableComponentKey(void)
{
Orz::IInputManager::getSingleton().addKeyListener(this);
}
ComponentInterface * TableComponentKey::_queryInterface(const TypeInfo & info)
{
return NULL;
}
| [
"[email protected]"
]
| [
[
[
1,
44
]
]
]
|
4392010b40f2a6d80fd2c4bef77c04e961878670 | dc4f8d571e2ed32f9489bafb00b420ca278121c6 | /mojo_engine/cFinder_receive.cpp | de27cbf63c0e71b0e154baaa5234f4d636b8b3d8 | []
| no_license | mwiemarc/mojoware | a65eaa4ec5f6130425d2a1e489e8bda4f6f88ec0 | 168a2d3a9f87e6c585bde4a69b97db53f72deb7f | refs/heads/master | 2021-01-11T20:11:30.945122 | 2010-01-25T00:27:47 | 2010-01-25T00:27:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,409 | cpp | /***********************************************************************************************************************
/*
/* cFinder_receive.cpp / mojo_engine
/*
/* Copyright 2009 Robert Sacks. See end of file for more info.
/*
/**********************************************************************************************************************/
#include "stdafx.h"
#include "cFinder.h"
#include <process.h>
#include "cPool.h"
using namespace mojo;
//======================================================================================================================
// DATA
//======================================================================================================================
extern cPool g_Pool;
//======================================================================================================================
// PROTOTYPES
//======================================================================================================================
bool get_broadcast_addresses ( tArray<DWORD> * );
bool get_ip_addresses ( cArrayU * );
bool get_best_ip ( DWORD * pdwFromIP, DWORD dwDestIP );
//======================================================================================================================
// CODE
//======================================================================================================================
//----------------------------------------------------------------------------------------------------------------------
// RECEIVE
//----------------------------------------------------------------------------------------------------------------------
bool cFinder :: receive ()
{
SOCKET ReceiveSocket;
make_receive_socket ( &ReceiveSocket );
for ( ;; )
{
if ( ! g_Settings.bConnect )
{
Sleep ( 5000 );
continue;
}
char acBuf [ 2000 ];
SOCKADDR_IN sinRemote;
int iRemoteSize = sizeof ( sinRemote );
//--------------------------------------------------
// RECEIVE DATAGRAM (THREAD WAITS HERE)
//--------------------------------------------------
int iResult = recvfrom ( ReceiveSocket, acBuf, sizeof(acBuf)-1, 0, (SOCKADDR *) &sinRemote, &iRemoteSize );
if ( iResult == SOCKET_ERROR )
{
LOG_SYSTEM_ERROR_TE ( L"recvfrom", WSAGetLastError() );
continue;
}
//--------------------------------------------------
// HAS "ONE PC" BEEN SELECTED SINCE WE STARTED
// LISTENING?
//--------------------------------------------------
if ( ! g_Settings.bConnect ) // added dec 8 2009 without testing
{
continue;
}
//--------------------------------------------------
// WAS SOMETHING VALID RECEIVED?
//--------------------------------------------------
else if ( 0 < iResult )
{
const wchar_t * pRemoteName = 0, * pDisplayList = 0, * pRemoteAppTitle;
cVersion * pRemoteVersion;
acBuf [ iResult ] = '\0';
DWORD dwRemoteIP = *(DWORD*) &sinRemote.sin_addr;
//--------------------------------------------------
// PARSE AND CHECK SIGNATURE
//--------------------------------------------------
if ( ! cSignature::parse ( &pDisplayList, &pRemoteName, &pRemoteAppTitle, &pRemoteVersion, acBuf ) )
{
LOG ( L"Bad signature (non-matching engine name) received by cFinder." );
continue;
}
//--------------------------------------------------
// CHECK FOR CORRECT VERSION
//--------------------------------------------------
else if ( *pRemoteVersion != g_Version )
{
cStrW sIP;
mojo::ip_dword_to_cStrW ( &sIP, dwRemoteIP );
mojo::put_ad_lib_memo ( cMemo::error, L"Cannot connect", L"Cannot connect to %s because it's running a different version of %s.", sIP.cstr(), g_sAppTitle.cstr() );
continue;
}
//--------------------------------------------------
// IS IT US BASED ON IP?
//--------------------------------------------------
else if ( dwRemoteIP == m_dwLocalIP )
continue;
//--------------------------------------------------
// IS IT US BASED ON NAME?
//--------------------------------------------------
if ( 0 == wcscmp ( pRemoteName, sLocalName.cstr() ) )
continue;
//--------------------------------------------------
// IS IT A KNOWN REMOTE?
//--------------------------------------------------
else if ( cMach * p = g_Machlist.get_by_ip ( dwRemoteIP ) )
{
//-----------------------------------
// SET NAME IF IT WASN'T KNOWN
//-----------------------------------
if ( 0 == p->sName.len() )
{
p->lock();
p->sName = pRemoteName;
p->unlock();
}
//-----------------------------------
// IF NECESSARY, SEND
// TCP CONNECTION REQUEST
//-----------------------------------
if ( ! g_Pool.get_connect_socket_info_by_ip ( dwRemoteIP ) )
{
g_Pool.connect_to ( dwRemoteIP );
}
}
//--------------------------------------------------
// FINALLY, WE KNOW THAT IT'S AN UNKNOWN PC
//--------------------------------------------------
else
{
g_Pool.connect_to ( dwRemoteIP );
//--------------------------------------------
// ADD THE NEW REMOTE MACHINE TO MACH LIST
//--------------------------------------------
{
cMach * pNewMach = g_Machlist.get_by_ip_or_add ( dwRemoteIP, pDisplayList );
pNewMach->lock();
pNewMach->dwIP = dwRemoteIP;
pNewMach->sName = pRemoteName;
pNewMach->unlock();
}
}
}
}
}
//----------------------------------------------------------------------------------------------------------------------
// MAKE RECEIVE SOCKET
//----------------------------------------------------------------------------------------------------------------------
bool cFinder :: make_receive_socket ( SOCKET * pRet )
{
SOCKET ReceiveSocket;
SOCKADDR_IN sinLocal;
ReceiveSocket = socket ( AF_INET, SOCK_DGRAM, 0 );
if ( ReceiveSocket == INVALID_SOCKET )
{
LOG_SYSTEM_ERROR_TE ( L"socket", WSAGetLastError() );
*pRet = INVALID_SOCKET;
return false;
}
sinLocal.sin_family = AF_INET;
sinLocal.sin_port = htons((short) g_Settings.uPort );
sinLocal.sin_addr.s_addr = htonl(INADDR_ANY);
if ( bind ( ReceiveSocket, ( SOCKADDR * ) &sinLocal, sizeof ( sinLocal ) ) == SOCKET_ERROR )
{
DWORD dwError = WSAGetLastError();
if ( WSAEADDRINUSE == dwError ) // 10048 means port in use
{
mojo::put_ad_lib_memo ( mojo::cMemo::error,
L"The program is trying to use a port that is already in use.",
L"Select a different port on Connections Settings, More Options." );
}
LOG_SYSTEM_ERROR_TE ( L"bind", dwError );
*pRet = INVALID_SOCKET;
return false;
}
*pRet = ReceiveSocket;
return true;
}
/***********************************************************************************************************************
/*
/* This file is part of Mojo. For more information, see http://mojoware.org.
/*
/* You may redistribute and/or modify Mojo under the terms of the GNU General Public License, version 3, as
/* published by the Free Software Foundation. You should have received a copy of the license with Mojo. If you
/* did not, go to http://www.gnu.org.
/*
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
/* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
/* IN NO EVENT SHALL THE COPYRIGHT HOLDER 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.
/*
/***********************************************************************************************************************/ | [
"[email protected]"
]
| [
[
[
1,
236
]
]
]
|
f201f60d37beec182c1ce3bcd2514f936e887f0e | 3e69b159d352a57a48bc483cb8ca802b49679d65 | /tags/release-2006-01-16/eeschema/component_class.h | 93a70e2c9c4c30d788e5a78366b12bd6c9f858ea | []
| no_license | BackupTheBerlios/kicad-svn | 4b79bc0af39d6e5cb0f07556eb781a83e8a464b9 | 4c97bbde4b1b12ec5616a57c17298c77a9790398 | refs/heads/master | 2021-01-01T19:38:40.000652 | 2006-06-19T20:01:24 | 2006-06-19T20:01:24 | 40,799,911 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,786 | h | /*****************************************************/
/* Definitions for the Component classes for EESchema */
/*****************************************************/
#ifndef COMPONENT_CLASS_H
#define COMPONENT_CLASS_H
#ifndef eda_global
#define eda_global extern
#endif
#include "macros.h"
#include "base_struct.h"
/* Definition de la representation du composant */
#define NUMBER_OF_FIELDS 12 /* Nombre de champs de texte affectes au composant */
typedef enum
{
REFERENCE = 0, /* Champ Reference of part, i.e. "IC21" */
VALUE, /* Champ Value of part, i.e. "3.3K" */
FOOTPRINT, /* Champ Name Module PCB, i.e. "16DIP300" */
SHEET_FILENAME, /* Champ Name Schema component, i.e. "cnt16.sch" */
FIELD1,
FIELD2,
FIELD3,
FIELD4,
FIELD5,
FIELD6,
FIELD7,
FIELD8
} NumFieldType;
/* Class to manage component fields.
component fields are texts attached to the component (not the graphic texts)
There are 2 major fields : Reference and Value
*/
class PartTextStruct: public EDA_BaseStruct, public EDA_TextStruct
{
public:
int m_FieldId;
public:
PartTextStruct(const wxPoint & pos = wxPoint(0,0), const wxString & text = wxEmptyString);
~PartTextStruct(void);
void PartTextCopy(PartTextStruct * target);
void Place(WinEDA_DrawFrame * frame, wxDC * DC);
EDA_Rect GetBoundaryBox(void);
bool IsVoid();
};
/* the class DrawPartStruct describes a basic virtual component
Not used directly:
used classes are EDA_SchComponentStruct (the "classic" schematic component
and the Pseudo component DrawSheetStruct
*/
class DrawPartStruct: public EDA_BaseStruct
{
public:
wxString m_ChipName; /* Key to look for in the library, i.e. "74LS00". */
PartTextStruct m_Field[NUMBER_OF_FIELDS];
wxPoint m_Pos; /* Exact position of part. */
public:
DrawPartStruct( DrawStructureType struct_type, const wxPoint & pos);
~DrawPartStruct(void);
static wxString ReturnFieldName(int FieldNumber);
};
/* the class EDA_SchComponentStruct describes a real component */
class EDA_SchComponentStruct: public DrawPartStruct
{
public:
int m_Multi; /* In multi unit chip - which unit to draw. */
int m_FlagControlMulti;
int m_Convert; /* Gestion des mutiples representations (ex: conversion De Morgan) */
int m_Transform[2][2]; /* The rotation/mirror transformation matrix. */
bool * m_PinIsDangling; // liste des indicateurs de pin non connectee
public:
EDA_SchComponentStruct(const wxPoint & pos = wxPoint(0,0));
~EDA_SchComponentStruct(void){}
EDA_SchComponentStruct * GenCopy(void);
void SetRotationMiroir( int type );
int GetRotationMiroir(void);
wxPoint GetScreenCoord(const wxPoint & coord);
void Display_Infos(WinEDA_DrawFrame * frame);
void ClearAnnotation(void);
EDA_Rect GetBoundaryBox( void );
};
#endif /* COMPONENT_CLASS_H */
| [
"bokeoa@244deca0-f506-0410-ab94-f4f3571dea26"
]
| [
[
[
1,
98
]
]
]
|
5e6f5f12020eef6349828cf41ed86fe1d28b7a6c | d418ee4fc1cea6246e8611b7b162abb03d0cd010 | /nachos-csci402/code/threads/simulationtest.cc | 7b12e0a0ebcfab65cd10ca42778d58a9bbee231a | [
"MIT-Modern-Variant"
]
| permissive | KWarp/cs402gregjustinkevin | 873cf49460f0574402b141e8db348940a86bfaa3 | a56dbfa3ae92c04c377b4cdeed9633ee58a578f8 | refs/heads/master | 2021-01-10T16:44:23.875963 | 2010-12-05T07:29:02 | 2010-12-05T07:29:02 | 53,481,712 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,341 | cc | #ifdef CHANGED
#include "simulation.h"
#include "synch.h"
#include "simulationtest.h"
/* Untested */
void TestCustomer()
{
int numTestCustomers = 1;
for (int i= 0; i < numTestCustomers; ++i)
Fork((int)Customer);
// Get the customers into the restaurant.
for (int i= 0; i < numTestCustomers; ++i)
checkLineToEnterRest();
// Take the customers' orders.
for (int i= 0; i < numTestCustomers; ++i)
serviceCustomer(0);
// Give the customers their orders
for (int token = 0; token < numTestCustomers; ++token)
{
if (ordersNeedingBagging[token] > 0)
{
// If the customer is eat-in.
if (Get_CustomerTogoOrEatinFromCustomerID[Get_CustomerIDFromToken[token]] == 1)
{
// Pretend we are waiter delivering food and signal the eat-in customer directly.
Acquire(lock_CustomerSittingFromCustomerID[Get_CustomerIDFromToken[token]]);
Signal(CV_CustomerSittingFromCustomerID[Get_CustomerIDFromToken[token]],
lock_CustomerSittingFromCustomerID[Get_CustomerIDFromToken[token]]);
Release(lock_CustomerSittingFromCustomerID[Get_CustomerIDFromToken[token]]);
}
else // if customer is togo.
{
// Tell the waiting togo customers that order i is ready.
Acquire(lock_OrCr_OrderReady);
bool_ListOrdersReadyFromToken[token] = 1;
Broadcast(lock_OrCr_OrderReady, CV_OrCr_OrderReady);
Release(lock_OrCr_OrderReady);
}
}
}
}
/* Untested */
void TestWaiter()
{
int token = 12; // Arbitrary order number.
Get_CustomerIDFromToken[token] = 1; // Also arbitrary.
Fork((int)Waiter);
Acquire(lock_OrWr_BaggedOrders);
baggedOrders[count_NumOrdersBaggedAndReady] = 12;
count_NumOrdersBaggedAndReady++;
Signal(CV_OrWr_BaggedOrders, lock_OrWr_BaggedOrders);
Acquire(lock_CustomerSittingFromCustomerID[Get_CustomerIDFromToken[token]]);
Release(lock_OrWr_BaggedOrders);
Wait(CV_CustomerSittingFromCustomerID[Get_CustomerIDFromToken[token]],
lock_CustomerSittingFromCustomerID[Get_CustomerIDFromToken[token]]);
// If we get here, the waiter signaled us correctly.
}
/* Untested */
void TestCook()
{
// Hire a cook for each type of food.
for (int i = 0; i < 5; ++i)
hireCook(i);
// Wait to verify all types of food are being cooked in print statements.
Yield(10000);
// Send all cooks on break.
for (int i = 0; i < 5; ++i)
{
Acquire(lock_MrCk_InventoryLocks[i]);
Get_CookOnBreakFromInventoryIndex[i] = TRUE;
Release(lock_MrCk_InventoryLocks[i]);
}
// Wait to verify no food is being cooked in print statements.
Yield(10000);
// Bring all cooks back from break.
for (int i = 0; i < 5; ++i)
{
Acquire(lock_MrCk_InventoryLocks[i]);
Get_CookOnBreakFromInventoryIndex[i] = FALSE;
Release(lock_MrCk_InventoryLocks[i]);
}
// Wait to verify all types of food are being cooked in print statements.
Yield(10000);
// Deplete the inventory for all food.
for (int i = 0; i < 5; ++i)
{
Acquire(lock_MrCk_InventoryLocks[i]);
inventoryCount[i] = 0;
Release(lock_MrCk_InventoryLocks[i]);
}
// Wait to verify all types of food are being cooked in print statements.
Yield(10000);
}
/* Untested / Unfinished */
void TestOrderTaker()
{
// "Cook" food for the OrderTaker to use.
// Test for an eat-in customer.
int orderCombo = menu[0];
Get_CustomerOrderFoodChoiceFromOrderTakerID[ID_Get_OrderTakerIDFromCustomerID[0]] = menu[orderCombo];
Get_CustomerTogoOrEatinFromCustomerID[0] = 1;
// Create an OrderTaker
Fork((int)OrderTaker);
printf("Customer::Ordering #%d from OrderTaker", orderCombo);
PrintNumber(orderCombo);
PrintOut(" from OrderTaker #", 17);
PrintOut("\n", 1);
Signal(CV_OrderTakerBusy[ID_Get_OrderTakerIDFromCustomerID[0]],
lock_OrderTakerBusy[ID_Get_OrderTakerIDFromCustomerID[0]]);
// Wait for order taker to respond.
Wait(CV_OrderTakerBusy[ID_Get_OrderTakerIDFromCustomerID[0]],
lock_OrderTakerBusy[ID_Get_OrderTakerIDFromCustomerID[0]]);
PrintOut("Customer", 8);
PrintNumber(0);
PrintOut("::Paying OrderTaker #", 21);
PrintNumber(ID_Get_OrderTakerIDFromCustomerID[0]);
PrintOut("\n", 1);
}
/* Untested */
void TestManager()
{
}
/* Untested / Unfinished */
void TestSimulation()
{
Initialize();
TestCustomer();
TestWaiter();
TestCook();
TestOrderTaker();
TestManager();
}
/*
Customers who wants to eat-in, must wait if the restaurant is full.
*/
void Test1CustomerWaitsIfRestaurantFull()
{
PrintOut("Test1::Customers who wants to eat-in, must wait if the restaurant is full.\n",75);
PrintOut("Starting Simulation\n",20);
PrintOut("Initializing...\n",16);
Initialize();
// Set the restaurant as full for test.
count_NumTablesAvailable = 0;
test_AllCustomersEatIn = TRUE;
int numOrderTakers = 0;
int numWaiters = 0;
int numCustomers = 1;
PrintOut("Initialized\n",12);
PrintOut("Running Simulation with:\n",25);
PrintNumber(numOrderTakers);
PrintOut(" OrderTaker(s)\n",15);
PrintNumber(numWaiters);
PrintOut(" Waiter(s)\n",11);
PrintNumber(numCustomers);
PrintOut(" Customer(s)\n",13);
PrintOut("===================================================\n",52);
Fork((int)Manager);
for (int i = 0; i < numOrderTakers; ++i)
Fork((int)OrderTaker);
for (int i = 0; i < numWaiters; ++i)
Fork((int)Waiter);
for (int i = 0; i < numCustomers; ++i)
Fork((int)Customer);
}
/*
OrderTaker/Manager gives order number to the Customer when the food is not ready.
*/
void Test2FoodNotReady()
{
PrintOut("Test2::OrderTaker/Manager gives order number to the Customer when the food is not ready.\n",89);
PrintOut("Starting Simulation\n",20);
PrintOut("Initializing...\n",16);
Initialize();
// Disable cooks so food will never be ready.
test_NoCooks = TRUE;
test_AllCustomersOrderThisCombo = 3;
int numOrderTakers = 1;
int numWaiters = 1;
int numCustomers = 1;
PrintOut("Initialized\n",12);
PrintOut("Running Simulation with:\n",25);
PrintNumber(numOrderTakers);
PrintOut(" OrderTaker(s)\n",15);
PrintNumber(numWaiters);
PrintOut(" Waiter(s)\n",11);
PrintNumber(numCustomers);
PrintOut(" Customer(s)\n",13);
PrintOut("===================================================\n",52);
Fork((int)Manager);
for (int i = 0; i < numOrderTakers; ++i)
Fork((int)OrderTaker);
for (int i = 0; i < numWaiters; ++i)
Fork((int)Waiter);
for (int i = 0; i < numCustomers; ++i)
Fork((int)Customer);
}
/*
Customers who have chosen to eat-in, must leave after they have their food and Customers
who have chosen to-go, must leave the restaurant after the OrderTaker/Manager has given the food.
*/
void Test3CustomerLeavingRestaurant()
{
PrintOut("Test3::Customers who have chosen to eat-in, must leave after they have their food and Customers\nwho have chosen to-go, must leave the restaurant after the OrderTaker/Manager has given the food.\n",194);
RunSimulation(3, 3, 4);
}
/*
Manager maintains the track of food inventory. Inventory is refilled when it goes below order level.
*/
void Test4InventoryTracking()
{
PrintOut("Test4::Manager maintains the track of food inventory. Inventory is refilled when it goes below order level.\n",108);
RunSimulation(3, 3, 20);
}
/*
A Customer who orders only soda need not wait.
*/
void Test5SodaWait()
{
PrintOut("Test5::A Customer who orders only soda need not wait.\n",54);
PrintOut("Starting Simulation\n",20);
PrintOut("Initializing...\n",16);
Initialize();
// Have all customers order a soda.
test_AllCustomersOrderThisCombo = 0;
test_AllCustomersEatOut = TRUE;
int numOrderTakers = 1;
int numWaiters = 1;
int numCustomers = 4;
PrintOut("Initialized\n",12);
PrintOut("Running Simulation with:\n",25);
PrintNumber(numOrderTakers);
PrintOut(" OrderTaker(s)\n",15);
PrintNumber(numWaiters);
PrintOut(" Waiter(s)\n",11);
PrintNumber(numCustomers);
PrintOut(" Customer(s)\n",13);
PrintOut("===================================================\n",52);
Fork((int)Manager);
for (int i = 0; i < numOrderTakers; ++i)
Fork((int)OrderTaker);
for (int i = 0; i < numWaiters; ++i)
Fork((int)Waiter);
for (int i = 0; i < numCustomers; ++i)
Fork((int)Customer);
}
/*
The OrderTaker and the Manager both somethimes bag the food.
*/
void Test6ManagerBagsFood()
{
PrintOut("Test6::The OrderTaker and the Manager both somethimes bag the food.\n",68);
RunSimulation(1, 1, 40);
}
/*
Manager goes to the bank for cash when inventory is to be refilled and there is no cash in the restaurant.
*/
void Test7BankTrip()
{
PrintOut("Test7::Manager goes to the bank for cash when inventory is to be refilled and there is no cash in the restaurant.\n",114);
RunSimulation(3, 3, 40);
}
/*
Cooks goes on break when informed by manager.
*/
void Test8CookBreak()
{
PrintOut("Test8::Cooks goes on break when informed by manager.\n",53);
RunSimulation(1, 1, 1);
}
#endif
| [
"[email protected]",
"lewij3@64a47c91-1020-2430-03ac-642e8966e14f"
]
| [
[
[
1,
13
],
[
15,
324
]
],
[
[
14,
14
]
]
]
|
d79a078037d9decdeee4b035d4821919536aeed7 | 15732b8e4190ae526dcf99e9ffcee5171ed9bd7e | /SRC/Trace_Stats/histograph.cc | 9c8a1b80dca559ccd678ce6d11de887a61c0c316 | []
| no_license | clovermwliu/whutnetsim | d95c07f77330af8cefe50a04b19a2d5cca23e0ae | 924f2625898c4f00147e473a05704f7b91dac0c4 | refs/heads/master | 2021-01-10T13:10:00.678815 | 2010-04-14T08:38:01 | 2010-04-14T08:38:01 | 48,568,805 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,424 | cc | //Copyright (c) 2010, Information Security Institute of Wuhan Universtiy(ISIWhu)
//All rights reserved.
//
//PLEASE READ THIS DOCUMENT CAREFULLY BEFORE UTILIZING THE PROGRAM
//BY UTILIZING THIS PROGRAM, YOU AGREE TO BECOME BOUND BY THE TERMS OF
//THIS LICENSE. IF YOU DO NOT AGREE TO THE TERMS OF THIS LICENSE, DO
//NOT USE THIS PROGRAM OR ANY PORTION THEREOF IN ANY FORM OR MANNER.
//
//This License allows you to:
//1. Make copies and distribute copies of the Program's source code provide that any such copy
// clearly displays any and all appropriate copyright notices and disclaimer of warranty as set
// forth in this License.
//2. Modify the original copy or copies of the Program or any portion thereof ("Modification(s)").
// Modifications may be copied and distributed under the terms and conditions as set forth above.
// Any and all modified files must be affixed with prominent notices that you have changed the
// files and the date that the changes occurred.
//Termination:
// If at anytime you are unable to comply with any portion of this License you must immediately
// cease use of the Program and all distribution activities involving the Program or any portion
// thereof.
//Statement:
// In this program, part of the code is from the GTNetS project, The Georgia Tech Network
// Simulator (GTNetS) is a full-featured network simulation environment that allows researchers in
// computer networks to study the behavior of moderate to large scale networks, under a variety of
// conditions. Our work have great advance due to this project, Thanks to Dr. George F. Riley from
// Georgia Tech Research Corporation. Anyone who wants to study the GTNetS can come to its homepage:
// http://www.ece.gatech.edu/research/labs/MANIACS/GTNetS/
//
//File Information:
//
//
//File Name:
//File Purpose:
//Original Author:
//Author Organization:
//Construct Data:
//Modify Author:
//Author Organization:
//Modify Data:
// Georgia Tech Network Simulator - Histograph Class
// George F. Riley. Georgia Tech, Fall 2003
// Defines a Histogram and CDF statistics collection
// and displays graphically using Qt.
#include <iostream>
#include "G_debug.h"
#include "histograph.h"
#ifdef HAVE_QT
#include "GUI_Defs.h"
#endif
using namespace std;
Histograph::Histograph()
: Histogram(), initialized(false), showCDF(false),
updateRate(1), updateCountdown(1)
#ifdef HAVE_QT
, app(nil), canvas(nil), view(nil)
#endif
{
}
Histograph::Histograph(double m)
: Histogram(m), initialized(false), showCDF(false),
updateRate(1), updateCountdown(1),
canvasXY(nil), app(nil), canvas(nil), view(nil),
textRect(nil)
{
}
Histograph::Histograph(double m, Count_t b, double mn)
: Histogram(m, b, mn), initialized(false), showCDF(false),
updateRate(1), updateCountdown(1),
canvasXY(nil), app(nil), canvas(nil), view(nil),
textRect(nil)
{
}
Histograph::Histograph(const Histograph& c) // Copy constructor
: Histogram(c), initialized(false), showCDF(c.showCDF),
updateRate(c.updateRate), updateCountdown(c.updateRate),
canvasXY(nil), app(nil), canvas(nil), view(nil),
textRect(nil)
{
}
Histograph::~Histograph()
{
#ifdef HAVE_QT
if (app) delete app;
#endif
}
Statistics* Histograph::Copy() const // Make a copy of the histograph
{
return new Histograph(*this);
}
void Histograph::UpdateRate(Count_t c )
{
updateRate = c;
}
// Overridden methods from Histogram
bool Histograph::Record(double v)
{
bool r = Histogram::Record(v);
if (!updateCountdown || --updateCountdown == 0)
{ // Time to update
if (showCDF)
{
UpdateCDF();
}
else
{
UpdateHisto();
}
updateCountdown = updateRate;
}
return r;
}
void Histograph::Reset()
{
Histogram::Reset();
if (showCDF)
{
UpdateCDF();
}
else
{
UpdateHisto();
}
}
// Private methods
void Histograph::UpdateCDF()
{
#ifdef HAVE_QT
if (!initialized) Initialize();
Count_t total = 0;
Count_t nBins = bins.size();
for (Count_t i = 0; i < nBins; ++i)
{
total += bins[i];
}
total += outOfRange;
double x = textRect->width(); // Initial x coordinate
double xAdder = (double)(canvasXY->x() - textRect->width()) / bins.size();
Count_t cumulative = 0;
Count_t usableY = canvasXY->y() - (int)(textRect->height() * 1.5);
MyPoint prior((int)x, canvasXY->y() - (int)(textRect->height()));
for (Count_t i = 0; i < nBins; ++i)
{ // Draw the cdf
if (items.size() <= i)
{ // too small, add empty
items.push_back(nil);
}
cumulative += bins[i];
x += xAdder;
double height = (double)cumulative / total * usableY;
MyPoint p1((int)x, (int)(canvasXY->y()-int(textRect->height())-height));
// check if same, and if so don't change (code later)
if (items[i]) delete items[i];
MyCanvasLine* l = new MyCanvasLine(canvas);
items[i] = l;
l->setPoints(prior.x(), prior.y(), p1.x(), p1.y());
l->setPen(QPen(Qt::black));
l->show();
prior = p1;
}
// Draw the registration lines
const Count_t n = 10;
for (Count_t i = 0; i <= n; ++i)
{
double v = (double)i / n;
Count_t h = (Count_t)(usableY * v);
// labels and lines always same size, so we take a shortcut here
if (i < labels.size())
{
delete labels[i];
delete lines[i];
}
else
{
labels.push_back(nil);
lines.push_back(nil);
}
QString qs = QString("%1").arg(v);
labels[i] = new MyCanvasText(qs, canvas);
labels[i]->moveBy(0,
canvasXY->y() - (int)(textRect->height()*1.5) - h);
labels[i]->show();
lines[i] = new MyCanvasLine(canvas);
lines[i]->setPen(QPen(Qt::lightGray));
lines[i]->setPoints(textRect->width(),
canvasXY->y() - (int)(textRect->height()) - h,
canvasXY->x(),
canvasXY->y() - (int)(textRect->height()) - h);
lines[i]->show();
}
canvas->update(); // Show the updates
while(app->hasPendingEvents())
{
app->processEvents( );
}
#endif
}
void Histograph::UpdateHisto()
{
#ifdef HAVE_QT
if (!initialized) Initialize();
if (bins.size())
{ // If bins not empty
Count_t largest = 0;
for (Count_t i = 0; i < bins.size(); ++i)
{
if (bins[i] > largest) largest = bins[i];
}
// Compute height of each bar
Count_t nBins = bins.size();
Count_t usableY = canvasXY->y() - (int)(textRect->height() * 1.5);
for (Count_t b = 0; b < nBins; ++b)
{
Count_t height = (Count_t)(usableY * (bins[b]/(double)largest));
DEBUG0((cout << "Height of bin " << b << " is " << height << endl));
MyCanvasRectangle* rect = (MyCanvasRectangle*)items[b];
rect->setSize(rect->width(), -height);
}
// Draw the registration lines and labels
Count_t n = 10;
if (largest < n) n = largest;
double each = (double)largest / n;
for (Count_t i = 0; i <= n; ++i)
{
double v = each * i;
Count_t h = (Count_t)(usableY * v / largest);
Count_t intV = (Count_t)v;
// labels and lines always same size, so we take a shortcut here
if (i < labels.size())
{
delete labels[i];
delete lines[i];
}
else
{
labels.push_back(nil);
lines.push_back(nil);
}
QString qs = QString("%1").arg(intV);
labels[i] = new MyCanvasText(qs, canvas);
labels[i]->moveBy(textRect->width() -
labels[i]->boundingRect().width(),
canvasXY->y() - (int)(textRect->height()*1.5) - h);
labels[i]->show();
lines[i] = new MyCanvasLine(canvas);
lines[i]->setPen(QPen(Qt::lightGray));
lines[i]->setPoints(textRect->width(),
canvasXY->y() - (int)(textRect->height()) - h,
canvasXY->x(),
canvasXY->y() - (int)(textRect->height()) - h);
lines[i]->show();
}
canvas->update(); // Show the updates
}
while(app->hasPendingEvents())
{
app->processEvents( );
}
#endif
}
void Histograph::Initialize()
{
#ifdef HAVE_QT
int argc = 1;
char* argv[] = { "GTNetS", nil};
app = new MyApplication(argc, argv);
canvasXY = new MyPoint(640, 640);
QString qs;
if (showCDF)
{
qs = QString("%1").arg(0.9);
}
else
{
qs = QString("%1").arg(12345);
}
// Fudge the Y size by one and a half times
// text height. This allows for a bottom row
// of box labels and half of the x-axis label
// on top
MyCanvasText txt(qs, canvas);
textRect = new MyRect(txt.boundingRect());
canvasXY->setY(canvasXY->y() + (int)(textRect->height() * 1.5));
// Adjust x by size of left side labels
canvasXY->setX(canvasXY->x() + textRect->width());
Count_t xAdder = 0;
if (showCDF)
{ // Need to finish coding this...
}
else
{
// xAdder is width of each bar (integer pixels)
xAdder = (canvasXY->x() - textRect->width()) / bins.size();
// Since possibly not evenly divisible, resize canvas
// to be correct size. Fudge two extra pixels
xAdder+=2; // two extra pixels between bars
//canvasXY->setX(textRect->width() + xAdder * bins.size() + xAdder);
// And fudge the X size by the width of a 5 digit label
canvasXY->setX(textRect->width() + xAdder * bins.size() + 4); // + 4???
}
// Create the canvas
canvas = new MyCanvas(canvasXY->x()-4, canvasXY->y());
canvas->setDoubleBuffering(true);
// Create the bars for the histogram or lines for CDF
for (Count_t i = 0; i < bins.size(); ++i)
{
if (showCDF)
{
MyCanvasLine* cp = new MyCanvasLine(canvas);
items.push_back(cp);
// Will set endpoints later
}
else
{
MyCanvasRectangle* cp = new MyCanvasRectangle(canvas);
// Set zero height for now, will adjust later
cp->setSize(xAdder, 0);
// And move to correct position
cp->moveBy(textRect->width() + xAdder * i,
canvasXY->y() - textRect->height());
cp->setPen(QPen(Qt::black));
cp->setBrush(QBrush(Qt::red));
cp->show();
items.push_back(cp);
}
}
view = new MyCanvasView(canvas);
//view->setHScrollBarMode(QScrollView::AlwaysOff);
//view->setVScrollBarMode(QScrollView::AlwaysOff);
view->resize(canvasXY->x(), canvasXY->y());
view->show();
app->setMainWidget(view);
while(app->hasPendingEvents())
{
app->processEvents( );
}
#endif
initialized = true;
}
| [
"pengelmer@f37e807c-cba8-11de-937e-2741d7931076"
]
| [
[
[
1,
375
]
]
]
|
42889a07c20f1f6f0a58b45cf1b85acbd200e69f | a405cf24ef417f6eca00c688ceb9008d80f84e1a | /trunk/FileContent.h | ce64656b096e4d86ce6746e68a9bbd4db0f24142 | []
| no_license | BackupTheBerlios/nassiplugin-svn | 186ac2b1ded4c0bf7994e6309150aa23bc70b644 | abd9d809851d58d7206008b470680a23d0548ef6 | refs/heads/master | 2020-06-02T21:23:32.923994 | 2010-02-23T21:37:37 | 2010-02-23T21:37:37 | 40,800,406 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,417 | h | #ifdef __GNUG__
// #pragma interface
#endif
#ifndef __FILE_CONTENT__
#define __FILE_CONTENT__
#include <wx/stream.h>
#include <set>
class FileContentObserver
{
public:
FileContentObserver();
virtual ~FileContentObserver();
virtual void Update(wxObject* hint) = 0;
};
class wxCommandProcessor;
class FileContent
{
public:
FileContent();
virtual ~FileContent(void);
virtual wxCommandProcessor* CreateCommandProcessor();
wxCommandProcessor* GetCommandProcessor();
bool Save(const wxString &filename);
bool Open(const wxString &filename);
bool GetModified();
void SetModified( bool modified );
void Modify( bool modified );
void NotifyObservers(wxObject* hint = NULL);
bool IsReadOnly();
virtual wxOutputStream& SaveObject(wxOutputStream& stream) = 0;
virtual wxInputStream& LoadObject(wxInputStream& stream) = 0;
//bool IsReadOnly();
virtual wxString GetWildcard() = 0;
private:
FileContent(const FileContent &rhs);
FileContent &operator=(const FileContent &rhs);
public:
void AddObserver(FileContentObserver *a);
void RemoveObserver(FileContentObserver *a);
private:
std::set<FileContentObserver *> observers;
// bool m_readOnly;
bool m_modified;
wxCommandProcessor *m_cmdProc;
//wxString m_filename;
};
#endif //__CB_FILE_CONTENT__
| [
"danselmi@1ca45b2e-1973-0410-a226-9012aad761af"
]
| [
[
[
1,
63
]
]
]
|
9eb569f9eb5211a2f4176e96ae7a46b0f7b8ea0d | b4bff7f61d078e3dddeb760e21174a781ed7f985 | /Source/Contrib/Video/src/VLC/OSGVLCManager.inl | d0406cc4ea9f16b835259612fc5362ec025f1ec7 | []
| no_license | Langkamp/OpenSGToolbox | 8283edb6074dffba477c2c4d632e954c3c73f4e3 | 5a4230441e68f001cdf3e08e9f97f9c0f3c71015 | refs/heads/master | 2021-01-16T18:15:50.951223 | 2010-05-19T20:24:52 | 2010-05-19T20:24:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,314 | inl | /*---------------------------------------------------------------------------*\
* OpenSG ToolBox Video *
* *
* *
* *
* *
* www.vrac.iastate.edu *
* *
* Authors: David Kabala, Daniel Guilliams *
* *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
* License *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Library General Public License as published *
* by the Free Software Foundation, version 2. *
* *
* This library is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *
* *
\*---------------------------------------------------------------------------*/
#include "OSGVLCManager.h"
OSG_BEGIN_NAMESPACE
OSG_END_NAMESPACE
| [
"[email protected]"
]
| [
[
[
1,
32
]
]
]
|
9d99b770d23e9ccc5761d464d861cf05b6aeca8f | 16ba8e891c084c827148d9c6cd6981a29772cb29 | /KaraokeMachine/trunk/tools/KMPackageBuilder/src/PBDoc.cpp | 83ed840ef802d70be7e84ec75dd1ef9131560202 | []
| no_license | RangelReale/KaraokeMachine | efa1d5d23d0759762f3d6f590e114396eefdb28a | abd3b05d7af8ebe8ace15e888845f1ca8c5e481f | refs/heads/master | 2023-06-29T20:32:56.869393 | 2008-09-16T18:09:40 | 2008-09-16T18:09:40 | 37,156,415 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,403 | cpp |
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
#include "PBDoc.h"
#include "PBView.h"
IMPLEMENT_DYNAMIC_CLASS(PBSongDocument, wxDocument)
PBSongDocument::~PBSongDocument(void)
{
}
bool PBSongDocument::OnNewDocument()
{
SetTitle(wxT("New song"));
return true;
}
bool PBSongDocument::OnSaveDocument(const wxString& filename)
{
songpackage_.Save(std::string(filename.mb_str(wxConvUTF8)));
Modify(false);
return true;
}
bool PBSongDocument::OnOpenDocument(const wxString& filename)
{
songpackage_.Load(std::string(filename.mb_str(wxConvUTF8)));
UpdateAllViews();
Modify(false);
return true;
}
/*
bool PBSongDocument::IsModified(void) const
{
return false;
}
void PBSongDocument::Modify(bool mod)
{
}
*/
IMPLEMENT_DYNAMIC_CLASS(PBImageDocument, wxDocument)
PBImageDocument::~PBImageDocument(void)
{
}
bool PBImageDocument::OnNewDocument()
{
SetTitle(wxT("New Image"));
return true;
}
bool PBImageDocument::OnSaveDocument(const wxString& filename)
{
imagepackage_.Save(std::string(filename.mb_str(wxConvUTF8)));
Modify(false);
return true;
}
bool PBImageDocument::OnOpenDocument(const wxString& filename)
{
imagepackage_.Load(std::string(filename.mb_str(wxConvUTF8)));
UpdateAllViews();
Modify(false);
return true;
}
| [
"hitnrun@6277c508-b546-0410-9041-f9c9960c1249"
]
| [
[
[
1,
77
]
]
]
|
3ebff66357a8ffdd309380ec97cc92ef69f732d7 | d64ed1f7018aac768ddbd04c5b465c860a6e75fa | /DlgProjectOptionsTabbed.h | 45ae5261db121c79afd736fe2dd36c2da5229228 | []
| no_license | roc2/archive-freepcb-codeproject | 68aac46d19ac27f9b726ea7246cfc3a4190a0136 | cbd96cd2dc81a86e1df57b86ce540cf7c120c282 | refs/heads/master | 2020-03-25T00:04:22.712387 | 2009-06-13T04:36:32 | 2009-06-13T04:36:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,614 | h | #pragma once
#include "TabCtrlSSL.h"
#include "Tab_ProjectOpt_Main.h"
#include "Tab_ProjectOpt_Spacing.h"
#include "Tab_ProjectOpt_Thermal.h"
// CDlgProjectOptionsTabbed dialog
class CDlgProjectOptionsTabbed : public CDialog
{
DECLARE_DYNAMIC(CDlgProjectOptionsTabbed)
public:
CDlgProjectOptionsTabbed(CWnd* pParent = NULL); // standard constructor
virtual ~CDlgProjectOptionsTabbed();
// Dialog Data
enum { IDD = IDD_PROJECT_OPTIONS_TABBED };
class CTabs : public CTabCtrlSSL
{
public:
CTab_ProjectOpt_Main m_Tab_Main;
CTab_ProjectOpt_Spacing m_Tab_Spacing;
CTab_ProjectOpt_Thermal m_Tab_Thermal;
BOOL m_new_project;
};
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
virtual BOOL OnInitDialog();
CTabs m_tabs;
friend CTab_ProjectOpt_Main;
friend CTab_ProjectOpt_Spacing;
friend CTab_ProjectOpt_Thermal;
DECLARE_MESSAGE_MAP()
public:
void Init( BOOL new_flag,
CString * name,
CString * path_to_folder,
CString * lib_folder,
int num_layers,
int ratline_w,
BOOL bSMT_connect_copper,
int glue_w,
CNetWidthInfo const &width,
int hole_clearance,
int auto_interval,
int thermal_width,
int thermal_clearance,
CArray<int> * w,
CArray<int> * v_w,
CArray<int> * v_h_w );
CString GetName() const { return m_tabs.m_Tab_Main.m_name; };
CString GetPathToFolder() const { return m_tabs.m_Tab_Main.m_path_to_folder; };
CString GetLibFolder() const { return m_tabs.m_Tab_Main.m_lib_folder; };
int GetNumCopperLayers() const { return m_tabs.m_Tab_Main.m_layers; };
int GetRatlineWidth() const { return m_tabs.m_Tab_Main.m_ratline_w; };
int GetAutoInterval() const { return m_tabs.m_Tab_Main.m_auto_interval; };
int GetGlueWidth() const { return m_tabs.m_Tab_Main.m_glue_w; };
BOOL Get_bSMT_connect_copper() const { return m_tabs.m_Tab_Main.m_bSMT_connect_copper; }
int GetTraceWidth() const { return m_tabs.m_Tab_Spacing.m_trace_w; };
int GetCopperAreaClearance() const { return m_tabs.m_Tab_Spacing.m_ca_clearance_trace; };
int GetHoleClearance() const { return m_tabs.m_Tab_Spacing.m_ca_clearance_hole; }
int GetViaWidth() const { return m_tabs.m_Tab_Spacing.m_via_w; };
int GetViaHoleWidth() const { return m_tabs.m_Tab_Spacing.m_hole_w; };
int GetThermalWidth() const { return m_tabs.m_Tab_Thermal.m_TR_line_w; }
int GetThermalClearance() const { return m_tabs.m_Tab_Thermal.m_TR_clearance; }
};
| [
"jamesdily@9bfb2a70-7351-0410-8a08-c5b0c01ed314"
]
| [
[
[
1,
79
]
]
]
|
c82dd39c9fb87e5e155909bad1cd575d58f7a613 | e7c45d18fa1e4285e5227e5984e07c47f8867d1d | /Scada/ScdOPC/Client/OPC ClientDoc.cpp | 3cfed56adfb6c18f15701ba36ac299004bf5059d | []
| no_license | abcweizhuo/Test3 | 0f3379e528a543c0d43aad09489b2444a2e0f86d | 128a4edcf9a93d36a45e5585b70dee75e4502db4 | refs/heads/master | 2021-01-17T01:59:39.357645 | 2008-08-20T00:00:29 | 2008-08-20T00:00:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 35,881 | cpp | //**************************************************************************
//
// Copyright (c) FactorySoft, INC. 1996-1998, All Rights Reserved
//
//**************************************************************************
//
// Filename : OPC ClientDoc.cpp
// $Author : Jim Hansen
//
// Description: The OPC actions are mostly handled by this Doc.
//
//
//**************************************************************************
#include "stdafx.h"
#include "OPC Client.h"
#include "OPC ClientDoc.h"
#include "OPCServerDlg.h"
#include "ServerStatus.h"
#include "GroupParamsDlg.h"
#include "AddItemDlg.h"
#include "WriteItemDlg.h"
#include "ItemPropertiesDlg.h"
#include "ItemParamsDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
OPCClientDoc* theDoc = NULL;
// The OPC data formats
UINT OPCSTMFORMATDATA = RegisterClipboardFormat(_T("OPCSTMFORMATDATA"));
UINT OPCSTMFORMATDATATIME = RegisterClipboardFormat(_T("OPCSTMFORMATDATATIME"));
UINT OPCSTMFORMATWRITECOMPLETE = RegisterClipboardFormat(_T("OPCSTMFORMATWRITECOMPLETE"));
#define FULL_TEST 1 // define this to test more interfaces
/////////////////////////////////////////////////////////////////////////////
// OPCClientDoc
IMPLEMENT_DYNCREATE(OPCClientDoc, CDocument)
BEGIN_MESSAGE_MAP(OPCClientDoc, CDocument)
//{{AFX_MSG_MAP(OPCClientDoc)
ON_COMMAND(ID_OPC_CONNECT, OnOpcConnect)
ON_UPDATE_COMMAND_UI(ID_OPC_CONNECT, OnUpdateOpcConnect)
ON_COMMAND(ID_OPC_DISCONNECT, OnOpcDisconnect)
ON_UPDATE_COMMAND_UI(ID_OPC_DISCONNECT, OnUpdateOpcDisconnect)
ON_COMMAND(ID_OPC_SERVERSTATUS, OnOpcServerstatus)
ON_UPDATE_COMMAND_UI(ID_OPC_SERVERSTATUS, OnUpdateOpcServerstatus)
ON_COMMAND(ID_OPC_GROUPPARAMETERS, OnOpcGroupparameters)
ON_UPDATE_COMMAND_UI(ID_OPC_GROUPPARAMETERS, OnUpdateOpcGroupparameters)
ON_COMMAND(ID_OPC_ADDITEM, OnOpcAdditem)
ON_UPDATE_COMMAND_UI(ID_OPC_ADDITEM, OnUpdateOpcAdditem)
ON_COMMAND(ID_OPC_ITEMPARAMETERS, OnOpcItemProperties)
ON_UPDATE_COMMAND_UI(ID_OPC_ITEMPARAMETERS, OnUpdateOpcItemProperties)
ON_COMMAND(ID_OPC_ITEMATTRIBUTES, OnOpcItemattributes)
ON_UPDATE_COMMAND_UI(ID_OPC_ITEMATTRIBUTES, OnUpdateOpcItemattributes)
ON_COMMAND(ID_OPC_WRITEVALUETOITEM, OnOpcWritevaluetoitem)
ON_UPDATE_COMMAND_UI(ID_OPC_WRITEVALUETOITEM, OnUpdateOpcWritevaluetoitem)
ON_COMMAND(ID_OPC_READITEM, OnOpcReaditem)
ON_UPDATE_COMMAND_UI(ID_OPC_READITEM, OnUpdateOpcReaditem)
ON_COMMAND(ID_OPC_REFRESH, OnOpcRefresh)
ON_UPDATE_COMMAND_UI(ID_OPC_REFRESH, OnUpdateOpcRefresh)
ON_COMMAND(ID_OPC_REMOVEITEM, OnOpcRemoveitem)
ON_UPDATE_COMMAND_UI(ID_OPC_REMOVEITEM, OnUpdateOpcRemoveitem)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
//**************************************************************************
// OPCClientDoc construction/destruction
OPCClientDoc::OPCClientDoc()
{
groupHandle = 0;
pCurrentItem = NULL;
hView = NULL;
transactionID = 0;
dwConnection1 = 0;
dwConnection2 = 0;
testSink = new CAdviseSink; // create the advise sink for notifications
testSink->AddRef();
callbackCP = new OPCCallbackObject; // create the ConnectionPoint for notifications
callbackCP->AddRef();
shutdownCP = new OPCShutdownObject; // create the ConnectionPoint for notifications
shutdownCP->AddRef();
dwShutdownConnection = 0;
usingCP = FALSE;
AfxOleLockApp();
theDoc = this;
// Everyone can connect back to IAdviseSink
HRESULT hr = CoInitializeSecurity(NULL, -1, NULL, NULL,
RPC_C_AUTHN_LEVEL_NONE, RPC_C_IMP_LEVEL_IDENTIFY, NULL, EOAC_NONE, NULL);
if (FAILED(hr))
{
TRACE(_T("CoInitializeSecurity failed, %lx"), hr);
}
// Get last server, node, and comments
lastServer = AfxGetApp()->GetProfileString(_T("Recent"), _T("Server"));
lastNode = AfxGetApp()->GetProfileString(_T("Recent"), _T("Node"));
}
OPCClientDoc::~OPCClientDoc()
{
AfxOleUnlockApp();
if( opcServer.IsOk() )
OnOpcDisconnect();
testSink->Release(); // OLE should clean this up, but may not have time!
callbackCP->Release();
shutdownCP->Release();
Sleep( 100 );
AfxGetApp()->WriteProfileString(_T("Recent"), _T("Server"), lastServer);
AfxGetApp()->WriteProfileString(_T("Recent"), _T("Node"), lastNode);
}
BOOL OPCClientDoc::OnNewDocument()
{
if (!CDocument::OnNewDocument())
return FALSE;
return TRUE;
}
//**************************************************************************
// OPCClientDoc serialization
void OPCClientDoc::Serialize(CArchive& ar)
{
if (ar.IsStoring())
{
// TODO: add storing code here
}
else
{
// TODO: add loading code here
}
}
//**************************************************************************
// OPCClientDoc diagnostics
#ifdef _DEBUG
void OPCClientDoc::AssertValid() const
{
CDocument::AssertValid();
}
void OPCClientDoc::Dump(CDumpContext& dc) const
{
CDocument::Dump(dc);
}
#endif //_DEBUG
//**************************************************************************
// OnOpcConnect()
// Called to find a server name from the prompt dialog box,
// and connect to that server.
// The node name is used to connect to servers on remote nodes.
//
//**************************************************************************
void OPCClientDoc::OnOpcConnect()
{
USES_CONVERSION;
ASSERT( !opcServer.IsOk() );
HRESULT hr = S_OK;
// Prompt user for the server name (from list of installed servers)
OPCServerDlg dlg;
dlg.m_Server = lastServer;
dlg.m_Node = lastNode;
if( dlg.DoModal() != IDOK )
return;
CWaitCursor wait;
lastServer = dlg.m_Server;
lastNode = dlg.m_Node;
// Check, if the specified node is the local node
// In this case continue as if no node has been specified.
BOOL useNode = TRUE;
if ( dlg.m_Node.IsEmpty()
|| _tcsicmp(_T(""), dlg.m_Node) == 0
|| _tcsicmp(_T("127.0.0.1"), dlg.m_Node) == 0
|| _tcsicmp(_T("localhost"), dlg.m_Node) == 0)
useNode = FALSE;
if( useNode )
{
TCHAR szLocalHost[MAX_COMPUTERNAME_LENGTH + 1]; // my computer name
DWORD dwHostSize = sizeof(szLocalHost);
// get own computer name
if (GetComputerName(szLocalHost, &dwHostSize) == TRUE)
if (_tcsicmp(szLocalHost, dlg.m_Node) == 0 )
useNode = FALSE;
}
// Create a running object from the class ID
// (CLSCTX_ALL will allow in-proc, local and remote)
LPUNKNOWN pUnkn = NULL;
if( !useNode )
{
hr = CoCreateInstance(dlg.m_clsid, NULL, CLSCTX_ALL, IID_IUnknown, (LPVOID *)&pUnkn);
if( FAILED(hr) || pUnkn == NULL)
{
CString format( (LPCSTR)IDS_CONNECT_ERROR );
CString msg;
msg.Format( format, dlg.m_Server );
msg += _T("CoCreateInstance: ");
ReportError( msg, hr );
return;
}
}
else // use the node name
{
COSERVERINFO si;
MULTI_QI qi;
si.dwReserved1 = 0;
si.pwszName = T2OLE(dlg.m_Node.GetBuffer(0));
si.pAuthInfo = NULL;
si.dwReserved2 = 0;
qi.pIID = &IID_IOPCServer;
qi.pItf = NULL;
qi.hr = 0;
hr = CoCreateInstanceEx(dlg.m_clsid, NULL, CLSCTX_REMOTE_SERVER, &si, 1, &qi);
if (FAILED(hr))
{
CString format( (LPCSTR)IDS_CONNECT_ERROR );
CString msg;
msg.Format( format, dlg.m_Server );
msg += _T("CoCreateInstance: ");
ReportError( msg, hr );
return;
}
if (FAILED(qi.hr))
{
ReportError( _T("MultiQI: "), qi.hr );
return;
}
pUnkn = qi.pItf;
}
// Get the IOPCServer interface.
hr = opcServer.Attach( pUnkn );
pUnkn->Release(); // Don't need this anymore.
pUnkn = NULL;
if( FAILED(hr) )
{
CString appName((LPCSTR)AFX_IDS_APP_TITLE);
MessageBox(0, _T("You may not have registered the OPC Proxy dll!\n"), appName, MB_OK);
return;
}
SetTitle( dlg.m_Server ); // display the server name
// OPC 2.0 Server shutdown ConnectionPoint
hr = AtlAdvise( opcServer, shutdownCP->GetUnknown(),IID_IOPCShutdown, &dwShutdownConnection );
// Create a single group that will contain all the items
FLOAT deadband = 0.0;
DWORD rate;
hr = opcServer.AddGroup( L"Fred", TRUE, 1000, // name, active, rate
1324, NULL, &deadband, // handle, bias, band
0, &groupHandle, &rate,
IID_IOPCGroupStateMgt, // interface to return
opcGroup ); // this holds the group ptr
if( FAILED(hr) )
{
ReportError( _T("AddGroup: "), hr );
return;
}
// Test GetGroupByName and SetName
#ifdef FULL_TEST
IOPCGroupStateMgt* pTest=NULL;
hr = opcServer.GetGroupByName( L"Fred", IID_IOPCGroupStateMgt, (LPUNKNOWN*)&pTest );
if( SUCCEEDED(hr) )
{
ASSERT( pTest == (IOPCGroupStateMgt*)opcGroup ); // should get the same
hr = pTest->SetName( L"Group one" ); // set new name
pTest->Release();
if( FAILED(hr) )
{
ReportError( _T("IOPCGroupStateMgt::SetName: "), hr );
}
else
{
// should now go by this new name
hr = opcServer.GetGroupByName( L"Group one", IID_IOPCGroupStateMgt, (LPUNKNOWN*)&pTest );
if( SUCCEEDED(hr) )
{
ASSERT( pTest == (IOPCGroupStateMgt*)opcGroup );
pTest->Release();
}
}
}
#endif // FULL_TEST
// OPC 2.0 ConnectionPoints
hr = AtlAdvise( opcGroup, callbackCP->GetUnknown(),IID_IOPCDataCallback, &dwConnection1 );
if( SUCCEEDED(hr) ) // This server supports 2.0
usingCP = TRUE;
if( !usingCP )
{
// OPC 1.0 data advise format
FORMATETC formatEtc ;
formatEtc.tymed = TYMED_HGLOBAL;
formatEtc.ptd = NULL;
formatEtc.dwAspect = DVASPECT_CONTENT;
formatEtc.lindex = -1;
// IAdviseSink is an interface on OUR object that is passed to
// the server for callbacks
IAdviseSink *pAdviseSink = NULL;
hr = testSink->QueryInterface(IID_IAdviseSink, (LPVOID *)&pAdviseSink);
if( FAILED(hr) )
{
ReportError( _T("IAdviseSink: "), hr );
opcGroup.Detach();
opcServer.Detach();
return;
}
// Get an IDataObject interface on the group
DataObject dataObject;
hr = dataObject.Attach( opcGroup );
if(FAILED(hr) || !dataObject.IsOk() )
{
// some servers don't do this, so don't quit altogether
MessageBox( 0, _T("IDataObject not supported by this server\nNo data notifications will take place"), _T("FactorySoft Client"), MB_OK );
return;
}
// Register our IAdvise with the group
// Need to register both formats: data change, and write complete
formatEtc.cfFormat = OPCSTMFORMATWRITECOMPLETE ;
hr = dataObject.DAdvise(&formatEtc,
ADVF_PRIMEFIRST, // ADVF flag
pAdviseSink,
&dwConnection2);
if( FAILED(hr) )
{
ReportError( _T("IDataObject::DAdvise: "), hr );
return;
}
#ifdef DATATIMEFORMAT
formatEtc.cfFormat = OPCSTMFORMATDATATIME ;
#else
formatEtc.cfFormat = OPCSTMFORMATDATA ;
#endif // DATATIMEFORMAT
hr = dataObject.DAdvise(&formatEtc,
ADVF_PRIMEFIRST, // ADVF flag
pAdviseSink,
&dwConnection1);
pAdviseSink->Release();
if( FAILED(hr) )
{
ReportError( _T("IDataObject::DAdvise: "), hr );
return;
}
}
}
void OPCClientDoc::OnUpdateOpcConnect(CCmdUI* pCmdUI)
{
pCmdUI->Enable( !opcServer.IsOk() );
}
//*******************************************************************
void OPCClientDoc::OnOpcDisconnect()
{
CWaitCursor wait;
HRESULT hr = S_OK;
if( opcServer.IsOk() && opcGroup.IsOk() )
{
if( dwShutdownConnection )
{
hr = AtlUnadvise( opcServer,IID_IOPCShutdown, dwShutdownConnection );
}
if( usingCP )
{
// OPC 2.0 ConnectionPoints
hr = AtlUnadvise( opcGroup,IID_IOPCDataCallback, dwConnection1 );
}
else
// call IDataObject::DUnadvise to turn off data notification
{
DataObject dataObject;
HRESULT hr = dataObject.Attach( opcGroup );
if( SUCCEEDED(hr) )
{
if( dwConnection1 )
hr = dataObject.DUnadvise(dwConnection1);
if( dwConnection2 )
hr = dataObject.DUnadvise(dwConnection2);
dataObject.Detach();
}
}
// test RemoveItems (RemoveGroup cleans up anyway.)
#ifdef FULL_TEST
OPCItemMgt itemMgt;
hr = itemMgt.Attach( opcGroup );
if( SUCCEEDED(hr) && items.GetCount()>0 )
{
HRESULT *pErrors=0;
OPCHANDLE* handles = new OPCHANDLE[items.GetCount()];
POSITION pos = items.GetHeadPosition();
for( int index=0; pos; index++ )
{
Item* pItem = items.GetNext( pos );
handles[index] = pItem->hServerHandle;
}
hr = itemMgt.RemoveItems( items.GetCount(), handles, &pErrors );
if( SUCCEEDED(hr) )
CoTaskMemFree( pErrors );
delete [] handles;
}
#endif // FULL_TEST
opcServer.RemoveGroup(groupHandle, FALSE);
}
opcGroup.Detach();
opcServer.Detach();
Sleep( 100 );
// now that the group is released and unadvised, no more data will
// be sent from the server. It is safe to delete the items
while( !items.IsEmpty() )
delete items.RemoveTail();
pCurrentItem = NULL;
UpdateAllViews(NULL);
SetTitle( _T("Unconnected ") );
}
void OPCClientDoc::OnUpdateOpcDisconnect(CCmdUI* pCmdUI)
{
pCmdUI->Enable( opcServer.IsOk() );
}
//*******************************************************************
void OPCClientDoc::OnOpcServerstatus()
{
ASSERT( opcServer.IsOk() );
CServerStatus dlg(opcServer);
dlg.DoModal();
}
void OPCClientDoc::OnUpdateOpcServerstatus(CCmdUI* pCmdUI)
{
pCmdUI->Enable( opcServer.IsOk() );
}
//*******************************************************************
void OPCClientDoc::OnOpcGroupparameters()
{
GroupParamsDlg dlg( opcGroup );
dlg.DoModal();
}
void OPCClientDoc::OnUpdateOpcGroupparameters(CCmdUI* pCmdUI)
{
pCmdUI->Enable( opcGroup.IsOk() );
}
//*******************************************************************
void OPCClientDoc::OnOpcAdditem()
{
ASSERT( opcGroup.IsOk() );
AddItemDlg dlg( this, opcServer );
dlg.DoModal();
}
void OPCClientDoc::OnUpdateOpcAdditem(CCmdUI* pCmdUI)
{
pCmdUI->Enable( opcServer.IsOk() && opcGroup.IsOk() );
}
//*******************************************************************
void OPCClientDoc::AddItem(LPCTSTR itemID, LPCTSTR accessPath, VARTYPE type)
{
USES_CONVERSION;
CWaitCursor wait;
// get an interface pointer
OPCItemMgt itemMgt;
HRESULT hr = itemMgt.Attach( opcGroup );
if( FAILED(hr) )
return;
// Add a new item
Item* item = new Item;
item->quality = OPC_QUALITY_GOOD;
item->name = itemID;
// fill out its definition
OPCITEMDEF idef;
idef.szItemID = T2OLE((LPTSTR)itemID);
idef.dwBlobSize = 0;
idef.pBlob = NULL;
idef.bActive = TRUE;
idef.hClient = (OPCHANDLE)item; // pointer to item is its "handle"
idef.szAccessPath = T2OLE((LPTSTR)accessPath);
idef.vtRequestedDataType = type;
// add the item
OPCITEMRESULT * pResults;
HRESULT *pErrors;
hr = itemMgt.AddItems(1, &idef, &pResults, &pErrors);
if( FAILED( hr ) ) // if the call failed, get out
{
ReportError( _T("AddItems: "), hr );
delete item;
return;
}
// If the call was successful, memory must be cleaned up
item->hServerHandle = pResults->hServer; // save the server handle
type = pResults->vtCanonicalDataType;
// Save the result in pErrors before freeing
HRESULT itemResult = pErrors[0]; // and the item's result
if( pResults->pBlob != NULL )
CoTaskMemFree( pResults->pBlob );
CoTaskMemFree( pResults );
CoTaskMemFree( pErrors );
// It this item failed, don't keep it (the server didn't)
if( FAILED(itemResult) )
{
ReportError( _T("AddItems: "), itemResult );
delete item;
return;
}
items.AddTail( item ); // store this item in the item list
// Read its initial value
OPCSyncIO opcSyncIO;
if( opcSyncIO.Attach( opcGroup ) == S_OK )
{
OPCITEMSTATE* pItemState;
hr = opcSyncIO.Read(OPC_DS_CACHE, 1, &item->hServerHandle, &pItemState, &pErrors);
if( SUCCEEDED(hr) )
{
ASSERT( pItemState->hClient == (OPCHANDLE)item );
item->quality = pItemState->wQuality;
item->value = pItemState->vDataValue;
VariantClear( &pItemState->vDataValue );
CoTaskMemFree( pItemState );
CoTaskMemFree( pErrors );
}
else
{
ReportError( _T("Sync Read: "), hr );
return;
}
}
// test some more interfaces
#ifdef FULL_TEST
if( itemMgt.IsOk() )
{
hr = itemMgt.SetActiveState( 1, &item->hServerHandle, FALSE, &pErrors);
if( SUCCEEDED(hr) )
CoTaskMemFree( pErrors );
hr = itemMgt.SetActiveState( 1, &item->hServerHandle, TRUE, &pErrors);
if( SUCCEEDED(hr) )
CoTaskMemFree( pErrors );
hr = itemMgt.SetClientHandles( 1, &item->hServerHandle, (OPCHANDLE*)&item, &pErrors);
if( SUCCEEDED(hr) )
CoTaskMemFree( pErrors );
}
#endif // FULL_TEST
UpdateAllViews(NULL);
}
//*******************************************************************
// This is the 2.0 Item Properties interface
void OPCClientDoc::OnOpcItemProperties()
{
CItemPropertiesDlg dlg(pCurrentItem->name);
dlg.SetOPCPointer( (IUnknown*)opcServer );
dlg.DoModal();
}
void OPCClientDoc::OnUpdateOpcItemProperties(CCmdUI* pCmdUI)
{
pCmdUI->Enable( opcServer.IsOk() && pCurrentItem );
}
//*******************************************************************
void OPCClientDoc::OnOpcItemattributes()
{
// get an interface pointer
OPCItemMgt itemMgt;
HRESULT hr = itemMgt.Attach( opcGroup );
if( FAILED(hr) )
return;
// test the item attributes enumerator
EnumOPCItemAttributes enumerator;
hr = itemMgt.CreateEnumerator( IID_IEnumOPCItemAttributes, enumerator );
while( hr==S_OK && enumerator.IsOk() )
{
OPCITEMATTRIBUTES* pAttributes = NULL;
ULONG count=0;
hr = enumerator.Next( 1, &pAttributes, &count );
if( hr == S_OK )
{
if( pAttributes->hClient == (OPCHANDLE)pCurrentItem )
{
// found the matching attributes for this item
ItemParamsDlg dlg;
dlg.pItemAttr = pAttributes;
if( dlg.DoModal() == IDOK )
{
HRESULT *pErrors;
hr = itemMgt.SetActiveState( 1, &pCurrentItem->hServerHandle, dlg.m_active, &pErrors);
if( SUCCEEDED(hr) )
CoTaskMemFree( pErrors );
}
}
VariantClear( &pAttributes->vEUInfo );
CoTaskMemFree( pAttributes->szAccessPath );
CoTaskMemFree( pAttributes->szItemID );
if( pAttributes->pBlob )
CoTaskMemFree( pAttributes->pBlob );
CoTaskMemFree( pAttributes );
}
else if( FAILED(hr) )
ReportError( _T("EnumOPCItemAttributes: "), hr );
}
}
//*******************************************************************
void OPCClientDoc::OnUpdateOpcItemattributes(CCmdUI* pCmdUI)
{
pCmdUI->Enable( opcServer.IsOk() && pCurrentItem );
}
//*******************************************************************
// the user enters something to write to the item in the dialog.
// COleVariant's ChangeType converts the string into the proper format
// or else puts up a dialog that it couldn't convert.
// Write can be sync or async
void OPCClientDoc::OnOpcWritevaluetoitem()
{
WriteItemDlg dlg;
dlg.m_item = pCurrentItem->name;
if( dlg.DoModal() == IDOK )
{
CWaitCursor wait;
HRESULT *pErrors = NULL;
if( dlg.m_async )
{
if( usingCP )
{
OPCAsyncIO2 opcAsyncIO2;
if( opcAsyncIO2.Attach( opcGroup ) == S_OK )
{
transactionID = 2; // any number the client wants
COleVariant vt( dlg.m_value ); // initialize as a string
vt.ChangeType( pCurrentItem->value.vt ); // let COleVariant convert!
HRESULT hr = opcAsyncIO2.Write(1, &pCurrentItem->hServerHandle,
vt, transactionID, &transactionID, &pErrors);
if( SUCCEEDED(hr) )
{
if( FAILED(pErrors[0]) )
{
ReportError( _T("ASync Write: "), pErrors[0] );
}
CoTaskMemFree( pErrors );
}
else
{
ReportError( _T("ASync Write: "), hr );
}
}
}
else
{
OPCAsyncIO opcAsyncIO;
if( opcAsyncIO.Attach( opcGroup ) == S_OK )
{
COleVariant vt( dlg.m_value ); // initialize as a string
vt.ChangeType( pCurrentItem->value.vt ); // let COleVariant convert!
HRESULT hr = opcAsyncIO.Write(dwConnection2, 1, &pCurrentItem->hServerHandle,
vt, &transactionID, &pErrors);
if( SUCCEEDED(hr) )
{
if( FAILED(pErrors[0]) )
{
ReportError( _T("ASync Write: "), pErrors[0] );
}
CoTaskMemFree( pErrors );
}
else
{
ReportError( _T("ASync Write: "), hr );
}
}
}
}
else
{
OPCSyncIO opcSyncIO;
if( opcSyncIO.Attach( opcGroup ) == S_OK )
{
COleVariant vt( dlg.m_value ); // initialize as a string
vt.ChangeType( pCurrentItem->value.vt ); // let COleVariant convert!
HRESULT hr = opcSyncIO.Write( 1, &pCurrentItem->hServerHandle, vt, &pErrors);
if( SUCCEEDED(hr) )
{
if( FAILED(pErrors[0]) )
{
ReportError( _T("Sync Write: "), pErrors[0] );
}
CoTaskMemFree( pErrors );
}
else
{
ReportError( _T("Sync Write: "), hr );
}
}
}
}
}
void OPCClientDoc::OnUpdateOpcWritevaluetoitem(CCmdUI* pCmdUI)
{
pCmdUI->Enable( opcServer.IsOk() && pCurrentItem );
}
//*******************************************************************
// Test async reading by calling 4 times (server will queue them up)
void OPCClientDoc::OnOpcReaditem()
{
HRESULT *pErrors;
CWaitCursor wait;
{ // also test sync read since data is returned differently
OPCSyncIO opcSyncIO;
if( opcSyncIO.Attach( opcGroup ) == S_OK )
{
OPCITEMSTATE* pItemState;
HRESULT hr = opcSyncIO.Read(OPC_DS_DEVICE, 1, &pCurrentItem->hServerHandle, &pItemState, &pErrors);
if( SUCCEEDED(hr) )
{
if( FAILED(pErrors[0]) )
{
ReportError( _T("Sync Read: "), pErrors[0] );
}
else
{
pCurrentItem->quality = pItemState->wQuality;
pCurrentItem->value = pItemState->vDataValue;
}
VariantClear( &pItemState->vDataValue );
CoTaskMemFree( pItemState );
CoTaskMemFree( pErrors );
}
else
{
ReportError( _T("Sync Read: "), hr );
}
}
}
// Use AsyncIO2 here
if( usingCP )
{
OPCAsyncIO2 opcAsyncIO2;
if( opcAsyncIO2.Attach( opcGroup ) == S_OK )
{
transactionID = 3;
HRESULT hr = opcAsyncIO2.Read(1, &pCurrentItem->hServerHandle, transactionID, &transactionID, &pErrors);
if( SUCCEEDED(hr) )
{
if( FAILED(pErrors[0]) )
{
ReportError( _T("Async Read: "), pErrors[0] );
}
CoTaskMemFree( pErrors );
}
else
{
ReportError( _T("Async Read: "), hr );
}
#ifdef FULL_TEST
transactionID = 3;
hr = opcAsyncIO2.Read(1, &pCurrentItem->hServerHandle, transactionID, &transactionID, &pErrors);
if( SUCCEEDED(hr) )
{
CoTaskMemFree( pErrors );
}
transactionID = 3;
hr = opcAsyncIO2.Read(1, &pCurrentItem->hServerHandle, transactionID, &transactionID, &pErrors);
if( SUCCEEDED(hr) )
{
CoTaskMemFree( pErrors );
}
// ask for a few this time (it doesn't matter that its the same one)
transactionID = 3;
OPCHANDLE serverHandles[3];
for( int i=0; i<3; i++ )
serverHandles[i] = pCurrentItem->hServerHandle;
hr = opcAsyncIO2.Read(3, serverHandles, transactionID, &transactionID, &pErrors);
if( SUCCEEDED(hr) )
{
CoTaskMemFree( pErrors );
}
#endif // FULL_TEST
}
}
else
{
OPCAsyncIO opcAsyncIO;
if( opcAsyncIO.Attach( opcGroup ) == S_OK )
{
HRESULT hr = opcAsyncIO.Read(dwConnection1, OPC_DS_CACHE, 1, &pCurrentItem->hServerHandle, &transactionID, &pErrors);
if( SUCCEEDED(hr) )
{
if( FAILED(pErrors[0]) )
{
ReportError( _T("Async Read: "), pErrors[0] );
}
CoTaskMemFree( pErrors );
}
else
{
ReportError( _T("Async Read: "), hr );
}
#ifdef FULL_TEST
hr = opcAsyncIO.Read(dwConnection1, OPC_DS_DEVICE, 1, &pCurrentItem->hServerHandle, &transactionID, &pErrors);
if( SUCCEEDED(hr) )
{
CoTaskMemFree( pErrors );
}
hr = opcAsyncIO.Read(dwConnection1, OPC_DS_CACHE, 1, &pCurrentItem->hServerHandle, &transactionID, &pErrors);
if( SUCCEEDED(hr) )
{
CoTaskMemFree( pErrors );
}
// ask for a few this time (it doesn't matter that its the same one)
OPCHANDLE serverHandles[3];
for( int i=0; i<3; i++ )
serverHandles[i] = pCurrentItem->hServerHandle;
hr = opcAsyncIO.Read(dwConnection1, OPC_DS_DEVICE, 3, serverHandles, &transactionID, &pErrors);
if( SUCCEEDED(hr) )
{
CoTaskMemFree( pErrors );
}
#endif // FULL_TEST
}
}
UpdateAllViews(NULL);
}
void OPCClientDoc::OnUpdateOpcReaditem(CCmdUI* pCmdUI)
{
pCmdUI->Enable( opcServer.IsOk() && pCurrentItem );
}
//*******************************************************************
// Refresh causes all items to be advised immediately.
void OPCClientDoc::OnOpcRefresh()
{
CWaitCursor wait;
if( usingCP )
{
OPCAsyncIO2 opcAsyncIO2;
if( opcAsyncIO2.Attach( opcGroup ) == S_OK )
{
// test both Device and Cache data sources
// This should cause the server to queue a refresh while one is going on.
transactionID = 2; // any number the client wants
HRESULT hr = opcAsyncIO2.Refresh2(OPC_DS_DEVICE, transactionID, &transactionID);
if( FAILED(hr) )
{
ReportError( _T("Refresh2: "), hr );
return;
}
#ifdef FULL_TEST
transactionID = 3; // any number the client wants
hr = opcAsyncIO2.Refresh2(OPC_DS_DEVICE, transactionID, &transactionID);
if( FAILED(hr) )
{
ReportError( _T("Refresh: "), hr );
return;
}
#endif // FULL_TEST
}
}
else
{
OPCAsyncIO opcAsyncIO;
if( opcAsyncIO.Attach( opcGroup ) == S_OK )
{
// test both Device and Cache data sources
// This should cause the server to queue a refresh while one is going on.
HRESULT hr = opcAsyncIO.Refresh(dwConnection1, OPC_DS_DEVICE, &transactionID);
if( FAILED(hr) )
{
ReportError( _T("Refresh: "), hr );
return;
}
#ifdef FULL_TEST
hr = opcAsyncIO.Refresh(dwConnection1, OPC_DS_CACHE, &transactionID);
if( FAILED(hr) )
{
ReportError( _T("Refresh: "), hr );
return;
}
#endif // FULL_TEST
}
}
}
void OPCClientDoc::OnUpdateOpcRefresh(CCmdUI* pCmdUI)
{
pCmdUI->Enable( opcServer.IsOk() );
}
//*******************************************************************
void OPCClientDoc::OnOpcRemoveitem()
{
OPCItemMgt itemMgt;
HRESULT hr = itemMgt.Attach( opcGroup );
if( SUCCEEDED(hr) )
{
HRESULT *pErrors=0;
OPCHANDLE handle = pCurrentItem->hServerHandle;
hr = itemMgt.RemoveItems( 1, &handle, &pErrors );
if( SUCCEEDED(hr) )
CoTaskMemFree( pErrors );
POSITION pos = items.Find( pCurrentItem );
items.RemoveAt( pos );
delete pCurrentItem;
pCurrentItem = NULL;
UpdateAllViews(NULL);
}
}
void OPCClientDoc::OnUpdateOpcRemoveitem(CCmdUI* pCmdUI)
{
pCmdUI->Enable( opcServer.IsOk() && pCurrentItem );
}
//*******************************************************************
CString OPCClientDoc::GetErrorString(LPCTSTR description, HRESULT error)
{
CString temp(description);
temp += _T(" ");
TCHAR msg[MAX_PATH*5];
DWORD ok = FormatMessage( FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
error,
MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL),
msg, MAX_PATH, NULL );
if( ok )
{
TRACE(msg);
TRACE(_T("\n"));
temp += msg;
return temp;
}
// else try the server
LPWSTR pString = NULL;
if( opcServer.IsOk() )
{
HRESULT hr = opcServer.GetErrorString( error, LOCALE_SYSTEM_DEFAULT, &pString );
if( SUCCEEDED(hr) )
{
temp += pString;
TRACE(temp);
CoTaskMemFree( pString );
}
else
temp += _T("OPC Server failed GetErrorString.");
}
else
temp += _T("Unknown Error.");
return temp;
}
//*******************************************************************
void OPCClientDoc::ReportError(LPCTSTR description, HRESULT error)
{
CString msg( GetErrorString(description,error) );
CString appName((LPCSTR)AFX_IDS_APP_TITLE);
MessageBox(0, msg, appName, MB_OK);
}
//**************************************************************************
//
// VariantToString() convert the value to String format
//
//**************************************************************************
void VariantToString(VARIANT value, CString& strText)
{
strText.Empty();
switch(value.vt)
{
case VT_BOOL:
strText = value.boolVal ? _T("On") : _T("Off");
break;
case VT_UI1:
strText.Format( _T("%hd"), (USHORT)value.bVal );
break;
case VT_UI2:
case VT_I2:
strText.Format( _T("%hd"), value.iVal );
break;
case VT_I4:
strText.Format( _T("%d"), value.lVal );
break;
case VT_R4:
strText.Format( _T("%g"), value.fltVal );
break;
case VT_R8:
strText.Format( _T("%g"), value.dblVal );
break;
case VT_BSTR:
strText = value.bstrVal;
break;
default: // Arrays of simple types
{
if( (value.vt & VT_ARRAY)==VT_ARRAY )
{
CString temp;
SAFEARRAY* pArray = value.parray;
LONG lBound = 0, uBound = 0;
SafeArrayGetLBound( pArray, 1, &lBound );
SafeArrayGetUBound( pArray, 1, &uBound );
for( long element=lBound; element<=uBound; element++ )
{
if( strText.IsEmpty() )
strText.Format( _T("(%d) "), uBound-lBound+1);
else
strText += _T(", ");
switch( value.vt & ~VT_ARRAY )
{
case VT_BOOL:
{
VARIANT_BOOL b=0;
SafeArrayGetElement(pArray, &element, &b);
temp = b ? _T("1") : _T("0");
}
break;
case VT_UI1:
{
BYTE b=0;
SafeArrayGetElement(pArray, &element, &b);
temp.Format( _T("%hd"), b );
}
break;
case VT_UI2:
case VT_I2:
{
short b=0;
SafeArrayGetElement(pArray, &element, &b);
temp.Format( _T("%hd"), b );
}
break;
case VT_I4:
{
long b=0;
SafeArrayGetElement(pArray, &element, &b);
temp.Format( _T("%d"), b );
}
break;
case VT_R4:
{
float d=0;
SafeArrayGetElement(pArray, &element, &d);
temp.Format( _T("%g"), d );
}
break;
case VT_R8:
{
double d=0;
SafeArrayGetElement(pArray, &element, &d);
temp.Format( _T("%g"), d );
}
break;
case VT_BSTR:
{
BSTR b;
SafeArrayGetElement(pArray, &element, &b);
temp = b;
}
break;
}
strText += temp;
}
}
else
strText = _T("?");
}
}
}
| [
"[email protected]"
]
| [
[
[
1,
1113
]
]
]
|
317523ded73800c557ba8e3d50fa01947ba660d5 | 6ee200c9dba87a5d622c2bd525b50680e92b8dab | /Walkyrie Dx9/Valkyrie/Moteur/Polygonlist.cpp | 77df4ac2151cd66a414d0861fa042b33d8bb9bdd | []
| no_license | Ishoa/bizon | 4dbcbbe94d1b380f213115251e1caac5e3139f4d | d7820563ab6831d19e973a9ded259d9649e20e27 | refs/heads/master | 2016-09-05T11:44:00.831438 | 2010-03-10T23:14:22 | 2010-03-10T23:14:22 | 32,632,823 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 16,082 | cpp | #include "Polygonlist.h"
// ************************ Classe CPolygonContainer *************************
// Cette classe, qui représente un noeud de la liste, permet de contenir un
// polygone, ou une adresse vers un polygone si la liste est une copie d'une
// autre liste.
// Constructeur de la classe E_PolygonContainer.
CPolygonContainer::CPolygonContainer()
{
p_Polygon = NULL;
p_Next = NULL;
p_IsCopy = false;
}
// Destructeur de la classe E_PolygonContainer.
CPolygonContainer::~CPolygonContainer()
{
// On nettoie la ressource, à condition que celle-ci soit locale.
if ( p_Polygon != NULL && p_IsCopy == false )
{
delete p_Polygon;
p_Polygon = NULL;
}
}
// Obtient le polygone, ou l'adresse du polygone.
CPolygon* CPolygonContainer::GetPolygon()
{
return p_Polygon;
}
// Définit le polygone, ou l'adresse du polygone.
void CPolygonContainer::SetPolygon( CPolygon* Polygon, bool IsCopy )
{
p_Polygon = Polygon;
p_IsCopy = IsCopy;
}
// Obtient le pointeur vers le noeud suivant.
CPolygonContainer* CPolygonContainer::GetNext()
{
return p_Next;
}
// Définit le pointeur vers le noeud suivant.
void CPolygonContainer::SetNext( CPolygonContainer* Next )
{
p_Next = Next;
}
// ************************** Classe CPolygonList ****************************
// Cette classe est une liste de polygones, utilisée par exemple pour la
// détection des collisions. Elle permet un accès simplifié aux données
// spaciales représentant un objet, et mets à disposition des outils comme la
// création d'une boîte de collisions pour l'objet.
// Constructeur de la classe E_PolygonList.
CPolygonList::CPolygonList()
{
p_First = NULL;
p_Current = NULL;
p_FirstBox = NULL;
p_CurrentBox = NULL;
p_PolygonCount = 0;
}
// Destructeur de la classe E_PolygonList.
CPolygonList::~CPolygonList()
{
// On appelle la fonction de nettoyage de la liste.
ReleaseList();
}
// Cette fonction permet l'ajout d'un polygone dans la liste.
bool CPolygonList::AddPolygon( CPolygon* Polygon, bool IsCopy )
{
// On commence par tester si l'objet est valide.
if ( Polygon == NULL )
{
// Si ce n'est pas le cas, on retourne une erreur.
return false;
}
// Ensuite, on crée un nouveau conteneur.
CPolygonContainer* p_New = new CPolygonContainer();
// Puis, on teste si le conteneur a été correctement alloué en mémoire.
if ( p_New == NULL )
{
// Si ce n'est pas le cas, on retourne une erreur.
return false;
}
// On alloue ensuite le pointeur vers le polygone dans le conteneur.
p_New->SetPolygon( Polygon, IsCopy );
// On teste si le premier conteneur de la liste d'objets a déjà été crée.
if ( p_First == NULL )
{
// Si ce n'est pas le cas, on définit le nouveau conteneur comme
// premier conteneur de la liste d'objets, et on définit le pointeur
// courant sur le premier conteneur de la liste.
p_First = p_New;
p_Current = p_First;
}
else
{
// Si le premier conteneur est défini, on ajoute le nouveau conteneur à
// la fin de la liste. On commence par définir le pointeur courant sur
// le premier conteneur.
p_Current = p_First;
// Puis, on passe toute la liste d'objets, jusqu'à pointer sur le
// dernier objet de la liste.
while ( p_Current->GetNext() != NULL )
{
// On passe à l'objet suivant.
p_Current = p_Current->GetNext();
}
// Maintenant, on sait que p_Current contient le dernier objet de la
// liste. On définit le pointeur vers le prochain conteneur sur le
// nouveau conteneur que l'on a crée.
p_Current->SetNext( p_New );
}
// On additionne le compteur interne de polygones.
p_PolygonCount++;
// Pour finir, on retourne un message de réussite.
return true;
}
// Cette fonction permet l'ajout d'un polygone dans la liste.
bool CPolygonList::AddPolygon( D3DXVECTOR3 Vertex1,
D3DXVECTOR3 Vertex2,
D3DXVECTOR3 Vertex3 )
{
// On crée un nouveau polygone.
CPolygon* Polygon = new CPolygon( Vertex1, Vertex2, Vertex3 );
// Puis, on teste si le polygone a bien été crée en mémoire.
if ( Polygon == NULL )
{
return false;
}
// Pour finir, on tente d'ajouter le polygone à la liste, et on retourne
// la réponse.
return AddPolygon( Polygon, false );
}
// Cette fonction permet de créer une liste depuis un objet.
bool CPolygonList::CreateListFromMesh( LPD3DXMESH Mesh )
{
// On teste d'abord si l'objet est valide.
if ( Mesh == NULL )
{
return false;
}
D3DXVECTOR3 Vertex[3];
D3DXVECTOR3 CurVertex;
WORD* p_Indices;
D3DXVECTOR3* p_Vertices;
// Puis, on obtient le nombre de faces et d'index contenus dans l'objet.
DWORD NbVertices = Mesh->GetNumVertices();
DWORD NbFaces = Mesh->GetNumFaces();
// On verrouille ensuite le buffer d'index, ...
if ( FAILED( Mesh->LockIndexBuffer( D3DLOCK_READONLY,
(void**)&p_Indices ) ) )
{
// Si le verrouillage échoue, on retourne une erreur.
return false;
}
// ... ainsi que le buffer de sommets.
if ( FAILED( Mesh->LockVertexBuffer( D3DLOCK_READONLY,
(void**)&p_Vertices ) ) )
{
// Si le verrouillage échoue, on retourne une erreur.
return false;
}
// On extrait ensuite les données nécessaires à l'initialisation.
for ( DWORD i = 0; i < NbFaces; i++ )
{
// On copie les données du polygone.
for ( DWORD j = 0; j < 3; j++ )
{
CurVertex = (float*)&p_Vertices[p_Indices[3*i+j]];
Vertex[j] = CurVertex;
}
// Puis, on tente d'ajouter le polygone dans la liste.
if ( AddPolygon( Vertex[0], Vertex[1], Vertex[2] ) == false )
{
// Si l'ajout échoue, on déverrouille les buffers, et on retourne
// une erreur.
Mesh->UnlockVertexBuffer();
Mesh->UnlockIndexBuffer();
return false;
}
}
// Puis, on déverrouille les buffers, ...
Mesh->UnlockVertexBuffer();
Mesh->UnlockIndexBuffer();
// ... et on retourne le message de réussite.
return true;
}
// Cette fonction teste si un polygone existe déjà dans la liste.
bool CPolygonList::Exist( CPolygon* Polygon )
{
p_Current = p_First;
// On passe toute la liste en revue.
while ( p_Current != NULL )
{
// Puis, on teste si le polygone existe déjà dans la liste.
if ( p_Current->GetPolygon() == Polygon )
{
// Si c'est le cas, on retourne une réponse positive.
return true;
}
// Sinon, on passe au prochain polygone.
p_Current = p_Current->GetNext();
}
// Si aucun polygone n'est trouvé, on retourne une réponse négative.
return false;
}
// Cette fonction permet de créer une boîte de collisions pour l'objet.
void CPolygonList::CreateBoundingBox()
{
D3DXVECTOR3 Max = D3DXVECTOR3( 0.0f, 0.0f, 0.0f );
D3DXVECTOR3 Min = D3DXVECTOR3( 0.0f, 0.0f, 0.0f );
p_Current = p_First;
// On passe toute la liste des polygones en revue.
while ( p_Current != NULL )
{
// Puis, on extrait chaque sommet.
for ( int i = 0; i < 3; i++ )
{
D3DXVECTOR3 v = p_Current->GetPolygon()->GetVertex( i );
// Pour chaque sommet, on recherche si la valeur courante est
// plus grande ou plus petite que les valeurs maximales et
// minimales déjà trouvées. Si c'est le cas, on met à jour les
// valeurs.
Max = CMaths::GetMaxValue( Max, v );
Min = CMaths::GetMinValue( Min, v );
}
// Puis, on passe au polygone suivant.
p_Current = p_Current->GetNext();
}
// Enfin, on inscrit les valeurs trouvées dans la boîte de collisions.
p_BoundingBox.SetMax( Max );
p_BoundingBox.SetMin( Min );
CreateListBoundingBox (Min,Max);
}
// Obtient la boîte de collisions de l'objet.
CBoundingBox& CPolygonList::GetBoundingBox()
{
return p_BoundingBox;
}
// Cette fonction permet de créer une sphère de collisions pour l'objet.
void CPolygonList::CreateBoundingSphere()
{
D3DXVECTOR3 Max = D3DXVECTOR3( 0.0f, 0.0f, 0.0f );
D3DXVECTOR3 Min = D3DXVECTOR3( 0.0f, 0.0f, 0.0f );
p_Current = p_First;
// On passe toute la liste des polygones en revue.
while ( p_Current != NULL )
{
// Puis, on extrait chaque sommet.
for ( int i = 0; i < 3; i++ )
{
D3DXVECTOR3 v = p_Current->GetPolygon()->GetVertex( i );
// Pour chaque sommet, on recherche si la valeur courante est
// plus grande ou plus petite que les valeurs maximales et
// minimales déjà trouvées. Si c'est le cas, on met à jour les
// valeurs.
Max = CMaths::GetMaxValue( Max, v );
Min = CMaths::GetMinValue( Min, v );
}
// Puis, on passe au polygone suivant.
p_Current = p_Current->GetNext();
}
D3DXMATRIXA16 matIdentity;
D3DXMatrixIdentity( &matIdentity );
p_BoundingSphere.SetSphere(matIdentity,Min,Max);
}
// Obtient la sphère de collisions de l'objet.
CBoundingSphere& CPolygonList::GetBoundingSphere()
{
return p_BoundingSphere;
}
// Obtient le nombre de polygones de l'objet.
int CPolygonList::GetCount()
{
return p_PolygonCount;
}
// Obtient le premier conteneur de polygone de la liste.
CPolygonContainer* CPolygonList::GetFirst()
{
return p_First;
}
// Obtient le premier conteneur de polygone de la liste.
CPolygonContainer* CPolygonList::GetFirstBox()
{
return p_FirstBox;
}
// Cette fonction permet de libérer les ressources de la liste.
void CPolygonList::ReleaseList()
{
p_Current = p_First;
// On détruit toute la liste d'objets.
while ( p_Current != NULL )
{
CPolygonContainer* p_Tmp = p_Current->GetNext();
delete p_Current;
p_Current = p_Tmp;
}
p_First = NULL;
p_Current = NULL;
p_CurrentBox = p_FirstBox;
// On détruit toute la liste d'objets.
while ( p_CurrentBox != NULL )
{
CPolygonContainer* p_Tmp = p_CurrentBox->GetNext();
delete p_CurrentBox;
p_CurrentBox = p_Tmp;
}
p_FirstBox = NULL;
p_CurrentBox = NULL;
}
void CPolygonList::RenduPolygonList()
{
}
bool CPolygonList::CreateListBoundingBox (D3DXVECTOR3 BoxMin,D3DXVECTOR3 BoxMax)
{
//face 1
CPolygon* Polygon = new CPolygon( BoxMin,
D3DXVECTOR3(BoxMax.x,BoxMin.y,BoxMin.z),
D3DXVECTOR3(BoxMin.x,BoxMax.y,BoxMin.z) );
if(!AddPolygonBox(Polygon,false))
return false;
Polygon = new CPolygon( D3DXVECTOR3(BoxMin.x,BoxMax.y,BoxMin.z),
D3DXVECTOR3(BoxMax.x,BoxMin.y,BoxMin.z),
D3DXVECTOR3(BoxMax.x,BoxMax.y,BoxMin.z) );
if(!AddPolygonBox(Polygon,false))
return false;
//face 2
Polygon = new CPolygon( D3DXVECTOR3(BoxMax.x,BoxMin.y,BoxMin.z),
D3DXVECTOR3(BoxMax.x,BoxMin.y,BoxMax.z),
D3DXVECTOR3(BoxMax.x,BoxMax.y,BoxMin.z) );
if(!AddPolygonBox(Polygon,false))
return false;
Polygon = new CPolygon( D3DXVECTOR3(BoxMax.x,BoxMax.y,BoxMin.z),
D3DXVECTOR3(BoxMax.x,BoxMin.y,BoxMax.z),
BoxMax);
if(!AddPolygonBox(Polygon,false))
return false;
//face 3
Polygon = new CPolygon( D3DXVECTOR3(BoxMax.x,BoxMin.y,BoxMax.z),
D3DXVECTOR3(BoxMin.x,BoxMin.y,BoxMax.z),
BoxMax);
if(!AddPolygonBox(Polygon,false))
return false;
Polygon = new CPolygon( D3DXVECTOR3(BoxMin.x,BoxMin.y,BoxMax.z),
D3DXVECTOR3(BoxMin.x,BoxMax.y,BoxMax.z),
BoxMax);
if(!AddPolygonBox(Polygon,false))
return false;
//face 4
Polygon = new CPolygon( BoxMin,
D3DXVECTOR3(BoxMin.x,BoxMax.y,BoxMin.z),
D3DXVECTOR3(BoxMin.x,BoxMin.y,BoxMax.z));
if(!AddPolygonBox(Polygon,false))
return false;
Polygon = new CPolygon( D3DXVECTOR3(BoxMin.x,BoxMax.y,BoxMin.z),
D3DXVECTOR3(BoxMin.x,BoxMax.y,BoxMax.z),
D3DXVECTOR3(BoxMin.x,BoxMin.y,BoxMax.z));
if(!AddPolygonBox(Polygon,false))
return false;
//face 5
Polygon = new CPolygon( BoxMin,
D3DXVECTOR3(BoxMin.x,BoxMin.y,BoxMax.z),
D3DXVECTOR3(BoxMax.x,BoxMin.y,BoxMin.z));
if(!AddPolygonBox(Polygon,false))
return false;
Polygon = new CPolygon( D3DXVECTOR3(BoxMin.x,BoxMin.y,BoxMax.z),
D3DXVECTOR3(BoxMax.x,BoxMin.y,BoxMax.z),
D3DXVECTOR3(BoxMax.x,BoxMin.y,BoxMin.z));
if(!AddPolygonBox(Polygon,false))
return false;
//face 6
Polygon = new CPolygon( D3DXVECTOR3(BoxMin.x,BoxMax.y,BoxMin.z),
D3DXVECTOR3(BoxMax.x,BoxMax.y,BoxMin.z),
D3DXVECTOR3(BoxMin.x,BoxMax.y,BoxMax.z));
if(!AddPolygonBox(Polygon,false))
return false;
Polygon = new CPolygon( D3DXVECTOR3(BoxMin.x,BoxMax.y,BoxMax.z),
D3DXVECTOR3(BoxMax.x,BoxMax.y,BoxMin.z),
BoxMax);
if(!AddPolygonBox(Polygon,false))
return false;
return true;
}
// Cette fonction permet l'ajout d'un polygone dans la liste.
bool CPolygonList::AddPolygonBox( CPolygon* Polygon, bool IsCopy )
{
// On commence par tester si l'objet est valide.
if ( Polygon == NULL )
{
// Si ce n'est pas le cas, on retourne une erreur.
return false;
}
// Ensuite, on crée un nouveau conteneur.
CPolygonContainer* p_New = new CPolygonContainer();
// Puis, on teste si le conteneur a été correctement alloué en mémoire.
if ( p_New == NULL )
{
// Si ce n'est pas le cas, on retourne une erreur.
return false;
}
// On alloue ensuite le pointeur vers le polygone dans le conteneur.
p_New->SetPolygon( Polygon, IsCopy );
// On teste si le premier conteneur de la liste d'objets a déjà été crée.
if ( p_FirstBox == NULL )
{
// Si ce n'est pas le cas, on définit le nouveau conteneur comme
// premier conteneur de la liste d'objets, et on définit le pointeur
// courant sur le premier conteneur de la liste.
p_FirstBox = p_New;
p_CurrentBox = p_FirstBox;
}
else
{
// Si le premier conteneur est défini, on ajoute le nouveau conteneur à
// la fin de la liste. On commence par définir le pointeur courant sur
// le premier conteneur.
p_CurrentBox = p_FirstBox;
// Puis, on passe toute la liste d'objets, jusqu'à pointer sur le
// dernier objet de la liste.
while ( p_CurrentBox->GetNext() != NULL )
{
// On passe à l'objet suivant.
p_CurrentBox = p_CurrentBox->GetNext();
}
// Maintenant, on sait que p_Current contient le dernier objet de la
// liste. On définit le pointeur vers le prochain conteneur sur le
// nouveau conteneur que l'on a crée.
p_CurrentBox->SetNext( p_New );
}
// Pour finir, on retourne un message de réussite.
return true;
}
// Cette fonction permet l'ajout d'un polygone dans la liste.
bool CPolygonList::AddPolygonBox( D3DXVECTOR3 Vertex1,
D3DXVECTOR3 Vertex2,
D3DXVECTOR3 Vertex3 )
{
// On crée un nouveau polygone.
CPolygon* Polygon = new CPolygon( Vertex1, Vertex2, Vertex3 );
// Puis, on teste si le polygone a bien été crée en mémoire.
if ( Polygon == NULL )
{
return false;
}
// Pour finir, on tente d'ajouter le polygone à la liste, et on retourne
// la réponse.
return AddPolygonBox( Polygon, false );
}
| [
"Colas.Vincent@ab19582e-f48f-11de-8f43-4547254af6c6"
]
| [
[
[
1,
553
]
]
]
|
aa6752a1f8ac4afbd73d2df67e420e5ac78b7e94 | 465943c5ffac075cd5a617c47fd25adfe496b8b4 | /ATCINPUT.H | bf34161d252a6eb7826af13205fa755f063513d9 | []
| no_license | paulanthonywilson/airtrafficcontrol | 7467f9eb577b24b77306709d7b2bad77f1b231b7 | 6c579362f30ed5f81cabda27033f06e219796427 | refs/heads/master | 2016-08-08T00:43:32.006519 | 2009-04-09T21:33:22 | 2009-04-09T21:33:22 | 172,292 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 693 | h | /*
Input class for ATC
*/
# ifndef _INPUT_H
# define _INPUT_H
# include <conio.h>
# include <stdio.h>
# include <ctype.h>
# include "stdatc.h"
# include "table.h"
# include "traffic.h"
# include "landmars.h"
# include "allcmnds.h"
# include "atcscree.h"
# define INPUT_LINE 1
# define PROMPT_LINE 3
class ATCInputScreen : public ATCScreen {
private:
//Screen commands & data
int CrntColumn_c;
int PromptColumn_c;
void Cursor();
public:
ATCInputScreen ();
void Refresh();
void Select();
void Echo (char *Msg_i);
void ClearEchoBy (int Column_i);
void Prompt (char *Msg);
void AddToPrompt (char *Msg);
};
# endif | [
"[email protected]"
]
| [
[
[
1,
53
]
]
]
|
9d92cb7548285c07b3b4aef6f364bd52aa1438c0 | 5ed707de9f3de6044543886ea91bde39879bfae6 | /ASHockey/ASFIsOrb/Source/ASHockeyPlayerScoutRqst.cpp | 7086f53fa113660378931d1d697bcc9f9307b424 | []
| no_license | grtvd/asifantasysports | 9e472632bedeec0f2d734aa798b7ff00148e7f19 | 76df32c77c76a76078152c77e582faa097f127a8 | refs/heads/master | 2020-03-19T02:25:23.901618 | 1999-12-31T16:00:00 | 2018-05-31T19:48:19 | 135,627,290 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,855 | cpp | /* ASHockeyPlayerScoutRqst.cpp */
/******************************************************************************/
/******************************************************************************/
#include "CBldVCL.h"
#pragma hdrstop
#include "ASHockeyType.h"
#include "ASHockeyPlayerScoutRqst.h"
namespace ashockey
{
/******************************************************************************/
/******************************************************************************/
PlayerStatValue ASHockeyPlayerScoutRqst::getDefaultPlayerStatValue(
int playerStatType)
{
if(isPlayerStatTypeOffensive(playerStatType))
return(THockeyOffGameStat::getDefaultStatStr(playerStatType).c_str());
return(THockeyDefGameStat::getDefaultStatStr(playerStatType).c_str());
}
/******************************************************************************/
bool ASHockeyPlayerScoutRqst::isPlayerStatTypeOffensive(int playerStatType)
{
THockeyPlayerStatType hockeyPlayerStatType(playerStatType);
if((hockeyPlayerStatType == pst_TotalPoints) ||
(hockeyPlayerStatType == pst_GamesPlayed))
return(true);
return(hockeyPlayerStatType.isOffensive());
}
/******************************************************************************/
bool ASHockeyPlayerScoutRqst::isPlayerStatTypeDefensive(int playerStatType)
{
THockeyPlayerStatType hockeyPlayerStatType(playerStatType);
if((hockeyPlayerStatType == pst_TotalPoints) ||
(hockeyPlayerStatType == pst_GamesPlayed))
return(true);
return(!hockeyPlayerStatType.isOffensive());
}
/******************************************************************************/
}; // ashockey
/******************************************************************************/
/******************************************************************************/
| [
"[email protected]"
]
| [
[
[
1,
58
]
]
]
|
6ea5a5410ae06ca3aef8ed1beaf47149da1ea2c4 | a52ab677945cab174095a4f2315a63acf1903567 | /p438/wiretap/trunk/pck_stats.cpp | 417aeccea86245d9d5a39ee9959b98371885bf98 | []
| no_license | grpatter/iu_cs_jegm | fe5f499c79fbbb7e0cd3d954d4fac95d0a0f631e | 2a2d45eb4f7c5560a945d94a0e4e32f50ca46817 | refs/heads/master | 2021-01-19T18:30:34.722909 | 2009-12-30T02:51:20 | 2009-12-30T02:51:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,726 | cpp | #include <map>
#include <string>//to support strings
#include "pck_stats.h"
using namespace std;
void show_pck_stats(void){
struct pck_stats *ptr_stats;
*ptr_stats = &cur_stats;
map<string,int>::iterator iter;
printf("\n*****Beginning packet statistics dump.*****\n");
for( iter = cur_stats->eth_uniq_src.begin(); iter != cur_stats->eth_uniq_src.end(); ++iter ) {
cout << "ESrcKey: '" << iter->first << "', ESrcValue: " << iter->second << endl;
}
for( iter = cur_stats->eth_uniq_dst.begin(); iter != cur_stats->eth_uniq_dst.end(); ++iter ) {
cout << "EDstKey: '" << iter->first << "', EDstValue: " << iter->second << endl;
}
for( iter = cur_stats->ip_uniq_src.begin(); iter != cur_stats->ip_uniq_src.end(); ++iter ) {
cout << "IPSrcKey: '" << iter->first << "', IPSrcValue: " << iter->second << endl;
}
for( iter = cur_stats->ip_uniq_dst.begin(); iter != cur_stats->ip_uniq_dst.end(); ++iter ) {
cout << "IPDstKey: '" << iter->first << "', IPDstValue: " << iter->second << endl;
}
map<int,int>::iterator iter2;
for( iter2 = cur_stats->udp_uniq_src.begin(); iter != cur_stats->udp_uniq_src.end(); ++iter2 ) {
cout << "UDPSrcKey: '" << iter->first << "', UDPSrcValue: " << iter->second << endl;
}
for( iter2 = cur_stats->udp_uniq_dst.begin(); iter != cur_stats->udp_uniq_dst.end(); ++iter2 ) {
cout << "UDPDstKey: '" << iter->first << "', UDPDstValue: " << iter->second << endl;
}
map<string,string>::iterator iter3;
for( iter3 = cur_stats->arp_machines.begin(); iter != cur_stats->arp_machines.end(); ++iter3 ) {
cout << "ARPKey: '" << iter->first << "', ARPValue: " << iter->second << endl;
}
printf("\n*****END packet statistics dump.*****\n");
}
| [
"[email protected]"
]
| [
[
[
1,
34
]
]
]
|
a2bf8f2f40081efe8c97d2e79fd8dc5e48300f96 | 2b32433353652d705e5558e7c2d5de8b9fbf8fc3 | /Dm_new_idz/Mlita/Exam/Ford_BelmanDlg.h | 637fd69c7864c1bc262ab0266f464699c9b6f90a | []
| no_license | smarthaert/d-edit | 70865143db2946dd29a4ff52cb36e85d18965be3 | 41d069236748c6e77a5a457280846a300d38e080 | refs/heads/master | 2020-04-23T12:21:51.180517 | 2011-01-30T00:37:18 | 2011-01-30T00:37:18 | 35,532,200 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,417 | h | //{{AFX_INCLUDES()
#include "msflexgrid.h"
//}}AFX_INCLUDES
#if !defined(AFX_FORD_BELMANDLG_H__081AEEAF_6DF5_4011_9824_9E3EF1C28FEC__INCLUDED_)
#define AFX_FORD_BELMANDLG_H__081AEEAF_6DF5_4011_9824_9E3EF1C28FEC__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// Ford_BelmanDlg.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// CFord_BelmanDlg dialog
class CGraph;
class CFord_BelmanDlg : public CDialog
{
// Construction
public:
CGraph* Graph;
CFord_BelmanDlg(CWnd* pParent = NULL); // standard constructor
// Dialog Data
//{{AFX_DATA(CFord_BelmanDlg)
enum { IDD = IDD_Ford_BelmanDlg };
CListBox m_PathCtrl;
CMSFlexGrid m_ACtrl;
UINT m_Destination;
CString m_Price;
UINT m_Source;
//}}AFX_DATA
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CFord_BelmanDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(CFord_BelmanDlg)
afx_msg void OnStart();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_FORD_BELMANDLG_H__081AEEAF_6DF5_4011_9824_9E3EF1C28FEC__INCLUDED_)
| [
"[email protected]"
]
| [
[
[
1,
55
]
]
]
|
dbca0abb6710994a0bd525009116ea794c3a2316 | 3761dcce2ce81abcbe6d421d8729af568d158209 | /src/cybergarage/upnp/device/NT.cpp | 5bcc33ac8c54ee1adad8f325e97a8fb87a84681b | [
"BSD-3-Clause"
]
| permissive | claymeng/CyberLink4CC | af424e7ca8529b62e049db71733be91df94bf4e7 | a1a830b7f4caaeafd5c2db44ad78fbb5b9f304b2 | refs/heads/master | 2021-01-17T07:51:48.231737 | 2011-04-08T15:10:49 | 2011-04-08T15:10:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 544 | cpp | /******************************************************************
*
* CyberLink for C++
*
* Copyright (C) Satoshi Konno 2002-2003
*
* File: NT.cpp
*
* Revision:
*
* 07/07/03
* - first revision
*
******************************************************************/
#include <cybergarage/upnp/device/NT.h>
#include <cybergarage/util/StringUtil.h>
bool CyberLink::NT::IsRootDevice(const char *ntValue)
{
if (ntValue == NULL)
return false;
CyberUtil::String ntStr = ntValue;
return ntStr.startsWith(ROOTDEVICE);
}
| [
"skonno@b944b01c-6696-4570-ab44-a0e08c11cb0e"
]
| [
[
[
1,
25
]
]
]
|
25a6ea22fd5a669e89f4066ef7282bf59be6243b | 2982a765bb21c5396587c86ecef8ca5eb100811f | /util/wm5/LibMathematics/Rational/Wm5IVector2.cpp | 9680484b48fcee59190ded8bc46abae6ba610791 | []
| no_license | evanw/cs224final | 1a68c6be4cf66a82c991c145bcf140d96af847aa | af2af32732535f2f58bf49ecb4615c80f141ea5b | refs/heads/master | 2023-05-30T19:48:26.968407 | 2011-05-10T16:21:37 | 2011-05-10T16:21:37 | 1,653,696 | 27 | 9 | null | null | null | null | UTF-8 | C++ | false | false | 2,113 | cpp | // Geometric Tools, LLC
// Copyright (c) 1998-2010
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
//
// File Version: 5.0.0 (2010/01/01)
#include "Wm5MathematicsPCH.h"
#include "Wm5IVector2.h"
using namespace Wm5;
//----------------------------------------------------------------------------
IVector2::IVector2 ()
{
// uninitialized
}
//----------------------------------------------------------------------------
IVector2::IVector2 (const IVector2& vec)
{
mTuple[0] = vec.mTuple[0];
mTuple[1] = vec.mTuple[1];
}
//----------------------------------------------------------------------------
IVector2::IVector2 (const IVector<2>& vec)
{
mTuple[0] = vec[0];
mTuple[1] = vec[1];
}
//----------------------------------------------------------------------------
IVector2::IVector2 (const int64_t& x, const int64_t& y)
{
mTuple[0] = x;
mTuple[1] = y;
}
//----------------------------------------------------------------------------
IVector2& IVector2::operator= (const IVector2& vec)
{
mTuple[0] = vec.mTuple[0];
mTuple[1] = vec.mTuple[1];
return *this;
}
//----------------------------------------------------------------------------
IVector2& IVector2::operator= (const IVector<2>& vec)
{
mTuple[0] = vec[0];
mTuple[1] = vec[1];
return *this;
}
//----------------------------------------------------------------------------
int64_t IVector2::Dot (const IVector2& vec) const
{
return mTuple[0]*vec.mTuple[0] + mTuple[1]*vec.mTuple[1];
}
//----------------------------------------------------------------------------
IVector2 IVector2::Perp () const
{
return IVector2(mTuple[1], -mTuple[0]);
}
//----------------------------------------------------------------------------
int64_t IVector2::DotPerp (const IVector2& vec) const
{
return mTuple[0]*vec.mTuple[1] - mTuple[1]*vec.mTuple[0];
}
//----------------------------------------------------------------------------
| [
"[email protected]"
]
| [
[
[
1,
65
]
]
]
|
22d48dafce730256aa6a27849619d33fbe060c7d | aee9f4a7a277c3f44eac40072adb81dc52db3079 | /Code/core/ComponentOutputFramesImages.h | 911fbd9a12f6eaae03ea66c520ffd01d25f9f020 | []
| no_license | SiChiTong/swistrackplus | 1a1bbc7dd8457ec908ced0cae3e30ef1f0d85551 | 7746c32dcfdbe1988c82e7a1561534c519ac0872 | refs/heads/master | 2020-04-05T02:31:55.840432 | 2010-06-01T14:12:46 | 2010-06-01T14:12:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,208 | h | #ifndef HEADER_ComponentOutputFramesImages
#define HEADER_ComponentOutputFramesImages
#include <vector>
#include <cv.h>
#include <highgui.h>
#include "Component.h"
//! An input component that reads an AVI file using the CV library.
class ComponentOutputFramesImages: public Component {
public:
enum eFileType { // see cvLoadImage for supported file types
FileTypePNG = 0,
FileTypeBMP = 1,
FileTypeJPEG = 2,
};
//! Constructor.
ComponentOutputFramesImages(SwisTrackCore *stc);
//! Destructor.
~ComponentOutputFramesImages();
// Overwritten Component methods
void OnStart();
void OnReloadConfiguration();
void OnStep();
void OnStepCleanup();
void OnStop();
Component *Create() {
return new ComponentOutputFramesImages(mCore);
}
void DrawParticles(Display *mDisplay, IplImage* mImage);
private:
int mInputSelection; //!< (configuration) Selects the input channel.
wxFileName mFileName; //!< (configuration) directory and filename prefix
eFileType mFileType; //!< (configuration) directory and filename prefix
Display mDisplayOutput; //!< The DisplayImage showing the output of this component.
CvFont mFontMain;
};
#endif
| [
"root@newport-ril-server.(none)",
"[email protected]"
]
| [
[
[
1,
31
],
[
34,
38
],
[
41,
44
]
],
[
[
32,
33
],
[
39,
40
]
]
]
|
bf6b886bddc95d24f6726c9c7bfc9e3f35fcefc8 | e7c45d18fa1e4285e5227e5984e07c47f8867d1d | /Common/Models/CONTROL2/OptLib/ZArrCode.hpp | 100423c7e78ae2581223a14a9fe9f2b03c2286ed | []
| no_license | abcweizhuo/Test3 | 0f3379e528a543c0d43aad09489b2444a2e0f86d | 128a4edcf9a93d36a45e5585b70dee75e4502db4 | refs/heads/master | 2021-01-17T01:59:39.357645 | 2008-08-20T00:00:29 | 2008-08-20T00:00:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,742 | hpp | #ifndef Z_ARR_CODE_HPP
#define Z_ARR_CODE_HPP
//-----------------------------------------------------------------------------
#include <stdlib.h>
#include "ZComplex.h"
#include "ZArr.hpp"
//-----------------------------------------------------------------------------
#ifdef DEBUG_MEMORY
#include "DebugMemory.h"
#endif
//-----------------------------------------------------------------------------
//#define DEBUG_MSG
//-----------------------------------------------------------------------------
#ifdef DEBUG_MSG
void print_carr_debug_msg(char *msg)
{
printf("ZArr::Debug:<%s>\n", msg);
}
#endif DEBUG_MSG
//-----------------------------------------------------------------------------
// CODE IMPLEMENTATION
//-----------------------------------------------------------------------------
template <typename Type>
ZArr<Type>::ZArr(int arraySize)
{
#ifdef DEBUG_MSG
print_carr_debug_msg("\"ZArr(int arraySize)\" called");
#endif
prSize = arraySize;
prA = new Type[arraySize];
#ifdef DEBUG_MEMORY
DebugMemAllocate((pvoid)prA, "ZArr::ZArr(int)");
#endif
}
//-----------------------------------------------------------------------------
template <typename Type>
ZArr<Type>::ZArr(const ZArr & Arr) // Copy Constructor
{
#ifdef DEBUG_MSG
print_carr_debug_msg("Copy constructor called");
#endif
prSize = Arr.prSize;
prA = new Type[prSize];
#ifdef DEBUG_MEMORY
DebugMemAllocate((pvoid)prA, "ZArr::ZArr(ZArr&)");
#endif
for (int i = 0; i < prSize; i++)
prA[i] = Arr.prA[i];
}
//-----------------------------------------------------------------------------
template <typename Type>
ZArr<Type>::ZArr(int arraySize, const Type & InitValue) // Gives an initial value
{
#ifdef DEBUG_MSG
print_carr_debug_msg("\"ZArr(int arraySize, const Type & InitValue)\" called");
#endif
int i;
prSize = arraySize;
prA = new Type[arraySize];
#ifdef DEBUG_MEMORY
DebugMemAllocate((pvoid)prA, "ZArr::ZArr(int,Type&)");
#endif
for (i = 0; i < arraySize; i++)
prA[i] = InitValue;
};
//-----------------------------------------------------------------------------
template <typename Type>
ZArr<Type>::~ZArr()
{
#ifdef DEBUG_MSG
print_carr_debug_msg("Destructor called");
#endif
if (prA)
{
#ifdef DEBUG_MEMORY
DebugMemDestroy((pvoid)prA, "ZArr::~ZArr");
#endif
delete [] prA;
}
}
//-----------------------------------------------------------------------------
template <typename Type>
Type & ZArr<Type>::operator[](int index) throw(ZException)
{
#ifdef DEBUG_MSG
print_carr_debug_msg("\"operator[](int index)\" called");
#endif
if ((index < 0) || (index >= prSize))
{
throw ZException("ZArr::operator[]:Error: index out of range",0);
} // ELSE
return prA[index];
};
//-----------------------------------------------------------------------------
template <typename Type>
const Type & ZArr<Type>::operator[](int index) const throw(ZException)
{
#ifdef DEBUG_MSG
print_carr_debug_msg("\"const operator[](int index) const\" called");
#endif
if ((index < 0) || (index >= prSize))
{
throw ZException("ZArr::operator[]:Error: index out of range",0);
} // ELSE
return prA[index];
}
//-----------------------------------------------------------------------------
template <typename Type>
ZArr<Type> & ZArr<Type>::operator=(const ZArr<Type> & rhs)
{
// this = rhs
// this = this.operator=(rhs)
#ifdef DEBUG_MSG
print_carr_debug_msg("\"operator=(ZArr<Type> & rhs)\" called");
#endif
int i;
if (rhs.prSize != this->prSize)
{
if (prA)
{
#ifdef DEBUG_MEMORY
DebugMemDestroy((pvoid)prA, "ZArr::operator=(ZArr&)");
#endif
delete [] prA;
}
prA = new Type[rhs.prSize];
#ifdef DEBUG_MEMORY
DebugMemAllocate((pvoid)prA, "ZArr::operator=(ZArr&)");
#endif
prSize = rhs.prSize;
} // IF
for (i = 0; i < rhs.prSize; i++)
{
prA[i] = rhs.prA[i];
} // FOR
return (*this);
}
//-----------------------------------------------------------------------------
template <typename Type>
ZArr<Type> ZArr<Type>::operator+(const ZArr<Type> & rhs)
{
// A = this + rhs
// A = this.operator+(rhs)
if (rhs.prSize != prSize)
{
cout << "Error in ZArr<Type>::operator+(ZArr<Type> & rhs). Different array sizes\n";
return this;
}
ZArr<Type> A(this.prSize);
for (int i = 0; i < prSize; i++)
A.prA[i] = prA[i] + rhs.prA[i];
return A; // Returns a copy of A that is used as the rhs arguament for the
// assignment operator method
}
//-----------------------------------------------------------------------------
template <typename Type>
ZArr<Type> ZArr<Type>::operator-(const ZArr<Type> & rhs)
{
// A = this - rhs
// A = this.operator-(rhs)
if (rhs.prSize != prSize)
{
cout << "Error in ZArr<Type>::operator-(ZArr<Type> & rhs). Different array sizes\n";
return this;
}
ZArr<Type> A(this.prSize);
for (int i = 0; i < prSize; i++)
A.prA[i] = prA[i] - rhs.prA[i];
return A; // Returns a copy of A that is used as the rhs arguament for the
// assignment operator method
}
//-----------------------------------------------------------------------------
template <typename Type>
ZArr<Type> ZArr<Type>::operator*(const Type & rhs)
{
// A = this*rhs
// A = this.operator*(rhs)
ZArr<Type> A(*this);
for (int i = 0; i < prSize; i++)
A.prA[i] *= rhs;
return A;
}
//-----------------------------------------------------------------------------
template <typename Type>
ZArr<Type> ZArr<Type>::operator*(const ZArr<Type> & rhs)
{
int size = this->prSize + rhs.prSize - 1;
ZArr<Type> tempArr(size);
int i, left, right;
for (i = 0; i < size; i++)
tempArr[i] = 0.0;
for (left = 0; left < this->prSize; left++)
for (right = 0; right < rhs.prSize; right++)
tempArr[left+right] += this->operator[](left)*rhs[right];
return tempArr;
}
//-----------------------------------------------------------------------------
template <typename Type>
ZArr<Type> ZArr<Type>::operator/(const Type & rhs)
{
// A = this/rhs // rhs == scalar
// A = this.operator/(rhs)
ZArr<Type> A(*this);
for (int i = 0; i < prSize; i++)
A.prA[i] /= rhs;
return A;
}
//-----------------------------------------------------------------------------
template <typename Type>
ZArr<Type> & ZArr<Type>::operator+=(const ZArr<Type> & rhs)
{
// this += rhs
// this.operator+=(rhs)
if (rhs.prSize != prSize)
{
cout << "Error in ZArr<Type>::operator+=(ZArr<Type> & rhs). Different array sizes\n";
return *this;
}
for (int i = 0; i < prSize; i++)
prA[i] += rhs.prA[i];
return *this;
}
//-----------------------------------------------------------------------------
template <typename Type>
ZArr<Type> & ZArr<Type>::operator-=(const ZArr<Type> & rhs)
{
// this -= rhs
// this.operator-=(rhs)
if (rhs.prSize != prSize)
{
cout << "Error in ZArr<Type>::operator-=(ZArr<Type> & rhs). Different array sizes\n";
return *this;
}
for (int i = 0; i < prSize; i++)
prA[i] -= rhs.prA[i];
return *this;
}
//-----------------------------------------------------------------------------
template <typename Type>
ZArr<Type> & ZArr<Type>::operator*=(const Type & rhs)
{
// this *= rhs // rhs is a scalar
// this.operator*=(rhs)
for (int i = 0; i < prSize; i++)
prA[i] *= rhs;
return *this;
}
//-----------------------------------------------------------------------------
template <typename Type>
ZArr<Type> & ZArr<Type>::operator*=(const ZArr<Type> & rhs)
{
int size = this->prSize + rhs.prSize - 1;
ZArr<Type> tempArr(size);
int i, left, right;
for (i = 0; i < size; i++)
tempArr[i] = 0.0;
for (left = 0; left < this->prSize; left++)
for (right = 0; right < rhs.prSize; right++)
tempArr[left+right] += this->operator[](left)*rhs[right];
(*this) = tempArr;
return *this;
}
//-----------------------------------------------------------------------------
template <typename Type>
ZArr<Type> & ZArr<Type>::operator/=(const Type & rhs)
{
// this /= rhs // rhs is a scalar
// this.operator/=(rhs)
for (int i = 0; i < prSize; i++)
prA[i] /= rhs;
return *this;
}
//-----------------------------------------------------------------------------
template <typename Type>
ZArr<Type> & ZArr<Type>::Set(Type arr[], int len)
{
if (len <= 0)
return *this;
if (prSize != len)
{
if (prA)
{
#ifdef DEBUG_MEMORY
DebugMemDestroy((pvoid)prA, "ZArr::Set(Type[],int)");
#endif
delete [] prA;
}
prA = new Type[len];
#ifdef DEBUG_MEMORY
DebugMemAllocate((pvoid)prA, "ZArr::Set(Type[],int)");
#endif
if (prA)
prSize = len;
else
prSize = 0;
}
if (prSize)
memcpy(prA, arr, sizeof(prA));
return *this;
}
//-----------------------------------------------------------------------------
template <typename Type>
ZArr<Type> & ZArr<Type>::Append(Type arr[], int len)
{
Type *pType;
int i;
if (len <= 0)
return *this;
pType = new Type[len + prSize];
#ifdef DEBUG_MEMORY
DebugMemAllocate((pvoid)pType, "ZArr::Append(Type,int)");
#endif
if (!pType)
return *this;
// copy old array into first part of new array
for (i = 0; i < prSize; i++)
pType[i] = prA[i];
// copy arr onto last part of new array
for (i = 0; i < len; i++)
pType[i+prSize] = arr[i];
prSize = prSize + len;
if (prA)
{
#ifdef DEBUG_MEMORY
DebugMemDestroy((pvoid)prA, "ZArr::Append(Type[],int)");
#endif
delete [] prA;
}
prA = pType;
return *this;
}
//-----------------------------------------------------------------------------
template <typename Type>
ZArr<Type> & ZArr<Type>::Append(Type Element)
{
Type *pType;
int i;
pType = new Type[prSize+1];
#ifdef DEBUG_MEMORY
DebugMemAllocate((pvoid)pType, "ZArr::Append(Type)");
#endif
if (!pType)
return *this;
// copy old array into first part of new array
for (i = 0; i < prSize; i++)
pType[i] = prA[i];
// copy arr onto last part of new array
pType[prSize] = Element;
prSize++;
if (prA)
{
#ifdef DEBUG_MEMORY
DebugMemDestroy((pvoid)prA, "ZArr::Append(Type)");
#endif
delete [] prA;
}
prA = pType;
return *this;
}
//-----------------------------------------------------------------------------
template <typename Type>
ZArr<Type> & ZArr<Type>::Delete(int index) throw(ZException)
{
if ((index >= prSize) || (index < 0))
{
throw ZException("ZArr<Type>::Delete: Index out of range",0);
}
if (prSize == 1)
{
#ifdef DEBUG_MEMORY
DebugMemDestroy((pvoid)prA, "ZArr::Delete(int)");
#endif
delete [] prA;
prSize = 0;
return *this;
}
Type *pType;
int i;
pType = new Type[prSize-1];
#ifdef DEBUG_MEMORY
DebugMemAllocate((pvoid)pType, "ZArr::Delete(int)");
#endif
if (!pType)
{
throw ZException("ZArr<Type>::Delete: Out of Memory",0);
}
// copy old array upto but not including index into first part of new array
for (i = 0; i < index; i++)
pType[i] = prA[i];
// copy rest of old array after index into rest of new array
for (i = index+1; i < prSize; i++)
pType[i-1] = prA[i];
prSize--;
if (prA)
{
#ifdef DEBUG_MEMORY
DebugMemDestroy((pvoid)prA, "ZArr::Delete(int)");
#endif
delete [] prA;
}
prA = pType;
return *this;
}
//-----------------------------------------------------------------------------
template <typename Type>
const Type * ZArr<Type>::Get(int * len) const
{
(*len) = prSize;
return prA;
}
//-----------------------------------------------------------------------------
template <typename Type>
Type* ZArr<Type>::GetArrPointer(void) const
{
return prA;
}
//-----------------------------------------------------------------------------
template <typename Type>
ZArr<Type> ZArr<Type>::SubArr(int index, int count)
{
ZArr tempArr(0);
if ((index < 0) || ((index + count) > prSize))
{
printf("Index/count out of range");
return tempArr;
}
if (count == 0)
return tempArr;
if (count < 0)
{
printf("count < 0");
return tempArr;
}
tempArr.SetLength(count);
for (int i = index; i < index+count; i++)
tempArr[i - index] = prA[i];
return tempArr;
}
//-----------------------------------------------------------------------------
template <typename Type>
ZArr<Type> ZArr<Type>::SubArr(int index)
{
int count = prSize - index;
return SubArr(index,count);
}
//-----------------------------------------------------------------------------
template <typename Type>
const int ZArr<Type>::Length(void) const
{
return prSize;
}
//-----------------------------------------------------------------------------
template <typename Type>
const int ZArr<Type>::Count(void) const
{
return prSize;
}
//-----------------------------------------------------------------------------
template <typename Type>
void ZArr<Type>::SetLength(int Size)
{
Type *pType;
int n;
if (prSize != Size)
{
pType = new Type[Size];
#ifdef DEBUG_MEMORY
DebugMemAllocate((pvoid)pType, "ZArr::SetLength(int)");
#endif
n = prSize;
if (n > Size)
n = Size;
for (int i = 0; i < n; i++)
pType[i] = prA[i];
if (prA)
{
#ifdef DEBUG_MEMORY
DebugMemDestroy((pvoid)prA, "ZArr::SetLength(int)");
#endif
delete [] prA;
}
prA = pType;
prSize = Size;
}
}
//-----------------------------------------------------------------------------
template <typename Type>
ZArr<Type> & ZArr<Type>::DoReset()
{
if (prA)
{
#ifdef DEBUG_MEMORY
DebugMemDestroy((pvoid)prA, "ZArr::DoReset()");
#endif
delete [] prA;
}
prA = NULL;
prSize = 0;
return *this;
}
//-----------------------------------------------------------------------------
// friend class
template <typename Type>
std::ostream & operator<<(std::ostream & os, const ZArr<Type> & rhs)
{
#ifdef DEBUG_MSG
print_carr_debug_msg("\"operator<<(ostream & os, ZArr<Type> & rhs)\" called");
#endif
int i;
if (rhs.prSize == 0)
{
os << "[]";
return os;
}
os << "[" << rhs.prA[0];
for ( i = 1; i < rhs.prSize; i++)
{
os << "," << rhs.prA[i];
if ((i % 5 == 4) && (i != (rhs.prSize-1)))
os << endl;
} // FOR
os << "]";
return os;
}
//-----------------------------------------------------------------------------
#endif Z_ARR_CODE_HPP | [
"[email protected]"
]
| [
[
[
1,
620
]
]
]
|
d4f168e8ea42f6f0d6b31fd21ebd8fc5793d7f6a | 5fea042a436493f474afaf862ea592fa37c506ab | /Antihack/connection.h | 5749856e582e61e9ce19356ee18ea660c916837a | []
| no_license | Danteoriginal/twilight-antihack | 9fde8fbd2f34954752dc2de3927490d657b43739 | 4ccc51c13c33abcb5e370ef1b992436e6a1533c9 | refs/heads/master | 2021-01-13T06:25:31.618338 | 2009-10-25T14:44:34 | 2009-10-25T14:44:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 538 | h | #ifndef INC_CONNECTION
#define INC_CONNECTION
#include <windows.h>
#include <winsock.h>
#include <string>
#include <list>
#include "packet.h"
#pragma comment(lib, "wsock32.lib")
class CConnection {
public:
CConnection();
~CConnection();
int Init(SOCKET s);
int Shutdown(SOCKET s);
int Connected();
int SendBuffer(void* buffer, unsigned int size);
int ReceiveBuffer(void* buffer, unsigned int size);
int SendPacket(PACKET* packet);
private:
SOCKET hSocket;
int connected;
};
#endif | [
"[email protected]"
]
| [
[
[
1,
30
]
]
]
|
95be244b419b3f74cd724a730f14a8738a186f07 | ed2a1c83681d8ed2d08f8a74707536791e5cd057 | /d3d8.DLL/Built-in Extension Files/Computron Files/Computron.cpp | 0ac7b9320cf9ee4bb307219de16b01057072dead | [
"Apache-2.0"
]
| permissive | MartinMReed/XenDLL | e33d5c27187e58fd4401b2dbcaae3ebab8279bc2 | 51a05c3cec7b2142f704f2ea131202a72de843ec | refs/heads/master | 2021-01-10T19:10:40.492482 | 2007-10-31T16:38:00 | 2007-10-31T16:38:00 | 12,150,175 | 13 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 56,197 | cpp | #include "WinPcap Files/WinPcap.h"
#include "../../CustomDevice Files/CustomDevice.h"
unsigned threadA;
unsigned __stdcall RunThreadA(void* params);
unsigned threadB;
unsigned __stdcall RunThreadB(void* params);
Computron* g_Computron = NULL;
//-------------------------------------------------------
//
//-------------------------------------------------------
bool Computron::Initialize(void)
{
initialized = false;
const char* data = NULL;
char buffer[256];
// make sure the menu item texture exists
if (GetFileAttributes("XenDLL Files/Extensions/Computron/Computron.bmp") == 0xFFFFFFFF)
return Uninitialize();
// create the texture for the menu item
IDDTexture* bmpComputron = _CreateIDDTextureFromFile(64.0f, 64.0f, "XenDLL Files/Extensions/Computron/Computron.bmp", COLOR_RED);
// create the extension
extComputron = _CreateExtension( // Function
bmpComputron, // Texture
NULL); // Rect
// load the extension menu item io information
data = _ReadConfigItem("MenuItemIO", "XenDLL Files/Extensions/Computron/Computron.xml");
if (data && _stricmp(data, "true") == 0)
{
_SetExtMenuIO(extComputron, true);
}
else
{
_SetExtMenuIO(extComputron, false);
}
// if the folder does not exist, create it
if (GetFileAttributes("XenDLL Files/Extensions/Computron/Scripts/") == 0xFFFFFFFF)
CreateDirectory("XenDLL Files/Extensions/Computron/Scripts/", NULL);
// open an internet connection
g_hInet = InternetOpen(
"computron",
INTERNET_OPEN_TYPE_DIRECT,
NULL,
NULL,
0);
// connect to the server
if (g_hInet)
{
g_hInetConnection = InternetConnect(
g_hInet,
"calc.xentales.com",
INTERNET_DEFAULT_HTTP_PORT,
NULL,
NULL,
INTERNET_SERVICE_HTTP,
INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_NO_CACHE_WRITE,
0);
}
if (g_hInet == NULL || g_hInetConnection == NULL)
{
return Uninitialize();
}
// load the script filename
if (data = _ReadConfigItem("scriptFilename", "XenDLL Files/Extensions/Computron/Computron.xml"))
{
scriptFilename = _restring(data, 0, strlen(data));
}
else
{
_WriteConfigItem("scriptFilename", scriptFilename, "XenDLL Files/Extensions/Computron/Computron.xml");
}
// load the user handle
if (data = _ReadConfigItem("scriptHandle", "XenDLL Files/Extensions/Computron/Computron.xml"))
{
scriptHandle = _restring(data, 0, strlen(data));
}
else
{
_WriteConfigItem("scriptHandle", scriptHandle, "XenDLL Files/Extensions/Computron/Computron.xml");
}
// load the user password
if (data = _ReadConfigItem("scriptPassword", "XenDLL Files/Extensions/Computron/Computron.xml"))
{
scriptPassword = _restring(data, 0, strlen(data));
}
else
{
_WriteConfigItem("scriptPassword", scriptPassword, "XenDLL Files/Extensions/Computron/Computron.xml");
}
char* badLogin = NULL;
// send login information to the server
sprintf_s(buffer, sizeof(buffer), "xendll/computron/login.game.php?handle=%s&password=%s", scriptHandle, scriptPassword);
string receivedData = ReceiveData(buffer);
const char* loginData = receivedData.c_str();
// check the response
if (_stricmp(loginData, "b63265c00d6eaf05a6a6b20511247bfd") == 0)
{
// send script information to the server
sprintf_s(buffer, sizeof(buffer), "xendll/computron/download.script.php?script=%s&handle=%s&password=%s", scriptFilename, scriptHandle, scriptPassword);
receivedData = ReceiveData(buffer);
const char* scriptData = receivedData.c_str();
if (_stricmp(scriptData, "Failed to connect!") == 0)
{
badLogin = "Failed to connect!";
}
else if (_stricmp(scriptData, "Incorrect login.") == 0)
{
badLogin = "Incorrect login.";
}
else if (_stricmp(scriptData, "Script not found.") == 0)
{
badLogin = "Script not found.";
}
else
{
// write the script to a file
FILE* out = NULL;
sprintf_s(buffer, sizeof(buffer), "XenDLL Files/Extensions/Computron/Scripts/%s.xml", scriptFilename);
fopen_s(&out, buffer, "w");
if (out)
{
fprintf(out, "%s", scriptData);
fclose(out);
}
}
}
else
{
if (_stricmp(loginData, "Failed to connect!") == 0)
{
badLogin = "Failed to connect!";
}
else
{
badLogin = "Incorrect login.";
}
}
// check the response
if (badLogin != NULL)
{
// tell the user what went wrong
p1TextBar1 = _CreateTextBar(
badLogin,
1.0f,
1.0f);
_AttachObject2(extComputron, p1TextBar1);
_Move(
p1TextBar1,
(_ScreenWidth() - _GetWidth(p1TextBar1)) / 2.0f,
(_ScreenHeight() - _GetHeight(p1TextBar1)) / 2.0f);
logout = true;
initialized = true;
}
else
{
// load a memory address
if (data = _ReadConfigItem("progressXP", "XenDLL Files/Memory.xml"))
{
try
{
g_progressXP = (BYTE*)atoi(data);
}
catch (...) { return Uninitialize(); }
}
else
{
return Uninitialize();
}
// load a memory address
if (data = _ReadConfigItem("progressMP", "XenDLL Files/Memory.xml"))
{
try
{
g_progressMP = (BYTE*)atoi(data);
}
catch (...) { return Uninitialize(); }
}
else
{
return Uninitialize();
}
// load a memory address
if (data = _ReadConfigItem("progressHP", "XenDLL Files/Memory.xml"))
{
try
{
g_progressHP = (BYTE*)atoi(data);
}
catch (...) { return Uninitialize(); }
}
else
{
return Uninitialize();
}
// load a memory address
if (data = _ReadConfigItem("locationX", "XenDLL Files/Memory.xml"))
{
try
{
g_locationX = (DWORD*)atoi(data);
}
catch (...) { return Uninitialize(); }
}
else
{
return Uninitialize();
}
// load a memory address
if (data = _ReadConfigItem("locationY", "XenDLL Files/Memory.xml"))
{
try
{
g_locationY = (DWORD*)atoi(data);
}
catch (...) { return Uninitialize(); }
}
else
{
return Uninitialize();
}
// load start/play key
data = _ReadConfigItem("pauseRestartKey", "XenDLL Files/Extensions/Computron/Computron.xml");
if (data == NULL || (pauseRestartKey = _convertDIK_Name(data)) == 0x00)
{
pauseRestartKey = 0x00;
_WriteConfigItem("pauseRestartKey", "0x00", "XenDLL Files/Extensions/Computron/Computron.xml");
}
// load pause/play key
data = _ReadConfigItem("pauseResumeKey", "XenDLL Files/Extensions/Computron/Computron.xml");
if (data == NULL || (pauseResumeKey = _convertDIK_Name(data)) == 0x00)
{
pauseResumeKey = 0x00;
_WriteConfigItem("pauseResumeKey", "0x00", "XenDLL Files/Extensions/Computron/Computron.xml");
}
////////////////////////////////////////////////////////////////////////////
char currentDirectory[MAX_PATH];
GetCurrentDirectory(sizeof(currentDirectory), currentDirectory);
char WanPacketDll[MAX_PATH];
char PacketDll[MAX_PATH];
char pthreadVCDll[MAX_PATH];
char wpcapDll[MAX_PATH];
sprintf_s(WanPacketDll, sizeof(WanPacketDll), "%s/XenDLL Files/Extensions/Computron/WinPcap/WanPacket.dll", currentDirectory);
sprintf_s(PacketDll, sizeof(PacketDll), "%s/XenDLL Files/Extensions/Computron/WinPcap/Packet.dll", currentDirectory);
sprintf_s(pthreadVCDll, sizeof(pthreadVCDll), "%s/XenDLL Files/Extensions/Computron/WinPcap/pthreadVC.dll", currentDirectory);
sprintf_s(wpcapDll, sizeof(wpcapDll), "%s/XenDLL Files/Extensions/Computron/WinPcap/wpcap.dll", currentDirectory);
if (GetFileAttributes(WanPacketDll) == 0xFFFFFFFF ||
GetFileAttributes(PacketDll) == 0xFFFFFFFF ||
GetFileAttributes(pthreadVCDll) == 0xFFFFFFFF ||
GetFileAttributes(wpcapDll) == 0xFFFFFFFF)
return Uninitialize();
if (!(WanPacketMod = LoadLibrary(WanPacketDll)) ||
!(PacketMod = LoadLibrary(PacketDll)) ||
!(pthreadVCMod = LoadLibrary(pthreadVCDll)) ||
!(wpcapMod = LoadLibrary(wpcapDll)))
return Uninitialize();
if (!(_pcap_createsrcstr = (f_pcap_createsrcstr)GetProcAddress(wpcapMod, "pcap_createsrcstr")) ||
!(_pcap_open = (f_pcap_open)GetProcAddress(wpcapMod, "pcap_open")) ||
!(_pcap_datalink = (f_pcap_datalink)GetProcAddress(wpcapMod, "pcap_datalink")) ||
!(_pcap_sendqueue_alloc = (f_pcap_sendqueue_alloc)GetProcAddress(wpcapMod, "pcap_sendqueue_alloc")) ||
!(_pcap_next_ex = (f_pcap_next_ex)GetProcAddress(wpcapMod, "pcap_next_ex")) ||
!(_pcap_sendqueue_queue = (f_pcap_sendqueue_queue)GetProcAddress(wpcapMod, "pcap_sendqueue_queue")) ||
!(_pcap_sendqueue_destroy = (f_pcap_sendqueue_destroy)GetProcAddress(wpcapMod, "pcap_sendqueue_destroy")) ||
!(_pcap_sendqueue_transmit = (f_pcap_sendqueue_transmit)GetProcAddress(wpcapMod, "pcap_sendqueue_transmit")) ||
!(_pcap_geterr = (f_pcap_geterr)GetProcAddress(wpcapMod, "pcap_geterr")) ||
!(_pcap_close = (f_pcap_close)GetProcAddress(wpcapMod, "pcap_close")))
return Uninitialize();
////////////////////////////////////////////////////////////////////////////
IDDTexture* bmpList = _CreateIDDTextureFromFile(512.0f, 512.0f, "XenDLL Files/Images/list.bmp", COLOR_RED);
RECT rect;
SetRect(&rect, DefaultList_left, DefaultList_top, DefaultList_right, DefaultList_bottom);
panel1 = _CreateImage(
0.85f,
1.0f,
bmpList,
&rect);
_AttachObject2(extComputron, panel1);
float p1Width = _GetWidth(panel1) / _GetWidthScale(panel1);
float p1Height = _GetHeight(panel1) / _GetHeightScale(panel1);
_SetMoveable(panel1, MOVE_ALWAYS);
_Move(
panel1,
10.0f,
10.0f);
p1Width = _GetWidth(panel1);
p1Height = _GetHeight(panel1);
///
p1TextBar1 = _CreateTextBar( // Function
"Computron", // Description
1.0f, // Width Scale 0.0f - 1.0f+
1.0f); // Height Scale 0.0f - 1.0f+
_AttachObject1(panel1, p1TextBar1);
float tb1Width = _GetWidth(p1TextBar1) / _GetWidthScale(p1TextBar1);
float tb1Height = _GetHeight(p1TextBar1) / _GetHeightScale(p1TextBar1);
_SetStickyIO(p1TextBar1, true);
_Move(
p1TextBar1,
10.0f,
10.0f);
_ReScale(
p1TextBar1,
(tb1Width - abs(p1Width - tb1Width) - 20.0f) / (p1Width + abs(p1Width - tb1Width)),
0.5f);
tb1Width = _GetWidth(p1TextBar1);
tb1Height = _GetHeight(p1TextBar1);
///
float textScale = 0.5f;
p1ListViewer1 = _CreateListViewer(2.0f, 2.0f, true, textScale);
_AttachObject1(panel1, p1ListViewer1);
float lv1Width = _GetWidth(p1ListViewer1) / _GetWidthScale(p1ListViewer1);
float lv1Height = _GetHeight(p1ListViewer1) / _GetHeightScale(p1ListViewer1);
_SetAcceptAction(p1ListViewer1, false);
_SetBorderWidth(p1ListViewer1, 6.0f);
_SetBorderHeight(p1ListViewer1, 6.0f);
_Move(
p1ListViewer1,
10.0f,
_GetHeight(p1TextBar1) + 15.0f);
_ReScaleByLines(
p1ListViewer1,
(lv1Width - abs(p1Width - lv1Width) - 20.0f) / (p1Width + abs(p1Width - lv1Width)),
17);
lv1Width = _GetWidth(p1ListViewer1);
lv1Height = _GetHeight(p1ListViewer1);
_LoadString(p1ListViewer1, "Actual Surf ::"); // 0
_LoadString(p1ListViewer1, "HP ::"); // 1
_LoadString(p1ListViewer1, "MP ::"); // 2
_LoadString(p1ListViewer1, "XP ::"); // 3
_LoadString(p1ListViewer1, "LOC ::"); // 4
_LoadString(p1ListViewer1, ""); // 5
_LoadString(p1ListViewer1, "Previous ::"); // 6
_LoadString(p1ListViewer1, "Next ::"); // 7
_LoadString(p1ListViewer1, "Comment ::"); // 8
_LoadString(p1ListViewer1, "Command ::"); // 9
_LoadString(p1ListViewer1, "Expected Surf ::"); // 10
_LoadString(p1ListViewer1, "Expected LOC ::"); // 11
_LoadString(p1ListViewer1, ""); // 12
_LoadString(p1ListViewer1, "% Per Hour"); // 13
_LoadString(p1ListViewer1, "Hours till 100%"); // 14
_LoadString(p1ListViewer1, "% in %f hours"); // 15
_LoadString(p1ListViewer1, "Running for the last %f hours"); // 16
///
p1ListViewer2 = _CreateListViewer(2.0f, 2.0f, true, textScale);
_AttachObject1(panel1, p1ListViewer2);
float lv2Width = _GetWidth(p1ListViewer2) / _GetWidthScale(p1ListViewer2);
float lv2Height = _GetHeight(p1ListViewer2) / _GetHeightScale(p1ListViewer2);
_SetAcceptAction(p1ListViewer2, false);
_SetBorderWidth(p1ListViewer2, 6.0f);
_SetBorderHeight(p1ListViewer2, 6.0f);
_Move(
p1ListViewer2,
10.0f,
_GetHeight(p1TextBar1) + _GetHeight(p1ListViewer1) + 20.0f);
_ReScaleByLines(
p1ListViewer2,
(lv2Width - abs(p1Width - lv2Width) - 20.0f) / (p1Width + abs(p1Width - lv2Width)),
5);
lv2Width = _GetWidth(p1ListViewer2);
lv2Height = _GetHeight(p1ListViewer2);
///
float innerHeight = tb1Height + 5.0f + lv1Height + 5.0f + lv2Height;
p1Width = _GetWidth(panel1) / _GetWidthScale(panel1);
p1Height = _GetHeight(panel1) / _GetHeightScale(panel1);
_ReScale(
panel1,
0.85f,
(p1Height - abs(innerHeight - p1Height) + 20.0f) / (innerHeight + abs(innerHeight - p1Height)));
////////////////////////////////////////////////////////////////////////////
// open and read the script file
ReadScriptFile();
// reset the warning log
ClearWarnLog();
initialized = true;
// run the script
_beginthreadex(NULL, 0, RunThreadA, NULL, 0, &threadA);
// do a continuous memory check
_beginthreadex(NULL, 0, RunThreadB, NULL, 0, &threadB);
}
return initialized;
}
//-------------------------------------------------------
//
//-------------------------------------------------------
void Computron::Render(void)
{
if (logout)
{
_ActivateFull2(extComputron, _CheckExtMenuIO(extComputron));
return;
}
// take a screenshot
if (g_Screenshot && g_Screenshot->initialized && captureScreen)
g_Screenshot->CaptureScreen();
_ActivateFull2(extComputron, _CheckExtMenuIO(extComputron));
float p1Height = _GetHeight(panel1) / _GetHeightScale(panel1);
if (_CheckExtMenuIO(extComputron) && _GetIO(p1TextBar1))
{
_ActivateFull1(p1ListViewer1, false);
_ActivateFull1(p1ListViewer2, false);
_ReScale(
panel1,
_GetWidthScale(panel1),
(_GetHeight(p1TextBar1) + 20.0f) / p1Height);
}
else if (_CheckExtMenuIO(extComputron))
{
_ReScale(
panel1,
_GetWidthScale(panel1),
(_GetHeight(p1TextBar1) + _GetHeight(p1ListViewer1) + _GetHeight(p1ListViewer2) + 30.0f) / p1Height);
char buffer[256];
sprintf_s(buffer, sizeof(buffer), "Actual Surf :: %i", surfSaved);
_SetStringAt(p1ListViewer1, 0, buffer);
sprintf_s(buffer, sizeof(buffer), "HP :: %f %%", progressHP);
_SetStringAt(p1ListViewer1, 1, buffer);
sprintf_s(buffer, sizeof(buffer), "MP :: %f %%", progressMP);
_SetStringAt(p1ListViewer1, 2, buffer);
sprintf_s(buffer, sizeof(buffer), "XP :: %f %%", progressXP);
_SetStringAt(p1ListViewer1, 3, buffer);
sprintf_s(buffer, sizeof(buffer), "LOC :: %i , %i", locationX, locationY);
_SetStringAt(p1ListViewer1, 4, buffer);
///
if (instrucPrevious)
sprintf_s(buffer, sizeof(buffer), "Previous :: %i of %i", instrucPrevious->GetInstrucPosition() + 1, countTotal);
else
sprintf_s(buffer, sizeof(buffer), "Previous :: ? of %i", countTotal);
_SetStringAt(p1ListViewer1, 6, buffer);
///
if (!transform && ((int)((float)timeGetTime() / 100.0f) % 3) != 0)
{
if (instrucCurrent)
_SetStringAt(p1ListViewer1, 7, "Next :: stopped");
else
_SetStringAt(p1ListViewer1, 7, "Next :: zero instructions");
}
else
{
_SetStringAt(p1ListViewer1, 7, "-");
}
///
if (instrucCurrent)
{
if (transform)
{
if (!okayHP && !okayMP)
{
sprintf_s(buffer, sizeof(buffer), "Next :: %i%% HP, %i%% MP", 100 - (int)progressHP, 100 - (int)progressMP);
}
else if (okayHP == false)
{
sprintf_s(buffer, sizeof(buffer), "Next :: %i%% HP", 100 - (int)progressHP);
}
else if (okayMP == false)
{
sprintf_s(buffer, sizeof(buffer), "Next :: %i%% MP", 100 - (int)progressMP);
}
else if (instrucPrevious && instrucPrevious->GetInstrucPauseA() != instrucPrevious->GetInstrucPauseB())
{
sprintf_s(buffer, sizeof(buffer), "Next :: (r)%f", pauseLength - (((float)timeGetTime() / 1000.0f) - pauseStart));
}
else
{
sprintf_s(buffer, sizeof(buffer), "Next :: %f", pauseLength - (((float)timeGetTime() / 1000.0f) - pauseStart));
}
_SetStringAt(p1ListViewer1, 7, buffer);
}
//
sprintf_s(buffer, sizeof(buffer), "Comment :: %s", instrucCurrent->GetInstrucComment());
_SetStringAt(p1ListViewer1, 8, buffer);
///
if (instrucCurrent->GetInstrucUseKeystroke())
{
sprintf_s(buffer, sizeof(buffer), "Keystroke :: %s", _convertDIK_Key(instrucCurrent->GetInstrucKeystrokeCode()));
}
else if (instrucCurrent->GetInstrucUseMouseClick())
{
sprintf_s(buffer, sizeof(buffer), "Mouse Click :: (%i , %i)",
instrucCurrent->GetInstrucMouseClickX(),
instrucCurrent->GetInstrucMouseClickY());
}
else if (instrucCurrent->GetInstrucSendPacket())
{
sprintf_s(buffer, sizeof(buffer), "Send Packet :: %s.cap", instrucCurrent->GetInstrucPacketFile());
}
else
sprintf_s(buffer, sizeof(buffer), "Command :: Pause Only");
_SetStringAt(p1ListViewer1, 9, buffer);
///
if (instrucCurrent->GetSafetyUseSurfCheck())
{
sprintf_s(buffer, sizeof(buffer), "Expected Surf :: %i - %i",
instrucCurrent->GetSafetySurfMin(), instrucCurrent->GetSafetySurfMax());
}
else
sprintf_s(buffer, sizeof(buffer), "Expected Surf :: none");
_SetStringAt(p1ListViewer1, 10, buffer);
///
if (instrucCurrent->GetSafetyUseCoordCheck())
{
sprintf_s(buffer, sizeof(buffer), "Expected LOC :: %i , %i",
instrucCurrent->GetSafetyCoordX(), instrucCurrent->GetSafetyCoordY());
}
else
sprintf_s(buffer, sizeof(buffer), "Expected LOC :: none");
_SetStringAt(p1ListViewer1, 11, buffer);
///
float running_for = ((((float)timeGetTime() / 1000.0f) - startPerc) / 3600.0f);
if (transform && lastXP != initPerc && percPerHr != 0.0f)
sprintf_s(buffer, sizeof(buffer), "%% Per Hour = %f", percPerHr);
else if (transform == false)
sprintf_s(buffer, sizeof(buffer), "%% Per Hour = ?");
else
sprintf_s(buffer, sizeof(buffer), "[will start after next %% hits]");
_SetStringAt(p1ListViewer1, 13, buffer);
///
if (transform && lastXP != initPerc && hrTillHundert != 0.0f)
sprintf_s(buffer, sizeof(buffer), "Hours till 100%% = %f", (hrTillHundert - (running_for - endPerc)));
else if (transform == false)
sprintf_s(buffer, sizeof(buffer), "Hours till 100%% = ?");
else
sprintf_s(buffer, sizeof(buffer), "[will start after next %% hits]");
_SetStringAt(p1ListViewer1, 14, buffer);
///
if (transform && lastXP != initPerc)
sprintf_s(buffer, sizeof(buffer), "%f%% in %f hours", totalPerc, endPerc);
else if (transform == false)
sprintf_s(buffer, sizeof(buffer), "?%% in ? hours");
else
sprintf_s(buffer, sizeof(buffer), "[will start after next %% hits]");
_SetStringAt(p1ListViewer1, 15, buffer);
///
if (transform && lastXP != initPerc)
sprintf_s(buffer, sizeof(buffer), "Running for the last %f hours", running_for);
else if (transform == false)
sprintf_s(buffer, sizeof(buffer), "Running for the last ? hours");
else
sprintf_s(buffer, sizeof(buffer), "[will start after next %% hits]");
_SetStringAt(p1ListViewer1, 16, buffer);
}
else
{
_SetStringAt(p1ListViewer1, 8, "-");
_SetStringAt(p1ListViewer1, 9, "-");
_SetStringAt(p1ListViewer1, 10, "-");
_SetStringAt(p1ListViewer1, 11, "-");
_SetStringAt(p1ListViewer1, 13, "-");
_SetStringAt(p1ListViewer1, 14, "-");
_SetStringAt(p1ListViewer1, 15, "-");
_SetStringAt(p1ListViewer1, 16, "-");
}
///
float textScale = 0.5f;
float fontWidth = textScale * _FontWidth();
float fontHeight = textScale * _FontHeight();
_DrawText(
scriptFilename,
_ScreenWidth() - (fontWidth * strlen(scriptFilename)),
fontHeight * 0.0f,
textScale,
COLOR_WHITE);
sprintf_s(buffer, sizeof(buffer), "script has run %i times full through", ranTimes);
_DrawText(
buffer,
_ScreenWidth() - (fontWidth * strlen(buffer)),
fontHeight * 1.0f,
textScale,
COLOR_WHITE);
///
if (jreturnStack)
{
sprintf_s(buffer, sizeof(buffer), "Jump and Link Stack ");
_DrawText(
buffer,
_ScreenWidth() - (fontWidth * strlen(buffer)),
250.0f + (fontHeight * 0.0f),
textScale,
COLOR_WHITE);
sprintf_s(buffer, sizeof(buffer), "(Top 10 Instructions)");
_DrawText(
buffer,
_ScreenWidth() - (fontWidth * strlen(buffer)),
250.0f + (fontHeight * 1.0f),
textScale,
COLOR_WHITE);
sprintf_s(buffer, sizeof(buffer), "---------------------");
_DrawText(
buffer,
_ScreenWidth() - (fontWidth * strlen(buffer)),
250.0f + (fontHeight * 2.0f),
textScale,
COLOR_WHITE);
JReturnStack* temp = jreturnStack;
for (int i = 0; temp != NULL && i < 10; i++)
{
if ((temp->GetJReturn())->GetWarningsJAL() == false)
sprintf_s(buffer, sizeof(buffer), "no return");
else
sprintf_s(buffer, sizeof(buffer), "return");
if (i == 0)
sprintf_s(buffer, sizeof(buffer), "%s (%s, in %i)", (temp->GetJReturn())->GetInstrucComment(), buffer, (temp->GetJReturnFrom() - instrucCurrent->GetInstrucPosition()));
else
sprintf_s(buffer, sizeof(buffer), "%s (%s, in x)", (temp->GetJReturn())->GetInstrucComment(), buffer);
_DrawText(
buffer,
_ScreenWidth() - (fontWidth * strlen(buffer)),
250.0f + (fontHeight * (3.0f + i)),
textScale,
COLOR_WHITE);
temp = temp->GetNext();
}
}
DrawCursor();
}
captureScreen = false;
}
//-------------------------------------------------------
//
//-------------------------------------------------------
void Computron::DrawCursor()
{
char cursorXText[256];
char cursorYText[256];
sprintf_s(cursorXText, sizeof(cursorXText), "x: %i", (int)_Mouse().CursorX);
sprintf_s(cursorYText, sizeof(cursorYText), "y: %i", (int)_Mouse().CursorY);
float cursorX = _X2W(_Mouse().CursorX);
float cursorY = _Y2H(_Mouse().CursorY);
float x = 0.0f;
float xy = 0.0f;
float yy = 0.0f;
float textScale = 0.5f;
float fontWidth = textScale * _FontWidth();
float fontHeight = textScale * _FontHeight();
if (cursorY + 85.0f >= _ScreenHeight())
{
xy = _ScreenHeight() - (fontHeight * 2.0f);
yy = _ScreenHeight() - (fontHeight * 1.0f);
}
else
{
xy = cursorY + 85.0f - (fontHeight * 2.0f);
yy = cursorY + 85.0f - (fontHeight * 1.0f);
}
int longer = strlen(cursorYText);
if (strlen(cursorXText) > strlen(cursorYText))
{
longer = strlen(cursorXText);
}
if (cursorX + (fontWidth * longer) >= _ScreenWidth())
{
x = _ScreenWidth() - (fontWidth * longer);
}
else
{
x = cursorX;
}
_DrawText(cursorXText, x, xy, textScale, COLOR_WHITE);
_DrawText(cursorYText, x, yy, textScale, COLOR_WHITE);
}
//-------------------------------------------------------
//
//-------------------------------------------------------
unsigned __stdcall RunThreadA(void* params)
{
while (g_Computron && g_Computron->initialized)
{
g_Computron->ScriptCycleProc();
Sleep(1);
}
return 0;
}
//-------------------------------------------------------
//
//-------------------------------------------------------
unsigned __stdcall RunThreadB(void* params)
{
while (g_Computron && g_Computron->initialized)
{
g_Computron->MemoryCheckProc();
Sleep(1);
}
return 0;
}
//-------------------------------------------------------
//
//-------------------------------------------------------
string Computron::ReceiveData(char* threadcBuff)
{
string receivedData = "Failed to connect!";
HINTERNET g_hInetRequest;
if (g_hInetConnection)
{
g_hInetRequest = HttpOpenRequest(
g_hInetConnection,
"GET",
threadcBuff,
HTTP_VERSION,
NULL,
NULL,
INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_RELOAD | INTERNET_FLAG_PRAGMA_NOCACHE,
0);
if (g_hInetRequest && HttpSendRequest(g_hInetRequest,NULL, 0, NULL, 0) == TRUE)
{
char buffer[256];
DWORD byteCount;
BOOL received = InternetReadFile(g_hInetRequest, buffer, 256, &byteCount);
if (received)
receivedData = "";
while (received && (byteCount > 0))
{
receivedData.append(buffer, byteCount);
received = InternetReadFile(g_hInetRequest, buffer, 256, &byteCount);
}
InternetCloseHandle(g_hInetRequest);
g_hInetRequest = NULL;
}
}
return receivedData;
}
//-------------------------------------------------------
//
//-------------------------------------------------------
void Computron::AddWarnLog(int _position, char* _log)
{
FILE* out = NULL;
fopen_s(&out, "XenDLL Files/Extensions/Computron/warnLog.txt", "a");
if (out)
{
time_t rawTime;
tm timeInfo;
time(&rawTime);
localtime_s(&timeInfo, &rawTime);
fprintf(out, "%i/%i/%i %i:%i:%i - %i -> %s\n\n",
_position,
timeInfo.tm_year + 1900,
timeInfo.tm_mon,
timeInfo.tm_mday,
timeInfo.tm_hour,
timeInfo.tm_min,
timeInfo.tm_sec,
_log);
fclose(out);
}
}
//-------------------------------------------------------
//
//-------------------------------------------------------
void Computron::ClearWarnLog(void)
{
// clear the list of warnings
_Empty(p1ListViewer2);
_LoadString(p1ListViewer2, "Warnings ::");
// reset warning log
FILE* out = NULL;
fopen_s(&out, "XenDLL Files/Extensions/Computron/warnLog.txt", "w");
if (out) fclose(out);
}
//-------------------------------------------------------
//
//-------------------------------------------------------
void Computron::ClearInstructions(void)
{
ClearJReturnStack();
Instruction* prev = NULL;
Instruction* curr = instrucHeader;
while (curr)
{
prev = curr;
curr = curr->GetNext();
delete prev;
}
instrucHeader = NULL;
instrucCurrent = NULL;
instrucPrevious = NULL;
countTotal = 0;
countSpecial = 0;
countNormal = 0;
}
//-------------------------------------------------------
//
//-------------------------------------------------------
void Computron::ClearJReturnStack(void)
{
JReturnStack* temp = NULL;
while (temp = jreturnStack)
{
jreturnStack = jreturnStack->GetNext();
delete temp;
}
jreturnStack = NULL;
jjump = false;
}
//-------------------------------------------------------
//
//-------------------------------------------------------
void Computron::ResetTransform(void)
{
instrucPrevious = NULL;
instrucCurrent = instrucHeader;
pauseStart = 0.0f;
pauseLength = 0.0f;
ClearJReturnStack();
ClearWarnLog();
minuteJumpTriggered = false;
NextNormalInstruction();
totalPerc = 0.0f;
try { lastXP = (*g_progressXP / 63.0f) * 100.0f; }
catch (...) { }
hrTillHundert = 0.0f;
percPerHr = 0.0f;
initPerc = lastXP;
startPerc = (float)timeGetTime() / 1000.0f;
endPerc = 0.0f;
ranTimes = 0;
}
//-------------------------------------------------------
//
//-------------------------------------------------------
void Computron::ContinCheckProc(void)
{
char buffer[256];
if ((!okayHP || !okayMP || (((float)timeGetTime() / 1000.0f) - pauseStart < pauseLength)) &&
!checkconUsed &&
instrucPrevious->GetSafetyUseCoordCheckcon() &&
instrucPrevious->GetSafetyUseCoordCheck() &&
(instrucPrevious->GetSafetyCoordX() != locationX || instrucPrevious->GetSafetyCoordY() != locationY))
{
checkconUsed = true;
sprintf_s(buffer, sizeof(buffer), "Wrong Coordinates [continuous check] (actual = %i , %i | Allowed = %i , %i)",
locationX,
locationY,
instrucPrevious->GetSafetyCoordX(),
instrucPrevious->GetSafetyCoordY());
AddWarnLog(instrucPrevious->GetInstrucPosition(), buffer);
UseWarnings("WRONG COORDINATES (cont)");
}
else if ((!okayHP || !okayMP || (((float)timeGetTime() / 1000.0f) - pauseStart < pauseLength)) &&
!checkconUsed &&
instrucPrevious->GetSafetyUseSurfCheckcon() &&
instrucPrevious->GetSafetyUseSurfCheck())
{
if (surfSaved < instrucPrevious->GetSafetySurfMin())
{
checkconUsed = true;
sprintf_s(buffer, sizeof(buffer), "Low Surf Count [continuous check] (actual = %i | Allowed = %i - %i)",
surfSaved,
instrucPrevious->GetSafetySurfMin(),
instrucPrevious->GetSafetySurfMax());
AddWarnLog(instrucPrevious->GetInstrucPosition(), buffer);
UseWarnings("LOW SURF COUNT (cont)");
}
else if (surfSaved > instrucPrevious->GetSafetySurfMax())
{
checkconUsed = true;
sprintf_s(buffer, sizeof(buffer), "High Surf Count [continuous check] (actual = %i | Allowed = %i - %i)",
surfSaved,
instrucPrevious->GetSafetySurfMin(),
instrucPrevious->GetSafetySurfMax());
AddWarnLog(instrucPrevious->GetInstrucPosition(), buffer);
UseWarnings("HIGH SURF COUNT (cont)");
}
}
}
//-------------------------------------------------------
//
//-------------------------------------------------------
void Computron::ScriptCycleProc(void)
{
// do nothing if taking a screenshot
if (captureScreen) return;
char buffer[256];
if (transform)
{
if (progressHP <= 0.0f)
{
transform = false;
AddWarnLog(instrucCurrent->GetInstrucPosition(), "You Died");
UseWarnings("YOU DIED", true);
captureScreen = true;
return;
}
if (instrucPrevious)
{
ContinCheckProc();
}
if (instrucCurrent)
{
if (okayHP && okayMP && ((float)timeGetTime() / 1000.0f) - pauseStart >= pauseLength)
{
if (checkconUsed == false)
{
checkconUsed = true;
if (instrucCurrent->GetSafetyUseCoordCheck() && (
instrucCurrent->GetSafetyCoordX() != locationX ||
instrucCurrent->GetSafetyCoordY() != locationY))
{
// -1 is used to force a warning
if (instrucCurrent->GetSafetyCoordX() != -1 && instrucCurrent->GetSafetyCoordY() != -1)
{
sprintf_s(buffer, sizeof(buffer), "Wrong Coordinates [initial check] (actual = %i , %i | Allowed = %i , %i)",
locationX,
locationY,
instrucCurrent->GetSafetyCoordX(),
instrucCurrent->GetSafetyCoordY());
AddWarnLog(instrucCurrent->GetInstrucPosition(), buffer);
}
UseWarnings("WRONG COORDINATES");
}
else if (instrucCurrent->GetSafetyUseSurfCheck() &&
surfSaved < instrucCurrent->GetSafetySurfMin())
{
// -1 is used to force a warning
if (instrucCurrent->GetSafetySurfMin() != -1)
{
sprintf_s(buffer, sizeof(buffer), "Low Surf Count [initial check] (actual = %i | Allowed = %i - %i)",
surfSaved,
instrucCurrent->GetSafetySurfMin(),
instrucCurrent->GetSafetySurfMax());
AddWarnLog(instrucCurrent->GetInstrucPosition(), buffer);
}
UseWarnings("LOW SURF COUNT");
}
else if (instrucCurrent->GetSafetyUseSurfCheck() &&
surfSaved > instrucCurrent->GetSafetySurfMax())
{
// -1 is used to force a warning
if (instrucCurrent->GetSafetySurfMax() != -1)
{
sprintf_s(buffer, sizeof(buffer), "High Surf Count [initial check] (actual = %i | Allowed = %i - %i)",
surfSaved,
instrucCurrent->GetSafetySurfMin(),
instrucCurrent->GetSafetySurfMax());
AddWarnLog(instrucCurrent->GetInstrucPosition(), buffer);
}
UseWarnings("HIGH SURF COUNT");
}
}
else
{
if (instrucCurrent->GetInstrucClearReturnStack())
{
ClearJReturnStack();
}
else if (instrucCurrent->GetInstrucUseKeystroke())
{
g_CustomDevice->directInputHook->SetDIKeyState(instrucCurrent->GetInstrucKeystrokeCode(), 0x80);
}
else if (instrucCurrent->GetInstrucUseMouseClick())
{
g_CustomDevice->directInputHook->SetMouseClick(instrucCurrent->GetInstrucMouseClickX(),
instrucCurrent->GetInstrucMouseClickY(), MOUSEBUTTON_LEFT);
}
else if (instrucCurrent->GetInstrucSendPacket())
{
sprintf_s(buffer, sizeof(buffer), "%s.cap",
instrucCurrent->GetInstrucPacketFile());
SendCap(buffer, networkAdapter, "s");
}
GetPause();
NextNormalInstruction();
}
}
}
}
}
//-------------------------------------------------------
//
//-------------------------------------------------------
void Computron::MemoryCheckProc(void)
{
try { progressHP = (*g_progressHP / 63.0f) * 100.0f; }
catch (...) { }
if (useHealthKey && progressHP < healthPercentTrigger && progressHP > 0.0f)
g_CustomDevice->directInputHook->SetDIKeyState(healthMonitorKey, 0x80);
if (useManaKey && progressMP < manaPercentTrigger && progressMP > 0.0f)
g_CustomDevice->directInputHook->SetDIKeyState(manaMonitorKey, 0x80);
if (zeroPause || (instrucPrevious && instrucPrevious->GetSafetyUseHPWait() == false) ||
(instrucPrevious && instrucPrevious->GetSafetyUseHPWait() && progressHP >= 100.0f))
okayHP = true;
else
okayHP = false;
if (zeroPause || (instrucPrevious && instrucPrevious->GetSafetyUseMPWait() == false) ||
(instrucPrevious && instrucPrevious->GetSafetyUseMPWait() && progressMP >= 100.0f))
okayMP = true;
else
okayMP = false;
try { progressMP = (*g_progressMP / 63.0f) * 100.0f; }
catch (...) { }
try { progressXP = (*g_progressXP / 63.0f) * 100.0f; }
catch (...) { }
if (transform)
{
if (progressXP != lastXP)
{
if (lastXP != initPerc)
{
totalPerc += progressXP - lastXP;
percPerHr = ((100.0f * totalPerc) / ((((float)timeGetTime() / 1000.0f) - (float)startPerc) / 3600.0f));
hrTillHundert = (100.0f - progressXP) / percPerHr;
endPerc = (((float)timeGetTime() / 1000.0f) - startPerc) / 3600.0f;
}
else
{
startPerc = (float)timeGetTime() / 1000.0f;
}
lastXP = progressXP;
}
}
try { locationX = (int)*g_locationX; }
catch (...) { }
try { locationY = (int)*g_locationY; }
catch (...) { }
}
//-------------------------------------------------------
//
//-------------------------------------------------------
void Computron::NextNormalInstruction(void)
{
if (instrucCurrent)
{
instrucPrevious = instrucCurrent;
while (jjump && instrucCurrent->GetInstrucPosition() == jreturnStack->GetJReturnFrom())
{
if ((jreturnStack->GetJReturn())->GetWarningsJAL())
{
instrucCurrent = jreturnStack->GetJReturn();
}
JReturnStack* temp = jreturnStack;
jreturnStack = jreturnStack->GetNext();
delete temp;
if (jreturnStack == NULL)
jjump = false;
}
int findStart = instrucCurrent->GetInstrucPosition();
instrucCurrent = instrucCurrent->GetNext();
if (instrucCurrent == NULL)
{
instrucCurrent = instrucHeader->GetNext();
ranTimes++;
}
bool isSpecial = instrucCurrent->GetInstrucIsSpecial();
bool timeCheck = instrucCurrent->GetInstrucUseTimedUse();
bool okayTimedUse = true;
if (timeCheck)
okayTimedUse = (((float)timeGetTime() / 1000.0f) - instrucCurrent->GetTimedUseStart()) >= instrucCurrent->GetTimedUseLength();
if (okayTimedUse && instrucCurrent->GetInstrucNotFirstTimedUse() && instrucCurrent->GetTimedUseStart() == 0.0)
{
if (instrucCurrent->GetInstrucTimedUseA() != instrucCurrent->GetInstrucTimedUseB())
{
srand((int)timeGetTime());
instrucCurrent->SetTimedUseLength((rand() % (int)(instrucCurrent->GetInstrucTimedUseB() + 1 - instrucCurrent->GetInstrucTimedUseA())) + instrucCurrent->GetInstrucTimedUseA());
}
else
instrucCurrent->SetTimedUseLength(instrucCurrent->GetInstrucTimedUseA());
instrucCurrent->SetTimedUseStart((float)timeGetTime() / 1000.0f);
okayTimedUse = false;
}
// use to ignore specials
while (transform && ((timeCheck && !okayTimedUse) || (!jjump && isSpecial && instrucCurrent->GetInstrucPosition() != findStart)))
{
instrucCurrent = instrucCurrent->GetNext();
if (instrucCurrent == NULL)
{
instrucCurrent = instrucHeader->GetNext();
}
isSpecial = instrucCurrent->GetInstrucIsSpecial();
timeCheck = instrucCurrent->GetInstrucUseTimedUse();
if (timeCheck)
okayTimedUse = (((float)timeGetTime() / 1000.0f) - instrucCurrent->GetTimedUseStart()) >= instrucCurrent->GetTimedUseLength();
if (okayTimedUse && instrucCurrent->GetInstrucNotFirstTimedUse() && instrucCurrent->GetTimedUseStart() == 0.0)
{
if (instrucCurrent->GetInstrucTimedUseA() != instrucCurrent->GetInstrucTimedUseB())
{
srand((int)timeGetTime());
instrucCurrent->SetTimedUseLength((rand() % (int)(instrucCurrent->GetInstrucTimedUseB() + 1 - instrucCurrent->GetInstrucTimedUseA())) + instrucCurrent->GetInstrucTimedUseA());
}
else
instrucCurrent->SetTimedUseLength(instrucCurrent->GetInstrucTimedUseA());
instrucCurrent->SetTimedUseStart((float)timeGetTime() / 1000.0f);
okayTimedUse = false;
}
}
if (timeCheck)
{
if (instrucCurrent->GetInstrucTimedUseA() != instrucCurrent->GetInstrucTimedUseB())
{
srand((int)timeGetTime());
instrucCurrent->SetTimedUseLength((rand() % (int)(instrucCurrent->GetInstrucTimedUseB() + 1 - instrucCurrent->GetInstrucTimedUseA())) + instrucCurrent->GetInstrucTimedUseA());
}
else
instrucCurrent->SetTimedUseLength(instrucCurrent->GetInstrucTimedUseA());
instrucCurrent->SetTimedUseStart((float)timeGetTime() / 1000.0f);
}
checkconUsed = false;
}
}
//-------------------------------------------------------
//
//-------------------------------------------------------
void Computron::GetPause(int i)
{
if (instrucCurrent)
{
if (i == 0)
{
pauseLength = 0.0f;
zeroPause = true;
}
else
{
if (instrucCurrent->GetInstrucPauseA() != instrucCurrent->GetInstrucPauseB())
{
srand((int)timeGetTime());
pauseLength = (rand() % (int)(instrucCurrent->GetInstrucPauseB() + 1 - instrucCurrent->GetInstrucPauseA())) + instrucCurrent->GetInstrucPauseA();
}
else
pauseLength = instrucCurrent->GetInstrucPauseA();
zeroPause = false;
}
pauseStart = (float)timeGetTime() / 1000.0f;
}
else
{
pauseLength = 0.0f;
zeroPause = true;
}
}
//-------------------------------------------------------
//
//-------------------------------------------------------
void Computron::UseWarnings(char* str, bool justText, int pos)
{
char buffer[256];
bool ignoreDocumenting = false;
Instruction* toUse = NULL;
if (_stricmp(str, "LOW SURF COUNT (cont)") == 0 ||
_stricmp(str, "HIGH SURF COUNT (cont)") == 0 ||
_stricmp(str, "WRONG COORDINATES (cont)") == 0)
toUse = instrucPrevious;
else
toUse = instrucCurrent;
if ((_stricmp(str, "LOW SURF COUNT") == 0 && toUse->GetSafetySurfMin() == -1) ||
(_stricmp(str, "HIGH SURF COUNT") == 0 && toUse->GetSafetySurfMax() == -1) ||
(_stricmp(str, "WRONG COORDINATES") == 0 && (toUse->GetSafetyCoordX() == -1 || toUse->GetSafetyCoordY() == -1)))
{
ignoreDocumenting = true;
}
if (ignoreDocumenting == false)
{
if (pos >= 0)
sprintf_s(buffer, sizeof(buffer), "(%i) %s", toUse->GetInstrucPosition(), str);
else
sprintf_s(buffer, sizeof(buffer), "%s", str);
// add warning to the warning panel
_LoadString(p1ListViewer2, buffer);
}
if (toUse && justText == false)
{
if (toUse->GetWarningsTakeScreenshot())
{
captureScreen = true;
if (ignoreDocumenting == false)
{
//UseWarnings("SCREEN CAPTURED", true);
AddWarnLog(toUse->GetInstrucPosition(), "Screen Captured");
}
}
if (toUse->GetWarningsPlayAudio())
{
sprintf_s(buffer, sizeof(buffer), "%s.wav", toUse->GetWarningsAudioFile());
if (GetFileAttributes(buffer) != 0xFFFFFFFF)
{
PlaySound(buffer, NULL, SND_FILENAME | SND_ASYNC);
if (ignoreDocumenting == false)
{
//UseWarnings("AUDIO PLAYED", true);
sprintf_s(buffer, sizeof(buffer), "Audio Played (%s.wav)",
toUse->GetWarningsAudioFile());
AddWarnLog(toUse->GetInstrucPosition(), buffer);
}
}
}
if (toUse->GetWarningsJump())
{
Instruction* jumpTo = instrucHeader->GetNext();
while (jumpTo && jumpTo->GetInstrucPosition() != toUse->GetWarningsJumpA())
jumpTo = jumpTo->GetNext();
JReturnStack* jreturnNew = new JReturnStack(jreturnStack, toUse->GetWarningsJumpB(), instrucCurrent);
jreturnStack = jreturnNew;
instrucPrevious = NULL;
checkconUsed = false;
instrucCurrent = jumpTo;
jjump = true;
GetPause(0);
if (ignoreDocumenting == false)
{
sprintf_s(buffer, sizeof(buffer), "Jumped to %i",
toUse->GetWarningsJumpA());
AddWarnLog(toUse->GetInstrucPosition(), buffer);
}
}
}
}
//-------------------------------------------------------
//
//-------------------------------------------------------
void Computron::ReadScriptFile()
{
ClearInstructions();
char buffer[MAX_PATH];
sprintf_s(buffer, sizeof(buffer), "XenDLL Files/Extensions/Computron/Scripts/%s.xml", scriptFilename);
if (GetFileAttributes(buffer) == 0xFFFFFFFF) return;
TiXmlDocument document;
if (document.LoadFile(buffer) == false) return;
TiXmlElement* root = NULL;
int version;
if (!(root = document.FirstChildElement("script")) ||
!root->Attribute("version", &version) ||
version != SCRIPT_VERSION) return;
instrucHeader = new Instruction();
instrucHeader->SetInstrucPosition(-1);
Instruction* prev = instrucHeader;
Instruction* curr = NULL;
countTotal = 0;
countSpecial = 0;
countNormal = 0;
// get the script settings
TiXmlElement* element = root->FirstChildElement("setting");
while (element)
{
TiXmlElement* item = NULL;
item = element->FirstChildElement("scriptScreenSizeA");
if (item) screenSizeA = (float)atof(item->GetText());
item = element->FirstChildElement("scriptScreenSizeB");
if (item) screenSizeB = (float)atof(item->GetText());
item = element->FirstChildElement("scriptUseHealthKey");
if (item) useHealthKey = (_stricmp(item->GetText(), "true") == 0);
item = element->FirstChildElement("scriptHealthPercent");
if (item) healthPercentTrigger = atoi(item->GetText());
item = element->FirstChildElement("scriptHealthCode");
if (item) healthMonitorKey = atoi(item->GetText());
item = element->FirstChildElement("scriptUseManaKey");
if (item) useManaKey = (_stricmp(item->GetText(), "true") == 0);
item = element->FirstChildElement("scriptManaPercent");
if (item) manaPercentTrigger = atoi(item->GetText());
item = element->FirstChildElement("scriptManaCode");
if (item) manaMonitorKey = atoi(item->GetText());
element = element->NextSiblingElement();
}
// get the script instructions
element = root->FirstChildElement("instruction");
while (element)
{
TiXmlElement* item = NULL;
curr = new Instruction();
prev->SetNext(curr);
prev = curr;
curr->SetInstrucPosition(countTotal);
countTotal++;
// instruction
item = element->FirstChildElement("instrucIsSpecial");
if (item)
{
curr->SetInstrucIsSpecial(_stricmp(item->GetText(), "true") == 0);
if (curr->GetInstrucIsSpecial())
{
countSpecial++;
}
else
{
countNormal++;
}
}
item = element->FirstChildElement("instrucClearReturnStack");
if (item) curr->SetInstrucClearReturnStack(_stricmp(item->GetText(), "true") == 0);
item = element->FirstChildElement("instrucUseKeystroke");
if (item) curr->SetInstrucUseKeystroke(_stricmp(item->GetText(), "true") == 0);
item = element->FirstChildElement("instrucKeystrokeCode");
if (item) curr->SetInstrucKeystrokeCode(_convertDIK_Name(item->GetText()));
item = element->FirstChildElement("instrucUseMouseClick");
if (item) curr->SetInstrucUseMouseClick(_stricmp(item->GetText(), "true") == 0);
item = element->FirstChildElement("instrucMouseClickX");
if (item) curr->SetInstrucMouseClickX((int)(atoi(item->GetText()) * (_ScreenWidth() / screenSizeA)));
item = element->FirstChildElement("instrucMouseClickY");
if (item) curr->SetInstrucMouseClickY((int)(atoi(item->GetText()) * (_ScreenHeight() / screenSizeB)));
item = element->FirstChildElement("instrucSendPacket");
if (item) curr->SetInstrucSendPacket(_stricmp(item->GetText(), "true") == 0);
item = element->FirstChildElement("instrucPacketFile");
if (item) curr->SetInstrucPacketFile(_restring(item->GetText(), 0, strlen(item->GetText())));
item = element->FirstChildElement("instrucPauseA");
if (item) curr->SetInstrucPauseA((float)atof(item->GetText()));
item = element->FirstChildElement("instrucPauseB");
if (item) curr->SetInstrucPauseB((float)atof(item->GetText()));
item = element->FirstChildElement("instrucComment");
if (item) curr->SetInstrucComment(_restring(item->GetText(), 0, strlen(item->GetText())));
item = element->FirstChildElement("instrucUseTimedUse");
if (item) curr->SetInstrucUseTimedUse(_stricmp(item->GetText(), "true") == 0);
item = element->FirstChildElement("instrucTimedUseA");
if (item) curr->SetInstrucTimedUseA((float)atof(item->GetText()));
item = element->FirstChildElement("instrucTimedUseB");
if (item) curr->SetInstrucTimedUseB((float)atof(item->GetText()));
item = element->FirstChildElement("instrucNotFirstTimedUse");
if (item) curr->SetInstrucNotFirstTimedUse(_stricmp(item->GetText(), "true") == 0);
// safety
item = element->FirstChildElement("safetySurfMin");
if (item) curr->SetSafetySurfMin(atoi(item->GetText()));
item = element->FirstChildElement("safetySurfMax");
if (item) curr->SetSafetySurfMax(atoi(item->GetText()));
item = element->FirstChildElement("safetyUseSurfCheck");
if (item) curr->SetSafetyUseSurfCheck(_stricmp(item->GetText(), "true") == 0);
item = element->FirstChildElement("safetyUseSurfCheckcon");
if (item) curr->SetSafetyUseSurfCheckcon(_stricmp(item->GetText(), "true") == 0);
item = element->FirstChildElement("safetyUseCoordCheck");
if (item) curr->SetSafetyUseCoordCheck(_stricmp(item->GetText(), "true") == 0);
item = element->FirstChildElement("safetyUseCoordCheckcon");
if (item) curr->SetSafetyUseCoordCheckcon(_stricmp(item->GetText(), "true") == 0);
item = element->FirstChildElement("safetyCoordX");
if (item) curr->SetSafetyCoordX(atoi(item->GetText()));
item = element->FirstChildElement("safetyCoordY");
if (item) curr->SetSafetyCoordY(atoi(item->GetText()));
item = element->FirstChildElement("safetyUseHPWait");
if (item) curr->SetSafetyUseHPWait(_stricmp(item->GetText(), "true") == 0);
item = element->FirstChildElement("safetyUseMPWait");
if (item) curr->SetSafetyUseMPWait(_stricmp(item->GetText(), "true") == 0);
// warnings
item = element->FirstChildElement("warningsTakeScreenshot");
if (item) curr->SetWarningsTakeScreenshot(_stricmp(item->GetText(), "true") == 0);
item = element->FirstChildElement("warningsPlayAudio");
if (item) curr->SetWarningsPlayAudio(_stricmp(item->GetText(), "true") == 0);
item = element->FirstChildElement("warningsAudioFile");
if (item) curr->SetWarningsAudioFile(_restring(item->GetText(), 0, strlen(item->GetText())));
item = element->FirstChildElement("warningsJump");
if (item) curr->SetWarningsJump(_stricmp(item->GetText(), "true") == 0);
item = element->FirstChildElement("warningsJumpA");
if (item) curr->SetWarningsJumpA(atoi(item->GetText()));
item = element->FirstChildElement("warningsJumpB");
if (item) curr->SetWarningsJumpB(atoi(item->GetText()));
item = element->FirstChildElement("warningsJAL");
if (item) curr->SetWarningsJAL(_stricmp(item->GetText(), "true") == 0);
element = element->NextSiblingElement();
}
ResetTransform();
}
//-------------------------------------------------------
//
//-------------------------------------------------------
void Computron::SendCap(char* file, char* adapter, char* s)
{
//char buffer[256];
//pcap_t* inDesc = NULL;
//pcap_t* outDesc = NULL;
//char errorBuffer[PCAP_ERRBUF_SIZE];
//char source[PCAP_BUF_SIZE];
//FILE* capFilename = NULL;
//int capLength, sync;
//u_int res;
//pcap_send_queue* sendQueue = NULL;
//struct pcap_pkthdr* packetHeader = NULL;
//const u_char* packetData = NULL;
//float cpuTime;
//u_int npacks = 0;
//
//// retrieve the length of the capture file
//fopen_s(&capFilename, file,"rb");
//if(capFilename == NULL)
//{
// AddWarnLog(-1, "Capture file not found");
// UseWarnings(buffer);
// return;
//}
//
//fseek(capFilename , 0, SEEK_END);
//capLength = ftell(capFilename)- sizeof(struct pcap_file_header);
//fclose(capFilename);
//
//// chek if the timestamps must be respected
//if(s[0] == 's')
// sync = TRUE;
//else
// sync = FALSE;
//// open the capture
//// create the source string according to the new WinPcap syntax
//if (_pcap_createsrcstr( source, // variable that will keep the source string
// PCAP_SRC_FILE, // we want to open a file
// NULL, // remote host
// NULL, // port on the remote host
// file, // name of the file we want to open
// errorBuffer // error buffer
// ) != 0)
//{
// AddWarnLog(-1, "Error creating a source string");
// UseWarnings(buffer);
// return;
//}
//
//// open the capture file
//if ((inDesc = _pcap_open(source, 65536, PCAP_OPENFLAG_PROMISCUOUS, 1000, NULL, errorBuffer)) == NULL)
//{
// sprintf_s(buffer, sizeof(buffer), "Unable to open the file %s", source);
// AddWarnLog(-1, buffer);
// UseWarnings(buffer);
// return;
//}
//// open the output adapter
//if ((outDesc = _pcap_open(adapter, 100, PCAP_OPENFLAG_PROMISCUOUS, 1000, NULL, errorBuffer)) == NULL)
//{
// sprintf_s(buffer, sizeof(buffer), "Unable to open adapter %s", adapter);
// AddWarnLog(-1, buffer);
// UseWarnings(buffer);
// return;
//}
//// check the mac type
//if (_pcap_datalink(inDesc) != _pcap_datalink(outDesc))
//{
// AddWarnLog(-1, "Warning: the datalink of the capture differs from the one of the selected interface");
// UseWarnings(buffer);
//}
//// allocate a send queue
//sendQueue = _pcap_sendqueue_alloc(capLength);
//// fill the queue with the packets from the file
//while ((res = _pcap_next_ex(inDesc, &packetHeader, &packetData)) == 1)
//{
// if (_pcap_sendqueue_queue(sendQueue, packetHeader, packetData) == -1)
// {
// AddWarnLog(-1, "Warning: packet buffer too small, not all the packets will be sent");
// UseWarnings(buffer);
// break;
// }
// npacks++;
//}
//if (res == -1)
//{
// AddWarnLog(-1, "Corrupted input file");
// UseWarnings(buffer);
// _pcap_sendqueue_destroy(sendQueue);
// return;
//}
//// transmit the queue
//cpuTime = (float)clock();
//if ((res = _pcap_sendqueue_transmit(outDesc, sendQueue, sync)) < sendQueue->len)
//{
// sprintf_s(buffer, sizeof(buffer), "An error occurred sending the packets: %s. Only %d bytes were sent", _pcap_geterr(outDesc), res);
// AddWarnLog(-1, buffer);
// UseWarnings(buffer);
//}
//
//cpuTime = (clock() - cpuTime)/CLK_TCK;
//// free the send queue
//_pcap_sendqueue_destroy(sendQueue);
//// Close the input file
//_pcap_close(inDesc);
//// lose the output adapter
//// IMPORTANT: remember to close the adapter, otherwise there will be no guarantee that all the
//// packets will be sent!
//_pcap_close(outDesc);
}
//-------------------------------------------------------
// bDown is true when button is down (can be ignored)
// bRepeat is true if button is held down
// return false to stop processing of other keys
//-------------------------------------------------------
bool Computron::HandleKeyboard()
{
if (logout) return true;
KeyInfo xKey = _Key();
if (xKey.bDown)
{
if (instrucCurrent && xKey.cKey == pauseRestartKey)
{
return false;
}
else if (instrucCurrent && xKey.cKey == pauseResumeKey)
{
return false;
}
}
else if (xKey.bRepeat == false)
{
if (instrucCurrent && xKey.cKey == pauseRestartKey)
{
if (transform == false)
ResetTransform();
transform = !transform;
return false;
}
else if (instrucCurrent && xKey.cKey == pauseResumeKey)
{
if (!transform && instrucCurrent == NULL)
ResetTransform();
transform = !transform;
return false;
}
}
return true;
}
//-------------------------------------------------------
//
//-------------------------------------------------------
Computron::Computron(void)
{
initialized = false;
logout = false;
g_progressHP = NULL;
g_progressMP = NULL;
g_progressXP = NULL;
g_locationX = NULL;
g_locationY = NULL;
locationX = 0;
locationY = 0;
progressHP = 0.0f;
progressMP = 0.0f;
progressXP = 0.0f;
pauseRestartKey = 0x00;
pauseResumeKey = 0x00;
extComputron = NULL;
panel1 = NULL;
p1TextBar1 = NULL;
p1ListViewer1 = NULL;
p1ListViewer2 = NULL;
g_hInetConnection = NULL;
g_hInet = NULL;
captureScreen = false;
zeroPause = false;
okayHP = true;
okayMP = true;
checkconUsed = false;
jjump = false;
minuteJumpTriggered = false;
transform = false;
surfCount = 0;
surfSaved = 0;
countTotal = 0;
countSpecial = 0;
countNormal = 0;
ranTimes = 0;
screenSizeA = 0.0f;
screenSizeB = 0.0f;
useHealthKey = false;
healthPercentTrigger = 0;
healthMonitorKey = 0x00;
useManaKey = false;
manaPercentTrigger = 0;
manaMonitorKey = 0x00;
totalPerc = 0.0f;
lastXP = 0.0f;
hrTillHundert = 0.0f;
percPerHr = 0.0f;
initPerc = 0.0f;
startPerc = 0.0f;
endPerc = 0.0f;
scriptFilename = "";
scriptHandle = "";
scriptPassword = "";
pauseLength = 0.0f;
pauseStart = 0.0f;
instrucHeader = NULL;
instrucCurrent = NULL;
instrucPrevious = NULL;
jreturnStack = NULL;
PacketMod = NULL;
pthreadVCMod = NULL;
WanPacketMod = NULL;
wpcapMod = NULL;
}
//-------------------------------------------------------
//
//-------------------------------------------------------
bool Computron::Uninitialize(void)
{
initialized = false;
if (extComputron)
{
if (_CheckExtMenuIO(extComputron))
_WriteConfigItem("MenuItemIO", "true", "XenDLL Files/Extensions/Computron/Computron.xml");
else
_WriteConfigItem("MenuItemIO", "false", "XenDLL Files/Extensions/Computron/Computron.xml");
_UnloadExtension(extComputron);
}
ClearInstructions();
if (wpcapMod)
{
FreeLibrary(wpcapMod);
}
if (pthreadVCMod)
{
FreeLibrary(pthreadVCMod);
}
if (PacketMod)
{
FreeLibrary(PacketMod);
}
if (WanPacketMod)
{
FreeLibrary(WanPacketMod);
}
if (g_hInetConnection)
{
InternetCloseHandle(g_hInetConnection);
g_hInetConnection = NULL;
}
if (g_hInet)
{
InternetCloseHandle(g_hInetConnection);
g_hInetConnection = NULL;
}
return initialized;
}
//-------------------------------------------------------
//
//-------------------------------------------------------
Computron::~Computron(void)
{
Uninitialize();
}
| [
"[email protected]"
]
| [
[
[
1,
2045
]
]
]
|
bb1912891749650e25e9ea97a898a81809ab20f2 | c5176b11a3c23df5f4d9d9788c325ba05aaef545 | /src/underTest/wpan/Isabel/Analysis/AnalysisEnergy.h | b2ac0c60679f1c210d5774825c1e309ffba51602 | []
| no_license | canthefason/inetmanet | 77711b5e42d6e80a68e132a2f525fa448f71ac19 | f8f3cdf1d5e139dc62cbc60e5e6e73de7ba30b0f | refs/heads/master | 2021-01-18T07:37:08.633900 | 2009-04-14T22:59:13 | 2009-04-14T22:59:13 | 176,460 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,258 | h | /**
* @short This class provides facilities to obtain snapshots of the energy
* available in the network
* @author Isabel Dietrich
*/
#ifndef ANALYSIS_ENERGY_H
#define ANALYSIS_ENERGY_H
// SYSTEM INCLUDES
#include <omnetpp.h>
#include <vector>
#include <string>
#include <fstream>
#include "Coord.h" // provides: struct for position coordinates
#include "Energy.h" // provides: class for maintaining energy
#include "BasicBattery.h" // provides: access to the node batteries
#include "ChannelControl.h" // provides: global position knowledge
class AnalysisEnergy : public cSimpleModule
{
public:
// LIFECYCLE
virtual void initialize(int);
virtual void finish();
// OPERATIONS
void handleMessage(cMessage*);
void Snapshot();
private:
// OPERATIONS
void SnapshotEnergies();
void SnapshotLifetimes();
// MEMBER VARIABLES
/** Parameters */
bool mCoreDebug;
int mNumHosts;
std::string mpHostModuleName;
int mNumHostsDepleted;
/** Snapshot creation variables */
cMessage* mCreateSnapshot;
ChannelControl* mpCc;
ChannelControl::HostRef mTempHostRef;
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
54
]
]
]
|
2864dff55547f6a14e71ff60531e0fc6c3033daa | 968aa9bac548662b49af4e2b873b61873ba6f680 | /imgtools/imglib/patchdataprocessor/include/patchdataprocessor.h | e51fdfd05f4c2c511919198f08450d08b97d04f5 | []
| no_license | anagovitsyn/oss.FCL.sftools.dev.build | b3401a1ee3fb3c8f3d5caae6e5018ad7851963f3 | f458a4ce83f74d603362fe6b71eaa647ccc62fee | refs/heads/master | 2021-12-11T09:37:34.633852 | 2010-12-01T08:05:36 | 2010-12-01T08:05:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,179 | h | /*
* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of the License "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description:
* Class for Patching Exported Data
* @internalComponents
* @released
*
*/
#ifndef PATCHDATAPROCESSOR_H
#define PATCHDATAPROCESSOR_H
#include <e32def.h>
#include <string>
#include <iostream>
#include <vector>
#include <map>
#include <sstream>
using namespace std;
typedef vector<string> StringVector;
typedef vector<StringVector> VectorOfStringVector;
typedef map<string,string> MapOfString;
typedef map<string,string>::iterator MapOfStringIterator;
/**
Class for patching exported data.
@internalComponent
@released
*/
class CPatchDataProcessor
{
VectorOfStringVector iPatchDataStatements; // Vector of string containing patchdata statements.
MapOfString iRenamedFileMap; // Map containing information of renamed files.
public:
void AddPatchDataStatement(StringVector aPatchDataStatement);
void AddToRenamedFileMap(string aCurrentName, string aNewName);
VectorOfStringVector GetPatchDataStatements() const;
MapOfString GetRenamedFileMap() const;
};
class TRomNode;
/**
Class to form a patchdata linked-list contatining symbol size, address/ordinal
new value to be patched.
@internalComponent
@released
*/
class DllDataEntry
{
public:
DllDataEntry(TUint32 aSize, TUint32 aNewValue) :
iSize(aSize), iDataAddress((TUint32)-1), iOrdinal((TUint32)-1), iOffset(0),
iNewValue(aNewValue), iRomNode(NULL), iNextDllEntry(NULL)
{
}
TUint32 iSize;
TLinAddr iDataAddress;
TUint32 iOrdinal;
TUint32 iOffset;
TUint32 iNewValue;
TRomNode* iRomNode;
DllDataEntry* iNextDllEntry;
void AddDllDataEntry(DllDataEntry*);
DllDataEntry* NextDllDataEntry() const;
};
#endif //PATCHDATAPROCESSOR_H
| [
"none@none"
]
| [
[
[
1,
90
]
]
]
|
7fa2f79c58047973156dace87179d5ab36e947b9 | 9ba08620ddc3579995435d6e0e9cabc436e1c88d | /src/World.h | 2abef40a6067fd7007b2b69c197a78ea0d26fdd6 | [
"MIT"
]
| permissive | foxostro/CheeseTesseract | f5d6d7a280cbdddc94a5d57f32a50caf1f15e198 | 737ebbd19cee8f5a196bf39a11ca793c561e56cb | refs/heads/master | 2021-01-01T17:31:27.189613 | 2009-08-02T13:27:20 | 2009-08-02T13:27:33 | 267,008 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,974 | h | #ifndef _WORLD_H_
#define _WORLD_H_
#include "vec4.h"
#include "PropertyBag.h"
#include "ActorSet.h"
#include "Terrain.h"
#include "SkyBox.h"
#include "Camera.h"
#include "Fog.h"
#include "PhysicsEngine.h"
#include "ParticleEngine.h"
#include "SDLinput.h"
#include "ActionChangeMap.h"
#include "ActionDebugEnable.h"
#include "ActionDebugDisable.h"
class GraphicsDevice;
/**
Game world.
Contains the game world map, the player, game objects, and other entities
*/
class World : public ScopedEventHandler {
public:
/**
Constructor
@param uid UID to identify this blackboard subscriber
@param parentBlackBoard Communication with game subsystems
@param textureFactory Tracks loaded textures
*/
World(UID uid,
ScopedEventHandler *parentBlackBoard,
shared_ptr<class Renderer> renderer,
TextureFactory &textureFactory,
Camera *camera);
/** Loads the world from file */
void loadFromFile(const FileName &fileName);
/**
Retrieves the name of the realm
@return Name of the realm
*/
inline const string& getName() const {
return name;
}
/**
Sets the name of the realm
@param name New name of the realm
*/
inline void setName(const string &name) {
this->name = name;
}
/**
Gets the object database
@return object database
*/
inline ActorSet& getObjects() {
return objects;
}
/**
Gets the object database
@return object database
*/
inline const ActorSet& getObjects() const {
return objects;
}
/** Destroys all game world assets and resets the game world */
void destroy();
/**
Update the World
@param deltaTime Time elapsed since the last update
*/
void update(float deltaTime);
/** Draws the scene */
void draw() const;
/**
Gets the most recently calculated mean player position
@return mean player position
*/
inline const vec3& getAveragePlayerPosition() const {
return averagePlayerPosition;
}
inline shared_ptr<PhysicsEngine> getPhysicsEngine() const {
return physicsEngine;
}
TextureFactory& getTextureFactory() {
return textureFactory;
}
const TextureFactory& getTextureFactory() const {
return textureFactory;
}
/**
Generates an explosion in the game world
@param originator actor that originated the explosion (immune)
@param position Position of the explosion
@param rotation Rotation (radians) of the particle system about the Z-axis
@param baseDamage Base damage before distance falloff
@param soundFileName File name of the explosion sound effect
@param particlesFileName Filename of the particle system
*/
void generateExplosion(ActorID originator,
const vec3 &position,
float rotation,
int baseDamage,
const FileName &soundFileName,
const FileName &particlesFileName);
/**
Players enter the game world; recreate players in the game world
@param numPlayers Number of players entering the game
*/
void playersEnter(int numPlayers);
/** Given an actor, determine if it is one of the world's players */
bool isAPlayer(ActorID actor) const;
private:
/** Do not call the assignment operator */
World operator=(const World &rh);
/** Do not call the copy constructor */
World(const World &world);
void onKeyDownUp();
void onKeyDownDown();
void onKeyDownLeft();
void onKeyDownRight();
void onKeyDownFwd();
void onKeyDownRev();
void onKeyDownStrafeLeft();
void onKeyDownStrafeRight();
void onKeyToggleCamera();
void onKeyToggleDebugRendering();
void onKeyTogglePhysics();
void handleActionChangeMap(const ActionChangeMap *action);
void handleActionDebugEnable(const ActionDebugEnable *action);
void handleActionDebugDisable(const ActionDebugDisable *action);
void broadcastGameOverEvent();
/** Plays a sound */
void playSound(const FileName &sound);
/**
Loads the world state
@param xml data source
*/
void load(const PropertyBag &xml);
/**
Search for the player start point and set the initial camera position
to focus on that location
*/
void cameraLooksAtPlayerStartPoint();
/** Searches for the player start point and returns its position */
vec3 getPlayerStartPoint() const;
/**
Creates a single player entity from data (Adds it to "objects" set).
Please note that the position described in the playerData may be
interpreted as the starting position of the player (single-player) or as
the locus of the player party (multi-player) So, a second step where the
player's are repositioned around the party locus may be necessary after
the call to this method has completed.
@param initialPosition Initial player position
@param playerData Data describing the starting player configuration
@param playerNumber The player's number
@param numOfPlayers Number of players in the party (so we can center about
the party position)
@return Player
*/
ActorPtr createPlayer(const vec3 &initialPosition,
const PropertyBag &playerData,
int playerNumber,
int numOfPlayers);
/** Destroys all player characters in the game world */
void detroyAllPlayers();
/** Updates the camera positions */
void updateCamera(float deltaTime);
/** Harmonizes the camera with the current player positions */
void updateCamera_Overhead();
/**
Sets the camera position and looks at the average player position
@param theta Camera angle (radians) about the X axis
@param angleZ Camera angle (radians) about the Z axis
@param distance Greatest distance from a player to the average position
@param averagePlayerPosition Average of all player positions
*/
void setCameraLook(float theta,
float angleZ,
float distance,
const vec3 &averagePlayerPosition);
/** Flying 1st person camera */
void updateCamera_FirstPerson(float deltaTime);
/** Third person camera focused on player 0 */
void updateCamera_ThirdPerson();
/** Periodically calculates and caches the average player position */
inline void recalculateAveragePlayerPosition() {
averagePlayerPosition = findAveragePlayerPosition();
}
/**
Finds the mean position of all the players in the game
@return average position of all the players
*/
vec3 findAveragePlayerPosition() const;
inline void resetKeyFlags() {
w = s = a = d = i = k = j = l = false;
}
/** Updates game physics */
void updatePhysics( float deltaTime );
/** Process any pending requests to change the map */
void handleMapChangeRequest();
/**
Directly polls the players in the world to determine whether
game over conditions have occurred.
*/
bool isGameOver();
void sendPlayerNumber(int playerNumber, const ActorPtr &player);
void broadcastDebugModeEnable();
void broadcastDebugModeDisable();
void sendExplosionEvent(const vec3 & position,
int baseDamage,
ActorID originator);
void handleInputKeyPress(const InputKeyPress *input);
void handleInputKeyDown(const InputKeyDown *input);
public:
/** References to the players */
ActorSet players;
/** Particle engine manages all particle systems */
shared_ptr<ParticleEngine> particleEngine;
private:
/** Reference to the active camera for the application */
Camera *camera;
/** Name of the World */
string name;
/** Filename of most recent map data source */
FileName fileName;
/** Set of objects that reside within this World */
ActorSet objects;
/** Height map based terrain */
shared_ptr<Terrain> terrain;
/** Tracks loaded textures */
TextureFactory &textureFactory;
/** Periodically calculates and caches the average player position */
vec3 averagePlayerPosition;
/** Physics engine subsystem */
shared_ptr<PhysicsEngine> physicsEngine;
/** Indicates that the camera is in FP mode (true) or game mode (false) */
enum {
FIRST_PERSON_CAMERA,
OVERHEAD_CAMERA,
THIRD_PERSON_CAMERA,
} cameraMode;
/** Indicates that the physics engine is running */
bool physicsRunning;
/** Indicates that the debug rendering should be used */
bool displayDebugData;
/** Camera yaw and pitch while in FP camera mode */
float yaw, pitch;
bool w, s, a, d, i, j, k, l;
/**
Only valid when mapChangeRequested is true.
Indicates the map to change to
*/
FileName nextMap;
/** Indicates that a map change was requested in the previous tick */
bool mapChangeRequested;
/** References the game's renderer */
shared_ptr<class Renderer> renderer;
};
#endif
| [
"arfox@arfox-desktop"
]
| [
[
[
1,
325
]
]
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.